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