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