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