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