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