session.c revision 1.44 1 /* $NetBSD: session.c,v 1.44 2025/10/11 15:45:07 christos Exp $ */
2 /* $OpenBSD: session.c,v 1.344 2025/09/25 02:15:39 jsg Exp $ */
3
4 /*
5 * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
6 * All rights reserved
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 *
14 * SSH2 support by Markus Friedl.
15 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37
38 #include "includes.h"
39 __RCSID("$NetBSD: session.c,v 1.44 2025/10/11 15:45:07 christos Exp $");
40 #include <sys/types.h>
41 #include <sys/wait.h>
42 #include <sys/un.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #include <sys/queue.h>
46
47 #include <ctype.h>
48 #include <errno.h>
49 #include <fcntl.h>
50 #include <grp.h>
51 #include <login_cap.h>
52 #include <netdb.h>
53 #include <paths.h>
54 #include <pwd.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <stdarg.h>
60 #include <unistd.h>
61 #include <limits.h>
62
63 #include "xmalloc.h"
64 #include "ssh.h"
65 #include "ssh2.h"
66 #include "sshpty.h"
67 #include "packet.h"
68 #include "sshbuf.h"
69 #include "ssherr.h"
70 #include "match.h"
71 #include "uidswap.h"
72 #include "channels.h"
73 #include "sshkey.h"
74 #include "cipher.h"
75 #include "kex.h"
76 #include "hostfile.h"
77 #include "auth.h"
78 #include "auth-options.h"
79 #include "authfd.h"
80 #include "pathnames.h"
81 #include "log.h"
82 #include "misc.h"
83 #include "servconf.h"
84 #include "sshlogin.h"
85 #include "serverloop.h"
86 #include "canohost.h"
87 #include "session.h"
88 #ifdef GSSAPI
89 #include "ssh-gss.h"
90 #endif
91 #include "monitor_wrap.h"
92 #include "sftp.h"
93 #include "atomicio.h"
94
95 #ifdef KRB5
96 #include <krb5/kafs.h>
97 #endif
98
99 #define IS_INTERNAL_SFTP(c) \
100 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
101 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
102 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
103 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
104
105 /* func */
106
107 Session *session_new(void);
108 void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
109 void session_pty_cleanup(Session *);
110 void session_proctitle(Session *);
111 int session_setup_x11fwd(struct ssh *, Session *);
112 int do_exec_pty(struct ssh *, Session *, const char *);
113 int do_exec_no_pty(struct ssh *, Session *, const char *);
114 int do_exec(struct ssh *, Session *, const char *);
115 void do_login(struct ssh *, Session *, const char *);
116 __dead void do_child(struct ssh *, Session *, const char *);
117 void do_motd(void);
118 int check_quietlogin(Session *, const char *);
119
120 static void do_authenticated2(struct ssh *, Authctxt *);
121
122 static int session_pty_req(struct ssh *, Session *);
123
124 /* import */
125 extern ServerOptions options;
126 extern char *__progname;
127 extern int debug_flag;
128 extern struct sshbuf *loginmsg;
129 extern struct sshauthopt *auth_opts;
130 extern char *tun_fwd_ifnames; /* serverloop.c */
131
132 /* original command from peer. */
133 const char *original_command = NULL;
134
135 /* data */
136 static int sessions_first_unused = -1;
137 static int sessions_nalloc = 0;
138 static Session *sessions = NULL;
139
140 #define SUBSYSTEM_NONE 0
141 #define SUBSYSTEM_EXT 1
142 #define SUBSYSTEM_INT_SFTP 2
143 #define SUBSYSTEM_INT_SFTP_ERROR 3
144
145 #ifdef HAVE_LOGIN_CAP
146 login_cap_t *lc;
147 #endif
148
149 static int is_child = 0;
150 static int in_chroot = 0;
151
152 /* File containing userauth info, if ExposeAuthInfo set */
153 static char *auth_info_file = NULL;
154
155 /* Name and directory of socket for authentication agent forwarding. */
156 static char *auth_sock_name = NULL;
157
158 /* removes the agent forwarding socket */
159
160 static void
161 auth_sock_cleanup_proc(struct passwd *pw)
162 {
163 if (auth_sock_name != NULL) {
164 temporarily_use_uid(pw);
165 unlink(auth_sock_name);
166 auth_sock_name = NULL;
167 restore_uid();
168 }
169 }
170
171 static int
172 auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
173 {
174 Channel *nc;
175 int sock = -1;
176
177 if (auth_sock_name != NULL) {
178 error("authentication forwarding requested twice.");
179 return 0;
180 }
181
182 /* Temporarily drop privileged uid for mkdir/bind. */
183 temporarily_use_uid(pw);
184
185 if (agent_listener(pw->pw_dir, "sshd", &sock, &auth_sock_name) != 0) {
186 /* a more detailed error is already logged */
187 ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
188 "couldn't create listener socket");
189 restore_uid();
190 goto authsock_err;
191 }
192 restore_uid();
193
194 /* Allocate a channel for the authentication agent socket. */
195 nc = channel_new(ssh, "auth-listener",
196 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
197 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
198 0, "auth socket", 1);
199 nc->path = xstrdup(auth_sock_name);
200 return 1;
201
202 authsock_err:
203 free(auth_sock_name);
204 if (sock != -1)
205 close(sock);
206 auth_sock_name = NULL;
207 return 0;
208 }
209
210 static void
211 display_loginmsg(void)
212 {
213 int r;
214
215 if (sshbuf_len(loginmsg) == 0)
216 return;
217 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
218 fatal_fr(r, "sshbuf_put_u8");
219 printf("%s", (const char *)sshbuf_ptr(loginmsg));
220 sshbuf_reset(loginmsg);
221 }
222
223 static void
224 prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
225 {
226 int fd = -1, success = 0;
227
228 if (!options.expose_userauth_info || info == NULL)
229 return;
230
231 temporarily_use_uid(pw);
232 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
233 if ((fd = mkstemp(auth_info_file)) == -1) {
234 error_f("mkstemp: %s", strerror(errno));
235 goto out;
236 }
237 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
238 sshbuf_len(info)) != sshbuf_len(info)) {
239 error_f("write: %s", strerror(errno));
240 goto out;
241 }
242 if (close(fd) != 0) {
243 error_f("close: %s", strerror(errno));
244 goto out;
245 }
246 success = 1;
247 out:
248 if (!success) {
249 if (fd != -1)
250 close(fd);
251 free(auth_info_file);
252 auth_info_file = NULL;
253 }
254 restore_uid();
255 }
256
257 static void
258 set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
259 {
260 char *tmp, *cp, *host;
261 int port;
262 size_t i;
263
264 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
265 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
266 for (i = 0; i < auth_opts->npermitopen; i++) {
267 tmp = cp = xstrdup(auth_opts->permitopen[i]);
268 /* This shouldn't fail as it has already been checked */
269 if ((host = hpdelim2(&cp, NULL)) == NULL)
270 fatal_f("internal error: hpdelim");
271 host = cleanhostname(host);
272 if (cp == NULL || (port = permitopen_port(cp)) < 0)
273 fatal_f("internal error: permitopen port");
274 channel_add_permission(ssh,
275 FORWARD_USER, FORWARD_LOCAL, host, port);
276 free(tmp);
277 }
278 }
279 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
280 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
281 for (i = 0; i < auth_opts->npermitlisten; i++) {
282 tmp = cp = xstrdup(auth_opts->permitlisten[i]);
283 /* This shouldn't fail as it has already been checked */
284 if ((host = hpdelim(&cp)) == NULL)
285 fatal_f("internal error: hpdelim");
286 host = cleanhostname(host);
287 if (cp == NULL || (port = permitopen_port(cp)) < 0)
288 fatal_f("internal error: permitlisten port");
289 channel_add_permission(ssh,
290 FORWARD_USER, FORWARD_REMOTE, host, port);
291 free(tmp);
292 }
293 }
294 }
295
296 void
297 do_authenticated(struct ssh *ssh, Authctxt *authctxt)
298 {
299 setproctitle("%s", authctxt->pw->pw_name);
300
301 auth_log_authopts("active", auth_opts, 0);
302
303 /* setup the channel layer */
304 /* XXX - streamlocal? */
305 set_fwdpermit_from_authopts(ssh, auth_opts);
306
307 if (!auth_opts->permit_port_forwarding_flag ||
308 options.disable_forwarding) {
309 channel_disable_admin(ssh, FORWARD_LOCAL);
310 channel_disable_admin(ssh, FORWARD_REMOTE);
311 } else {
312 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
313 channel_disable_admin(ssh, FORWARD_LOCAL);
314 else
315 channel_permit_all(ssh, FORWARD_LOCAL);
316 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
317 channel_disable_admin(ssh, FORWARD_REMOTE);
318 else
319 channel_permit_all(ssh, FORWARD_REMOTE);
320 }
321 auth_debug_send(ssh);
322
323 prepare_auth_info_file(authctxt->pw, authctxt->session_info);
324
325 do_authenticated2(ssh, authctxt);
326
327 do_cleanup(ssh, authctxt);
328 }
329
330 /* Check untrusted xauth strings for metacharacters */
331 static int
332 xauth_valid_string(const char *s)
333 {
334 size_t i;
335
336 for (i = 0; s[i] != '\0'; i++) {
337 if (!isalnum((u_char)s[i]) &&
338 s[i] != '.' && s[i] != ':' && s[i] != '/' &&
339 s[i] != '-' && s[i] != '_')
340 return 0;
341 }
342 return 1;
343 }
344
345 #define USE_PIPES 1
346 /*
347 * This is called to fork and execute a command when we have no tty. This
348 * will call do_child from the child, and server_loop from the parent after
349 * setting up file descriptors and such.
350 */
351 int
352 do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
353 {
354 pid_t pid;
355 #ifdef USE_PIPES
356 int pin[2], pout[2], perr[2];
357
358 if (s == NULL)
359 fatal("do_exec_no_pty: no session");
360
361 /* Allocate pipes for communicating with the program. */
362 if (pipe(pin) == -1) {
363 error_f("pipe in: %.100s", strerror(errno));
364 return -1;
365 }
366 if (pipe(pout) == -1) {
367 error_f("pipe out: %.100s", strerror(errno));
368 close(pin[0]);
369 close(pin[1]);
370 return -1;
371 }
372 if (pipe(perr) == -1) {
373 error_f("pipe err: %.100s", strerror(errno));
374 close(pin[0]);
375 close(pin[1]);
376 close(pout[0]);
377 close(pout[1]);
378 return -1;
379 }
380 #else
381 int inout[2], err[2];
382
383 if (s == NULL)
384 fatal("do_exec_no_pty: no session");
385
386 /* Uses socket pairs to communicate with the program. */
387 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) {
388 error_f("socketpair #1: %.100s", strerror(errno));
389 return -1;
390 }
391 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) {
392 error_f("socketpair #2: %.100s", strerror(errno));
393 close(inout[0]);
394 close(inout[1]);
395 return -1;
396 }
397 #endif
398
399 session_proctitle(s);
400
401 /* Fork the child. */
402 switch ((pid = fork())) {
403 case -1:
404 error_f("fork: %.100s", strerror(errno));
405 #ifdef USE_PIPES
406 close(pin[0]);
407 close(pin[1]);
408 close(pout[0]);
409 close(pout[1]);
410 close(perr[0]);
411 close(perr[1]);
412 #else
413 close(inout[0]);
414 close(inout[1]);
415 close(err[0]);
416 close(err[1]);
417 #endif
418 return -1;
419 case 0:
420 is_child = 1;
421
422 /*
423 * Create a new session and process group since the 4.4BSD
424 * setlogin() affects the entire process group.
425 */
426 if (setsid() == -1)
427 error("setsid failed: %.100s", strerror(errno));
428
429 #ifdef USE_PIPES
430 /*
431 * Redirect stdin. We close the parent side of the socket
432 * pair, and make the child side the standard input.
433 */
434 close(pin[1]);
435 if (dup2(pin[0], 0) == -1)
436 perror("dup2 stdin");
437 close(pin[0]);
438
439 /* Redirect stdout. */
440 close(pout[0]);
441 if (dup2(pout[1], 1) == -1)
442 perror("dup2 stdout");
443 close(pout[1]);
444
445 /* Redirect stderr. */
446 close(perr[0]);
447 if (dup2(perr[1], 2) == -1)
448 perror("dup2 stderr");
449 close(perr[1]);
450 #else
451 /*
452 * Redirect stdin, stdout, and stderr. Stdin and stdout will
453 * use the same socket, as some programs (particularly rdist)
454 * seem to depend on it.
455 */
456 close(inout[1]);
457 close(err[1]);
458 if (dup2(inout[0], 0) == -1) /* stdin */
459 perror("dup2 stdin");
460 if (dup2(inout[0], 1) == -1) /* stdout (same as stdin) */
461 perror("dup2 stdout");
462 close(inout[0]);
463 if (dup2(err[0], 2) == -1) /* stderr */
464 perror("dup2 stderr");
465 close(err[0]);
466 #endif
467
468 /* Do processing for the child (exec command etc). */
469 do_child(ssh, s, command);
470 /* NOTREACHED */
471 default:
472 break;
473 }
474
475 s->pid = pid;
476
477 #ifdef USE_PIPES
478 /* We are the parent. Close the child sides of the pipes. */
479 close(pin[0]);
480 close(pout[1]);
481 close(perr[1]);
482
483 session_set_fds(ssh, s, pin[1], pout[0], perr[0],
484 s->is_subsystem, 0);
485 #else
486 /* We are the parent. Close the child sides of the socket pairs. */
487 close(inout[0]);
488 close(err[0]);
489
490 /*
491 * Enter the interactive session. Note: server_loop must be able to
492 * handle the case that fdin and fdout are the same.
493 */
494 session_set_fds(ssh, s, inout[1], inout[1], err[1],
495 s->is_subsystem, 0);
496 #endif
497 return 0;
498 }
499
500 /*
501 * This is called to fork and execute a command when we have a tty. This
502 * will call do_child from the child, and server_loop from the parent after
503 * setting up file descriptors, controlling tty, updating wtmp, utmp,
504 * lastlog, and other such operations.
505 */
506 int
507 do_exec_pty(struct ssh *ssh, Session *s, const char *command)
508 {
509 int fdout, ptyfd, ttyfd, ptymaster;
510 pid_t pid;
511
512 if (s == NULL)
513 fatal("do_exec_pty: no session");
514 ptyfd = s->ptyfd;
515 ttyfd = s->ttyfd;
516
517 /*
518 * Create another descriptor of the pty master side for use as the
519 * standard input. We could use the original descriptor, but this
520 * simplifies code in server_loop. The descriptor is bidirectional.
521 * Do this before forking (and cleanup in the child) so as to
522 * detect and gracefully fail out-of-fd conditions.
523 */
524 if ((fdout = dup(ptyfd)) == -1) {
525 error_f("dup #1: %s", strerror(errno));
526 close(ttyfd);
527 close(ptyfd);
528 return -1;
529 }
530 /* we keep a reference to the pty master */
531 if ((ptymaster = dup(ptyfd)) == -1) {
532 error_f("dup #2: %s", strerror(errno));
533 close(ttyfd);
534 close(ptyfd);
535 close(fdout);
536 return -1;
537 }
538
539 /* Fork the child. */
540 switch ((pid = fork())) {
541 case -1:
542 error_f("fork: %.100s", strerror(errno));
543 close(fdout);
544 close(ptymaster);
545 close(ttyfd);
546 close(ptyfd);
547 return -1;
548 case 0:
549 is_child = 1;
550
551 close(fdout);
552 close(ptymaster);
553
554 /* Close the master side of the pseudo tty. */
555 close(ptyfd);
556
557 /* Make the pseudo tty our controlling tty. */
558 pty_make_controlling_tty(&ttyfd, s->tty);
559
560 /* Redirect stdin/stdout/stderr from the pseudo tty. */
561 if (dup2(ttyfd, 0) == -1)
562 error("dup2 stdin: %s", strerror(errno));
563 if (dup2(ttyfd, 1) == -1)
564 error("dup2 stdout: %s", strerror(errno));
565 if (dup2(ttyfd, 2) == -1)
566 error("dup2 stderr: %s", strerror(errno));
567
568 /* Close the extra descriptor for the pseudo tty. */
569 close(ttyfd);
570
571 /* record login, etc. similar to login(1) */
572 do_login(ssh, s, command);
573
574 /*
575 * Do common processing for the child, such as execing
576 * the command.
577 */
578 do_child(ssh, s, command);
579 /* NOTREACHED */
580 default:
581 break;
582 }
583 s->pid = pid;
584
585 /* Parent. Close the slave side of the pseudo tty. */
586 close(ttyfd);
587
588 /* Enter interactive session. */
589 s->ptymaster = ptymaster;
590 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
591 return 0;
592 }
593
594 /*
595 * This is called to fork and execute a command. If another command is
596 * to be forced, execute that instead.
597 */
598 int
599 do_exec(struct ssh *ssh, Session *s, const char *command)
600 {
601 int ret;
602 const char *forced = NULL, *tty = NULL;
603 char session_type[1024];
604
605 if (options.adm_forced_command) {
606 original_command = command;
607 command = options.adm_forced_command;
608 forced = "(config)";
609 } else if (auth_opts->force_command != NULL) {
610 original_command = command;
611 command = auth_opts->force_command;
612 forced = "(key-option)";
613 }
614 s->forced = 0;
615 if (forced != NULL) {
616 s->forced = 1;
617 if (IS_INTERNAL_SFTP(command)) {
618 s->is_subsystem = s->is_subsystem ?
619 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
620 } else if (s->is_subsystem)
621 s->is_subsystem = SUBSYSTEM_EXT;
622 snprintf(session_type, sizeof(session_type),
623 "forced-command %s '%.900s'", forced, command);
624 } else if (s->is_subsystem) {
625 snprintf(session_type, sizeof(session_type),
626 "subsystem '%.900s'", s->subsys);
627 } else if (command == NULL) {
628 snprintf(session_type, sizeof(session_type), "shell");
629 } else {
630 /* NB. we don't log unforced commands to preserve privacy */
631 snprintf(session_type, sizeof(session_type), "command");
632 }
633
634 if (s->ttyfd != -1) {
635 tty = s->tty;
636 if (strncmp(tty, "/dev/", 5) == 0)
637 tty += 5;
638 }
639
640 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
641 session_type,
642 tty == NULL ? "" : " on ",
643 tty == NULL ? "" : tty,
644 s->pw->pw_name,
645 ssh_remote_ipaddr(ssh),
646 ssh_remote_port(ssh),
647 s->self);
648
649 #ifdef GSSAPI
650 if (options.gss_authentication) {
651 temporarily_use_uid(s->pw);
652 ssh_gssapi_storecreds();
653 restore_uid();
654 }
655 #endif
656 if (s->ttyfd != -1)
657 ret = do_exec_pty(ssh, s, command);
658 else
659 ret = do_exec_no_pty(ssh, s, command);
660
661 original_command = NULL;
662
663 /*
664 * Clear loginmsg: it's the child's responsibility to display
665 * it to the user, otherwise multiple sessions may accumulate
666 * multiple copies of the login messages.
667 */
668 sshbuf_reset(loginmsg);
669
670 return ret;
671 }
672
673
674 /* administrative, login(1)-like work */
675 void
676 do_login(struct ssh *ssh, Session *s, const char *command)
677 {
678 socklen_t fromlen;
679 struct sockaddr_storage from;
680
681 /*
682 * Get IP address of client. If the connection is not a socket, let
683 * the address be 0.0.0.0.
684 */
685 memset(&from, 0, sizeof(from));
686 fromlen = sizeof(from);
687 if (ssh_packet_connection_is_on_socket(ssh)) {
688 if (getpeername(ssh_packet_get_connection_in(ssh),
689 (struct sockaddr *)&from, &fromlen) == -1) {
690 debug("getpeername: %.100s", strerror(errno));
691 cleanup_exit(255);
692 }
693 }
694
695 if (check_quietlogin(s, command))
696 return;
697
698 display_loginmsg();
699
700 do_motd();
701 }
702
703 /*
704 * Display the message of the day.
705 */
706 void
707 do_motd(void)
708 {
709 FILE *f;
710 char buf[256];
711
712 if (options.print_motd) {
713 #ifdef HAVE_LOGIN_CAP
714 f = fopen(login_getcapstr(lc, "welcome", __UNCONST("/etc/motd"),
715 __UNCONST("/etc/motd")), "r");
716 #else
717 f = fopen("/etc/motd", "r");
718 #endif
719 if (f) {
720 while (fgets(buf, sizeof(buf), f))
721 fputs(buf, stdout);
722 fclose(f);
723 }
724 }
725 }
726
727
728 /*
729 * Check for quiet login, either .hushlogin or command given.
730 */
731 int
732 check_quietlogin(Session *s, const char *command)
733 {
734 char buf[256];
735 struct passwd *pw = s->pw;
736 struct stat st;
737
738 /* Return 1 if .hushlogin exists or a command given. */
739 if (command != NULL)
740 return 1;
741 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
742 #ifdef HAVE_LOGIN_CAP
743 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
744 return 1;
745 #else
746 if (stat(buf, &st) >= 0)
747 return 1;
748 #endif
749 return 0;
750 }
751
752 /*
753 * Reads environment variables from the given file and adds/overrides them
754 * into the environment. If the file does not exist, this does nothing.
755 * Otherwise, it must consist of empty lines, comments (line starts with '#')
756 * and assignments of the form name=value. No other forms are allowed.
757 * If allowlist is not NULL, then it is interpreted as a pattern list and
758 * only variable names that match it will be accepted.
759 */
760 static void
761 read_environment_file(char ***env, u_int *envsize,
762 const char *filename, const char *allowlist)
763 {
764 FILE *f;
765 char *line = NULL, *cp, *value;
766 size_t linesize = 0;
767 u_int lineno = 0;
768
769 f = fopen(filename, "r");
770 if (!f)
771 return;
772
773 while (getline(&line, &linesize, f) != -1) {
774 if (++lineno > 1000)
775 fatal("Too many lines in environment file %s", filename);
776 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
777 ;
778 if (!*cp || *cp == '#' || *cp == '\n')
779 continue;
780
781 cp[strcspn(cp, "\n")] = '\0';
782
783 value = strchr(cp, '=');
784 if (value == NULL) {
785 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
786 filename);
787 continue;
788 }
789 /*
790 * Replace the equals sign by nul, and advance value to
791 * the value string.
792 */
793 *value = '\0';
794 value++;
795 if (allowlist != NULL &&
796 match_pattern_list(cp, allowlist, 0) != 1)
797 continue;
798 child_set_env(env, envsize, cp, value);
799 }
800 free(line);
801 fclose(f);
802 }
803
804 #if defined(USE_PAM) || defined(HAVE_CYGWIN)
805 static void
806 copy_environment_denylist(char **source, char ***env, u_int *envsize,
807 const char *denylist)
808 {
809 char *var_name, *var_val;
810 int i;
811
812 if (source == NULL)
813 return;
814
815 for(i = 0; source[i] != NULL; i++) {
816 var_name = xstrdup(source[i]);
817 if ((var_val = strstr(var_name, "=")) == NULL) {
818 free(var_name);
819 continue;
820 }
821 *var_val++ = '\0';
822
823 if (denylist == NULL ||
824 match_pattern_list(var_name, denylist, 0) != 1) {
825 debug3("Copy environment: %s=%s", var_name, var_val);
826 child_set_env(env, envsize, var_name, var_val);
827 }
828
829 free(var_name);
830 }
831 }
832 #endif /* defined(USE_PAM) || defined(HAVE_CYGWIN) */
833
834 static char **
835 do_setup_env(struct ssh *ssh, Session *s, const char *shell)
836 {
837 char buf[256];
838 size_t n;
839 u_int i, envsize;
840 char *ocp, *cp, *value, **env, *laddr;
841 struct passwd *pw = s->pw;
842
843 /* Initialize the environment. */
844 envsize = 100;
845 env = xcalloc(envsize, sizeof(char *));
846 env[0] = NULL;
847
848 #ifdef GSSAPI
849 /* Allow any GSSAPI methods that we've used to alter
850 * the child's environment as they see fit
851 */
852 ssh_gssapi_do_child(&env, &envsize);
853 #endif
854
855 /* Set basic environment. */
856 for (i = 0; i < s->num_env; i++)
857 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
858
859 child_set_env(&env, &envsize, "USER", pw->pw_name);
860 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
861 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
862 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
863 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
864 else
865 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
866
867 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name);
868 child_set_env(&env, &envsize, "MAIL", buf);
869
870 /* Normal systems set SHELL by default. */
871 child_set_env(&env, &envsize, "SHELL", shell);
872
873 if (getenv("TZ"))
874 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
875 if (s->term)
876 child_set_env(&env, &envsize, "TERM", s->term);
877 if (s->display)
878 child_set_env(&env, &envsize, "DISPLAY", s->display);
879 #ifdef KRB5
880 if (s->authctxt->krb5_ticket_file)
881 child_set_env(&env, &envsize, "KRB5CCNAME",
882 s->authctxt->krb5_ticket_file);
883 #endif
884 if (auth_sock_name != NULL)
885 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
886 auth_sock_name);
887
888
889 /* Set custom environment options from pubkey authentication. */
890 if (options.permit_user_env) {
891 for (n = 0 ; n < auth_opts->nenv; n++) {
892 ocp = xstrdup(auth_opts->env[n]);
893 cp = strchr(ocp, '=');
894 if (cp != NULL) {
895 *cp = '\0';
896 /* Apply PermitUserEnvironment allowlist */
897 if (options.permit_user_env_allowlist == NULL ||
898 match_pattern_list(ocp,
899 options.permit_user_env_allowlist, 0) == 1)
900 child_set_env(&env, &envsize,
901 ocp, cp + 1);
902 }
903 free(ocp);
904 }
905 }
906
907 /* read $HOME/.ssh/environment. */
908 if (options.permit_user_env) {
909 snprintf(buf, sizeof buf, "%.200s/%s/environment",
910 pw->pw_dir, _PATH_SSH_USER_DIR);
911 read_environment_file(&env, &envsize, buf,
912 options.permit_user_env_allowlist);
913 }
914
915 #ifdef USE_PAM
916 /*
917 * Pull in any environment variables that may have
918 * been set by PAM.
919 */
920 if (options.use_pam) {
921 char **p;
922
923 /*
924 * Don't allow PAM-internal env vars to leak
925 * back into the session environment.
926 */
927 #define PAM_ENV_DENYLIST "SSH_AUTH_INFO*,SSH_CONNECTION*"
928 p = fetch_pam_child_environment();
929 copy_environment_denylist(p, &env, &envsize,
930 PAM_ENV_DENYLIST);
931 free_pam_environment(p);
932
933 p = fetch_pam_environment();
934 copy_environment_denylist(p, &env, &envsize,
935 PAM_ENV_DENYLIST);
936 free_pam_environment(p);
937 }
938 #endif /* USE_PAM */
939
940 /* Environment specified by admin */
941 for (i = 0; i < options.num_setenv; i++) {
942 cp = xstrdup(options.setenv[i]);
943 if ((value = strchr(cp, '=')) == NULL) {
944 /* shouldn't happen; vars are checked in servconf.c */
945 fatal("Invalid config SetEnv: %s", options.setenv[i]);
946 }
947 *value++ = '\0';
948 child_set_env(&env, &envsize, cp, value);
949 free(cp);
950 }
951
952 /* SSH_CLIENT deprecated */
953 snprintf(buf, sizeof buf, "%.50s %d %d",
954 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
955 ssh_local_port(ssh));
956 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
957
958 laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
959 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
960 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
961 laddr, ssh_local_port(ssh));
962 free(laddr);
963 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
964
965 if (tun_fwd_ifnames != NULL)
966 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
967 if (auth_info_file != NULL)
968 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
969 if (s->ttyfd != -1)
970 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
971 if (original_command)
972 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
973 original_command);
974 #ifdef KRB4
975 if (s->authctxt->krb4_ticket_file)
976 child_set_env(&env, &envsize, "KRBTKFILE",
977 s->authctxt->krb4_ticket_file);
978 #endif
979 #ifdef KRB5
980 if (s->authctxt->krb5_ticket_file)
981 child_set_env(&env, &envsize, "KRB5CCNAME",
982 s->authctxt->krb5_ticket_file);
983 #endif
984
985
986 if (debug_flag) {
987 /* dump the environment */
988 fprintf(stderr, "Environment:\n");
989 for (i = 0; env[i]; i++)
990 fprintf(stderr, " %.200s\n", env[i]);
991 }
992 return env;
993 }
994
995 /*
996 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
997 * first in this order).
998 */
999 static void
1000 do_rc_files(struct ssh *ssh, Session *s, const char *shell)
1001 {
1002 FILE *f = NULL;
1003 char *cmd = NULL, *user_rc = NULL;
1004 int do_xauth;
1005 struct stat st;
1006
1007 do_xauth =
1008 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1009 xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC);
1010
1011 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
1012 if (!s->is_subsystem && options.adm_forced_command == NULL &&
1013 auth_opts->permit_user_rc && options.permit_user_rc &&
1014 stat(user_rc, &st) >= 0) {
1015 if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL,
1016 user_rc) == -1)
1017 fatal_f("xasprintf: %s", strerror(errno));
1018 if (debug_flag)
1019 fprintf(stderr, "Running %s\n", cmd);
1020 f = popen(cmd, "w");
1021 if (f) {
1022 if (do_xauth)
1023 fprintf(f, "%s %s\n", s->auth_proto,
1024 s->auth_data);
1025 pclose(f);
1026 } else
1027 fprintf(stderr, "Could not run %s\n",
1028 user_rc);
1029 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1030 if (debug_flag)
1031 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1032 _PATH_SSH_SYSTEM_RC);
1033 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1034 if (f) {
1035 if (do_xauth)
1036 fprintf(f, "%s %s\n", s->auth_proto,
1037 s->auth_data);
1038 pclose(f);
1039 } else
1040 fprintf(stderr, "Could not run %s\n",
1041 _PATH_SSH_SYSTEM_RC);
1042 } else if (do_xauth && options.xauth_location != NULL) {
1043 /* Add authority data to .Xauthority if appropriate. */
1044 if (debug_flag) {
1045 fprintf(stderr,
1046 "Running %.500s remove %.100s\n",
1047 options.xauth_location, s->auth_display);
1048 fprintf(stderr,
1049 "%.500s add %.100s %.100s %.100s\n",
1050 options.xauth_location, s->auth_display,
1051 s->auth_proto, s->auth_data);
1052 }
1053 if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1)
1054 fatal_f("xasprintf: %s", strerror(errno));
1055 f = popen(cmd, "w");
1056 if (f) {
1057 fprintf(f, "remove %s\n",
1058 s->auth_display);
1059 fprintf(f, "add %s %s %s\n",
1060 s->auth_display, s->auth_proto,
1061 s->auth_data);
1062 pclose(f);
1063 } else {
1064 fprintf(stderr, "Could not run %s\n",
1065 cmd);
1066 }
1067 }
1068 free(cmd);
1069 free(user_rc);
1070 }
1071
1072 static void
1073 do_nologin(struct passwd *pw)
1074 {
1075 FILE *f = NULL;
1076 char buf[1024], *nl, *def_nl = __UNCONST(_PATH_NOLOGIN);
1077 struct stat sb;
1078
1079 #ifdef HAVE_LOGIN_CAP
1080 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
1081 return;
1082 nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
1083 #else
1084 if (pw->pw_uid == 0)
1085 return;
1086 nl = def_nl;
1087 #endif
1088 if (stat(nl, &sb) == -1) {
1089 if (nl != def_nl)
1090 free(nl);
1091 return;
1092 }
1093
1094 /* /etc/nologin exists. Print its contents if we can and exit. */
1095 logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
1096 if ((f = fopen(nl, "r")) != NULL) {
1097 while (fgets(buf, sizeof(buf), f))
1098 fputs(buf, stderr);
1099 fclose(f);
1100 }
1101 exit(254);
1102 }
1103
1104 /*
1105 * Chroot into a directory after checking it for safety: all path components
1106 * must be root-owned directories with strict permissions.
1107 */
1108 static void
1109 safely_chroot(const char *path, uid_t uid)
1110 {
1111 const char *cp;
1112 char component[PATH_MAX];
1113 struct stat st;
1114
1115 if (!path_absolute(path))
1116 fatal("chroot path does not begin at root");
1117 if (strlen(path) >= sizeof(component))
1118 fatal("chroot path too long");
1119
1120 /*
1121 * Descend the path, checking that each component is a
1122 * root-owned directory with strict permissions.
1123 */
1124 for (cp = path; cp != NULL;) {
1125 if ((cp = strchr(cp, '/')) == NULL)
1126 strlcpy(component, path, sizeof(component));
1127 else {
1128 cp++;
1129 memcpy(component, path, cp - path);
1130 component[cp - path] = '\0';
1131 }
1132
1133 debug3_f("checking '%s'", component);
1134
1135 if (stat(component, &st) != 0)
1136 fatal_f("stat(\"%s\"): %s",
1137 component, strerror(errno));
1138 if (st.st_uid != 0 || (st.st_mode & 022) != 0)
1139 fatal("bad ownership or modes for chroot "
1140 "directory %s\"%s\"",
1141 cp == NULL ? "" : "component ", component);
1142 if (!S_ISDIR(st.st_mode))
1143 fatal("chroot path %s\"%s\" is not a directory",
1144 cp == NULL ? "" : "component ", component);
1145
1146 }
1147
1148 if (chdir(path) == -1)
1149 fatal("Unable to chdir to chroot path \"%s\": "
1150 "%s", path, strerror(errno));
1151 if (chroot(path) == -1)
1152 fatal("chroot(\"%s\"): %s", path, strerror(errno));
1153 if (chdir("/") == -1)
1154 fatal_f("chdir(/) after chroot: %s", strerror(errno));
1155 verbose("Changed root directory to \"%s\"", path);
1156 }
1157
1158 /* Set login name, uid, gid, and groups. */
1159 void
1160 do_setusercontext(struct passwd *pw)
1161 {
1162 char uidstr[32], *chroot_path, *tmp;
1163
1164 if (getuid() == 0 || geteuid() == 0) {
1165 #ifdef HAVE_LOGIN_CAP
1166 # ifdef USE_PAM
1167 if (options.use_pam) {
1168 do_pam_setcred();
1169 }
1170 # endif /* USE_PAM */
1171 /* Prepare groups */
1172 if (setusercontext(lc, pw, pw->pw_uid,
1173 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
1174 perror("unable to set user context");
1175 exit(1);
1176 }
1177 #else
1178
1179 if (setlogin(pw->pw_name) < 0)
1180 error("setlogin failed: %s", strerror(errno));
1181 if (setgid(pw->pw_gid) < 0) {
1182 perror("setgid");
1183 exit(1);
1184 }
1185 /* Initialize the group list. */
1186 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1187 perror("initgroups");
1188 exit(1);
1189 }
1190 endgrent();
1191 # ifdef USE_PAM
1192 /*
1193 * PAM credentials may take the form of supplementary groups.
1194 * These will have been wiped by the above initgroups() call.
1195 * Reestablish them here.
1196 */
1197 if (options.use_pam) {
1198 do_pam_setcred();
1199 }
1200 # endif /* USE_PAM */
1201 #endif
1202 if (!in_chroot && options.chroot_directory != NULL &&
1203 strcasecmp(options.chroot_directory, "none") != 0) {
1204 tmp = tilde_expand_filename(options.chroot_directory,
1205 pw->pw_uid);
1206 snprintf(uidstr, sizeof(uidstr), "%llu",
1207 (unsigned long long)pw->pw_uid);
1208 chroot_path = percent_expand(tmp, "h", pw->pw_dir,
1209 "u", pw->pw_name, "U", uidstr, (char *)NULL);
1210 safely_chroot(chroot_path, pw->pw_uid);
1211 free(tmp);
1212 free(chroot_path);
1213 /* Make sure we don't attempt to chroot again */
1214 free(options.chroot_directory);
1215 options.chroot_directory = NULL;
1216 in_chroot = 1;
1217 }
1218
1219 #ifdef HAVE_LOGIN_CAP
1220 /* Set UID */
1221 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
1222 perror("unable to set user context (setuser)");
1223 exit(1);
1224 }
1225 #else
1226 /* Permanently switch to the desired uid. */
1227 permanently_set_uid(pw);
1228 #endif
1229 } else if (options.chroot_directory != NULL &&
1230 strcasecmp(options.chroot_directory, "none") != 0) {
1231 fatal("server lacks privileges to chroot to ChrootDirectory");
1232 }
1233
1234 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1235 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1236 }
1237
1238 __dead static void
1239 do_pwchange(Session *s)
1240 {
1241 fflush(NULL);
1242 fprintf(stderr, "WARNING: Your password has expired.\n");
1243 if (s->ttyfd != -1) {
1244 fprintf(stderr,
1245 "You must change your password now and log in again!\n");
1246 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
1247 perror("passwd");
1248 } else {
1249 fprintf(stderr,
1250 "Password change required but no TTY available.\n");
1251 }
1252 exit(1);
1253 }
1254
1255 static void
1256 child_close_fds(struct ssh *ssh)
1257 {
1258 extern int auth_sock;
1259
1260 if (auth_sock != -1) {
1261 close(auth_sock);
1262 auth_sock = -1;
1263 }
1264
1265 if (ssh_packet_get_connection_in(ssh) ==
1266 ssh_packet_get_connection_out(ssh))
1267 close(ssh_packet_get_connection_in(ssh));
1268 else {
1269 close(ssh_packet_get_connection_in(ssh));
1270 close(ssh_packet_get_connection_out(ssh));
1271 }
1272 /*
1273 * Close all descriptors related to channels. They will still remain
1274 * open in the parent.
1275 */
1276 /* XXX better use close-on-exec? -markus */
1277 channel_close_all(ssh);
1278
1279 /*
1280 * Close any extra file descriptors. Note that there may still be
1281 * descriptors left by system functions. They will be closed later.
1282 */
1283 endpwent();
1284
1285 /* Stop directing logs to a high-numbered fd before we close it */
1286 log_redirect_stderr_to(NULL);
1287
1288 /*
1289 * Close any extra open file descriptors so that we don't have them
1290 * hanging around in clients. Note that we want to do this after
1291 * initgroups, because at least on Solaris 2.3 it leaves file
1292 * descriptors open.
1293 */
1294 (void)closefrom(STDERR_FILENO + 1);
1295 }
1296
1297 /*
1298 * Performs common processing for the child, such as setting up the
1299 * environment, closing extra file descriptors, setting the user and group
1300 * ids, and executing the command or shell.
1301 */
1302 #define ARGV_MAX 10
1303 void
1304 do_child(struct ssh *ssh, Session *s, const char *command)
1305 {
1306 extern char **environ;
1307 char **env, *argv[ARGV_MAX], remote_id[512];
1308 const char *shell, *shell0;
1309 struct passwd *pw = s->pw;
1310 int r = 0;
1311
1312 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
1313
1314 /* remove keys from memory */
1315 ssh_packet_clear_keys(ssh);
1316
1317 /* Force a password change */
1318 if (s->authctxt->force_pwchange) {
1319 do_setusercontext(pw);
1320 child_close_fds(ssh);
1321 do_pwchange(s);
1322 }
1323
1324 /*
1325 * Login(1) does this as well, and it needs uid 0 for the "-h"
1326 * switch, so we let login(1) to this for us.
1327 */
1328 /* When PAM is enabled we rely on it to do the nologin check */
1329 if (!options.use_pam)
1330 do_nologin(pw);
1331 do_setusercontext(pw);
1332 /*
1333 * PAM session modules in do_setusercontext may have
1334 * generated messages, so if this in an interactive
1335 * login then display them too.
1336 */
1337 if (!check_quietlogin(s, command))
1338 display_loginmsg();
1339
1340 #ifdef USE_PAM
1341 if (options.use_pam && !is_pam_session_open()) {
1342 debug3("PAM session not opened, exiting");
1343 display_loginmsg();
1344 exit(254);
1345 }
1346 #endif
1347
1348 /*
1349 * Get the shell from the password data. An empty shell field is
1350 * legal, and means /bin/sh.
1351 */
1352 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1353
1354 /*
1355 * Make sure $SHELL points to the shell from the password file,
1356 * even if shell is overridden from login.conf
1357 */
1358 env = do_setup_env(ssh, s, shell);
1359
1360 #ifdef HAVE_LOGIN_CAP
1361 shell = login_getcapstr(lc, "shell", __UNCONST(shell),
1362 __UNCONST(shell));
1363 #endif
1364
1365 /*
1366 * Close the connection descriptors; note that this is the child, and
1367 * the server will still have the socket open, and it is important
1368 * that we do not shutdown it. Note that the descriptors cannot be
1369 * closed before building the environment, as we call
1370 * ssh_remote_ipaddr there.
1371 */
1372 child_close_fds(ssh);
1373
1374 /*
1375 * Must take new environment into use so that .ssh/rc,
1376 * /etc/ssh/sshrc and xauth are run in the proper environment.
1377 */
1378 environ = env;
1379
1380 #ifdef KRB5
1381 /*
1382 * At this point, we check to see if AFS is active and if we have
1383 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
1384 * if we can (and need to) extend the ticket into an AFS token. If
1385 * we don't do this, we run into potential problems if the user's
1386 * home directory is in AFS and it's not world-readable.
1387 */
1388
1389 if (options.kerberos_get_afs_token && k_hasafs() &&
1390 (s->authctxt->krb5_ctx != NULL)) {
1391 char cell[64];
1392
1393 debug("Getting AFS token");
1394
1395 k_setpag();
1396
1397 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1398 krb5_afslog(s->authctxt->krb5_ctx,
1399 s->authctxt->krb5_fwd_ccache, cell, NULL);
1400
1401 krb5_afslog_home(s->authctxt->krb5_ctx,
1402 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
1403 }
1404 #endif
1405
1406 /* Change current directory to the user's home directory. */
1407 if (chdir(pw->pw_dir) == -1) {
1408 /* Suppress missing homedir warning for chroot case */
1409 r = login_getcapbool(lc, "requirehome", 0);
1410 if (r || !in_chroot) {
1411 fprintf(stderr, "Could not chdir to home "
1412 "directory %s: %s\n", pw->pw_dir,
1413 strerror(errno));
1414 }
1415 if (r)
1416 exit(1);
1417 }
1418
1419 (void)closefrom(STDERR_FILENO + 1);
1420
1421 do_rc_files(ssh, s, shell);
1422
1423 /* restore SIGPIPE for child */
1424 ssh_signal(SIGPIPE, SIG_DFL);
1425
1426 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
1427 error("Connection from %s: refusing non-sftp session",
1428 remote_id);
1429 printf("This service allows sftp connections only.\n");
1430 fflush(NULL);
1431 exit(1);
1432 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
1433 extern int optind, optreset;
1434 int i;
1435 char *p, *args;
1436
1437 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
1438 args = xstrdup(command ? command : "sftp-server");
1439 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
1440 if (i < ARGV_MAX - 1)
1441 argv[i++] = p;
1442 argv[i] = NULL;
1443 optind = optreset = 1;
1444 __progname = argv[0];
1445 exit(sftp_server_main(i, argv, s->pw));
1446 }
1447
1448 fflush(NULL);
1449
1450 /* Get the last component of the shell name. */
1451 if ((shell0 = strrchr(shell, '/')) != NULL)
1452 shell0++;
1453 else
1454 shell0 = shell;
1455
1456 /*
1457 * If we have no command, execute the shell. In this case, the shell
1458 * name to be passed in argv[0] is preceded by '-' to indicate that
1459 * this is a login shell.
1460 */
1461 if (!command) {
1462 char argv0[256];
1463
1464 /* Start the shell. Set initial character to '-'. */
1465 argv0[0] = '-';
1466
1467 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1468 >= sizeof(argv0) - 1) {
1469 errno = EINVAL;
1470 perror(shell);
1471 exit(1);
1472 }
1473
1474 /* Execute the shell. */
1475 argv[0] = argv0;
1476 argv[1] = NULL;
1477 execve(shell, argv, env);
1478
1479 /* Executing the shell failed. */
1480 perror(shell);
1481 exit(1);
1482 }
1483 /*
1484 * Execute the command using the user's shell. This uses the -c
1485 * option to execute the command.
1486 */
1487 argv[0] = __UNCONST(shell0);
1488 argv[1] = __UNCONST("-c");
1489 argv[2] = __UNCONST(command);
1490 argv[3] = NULL;
1491 execve(shell, argv, env);
1492 perror(shell);
1493 exit(1);
1494 }
1495
1496 void
1497 session_unused(int id)
1498 {
1499 debug3_f("session id %d unused", id);
1500 if (id >= options.max_sessions ||
1501 id >= sessions_nalloc) {
1502 fatal_f("insane session id %d (max %d nalloc %d)",
1503 id, options.max_sessions, sessions_nalloc);
1504 }
1505 memset(&sessions[id], 0, sizeof(*sessions));
1506 sessions[id].self = id;
1507 sessions[id].used = 0;
1508 sessions[id].chanid = -1;
1509 sessions[id].ptyfd = -1;
1510 sessions[id].ttyfd = -1;
1511 sessions[id].ptymaster = -1;
1512 sessions[id].x11_chanids = NULL;
1513 sessions[id].next_unused = sessions_first_unused;
1514 sessions_first_unused = id;
1515 }
1516
1517 Session *
1518 session_new(void)
1519 {
1520 Session *s, *tmp;
1521
1522 if (sessions_first_unused == -1) {
1523 if (sessions_nalloc >= options.max_sessions)
1524 return NULL;
1525 debug2_f("allocate (allocated %d max %d)",
1526 sessions_nalloc, options.max_sessions);
1527 tmp = xrecallocarray(sessions, sessions_nalloc,
1528 sessions_nalloc + 1, sizeof(*sessions));
1529 if (tmp == NULL) {
1530 error_f("cannot allocate %d sessions",
1531 sessions_nalloc + 1);
1532 return NULL;
1533 }
1534 sessions = tmp;
1535 session_unused(sessions_nalloc++);
1536 }
1537
1538 if (sessions_first_unused >= sessions_nalloc ||
1539 sessions_first_unused < 0) {
1540 fatal_f("insane first_unused %d max %d nalloc %d",
1541 sessions_first_unused, options.max_sessions,
1542 sessions_nalloc);
1543 }
1544
1545 s = &sessions[sessions_first_unused];
1546 if (s->used)
1547 fatal_f("session %d already used", sessions_first_unused);
1548 sessions_first_unused = s->next_unused;
1549 s->used = 1;
1550 s->next_unused = -1;
1551 debug("session_new: session %d", s->self);
1552
1553 return s;
1554 }
1555
1556 static void
1557 session_dump(void)
1558 {
1559 int i;
1560 for (i = 0; i < sessions_nalloc; i++) {
1561 Session *s = &sessions[i];
1562
1563 debug("dump: used %d next_unused %d session %d "
1564 "channel %d pid %ld",
1565 s->used,
1566 s->next_unused,
1567 s->self,
1568 s->chanid,
1569 (long)s->pid);
1570 }
1571 }
1572
1573 int
1574 session_open(Authctxt *authctxt, int chanid)
1575 {
1576 Session *s = session_new();
1577 debug("session_open: channel %d", chanid);
1578 if (s == NULL) {
1579 error("no more sessions");
1580 return 0;
1581 }
1582 s->authctxt = authctxt;
1583 s->pw = authctxt->pw;
1584 if (s->pw == NULL || !authctxt->valid)
1585 fatal("no user for session %d", s->self);
1586 debug("session_open: session %d: link with channel %d", s->self, chanid);
1587 s->chanid = chanid;
1588 return 1;
1589 }
1590
1591 Session *
1592 session_by_tty(char *tty)
1593 {
1594 int i;
1595 for (i = 0; i < sessions_nalloc; i++) {
1596 Session *s = &sessions[i];
1597 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1598 debug("session_by_tty: session %d tty %s", i, tty);
1599 return s;
1600 }
1601 }
1602 debug("session_by_tty: unknown tty %.100s", tty);
1603 session_dump();
1604 return NULL;
1605 }
1606
1607 static Session *
1608 session_by_channel(int id)
1609 {
1610 int i;
1611 for (i = 0; i < sessions_nalloc; i++) {
1612 Session *s = &sessions[i];
1613 if (s->used && s->chanid == id) {
1614 debug("session_by_channel: session %d channel %d",
1615 i, id);
1616 return s;
1617 }
1618 }
1619 debug("session_by_channel: unknown channel %d", id);
1620 session_dump();
1621 return NULL;
1622 }
1623
1624 static Session *
1625 session_by_x11_channel(int id)
1626 {
1627 int i, j;
1628
1629 for (i = 0; i < sessions_nalloc; i++) {
1630 Session *s = &sessions[i];
1631
1632 if (s->x11_chanids == NULL || !s->used)
1633 continue;
1634 for (j = 0; s->x11_chanids[j] != -1; j++) {
1635 if (s->x11_chanids[j] == id) {
1636 debug("session_by_x11_channel: session %d "
1637 "channel %d", s->self, id);
1638 return s;
1639 }
1640 }
1641 }
1642 debug("session_by_x11_channel: unknown channel %d", id);
1643 session_dump();
1644 return NULL;
1645 }
1646
1647 static Session *
1648 session_by_pid(pid_t pid)
1649 {
1650 int i;
1651 debug("session_by_pid: pid %ld", (long)pid);
1652 for (i = 0; i < sessions_nalloc; i++) {
1653 Session *s = &sessions[i];
1654 if (s->used && s->pid == pid)
1655 return s;
1656 }
1657 error("session_by_pid: unknown pid %ld", (long)pid);
1658 session_dump();
1659 return NULL;
1660 }
1661
1662 static int
1663 session_window_change_req(struct ssh *ssh, Session *s)
1664 {
1665 int r;
1666
1667 if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1668 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1669 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1670 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
1671 (r = sshpkt_get_end(ssh)) != 0)
1672 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1673 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1674 return 1;
1675 }
1676
1677 static int
1678 session_pty_req(struct ssh *ssh, Session *s)
1679 {
1680 int r;
1681
1682 if (!auth_opts->permit_pty_flag || !options.permit_tty) {
1683 debug("Allocating a pty not permitted for this connection.");
1684 return 0;
1685 }
1686 if (s->ttyfd != -1) {
1687 ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
1688 return 0;
1689 }
1690
1691 if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
1692 (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
1693 (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
1694 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
1695 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
1696 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1697
1698 if (strcmp(s->term, "") == 0) {
1699 free(s->term);
1700 s->term = NULL;
1701 }
1702
1703 /* Allocate a pty and open it. */
1704 debug("Allocating pty.");
1705 if (!mm_pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1706 free(s->term);
1707 s->term = NULL;
1708 s->ptyfd = -1;
1709 s->ttyfd = -1;
1710 error("session_pty_req: session %d alloc failed", s->self);
1711 return 0;
1712 }
1713 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1714
1715 ssh_tty_parse_modes(ssh, s->ttyfd);
1716
1717 if ((r = sshpkt_get_end(ssh)) != 0)
1718 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1719
1720 /* Set window size from the packet. */
1721 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1722
1723 session_proctitle(s);
1724 return 1;
1725 }
1726
1727 static int
1728 session_subsystem_req(struct ssh *ssh, Session *s)
1729 {
1730 struct stat st;
1731 int r, success = 0;
1732 char *prog, *cmd, *type;
1733 u_int i;
1734
1735 if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
1736 (r = sshpkt_get_end(ssh)) != 0)
1737 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1738 debug2("subsystem request for %.100s by user %s", s->subsys,
1739 s->pw->pw_name);
1740
1741 for (i = 0; i < options.num_subsystems; i++) {
1742 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
1743 prog = options.subsystem_command[i];
1744 cmd = options.subsystem_args[i];
1745 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
1746 s->is_subsystem = SUBSYSTEM_INT_SFTP;
1747 debug("subsystem: %s", prog);
1748 } else {
1749 if (stat(prog, &st) == -1)
1750 debug("subsystem: cannot stat %s: %s",
1751 prog, strerror(errno));
1752 s->is_subsystem = SUBSYSTEM_EXT;
1753 debug("subsystem: exec() %s", cmd);
1754 }
1755 xasprintf(&type, "session:subsystem:%s",
1756 options.subsystem_name[i]);
1757 channel_set_xtype(ssh, s->chanid, type);
1758 free(type);
1759 success = do_exec(ssh, s, cmd) == 0;
1760 break;
1761 }
1762 }
1763
1764 if (!success)
1765 logit("subsystem request for %.100s by user %s failed, "
1766 "subsystem not found", s->subsys, s->pw->pw_name);
1767
1768 return success;
1769 }
1770
1771 static int
1772 session_x11_req(struct ssh *ssh, Session *s)
1773 {
1774 int r, success;
1775 u_char single_connection = 0;
1776
1777 if (s->auth_proto != NULL || s->auth_data != NULL) {
1778 error("session_x11_req: session %d: "
1779 "x11 forwarding already active", s->self);
1780 return 0;
1781 }
1782 if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
1783 (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
1784 (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
1785 (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
1786 (r = sshpkt_get_end(ssh)) != 0)
1787 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1788
1789 s->single_connection = single_connection;
1790
1791 if (xauth_valid_string(s->auth_proto) &&
1792 xauth_valid_string(s->auth_data))
1793 success = session_setup_x11fwd(ssh, s);
1794 else {
1795 success = 0;
1796 error("Invalid X11 forwarding data");
1797 }
1798 if (!success) {
1799 free(s->auth_proto);
1800 free(s->auth_data);
1801 s->auth_proto = NULL;
1802 s->auth_data = NULL;
1803 }
1804 return success;
1805 }
1806
1807 static int
1808 session_shell_req(struct ssh *ssh, Session *s)
1809 {
1810 int r;
1811
1812 if ((r = sshpkt_get_end(ssh)) != 0)
1813 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1814
1815 channel_set_xtype(ssh, s->chanid, "session:shell");
1816
1817 return do_exec(ssh, s, NULL) == 0;
1818 }
1819
1820 static int
1821 session_exec_req(struct ssh *ssh, Session *s)
1822 {
1823 u_int success;
1824 int r;
1825 char *command = NULL;
1826
1827 if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
1828 (r = sshpkt_get_end(ssh)) != 0)
1829 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1830
1831 channel_set_xtype(ssh, s->chanid, "session:command");
1832
1833 success = do_exec(ssh, s, command) == 0;
1834 free(command);
1835 return success;
1836 }
1837
1838 static int
1839 session_break_req(struct ssh *ssh, Session *s)
1840 {
1841 int r;
1842
1843 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
1844 (r = sshpkt_get_end(ssh)) != 0)
1845 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1846
1847 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1)
1848 return 0;
1849 return 1;
1850 }
1851
1852 static int
1853 session_env_req(struct ssh *ssh, Session *s)
1854 {
1855 char *name, *val;
1856 u_int i;
1857 int r;
1858
1859 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
1860 (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
1861 (r = sshpkt_get_end(ssh)) != 0)
1862 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1863
1864 /* Don't set too many environment variables */
1865 if (s->num_env > 128) {
1866 debug2("Ignoring env request %s: too many env vars", name);
1867 goto fail;
1868 }
1869
1870 for (i = 0; i < options.num_accept_env; i++) {
1871 if (match_pattern(name, options.accept_env[i])) {
1872 debug2("Setting env %d: %s=%s", s->num_env, name, val);
1873 s->env = xrecallocarray(s->env, s->num_env,
1874 s->num_env + 1, sizeof(*s->env));
1875 s->env[s->num_env].name = name;
1876 s->env[s->num_env].val = val;
1877 s->num_env++;
1878 return (1);
1879 }
1880 }
1881 debug2("Ignoring env request %s: disallowed name", name);
1882
1883 fail:
1884 free(name);
1885 free(val);
1886 return (0);
1887 }
1888
1889 /*
1890 * Conversion of signals from ssh channel request names.
1891 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
1892 * local extension.
1893 */
1894 static int
1895 name2sig(char *name)
1896 {
1897 #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
1898 SSH_SIG(HUP);
1899 SSH_SIG(INT);
1900 SSH_SIG(KILL);
1901 SSH_SIG(QUIT);
1902 SSH_SIG(TERM);
1903 SSH_SIG(USR1);
1904 SSH_SIG(USR2);
1905 #undef SSH_SIG
1906 if (strcmp(name, "INFO (at) openssh.com") == 0)
1907 return SIGINFO;
1908 return -1;
1909 }
1910
1911 static int
1912 session_signal_req(struct ssh *ssh, Session *s)
1913 {
1914 char *signame = NULL;
1915 int r, sig, success = 0;
1916
1917 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
1918 (r = sshpkt_get_end(ssh)) != 0) {
1919 error_fr(r, "parse");
1920 goto out;
1921 }
1922 if ((sig = name2sig(signame)) == -1) {
1923 error_f("unsupported signal \"%s\"", signame);
1924 goto out;
1925 }
1926 if (s->pid <= 0) {
1927 error_f("no pid for session %d", s->self);
1928 goto out;
1929 }
1930 if (s->forced || s->is_subsystem) {
1931 error_f("refusing to send signal %s to %s session",
1932 signame, s->forced ? "forced-command" : "subsystem");
1933 goto out;
1934 }
1935
1936 debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig);
1937 temporarily_use_uid(s->pw);
1938 r = killpg(s->pid, sig);
1939 restore_uid();
1940 if (r != 0) {
1941 error_f("killpg(%ld, %d): %s", (long)s->pid,
1942 sig, strerror(errno));
1943 goto out;
1944 }
1945
1946 /* success */
1947 success = 1;
1948 out:
1949 free(signame);
1950 return success;
1951 }
1952
1953 static int
1954 session_auth_agent_req(struct ssh *ssh, Session *s)
1955 {
1956 static int called = 0;
1957 int r;
1958
1959 if ((r = sshpkt_get_end(ssh)) != 0)
1960 sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
1961 if (!auth_opts->permit_agent_forwarding_flag ||
1962 !options.allow_agent_forwarding ||
1963 options.disable_forwarding) {
1964 debug_f("agent forwarding disabled");
1965 return 0;
1966 }
1967 if (called) {
1968 return 0;
1969 } else {
1970 called = 1;
1971 return auth_input_request_forwarding(ssh, s->pw);
1972 }
1973 }
1974
1975 int
1976 session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
1977 {
1978 int success = 0;
1979 Session *s;
1980
1981 if ((s = session_by_channel(c->self)) == NULL) {
1982 logit_f("no session %d req %.100s", c->self, rtype);
1983 return 0;
1984 }
1985 debug_f("session %d req %s", s->self, rtype);
1986
1987 /*
1988 * a session is in LARVAL state until a shell, a command
1989 * or a subsystem is executed
1990 */
1991 if (c->type == SSH_CHANNEL_LARVAL) {
1992 if (strcmp(rtype, "shell") == 0) {
1993 success = session_shell_req(ssh, s);
1994 } else if (strcmp(rtype, "exec") == 0) {
1995 success = session_exec_req(ssh, s);
1996 } else if (strcmp(rtype, "pty-req") == 0) {
1997 success = session_pty_req(ssh, s);
1998 } else if (strcmp(rtype, "x11-req") == 0) {
1999 success = session_x11_req(ssh, s);
2000 } else if (strcmp(rtype, "auth-agent-req (at) openssh.com") == 0) {
2001 success = session_auth_agent_req(ssh, s);
2002 } else if (strcmp(rtype, "subsystem") == 0) {
2003 success = session_subsystem_req(ssh, s);
2004 } else if (strcmp(rtype, "env") == 0) {
2005 success = session_env_req(ssh, s);
2006 }
2007 }
2008 if (strcmp(rtype, "window-change") == 0) {
2009 success = session_window_change_req(ssh, s);
2010 } else if (strcmp(rtype, "break") == 0) {
2011 success = session_break_req(ssh, s);
2012 } else if (strcmp(rtype, "signal") == 0) {
2013 success = session_signal_req(ssh, s);
2014 }
2015
2016 return success;
2017 }
2018
2019 void
2020 session_set_fds(struct ssh *ssh, Session *s,
2021 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
2022 {
2023 /*
2024 * now that have a child and a pipe to the child,
2025 * we can activate our channel and register the fd's
2026 */
2027 if (s->chanid == -1)
2028 fatal("no channel for session %d", s->self);
2029 if(options.hpn_disabled)
2030 channel_set_fds(ssh, s->chanid,
2031 fdout, fdin, fderr,
2032 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2033 1, is_tty, CHAN_SES_WINDOW_DEFAULT);
2034 else
2035 channel_set_fds(ssh, s->chanid,
2036 fdout, fdin, fderr,
2037 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
2038 1, is_tty, options.hpn_buffer_size);
2039 }
2040
2041 /*
2042 * Function to perform pty cleanup. Also called if we get aborted abnormally
2043 * (e.g., due to a dropped connection).
2044 */
2045 void
2046 session_pty_cleanup2(Session *s)
2047 {
2048 if (s == NULL) {
2049 error_f("no session");
2050 return;
2051 }
2052 if (s->ttyfd == -1)
2053 return;
2054
2055 debug_f("session %d release %s", s->self, s->tty);
2056
2057 /* Record that the user has logged out. */
2058 if (s->pid != 0)
2059 record_logout(s->pid, s->tty);
2060
2061 /* Release the pseudo-tty. */
2062 if (getuid() == 0)
2063 pty_release(s->tty);
2064
2065 /*
2066 * Close the server side of the socket pairs. We must do this after
2067 * the pty cleanup, so that another process doesn't get this pty
2068 * while we're still cleaning up.
2069 */
2070 if (s->ptymaster != -1 && close(s->ptymaster) == -1)
2071 error("close(s->ptymaster/%d): %s",
2072 s->ptymaster, strerror(errno));
2073
2074 /* unlink pty from session */
2075 s->ttyfd = -1;
2076 }
2077
2078 void
2079 session_pty_cleanup(Session *s)
2080 {
2081 mm_session_pty_cleanup2(s);
2082 }
2083
2084 static const char *
2085 sig2name(int sig)
2086 {
2087 #define SSH_SIG(x) if (sig == SIG ## x) return #x
2088 SSH_SIG(ABRT);
2089 SSH_SIG(ALRM);
2090 SSH_SIG(FPE);
2091 SSH_SIG(HUP);
2092 SSH_SIG(ILL);
2093 SSH_SIG(INT);
2094 SSH_SIG(KILL);
2095 SSH_SIG(PIPE);
2096 SSH_SIG(QUIT);
2097 SSH_SIG(SEGV);
2098 SSH_SIG(TERM);
2099 SSH_SIG(USR1);
2100 SSH_SIG(USR2);
2101 #undef SSH_SIG
2102 return "SIG (at) openssh.com";
2103 }
2104
2105 static void
2106 session_close_x11(struct ssh *ssh, int id)
2107 {
2108 Channel *c;
2109
2110 if ((c = channel_by_id(ssh, id)) == NULL) {
2111 debug_f("x11 channel %d missing", id);
2112 } else {
2113 /* Detach X11 listener */
2114 debug_f("detach x11 channel %d", id);
2115 channel_cancel_cleanup(ssh, id);
2116 if (c->ostate != CHAN_OUTPUT_CLOSED)
2117 chan_mark_dead(ssh, c);
2118 }
2119 }
2120
2121 static void
2122 session_close_single_x11(struct ssh *ssh, int id, int force, void *arg)
2123 {
2124 Session *s;
2125 u_int i;
2126
2127 debug3_f("channel %d", id);
2128 channel_cancel_cleanup(ssh, id);
2129 if ((s = session_by_x11_channel(id)) == NULL)
2130 fatal_f("no x11 channel %d", id);
2131 for (i = 0; s->x11_chanids[i] != -1; i++) {
2132 debug_f("session %d: closing channel %d",
2133 s->self, s->x11_chanids[i]);
2134 /*
2135 * The channel "id" is already closing, but make sure we
2136 * close all of its siblings.
2137 */
2138 if (s->x11_chanids[i] != id)
2139 session_close_x11(ssh, s->x11_chanids[i]);
2140 }
2141 free(s->x11_chanids);
2142 s->x11_chanids = NULL;
2143 free(s->display);
2144 s->display = NULL;
2145 free(s->auth_proto);
2146 s->auth_proto = NULL;
2147 free(s->auth_data);
2148 s->auth_data = NULL;
2149 free(s->auth_display);
2150 s->auth_display = NULL;
2151 }
2152
2153 static void
2154 session_exit_message(struct ssh *ssh, Session *s, int status)
2155 {
2156 Channel *c;
2157 int r;
2158 char *note = NULL;
2159
2160 if ((c = channel_lookup(ssh, s->chanid)) == NULL)
2161 fatal_f("session %d: no channel %d", s->self, s->chanid);
2162
2163 if (WIFEXITED(status)) {
2164 channel_request_start(ssh, s->chanid, "exit-status", 0);
2165 if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
2166 (r = sshpkt_send(ssh)) != 0)
2167 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2168 xasprintf(¬e, "exit %d", WEXITSTATUS(status));
2169 } else if (WIFSIGNALED(status)) {
2170 channel_request_start(ssh, s->chanid, "exit-signal", 0);
2171 if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
2172 (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
2173 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2174 (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2175 (r = sshpkt_send(ssh)) != 0)
2176 sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
2177 xasprintf(¬e, "signal %d%s", WTERMSIG(status),
2178 WCOREDUMP(status) ? " core dumped" : "");
2179 } else {
2180 /* Some weird exit cause. Just exit. */
2181 ssh_packet_disconnect(ssh, "wait returned status %04x.",
2182 status);
2183 }
2184
2185 debug_f("session %d channel %d pid %ld %s", s->self, s->chanid,
2186 (long)s->pid, note == NULL ? "UNKNOWN" : note);
2187 free(note);
2188
2189 /* disconnect channel */
2190 debug_f("release channel %d", s->chanid);
2191
2192 /*
2193 * Adjust cleanup callback attachment to send close messages when
2194 * the channel gets EOF. The session will be then be closed
2195 * by session_close_by_channel when the child sessions close their fds.
2196 */
2197 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
2198
2199 /*
2200 * emulate a write failure with 'chan_write_failed', nobody will be
2201 * interested in data we write.
2202 * Note that we must not call 'chan_read_failed', since there could
2203 * be some more data waiting in the pipe.
2204 */
2205 if (c->ostate != CHAN_OUTPUT_CLOSED)
2206 chan_write_failed(ssh, c);
2207 }
2208
2209 void
2210 session_close(struct ssh *ssh, Session *s)
2211 {
2212 u_int i;
2213
2214 verbose("Close session: user %s from %.200s port %d id %d",
2215 s->pw->pw_name,
2216 ssh_remote_ipaddr(ssh),
2217 ssh_remote_port(ssh),
2218 s->self);
2219
2220 if (s->ttyfd != -1)
2221 session_pty_cleanup(s);
2222 free(s->term);
2223 free(s->display);
2224 free(s->x11_chanids);
2225 free(s->auth_display);
2226 free(s->auth_data);
2227 free(s->auth_proto);
2228 free(s->subsys);
2229 if (s->env != NULL) {
2230 for (i = 0; i < s->num_env; i++) {
2231 free(s->env[i].name);
2232 free(s->env[i].val);
2233 }
2234 free(s->env);
2235 }
2236 session_proctitle(s);
2237 session_unused(s->self);
2238 }
2239
2240 void
2241 session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
2242 {
2243 Session *s = session_by_pid(pid);
2244 if (s == NULL) {
2245 debug_f("no session for pid %ld", (long)pid);
2246 return;
2247 }
2248 if (s->chanid != -1)
2249 session_exit_message(ssh, s, status);
2250 if (s->ttyfd != -1)
2251 session_pty_cleanup(s);
2252 s->pid = 0;
2253 }
2254
2255 /*
2256 * this is called when a channel dies before
2257 * the session 'child' itself dies
2258 */
2259 void
2260 session_close_by_channel(struct ssh *ssh, int id, int force, void *arg)
2261 {
2262 Session *s = session_by_channel(id);
2263 u_int i;
2264
2265 if (s == NULL) {
2266 debug_f("no session for id %d", id);
2267 return;
2268 }
2269 debug_f("channel %d child %ld", id, (long)s->pid);
2270 if (s->pid != 0) {
2271 debug_f("channel %d: has child, ttyfd %d", id, s->ttyfd);
2272 /*
2273 * delay detach of session (unless this is a forced close),
2274 * but release pty, since the fd's to the child are already
2275 * closed
2276 */
2277 if (s->ttyfd != -1)
2278 session_pty_cleanup(s);
2279 if (!force)
2280 return;
2281 }
2282 /* detach by removing callback */
2283 channel_cancel_cleanup(ssh, s->chanid);
2284
2285 /* Close any X11 listeners associated with this session */
2286 if (s->x11_chanids != NULL) {
2287 for (i = 0; s->x11_chanids[i] != -1; i++) {
2288 session_close_x11(ssh, s->x11_chanids[i]);
2289 s->x11_chanids[i] = -1;
2290 }
2291 }
2292
2293 s->chanid = -1;
2294 session_close(ssh, s);
2295 }
2296
2297 void
2298 session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *))
2299 {
2300 int i;
2301 for (i = 0; i < sessions_nalloc; i++) {
2302 Session *s = &sessions[i];
2303 if (s->used) {
2304 if (closefunc != NULL)
2305 closefunc(s);
2306 else
2307 session_close(ssh, s);
2308 }
2309 }
2310 }
2311
2312 static char *
2313 session_tty_list(void)
2314 {
2315 static char buf[1024];
2316 int i;
2317 buf[0] = '\0';
2318 for (i = 0; i < sessions_nalloc; i++) {
2319 Session *s = &sessions[i];
2320 if (s->used && s->ttyfd != -1) {
2321 char *p;
2322 if (buf[0] != '\0')
2323 strlcat(buf, ",", sizeof buf);
2324 if ((p = strstr(s->tty, "/pts/")) != NULL)
2325 p++;
2326 else {
2327 if ((p = strrchr(s->tty, '/')) != NULL)
2328 p++;
2329 else
2330 p = s->tty;
2331 }
2332 strlcat(buf, p, sizeof buf);
2333 }
2334 }
2335 if (buf[0] == '\0')
2336 strlcpy(buf, "notty", sizeof buf);
2337 return buf;
2338 }
2339
2340 void
2341 session_proctitle(Session *s)
2342 {
2343 if (s->pw == NULL)
2344 error("no user for session %d", s->self);
2345 else
2346 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2347 }
2348
2349 int
2350 session_setup_x11fwd(struct ssh *ssh, Session *s)
2351 {
2352 struct stat st;
2353 char display[512], auth_display[512];
2354 char hostname[NI_MAXHOST];
2355 u_int i;
2356
2357 if (!auth_opts->permit_x11_forwarding_flag) {
2358 ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
2359 return 0;
2360 }
2361 if (!options.x11_forwarding || options.disable_forwarding) {
2362 debug("X11 forwarding disabled in server configuration file.");
2363 return 0;
2364 }
2365 if (options.xauth_location == NULL ||
2366 (stat(options.xauth_location, &st) == -1)) {
2367 ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
2368 return 0;
2369 }
2370 if (s->display != NULL) {
2371 debug("X11 display already set.");
2372 return 0;
2373 }
2374 if (x11_create_display_inet(ssh, options.x11_display_offset,
2375 options.x11_use_localhost, s->single_connection,
2376 &s->display_number, &s->x11_chanids) == -1) {
2377 debug("x11_create_display_inet failed.");
2378 return 0;
2379 }
2380 for (i = 0; s->x11_chanids[i] != -1; i++) {
2381 channel_register_cleanup(ssh, s->x11_chanids[i],
2382 session_close_single_x11, 0);
2383 }
2384
2385 /* Set up a suitable value for the DISPLAY variable. */
2386 if (gethostname(hostname, sizeof(hostname)) == -1)
2387 fatal("gethostname: %.100s", strerror(errno));
2388 /*
2389 * auth_display must be used as the displayname when the
2390 * authorization entry is added with xauth(1). This will be
2391 * different than the DISPLAY string for localhost displays.
2392 */
2393 if (options.x11_use_localhost) {
2394 snprintf(display, sizeof display, "localhost:%u.%u",
2395 s->display_number, s->screen);
2396 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
2397 s->display_number, s->screen);
2398 s->display = xstrdup(display);
2399 s->auth_display = xstrdup(auth_display);
2400 } else {
2401 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
2402 s->display_number, s->screen);
2403 s->display = xstrdup(display);
2404 s->auth_display = xstrdup(display);
2405 }
2406
2407 return 1;
2408 }
2409
2410 static void
2411 do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
2412 {
2413 server_loop2(ssh, authctxt);
2414 }
2415
2416 void
2417 do_cleanup(struct ssh *ssh, Authctxt *authctxt)
2418 {
2419 static int called = 0;
2420
2421 debug("do_cleanup");
2422
2423 /* no cleanup if we're in the child for login shell */
2424 if (is_child)
2425 return;
2426
2427 /* avoid double cleanup */
2428 if (called)
2429 return;
2430 called = 1;
2431
2432 if (authctxt == NULL || !authctxt->authenticated)
2433 return;
2434 #ifdef KRB4
2435 if (options.kerberos_ticket_cleanup)
2436 krb4_cleanup_proc(authctxt);
2437 #endif
2438 #ifdef KRB5
2439 if (options.kerberos_ticket_cleanup &&
2440 authctxt->krb5_ctx)
2441 krb5_cleanup_proc(authctxt);
2442 #endif
2443
2444 #ifdef GSSAPI
2445 if (options.gss_cleanup_creds)
2446 ssh_gssapi_cleanup_creds();
2447 #endif
2448
2449 #ifdef USE_PAM
2450 if (options.use_pam) {
2451 sshpam_cleanup();
2452 sshpam_thread_cleanup();
2453 }
2454 #endif
2455
2456 /* remove agent socket */
2457 auth_sock_cleanup_proc(authctxt->pw);
2458
2459 /* remove userauth info */
2460 if (auth_info_file != NULL) {
2461 temporarily_use_uid(authctxt->pw);
2462 unlink(auth_info_file);
2463 restore_uid();
2464 free(auth_info_file);
2465 auth_info_file = NULL;
2466 }
2467
2468 /*
2469 * Cleanup ptys/utmp only if privsep is disabled,
2470 * or if running in monitor.
2471 */
2472 if (mm_is_monitor())
2473 session_destroy_all(ssh, session_pty_cleanup2);
2474 }
2475
2476 /* Return a name for the remote host that fits inside utmp_size */
2477
2478 const char *
2479 session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
2480 {
2481 const char *remote = "";
2482
2483 if (utmp_size > 0)
2484 remote = auth_get_canonical_hostname(ssh, use_dns);
2485 if (utmp_size == 0 || strlen(remote) > utmp_size)
2486 remote = ssh_remote_ipaddr(ssh);
2487 return remote;
2488 }
2489
2490