1 /* 2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 3 * All rights reserved 4 * 5 * As far as I am concerned, the code I have written for this software 6 * can be used freely for any purpose. Any derived versions of this 7 * software must be clearly marked as such, and if the derived work is 8 * incompatible with the protocol description in the RFC file, it must be 9 * called by a name other than "ssh" or "Secure Shell". 10 * 11 * SSH2 support by Markus Friedl. 12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 13 * 14 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions 16 * are met: 17 * 1. Redistributions of source code must retain the above copyright 18 * notice, this list of conditions and the following disclaimer. 19 * 2. Redistributions in binary form must reproduce the above copyright 20 * notice, this list of conditions and the following disclaimer in the 21 * documentation and/or other materials provided with the distribution. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 33 */ 34 35 #include "includes.h" 36 RCSID("$OpenBSD: session.c,v 1.142 2002/06/26 13:49:26 deraadt Exp $"); 37 RCSID("$FreeBSD$"); 38 39 #include "ssh.h" 40 #include "ssh1.h" 41 #include "ssh2.h" 42 #include "xmalloc.h" 43 #include "sshpty.h" 44 #include "packet.h" 45 #include "buffer.h" 46 #include "mpaux.h" 47 #include "uidswap.h" 48 #include "compat.h" 49 #include "channels.h" 50 #include "bufaux.h" 51 #include "auth.h" 52 #include "auth-options.h" 53 #include "pathnames.h" 54 #include "log.h" 55 #include "servconf.h" 56 #include "sshlogin.h" 57 #include "serverloop.h" 58 #include "canohost.h" 59 #include "session.h" 60 #include "monitor_wrap.h" 61 62 #ifdef HAVE_CYGWIN 63 #include <windows.h> 64 #include <sys/cygwin.h> 65 #define is_winnt (GetVersion() < 0x80000000) 66 #endif 67 68 /* func */ 69 70 Session *session_new(void); 71 void session_set_fds(Session *, int, int, int); 72 void session_pty_cleanup(void *); 73 void session_proctitle(Session *); 74 int session_setup_x11fwd(Session *); 75 void do_exec_pty(Session *, const char *); 76 void do_exec_no_pty(Session *, const char *); 77 void do_exec(Session *, const char *); 78 void do_login(Session *, const char *); 79 #ifdef LOGIN_NEEDS_UTMPX 80 static void do_pre_login(Session *s); 81 #endif 82 void do_child(Session *, const char *); 83 void do_motd(void); 84 int check_quietlogin(Session *, const char *); 85 86 static void do_authenticated1(Authctxt *); 87 static void do_authenticated2(Authctxt *); 88 89 static int session_pty_req(Session *); 90 91 /* import */ 92 extern ServerOptions options; 93 extern char *__progname; 94 extern int log_stderr; 95 extern int debug_flag; 96 extern u_int utmp_len; 97 extern int startup_pipe; 98 extern void destroy_sensitive_data(void); 99 100 /* original command from peer. */ 101 const char *original_command = NULL; 102 103 /* data */ 104 #define MAX_SESSIONS 10 105 Session sessions[MAX_SESSIONS]; 106 107 #ifdef WITH_AIXAUTHENTICATE 108 char *aixloginmsg; 109 #endif /* WITH_AIXAUTHENTICATE */ 110 111 #ifdef HAVE_LOGIN_CAP 112 login_cap_t *lc; 113 #endif 114 115 /* Name and directory of socket for authentication agent forwarding. */ 116 static char *auth_sock_name = NULL; 117 static char *auth_sock_dir = NULL; 118 119 /* removes the agent forwarding socket */ 120 121 static void 122 auth_sock_cleanup_proc(void *_pw) 123 { 124 struct passwd *pw = _pw; 125 126 if (auth_sock_name != NULL) { 127 temporarily_use_uid(pw); 128 unlink(auth_sock_name); 129 rmdir(auth_sock_dir); 130 auth_sock_name = NULL; 131 restore_uid(); 132 } 133 } 134 135 static int 136 auth_input_request_forwarding(struct passwd * pw) 137 { 138 Channel *nc; 139 int sock; 140 struct sockaddr_un sunaddr; 141 142 if (auth_sock_name != NULL) { 143 error("authentication forwarding requested twice."); 144 return 0; 145 } 146 147 /* Temporarily drop privileged uid for mkdir/bind. */ 148 temporarily_use_uid(pw); 149 150 /* Allocate a buffer for the socket name, and format the name. */ 151 auth_sock_name = xmalloc(MAXPATHLEN); 152 auth_sock_dir = xmalloc(MAXPATHLEN); 153 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXX", MAXPATHLEN); 154 155 /* Create private directory for socket */ 156 if (mkdtemp(auth_sock_dir) == NULL) { 157 packet_send_debug("Agent forwarding disabled: " 158 "mkdtemp() failed: %.100s", strerror(errno)); 159 restore_uid(); 160 xfree(auth_sock_name); 161 xfree(auth_sock_dir); 162 auth_sock_name = NULL; 163 auth_sock_dir = NULL; 164 return 0; 165 } 166 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld", 167 auth_sock_dir, (long) getpid()); 168 169 /* delete agent socket on fatal() */ 170 fatal_add_cleanup(auth_sock_cleanup_proc, pw); 171 172 /* Create the socket. */ 173 sock = socket(AF_UNIX, SOCK_STREAM, 0); 174 if (sock < 0) 175 packet_disconnect("socket: %.100s", strerror(errno)); 176 177 /* Bind it to the name. */ 178 memset(&sunaddr, 0, sizeof(sunaddr)); 179 sunaddr.sun_family = AF_UNIX; 180 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path)); 181 182 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0) 183 packet_disconnect("bind: %.100s", strerror(errno)); 184 185 /* Restore the privileged uid. */ 186 restore_uid(); 187 188 /* Start listening on the socket. */ 189 if (listen(sock, 5) < 0) 190 packet_disconnect("listen: %.100s", strerror(errno)); 191 192 /* Allocate a channel for the authentication agent socket. */ 193 nc = channel_new("auth socket", 194 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1, 195 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 196 0, xstrdup("auth socket"), 1); 197 strlcpy(nc->path, auth_sock_name, sizeof(nc->path)); 198 return 1; 199 } 200 201 202 void 203 do_authenticated(Authctxt *authctxt) 204 { 205 /* 206 * Cancel the alarm we set to limit the time taken for 207 * authentication. 208 */ 209 alarm(0); 210 if (startup_pipe != -1) { 211 close(startup_pipe); 212 startup_pipe = -1; 213 } 214 #ifdef WITH_AIXAUTHENTICATE 215 /* We don't have a pty yet, so just label the line as "ssh" */ 216 if (loginsuccess(authctxt->user, 217 get_canonical_hostname(options.verify_reverse_mapping), 218 "ssh", &aixloginmsg) < 0) 219 aixloginmsg = NULL; 220 #endif /* WITH_AIXAUTHENTICATE */ 221 222 /* setup the channel layer */ 223 if (!no_port_forwarding_flag && options.allow_tcp_forwarding) 224 channel_permit_all_opens(); 225 226 if (compat20) 227 do_authenticated2(authctxt); 228 else 229 do_authenticated1(authctxt); 230 231 /* remove agent socket */ 232 if (auth_sock_name != NULL) 233 auth_sock_cleanup_proc(authctxt->pw); 234 #ifdef KRB4 235 if (options.kerberos_ticket_cleanup) 236 krb4_cleanup_proc(authctxt); 237 #endif 238 #ifdef KRB5 239 if (options.kerberos_ticket_cleanup) 240 krb5_cleanup_proc(authctxt); 241 #endif 242 } 243 244 /* 245 * Prepares for an interactive session. This is called after the user has 246 * been successfully authenticated. During this message exchange, pseudo 247 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings 248 * are requested, etc. 249 */ 250 static void 251 do_authenticated1(Authctxt *authctxt) 252 { 253 Session *s; 254 char *command; 255 int success, type, screen_flag; 256 int enable_compression_after_reply = 0; 257 u_int proto_len, data_len, dlen, compression_level = 0; 258 259 s = session_new(); 260 s->authctxt = authctxt; 261 s->pw = authctxt->pw; 262 263 /* 264 * We stay in this loop until the client requests to execute a shell 265 * or a command. 266 */ 267 for (;;) { 268 success = 0; 269 270 /* Get a packet from the client. */ 271 type = packet_read(); 272 273 /* Process the packet. */ 274 switch (type) { 275 case SSH_CMSG_REQUEST_COMPRESSION: 276 compression_level = packet_get_int(); 277 packet_check_eom(); 278 if (compression_level < 1 || compression_level > 9) { 279 packet_send_debug("Received illegal compression level %d.", 280 compression_level); 281 break; 282 } 283 if (!options.compression) { 284 debug2("compression disabled"); 285 break; 286 } 287 /* Enable compression after we have responded with SUCCESS. */ 288 enable_compression_after_reply = 1; 289 success = 1; 290 break; 291 292 case SSH_CMSG_REQUEST_PTY: 293 success = session_pty_req(s); 294 break; 295 296 case SSH_CMSG_X11_REQUEST_FORWARDING: 297 s->auth_proto = packet_get_string(&proto_len); 298 s->auth_data = packet_get_string(&data_len); 299 300 screen_flag = packet_get_protocol_flags() & 301 SSH_PROTOFLAG_SCREEN_NUMBER; 302 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag); 303 304 if (packet_remaining() == 4) { 305 if (!screen_flag) 306 debug2("Buggy client: " 307 "X11 screen flag missing"); 308 s->screen = packet_get_int(); 309 } else { 310 s->screen = 0; 311 } 312 packet_check_eom(); 313 success = session_setup_x11fwd(s); 314 if (!success) { 315 xfree(s->auth_proto); 316 xfree(s->auth_data); 317 s->auth_proto = NULL; 318 s->auth_data = NULL; 319 } 320 break; 321 322 case SSH_CMSG_AGENT_REQUEST_FORWARDING: 323 if (no_agent_forwarding_flag || compat13) { 324 debug("Authentication agent forwarding not permitted for this authentication."); 325 break; 326 } 327 debug("Received authentication agent forwarding request."); 328 success = auth_input_request_forwarding(s->pw); 329 break; 330 331 case SSH_CMSG_PORT_FORWARD_REQUEST: 332 if (no_port_forwarding_flag) { 333 debug("Port forwarding not permitted for this authentication."); 334 break; 335 } 336 if (!options.allow_tcp_forwarding) { 337 debug("Port forwarding not permitted."); 338 break; 339 } 340 debug("Received TCP/IP port forwarding request."); 341 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports); 342 success = 1; 343 break; 344 345 case SSH_CMSG_MAX_PACKET_SIZE: 346 if (packet_set_maxsize(packet_get_int()) > 0) 347 success = 1; 348 break; 349 350 #if defined(AFS) || defined(KRB5) 351 case SSH_CMSG_HAVE_KERBEROS_TGT: 352 if (!options.kerberos_tgt_passing) { 353 verbose("Kerberos TGT passing disabled."); 354 } else { 355 char *kdata = packet_get_string(&dlen); 356 packet_check_eom(); 357 358 /* XXX - 0x41, see creds_to_radix version */ 359 if (kdata[0] != 0x41) { 360 #ifdef KRB5 361 krb5_data tgt; 362 tgt.data = kdata; 363 tgt.length = dlen; 364 365 if (auth_krb5_tgt(s->authctxt, &tgt)) 366 success = 1; 367 else 368 verbose("Kerberos v5 TGT refused for %.100s", s->authctxt->user); 369 #endif /* KRB5 */ 370 } else { 371 #ifdef AFS 372 if (auth_krb4_tgt(s->authctxt, kdata)) 373 success = 1; 374 else 375 verbose("Kerberos v4 TGT refused for %.100s", s->authctxt->user); 376 #endif /* AFS */ 377 } 378 xfree(kdata); 379 } 380 break; 381 #endif /* AFS || KRB5 */ 382 383 #ifdef AFS 384 case SSH_CMSG_HAVE_AFS_TOKEN: 385 if (!options.afs_token_passing || !k_hasafs()) { 386 verbose("AFS token passing disabled."); 387 } else { 388 /* Accept AFS token. */ 389 char *token = packet_get_string(&dlen); 390 packet_check_eom(); 391 392 if (auth_afs_token(s->authctxt, token)) 393 success = 1; 394 else 395 verbose("AFS token refused for %.100s", 396 s->authctxt->user); 397 xfree(token); 398 } 399 break; 400 #endif /* AFS */ 401 402 case SSH_CMSG_EXEC_SHELL: 403 case SSH_CMSG_EXEC_CMD: 404 if (type == SSH_CMSG_EXEC_CMD) { 405 command = packet_get_string(&dlen); 406 debug("Exec command '%.500s'", command); 407 do_exec(s, command); 408 xfree(command); 409 } else { 410 do_exec(s, NULL); 411 } 412 packet_check_eom(); 413 session_close(s); 414 return; 415 416 default: 417 /* 418 * Any unknown messages in this phase are ignored, 419 * and a failure message is returned. 420 */ 421 log("Unknown packet type received after authentication: %d", type); 422 } 423 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE); 424 packet_send(); 425 packet_write_wait(); 426 427 /* Enable compression now that we have replied if appropriate. */ 428 if (enable_compression_after_reply) { 429 enable_compression_after_reply = 0; 430 packet_start_compression(compression_level); 431 } 432 } 433 } 434 435 /* 436 * This is called to fork and execute a command when we have no tty. This 437 * will call do_child from the child, and server_loop from the parent after 438 * setting up file descriptors and such. 439 */ 440 void 441 do_exec_no_pty(Session *s, const char *command) 442 { 443 pid_t pid; 444 445 #ifdef USE_PIPES 446 int pin[2], pout[2], perr[2]; 447 /* Allocate pipes for communicating with the program. */ 448 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0) 449 packet_disconnect("Could not create pipes: %.100s", 450 strerror(errno)); 451 #else /* USE_PIPES */ 452 int inout[2], err[2]; 453 /* Uses socket pairs to communicate with the program. */ 454 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 || 455 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) 456 packet_disconnect("Could not create socket pairs: %.100s", 457 strerror(errno)); 458 #endif /* USE_PIPES */ 459 if (s == NULL) 460 fatal("do_exec_no_pty: no session"); 461 462 session_proctitle(s); 463 464 #if defined(USE_PAM) 465 do_pam_session(s->pw->pw_name, NULL); 466 do_pam_setcred(1); 467 if (is_pam_password_change_required()) 468 packet_disconnect("Password change required but no " 469 "TTY available"); 470 #endif /* USE_PAM */ 471 472 /* Fork the child. */ 473 if ((pid = fork()) == 0) { 474 /* Child. Reinitialize the log since the pid has changed. */ 475 log_init(__progname, options.log_level, options.log_facility, log_stderr); 476 477 /* 478 * Create a new session and process group since the 4.4BSD 479 * setlogin() affects the entire process group. 480 */ 481 if (setsid() < 0) 482 error("setsid failed: %.100s", strerror(errno)); 483 484 #ifdef USE_PIPES 485 /* 486 * Redirect stdin. We close the parent side of the socket 487 * pair, and make the child side the standard input. 488 */ 489 close(pin[1]); 490 if (dup2(pin[0], 0) < 0) 491 perror("dup2 stdin"); 492 close(pin[0]); 493 494 /* Redirect stdout. */ 495 close(pout[0]); 496 if (dup2(pout[1], 1) < 0) 497 perror("dup2 stdout"); 498 close(pout[1]); 499 500 /* Redirect stderr. */ 501 close(perr[0]); 502 if (dup2(perr[1], 2) < 0) 503 perror("dup2 stderr"); 504 close(perr[1]); 505 #else /* USE_PIPES */ 506 /* 507 * Redirect stdin, stdout, and stderr. Stdin and stdout will 508 * use the same socket, as some programs (particularly rdist) 509 * seem to depend on it. 510 */ 511 close(inout[1]); 512 close(err[1]); 513 if (dup2(inout[0], 0) < 0) /* stdin */ 514 perror("dup2 stdin"); 515 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */ 516 perror("dup2 stdout"); 517 if (dup2(err[0], 2) < 0) /* stderr */ 518 perror("dup2 stderr"); 519 #endif /* USE_PIPES */ 520 521 /* Do processing for the child (exec command etc). */ 522 do_child(s, command); 523 /* NOTREACHED */ 524 } 525 #ifdef HAVE_CYGWIN 526 if (is_winnt) 527 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); 528 #endif 529 if (pid < 0) 530 packet_disconnect("fork failed: %.100s", strerror(errno)); 531 s->pid = pid; 532 /* Set interactive/non-interactive mode. */ 533 packet_set_interactive(s->display != NULL); 534 #ifdef USE_PIPES 535 /* We are the parent. Close the child sides of the pipes. */ 536 close(pin[0]); 537 close(pout[1]); 538 close(perr[1]); 539 540 if (compat20) { 541 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]); 542 } else { 543 /* Enter the interactive session. */ 544 server_loop(pid, pin[1], pout[0], perr[0]); 545 /* server_loop has closed pin[1], pout[0], and perr[0]. */ 546 } 547 #else /* USE_PIPES */ 548 /* We are the parent. Close the child sides of the socket pairs. */ 549 close(inout[0]); 550 close(err[0]); 551 552 /* 553 * Enter the interactive session. Note: server_loop must be able to 554 * handle the case that fdin and fdout are the same. 555 */ 556 if (compat20) { 557 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]); 558 } else { 559 server_loop(pid, inout[1], inout[1], err[1]); 560 /* server_loop has closed inout[1] and err[1]. */ 561 } 562 #endif /* USE_PIPES */ 563 } 564 565 /* 566 * This is called to fork and execute a command when we have a tty. This 567 * will call do_child from the child, and server_loop from the parent after 568 * setting up file descriptors, controlling tty, updating wtmp, utmp, 569 * lastlog, and other such operations. 570 */ 571 void 572 do_exec_pty(Session *s, const char *command) 573 { 574 int fdout, ptyfd, ttyfd, ptymaster; 575 pid_t pid; 576 577 if (s == NULL) 578 fatal("do_exec_pty: no session"); 579 ptyfd = s->ptyfd; 580 ttyfd = s->ttyfd; 581 582 #if defined(USE_PAM) 583 do_pam_session(s->pw->pw_name, s->tty); 584 do_pam_setcred(1); 585 #endif 586 587 /* Fork the child. */ 588 if ((pid = fork()) == 0) { 589 590 /* Child. Reinitialize the log because the pid has changed. */ 591 log_init(__progname, options.log_level, options.log_facility, log_stderr); 592 /* Close the master side of the pseudo tty. */ 593 close(ptyfd); 594 595 /* Make the pseudo tty our controlling tty. */ 596 pty_make_controlling_tty(&ttyfd, s->tty); 597 598 /* Redirect stdin/stdout/stderr from the pseudo tty. */ 599 if (dup2(ttyfd, 0) < 0) 600 error("dup2 stdin: %s", strerror(errno)); 601 if (dup2(ttyfd, 1) < 0) 602 error("dup2 stdout: %s", strerror(errno)); 603 if (dup2(ttyfd, 2) < 0) 604 error("dup2 stderr: %s", strerror(errno)); 605 606 /* Close the extra descriptor for the pseudo tty. */ 607 close(ttyfd); 608 609 /* record login, etc. similar to login(1) */ 610 #ifndef HAVE_OSF_SIA 611 if (!(options.use_login && command == NULL)) 612 do_login(s, command); 613 # ifdef LOGIN_NEEDS_UTMPX 614 else 615 do_pre_login(s); 616 # endif 617 #endif 618 619 /* Do common processing for the child, such as execing the command. */ 620 do_child(s, command); 621 /* NOTREACHED */ 622 } 623 #ifdef HAVE_CYGWIN 624 if (is_winnt) 625 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); 626 #endif 627 if (pid < 0) 628 packet_disconnect("fork failed: %.100s", strerror(errno)); 629 s->pid = pid; 630 631 /* Parent. Close the slave side of the pseudo tty. */ 632 close(ttyfd); 633 634 /* 635 * Create another descriptor of the pty master side for use as the 636 * standard input. We could use the original descriptor, but this 637 * simplifies code in server_loop. The descriptor is bidirectional. 638 */ 639 fdout = dup(ptyfd); 640 if (fdout < 0) 641 packet_disconnect("dup #1 failed: %.100s", strerror(errno)); 642 643 /* we keep a reference to the pty master */ 644 ptymaster = dup(ptyfd); 645 if (ptymaster < 0) 646 packet_disconnect("dup #2 failed: %.100s", strerror(errno)); 647 s->ptymaster = ptymaster; 648 649 /* Enter interactive session. */ 650 packet_set_interactive(1); 651 if (compat20) { 652 session_set_fds(s, ptyfd, fdout, -1); 653 } else { 654 server_loop(pid, ptyfd, fdout, -1); 655 /* server_loop _has_ closed ptyfd and fdout. */ 656 } 657 } 658 659 #ifdef LOGIN_NEEDS_UTMPX 660 static void 661 do_pre_login(Session *s) 662 { 663 socklen_t fromlen; 664 struct sockaddr_storage from; 665 pid_t pid = getpid(); 666 667 /* 668 * Get IP address of client. If the connection is not a socket, let 669 * the address be 0.0.0.0. 670 */ 671 memset(&from, 0, sizeof(from)); 672 if (packet_connection_is_on_socket()) { 673 fromlen = sizeof(from); 674 if (getpeername(packet_get_connection_in(), 675 (struct sockaddr *) & from, &fromlen) < 0) { 676 debug("getpeername: %.100s", strerror(errno)); 677 fatal_cleanup(); 678 } 679 } 680 681 record_utmp_only(pid, s->tty, s->pw->pw_name, 682 get_remote_name_or_ip(utmp_len, options.verify_reverse_mapping), 683 (struct sockaddr *)&from); 684 } 685 #endif 686 687 /* 688 * This is called to fork and execute a command. If another command is 689 * to be forced, execute that instead. 690 */ 691 void 692 do_exec(Session *s, const char *command) 693 { 694 if (forced_command) { 695 original_command = command; 696 command = forced_command; 697 debug("Forced command '%.900s'", command); 698 } 699 700 if (s->ttyfd != -1) 701 do_exec_pty(s, command); 702 else 703 do_exec_no_pty(s, command); 704 705 original_command = NULL; 706 } 707 708 709 /* administrative, login(1)-like work */ 710 void 711 do_login(Session *s, const char *command) 712 { 713 char *time_string; 714 socklen_t fromlen; 715 struct sockaddr_storage from; 716 struct passwd * pw = s->pw; 717 pid_t pid = getpid(); 718 719 /* 720 * Get IP address of client. If the connection is not a socket, let 721 * the address be 0.0.0.0. 722 */ 723 memset(&from, 0, sizeof(from)); 724 if (packet_connection_is_on_socket()) { 725 fromlen = sizeof(from); 726 if (getpeername(packet_get_connection_in(), 727 (struct sockaddr *) & from, &fromlen) < 0) { 728 debug("getpeername: %.100s", strerror(errno)); 729 fatal_cleanup(); 730 } 731 } 732 733 /* Record that there was a login on that tty from the remote host. */ 734 if (!use_privsep) 735 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, 736 get_remote_name_or_ip(utmp_len, 737 options.verify_reverse_mapping), 738 (struct sockaddr *)&from); 739 740 #ifdef USE_PAM 741 /* 742 * If password change is needed, do it now. 743 * This needs to occur before the ~/.hushlogin check. 744 */ 745 if (is_pam_password_change_required()) { 746 print_pam_messages(); 747 do_pam_chauthtok(); 748 } 749 #endif 750 751 if (check_quietlogin(s, command)) 752 return; 753 754 #ifdef USE_PAM 755 if (options.print_lastlog && !is_pam_password_change_required()) 756 print_pam_messages(); 757 #endif /* USE_PAM */ 758 #ifdef WITH_AIXAUTHENTICATE 759 if (aixloginmsg && *aixloginmsg) 760 printf("%s\n", aixloginmsg); 761 #endif /* WITH_AIXAUTHENTICATE */ 762 #ifndef USE_PAM 763 if (options.print_lastlog && s->last_login_time != 0) { 764 time_string = ctime(&s->last_login_time); 765 if (strchr(time_string, '\n')) 766 *strchr(time_string, '\n') = 0; 767 if (strcmp(s->hostname, "") == 0) 768 printf("Last login: %s\r\n", time_string); 769 else 770 printf("Last login: %s from %s\r\n", time_string, 771 s->hostname); 772 } 773 #endif /* !USE_PAM */ 774 775 do_motd(); 776 } 777 778 /* 779 * Display the message of the day. 780 */ 781 void 782 do_motd(void) 783 { 784 FILE *f; 785 char buf[256]; 786 #ifdef HAVE_LOGIN_CAP 787 const char *fname; 788 #endif 789 790 #ifdef HAVE_LOGIN_CAP 791 fname = login_getcapstr(lc, "copyright", NULL, NULL); 792 if (fname != NULL && (f = fopen(fname, "r")) != NULL) { 793 while (fgets(buf, sizeof(buf), f) != NULL) 794 fputs(buf, stdout); 795 fclose(f); 796 } else 797 #endif /* HAVE_LOGIN_CAP */ 798 (void)printf("%s\n\t%s %s\n", 799 "Copyright (c) 1980, 1983, 1986, 1988, 1990, 1991, 1993, 1994", 800 "The Regents of the University of California. ", 801 "All rights reserved."); 802 803 (void)printf("\n"); 804 805 if (options.print_motd) { 806 #ifdef HAVE_LOGIN_CAP 807 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd", 808 "/etc/motd"), "r"); 809 #else 810 f = fopen("/etc/motd", "r"); 811 #endif 812 if (f) { 813 while (fgets(buf, sizeof(buf), f)) 814 fputs(buf, stdout); 815 fclose(f); 816 } 817 } 818 } 819 820 821 /* 822 * Check for quiet login, either .hushlogin or command given. 823 */ 824 int 825 check_quietlogin(Session *s, const char *command) 826 { 827 char buf[256]; 828 struct passwd *pw = s->pw; 829 struct stat st; 830 831 /* Return 1 if .hushlogin exists or a command given. */ 832 if (command != NULL) 833 return 1; 834 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir); 835 #ifdef HAVE_LOGIN_CAP 836 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0) 837 return 1; 838 #else 839 if (stat(buf, &st) >= 0) 840 return 1; 841 #endif 842 return 0; 843 } 844 845 /* 846 * Sets the value of the given variable in the environment. If the variable 847 * already exists, its value is overriden. 848 */ 849 static void 850 child_set_env(char ***envp, u_int *envsizep, const char *name, 851 const char *value) 852 { 853 u_int i, namelen; 854 char **env; 855 856 /* 857 * Find the slot where the value should be stored. If the variable 858 * already exists, we reuse the slot; otherwise we append a new slot 859 * at the end of the array, expanding if necessary. 860 */ 861 env = *envp; 862 namelen = strlen(name); 863 for (i = 0; env[i]; i++) 864 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=') 865 break; 866 if (env[i]) { 867 /* Reuse the slot. */ 868 xfree(env[i]); 869 } else { 870 /* New variable. Expand if necessary. */ 871 if (i >= (*envsizep) - 1) { 872 if (*envsizep >= 1000) 873 fatal("child_set_env: too many env vars," 874 " skipping: %.100s", name); 875 (*envsizep) += 50; 876 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *)); 877 } 878 /* Need to set the NULL pointer at end of array beyond the new slot. */ 879 env[i + 1] = NULL; 880 } 881 882 /* Allocate space and format the variable in the appropriate slot. */ 883 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1); 884 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value); 885 } 886 887 /* 888 * Reads environment variables from the given file and adds/overrides them 889 * into the environment. If the file does not exist, this does nothing. 890 * Otherwise, it must consist of empty lines, comments (line starts with '#') 891 * and assignments of the form name=value. No other forms are allowed. 892 */ 893 static void 894 read_environment_file(char ***env, u_int *envsize, 895 const char *filename) 896 { 897 FILE *f; 898 char buf[4096]; 899 char *cp, *value; 900 u_int lineno = 0; 901 902 f = fopen(filename, "r"); 903 if (!f) 904 return; 905 906 while (fgets(buf, sizeof(buf), f)) { 907 if (++lineno > 1000) 908 fatal("Too many lines in environment file %s", filename); 909 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++) 910 ; 911 if (!*cp || *cp == '#' || *cp == '\n') 912 continue; 913 if (strchr(cp, '\n')) 914 *strchr(cp, '\n') = '\0'; 915 value = strchr(cp, '='); 916 if (value == NULL) { 917 fprintf(stderr, "Bad line %u in %.100s\n", lineno, 918 filename); 919 continue; 920 } 921 /* 922 * Replace the equals sign by nul, and advance value to 923 * the value string. 924 */ 925 *value = '\0'; 926 value++; 927 child_set_env(env, envsize, cp, value); 928 } 929 fclose(f); 930 } 931 932 void copy_environment(char **source, char ***env, u_int *envsize) 933 { 934 char *var_name, *var_val; 935 int i; 936 937 if (source == NULL) 938 return; 939 940 for(i = 0; source[i] != NULL; i++) { 941 var_name = xstrdup(source[i]); 942 if ((var_val = strstr(var_name, "=")) == NULL) { 943 xfree(var_name); 944 continue; 945 } 946 *var_val++ = '\0'; 947 948 debug3("Copy environment: %s=%s", var_name, var_val); 949 child_set_env(env, envsize, var_name, var_val); 950 951 xfree(var_name); 952 } 953 } 954 955 static char ** 956 do_setup_env(Session *s, const char *shell) 957 { 958 char buf[256]; 959 u_int i, envsize; 960 char **env; 961 #ifdef HAVE_LOGIN_CAP 962 extern char **environ; 963 char **senv, **var; 964 #endif 965 struct passwd *pw = s->pw; 966 967 /* Initialize the environment. */ 968 envsize = 100; 969 env = xmalloc(envsize * sizeof(char *)); 970 env[0] = NULL; 971 972 #ifdef HAVE_CYGWIN 973 /* 974 * The Windows environment contains some setting which are 975 * important for a running system. They must not be dropped. 976 */ 977 copy_environment(environ, &env, &envsize); 978 #endif 979 980 if (getenv("TZ")) 981 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 982 if (!options.use_login) { 983 /* Set basic environment. */ 984 child_set_env(&env, &envsize, "USER", pw->pw_name); 985 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 986 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 987 snprintf(buf, sizeof buf, "%.200s/%.50s", 988 _PATH_MAILDIR, pw->pw_name); 989 child_set_env(&env, &envsize, "MAIL", buf); 990 #ifdef HAVE_LOGIN_CAP 991 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 992 child_set_env(&env, &envsize, "TERM", "su"); 993 senv = environ; 994 environ = xmalloc(sizeof(char *)); 995 *environ = NULL; 996 (void) setusercontext(lc, pw, pw->pw_uid, 997 LOGIN_SETENV|LOGIN_SETPATH); 998 copy_environment(environ, &env, &envsize); 999 for (var = environ; *var != NULL; ++var) 1000 xfree(*var); 1001 xfree(environ); 1002 environ = senv; 1003 #else /* HAVE_LOGIN_CAP */ 1004 # ifndef HAVE_CYGWIN 1005 /* 1006 * There's no standard path on Windows. The path contains 1007 * important components pointing to the system directories, 1008 * needed for loading shared libraries. So the path better 1009 * remains intact here. 1010 */ 1011 # ifdef SUPERUSER_PATH 1012 child_set_env(&env, &envsize, "PATH", 1013 s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH); 1014 # else 1015 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 1016 # endif /* SUPERUSER_PATH */ 1017 # endif /* HAVE_CYGWIN */ 1018 #endif /* HAVE_LOGIN_CAP */ 1019 1020 /* Normal systems set SHELL by default. */ 1021 child_set_env(&env, &envsize, "SHELL", shell); 1022 } 1023 1024 /* Set custom environment options from RSA authentication. */ 1025 if (!options.use_login) { 1026 while (custom_environment) { 1027 struct envstring *ce = custom_environment; 1028 char *s = ce->s; 1029 1030 for (i = 0; s[i] != '=' && s[i]; i++) 1031 ; 1032 if (s[i] == '=') { 1033 s[i] = 0; 1034 child_set_env(&env, &envsize, s, s + i + 1); 1035 } 1036 custom_environment = ce->next; 1037 xfree(ce->s); 1038 xfree(ce); 1039 } 1040 } 1041 1042 snprintf(buf, sizeof buf, "%.50s %d %d", 1043 get_remote_ipaddr(), get_remote_port(), get_local_port()); 1044 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 1045 1046 if (s->ttyfd != -1) 1047 child_set_env(&env, &envsize, "SSH_TTY", s->tty); 1048 if (s->term) 1049 child_set_env(&env, &envsize, "TERM", s->term); 1050 if (s->display) 1051 child_set_env(&env, &envsize, "DISPLAY", s->display); 1052 if (original_command) 1053 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND", 1054 original_command); 1055 1056 #ifdef _AIX 1057 { 1058 char *cp; 1059 1060 if ((cp = getenv("AUTHSTATE")) != NULL) 1061 child_set_env(&env, &envsize, "AUTHSTATE", cp); 1062 if ((cp = getenv("KRB5CCNAME")) != NULL) 1063 child_set_env(&env, &envsize, "KRB5CCNAME", cp); 1064 read_environment_file(&env, &envsize, "/etc/environment"); 1065 } 1066 #endif 1067 #ifdef KRB4 1068 if (s->authctxt->krb4_ticket_file) 1069 child_set_env(&env, &envsize, "KRBTKFILE", 1070 s->authctxt->krb4_ticket_file); 1071 #endif 1072 #ifdef KRB5 1073 if (s->authctxt->krb5_ticket_file) 1074 child_set_env(&env, &envsize, "KRB5CCNAME", 1075 s->authctxt->krb5_ticket_file); 1076 #endif 1077 #ifdef USE_PAM 1078 /* Pull in any environment variables that may have been set by PAM. */ 1079 copy_environment(fetch_pam_environment(), &env, &envsize); 1080 #endif /* USE_PAM */ 1081 1082 if (auth_sock_name != NULL) 1083 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 1084 auth_sock_name); 1085 1086 /* read $HOME/.ssh/environment. */ 1087 if (!options.use_login) { 1088 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", 1089 pw->pw_dir); 1090 read_environment_file(&env, &envsize, buf); 1091 } 1092 if (debug_flag) { 1093 /* dump the environment */ 1094 fprintf(stderr, "Environment:\n"); 1095 for (i = 0; env[i]; i++) 1096 fprintf(stderr, " %.200s\n", env[i]); 1097 } 1098 return env; 1099 } 1100 1101 /* 1102 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found 1103 * first in this order). 1104 */ 1105 static void 1106 do_rc_files(Session *s, const char *shell) 1107 { 1108 FILE *f = NULL; 1109 char cmd[1024]; 1110 int do_xauth; 1111 struct stat st; 1112 1113 do_xauth = 1114 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL; 1115 1116 /* ignore _PATH_SSH_USER_RC for subsystems */ 1117 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) { 1118 snprintf(cmd, sizeof cmd, "%s -c '%s %s'", 1119 shell, _PATH_BSHELL, _PATH_SSH_USER_RC); 1120 if (debug_flag) 1121 fprintf(stderr, "Running %s\n", cmd); 1122 f = popen(cmd, "w"); 1123 if (f) { 1124 if (do_xauth) 1125 fprintf(f, "%s %s\n", s->auth_proto, 1126 s->auth_data); 1127 pclose(f); 1128 } else 1129 fprintf(stderr, "Could not run %s\n", 1130 _PATH_SSH_USER_RC); 1131 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) { 1132 if (debug_flag) 1133 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, 1134 _PATH_SSH_SYSTEM_RC); 1135 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w"); 1136 if (f) { 1137 if (do_xauth) 1138 fprintf(f, "%s %s\n", s->auth_proto, 1139 s->auth_data); 1140 pclose(f); 1141 } else 1142 fprintf(stderr, "Could not run %s\n", 1143 _PATH_SSH_SYSTEM_RC); 1144 } else if (do_xauth && options.xauth_location != NULL) { 1145 /* Add authority data to .Xauthority if appropriate. */ 1146 if (debug_flag) { 1147 fprintf(stderr, 1148 "Running %.500s add " 1149 "%.100s %.100s %.100s\n", 1150 options.xauth_location, s->auth_display, 1151 s->auth_proto, s->auth_data); 1152 } 1153 snprintf(cmd, sizeof cmd, "%s -q -", 1154 options.xauth_location); 1155 f = popen(cmd, "w"); 1156 if (f) { 1157 fprintf(f, "add %s %s %s\n", 1158 s->auth_display, s->auth_proto, 1159 s->auth_data); 1160 pclose(f); 1161 } else { 1162 fprintf(stderr, "Could not run %s\n", 1163 cmd); 1164 } 1165 } 1166 } 1167 1168 static void 1169 do_nologin(struct passwd *pw) 1170 { 1171 FILE *f = NULL; 1172 char buf[1024]; 1173 1174 #ifdef HAVE_LOGIN_CAP 1175 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid) 1176 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN, 1177 _PATH_NOLOGIN), "r"); 1178 #else 1179 if (pw->pw_uid) 1180 f = fopen(_PATH_NOLOGIN, "r"); 1181 #endif 1182 if (f) { 1183 /* /etc/nologin exists. Print its contents and exit. */ 1184 while (fgets(buf, sizeof(buf), f)) 1185 fputs(buf, stderr); 1186 fclose(f); 1187 exit(254); 1188 } 1189 } 1190 1191 /* Set login name, uid, gid, and groups. */ 1192 void 1193 do_setusercontext(struct passwd *pw) 1194 { 1195 char tty='\0'; 1196 1197 #ifdef HAVE_CYGWIN 1198 if (is_winnt) { 1199 #else /* HAVE_CYGWIN */ 1200 if (getuid() == 0 || geteuid() == 0) { 1201 #endif /* HAVE_CYGWIN */ 1202 #ifdef HAVE_SETPCRED 1203 setpcred(pw->pw_name); 1204 #endif /* HAVE_SETPCRED */ 1205 #ifdef HAVE_LOGIN_CAP 1206 #ifdef __bsdi__ 1207 setpgid(0, 0); 1208 #endif 1209 if (setusercontext(lc, pw, pw->pw_uid, 1210 (LOGIN_SETALL & ~(LOGIN_SETENV|LOGIN_SETPATH))) < 0) { 1211 perror("unable to set user context"); 1212 exit(1); 1213 } 1214 #else 1215 # if defined(HAVE_GETLUID) && defined(HAVE_SETLUID) 1216 /* Sets login uid for accounting */ 1217 if (getluid() == -1 && setluid(pw->pw_uid) == -1) 1218 error("setluid: %s", strerror(errno)); 1219 # endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */ 1220 1221 if (setlogin(pw->pw_name) < 0) 1222 error("setlogin failed: %s", strerror(errno)); 1223 if (setgid(pw->pw_gid) < 0) { 1224 perror("setgid"); 1225 exit(1); 1226 } 1227 /* Initialize the group list. */ 1228 if (initgroups(pw->pw_name, pw->pw_gid) < 0) { 1229 perror("initgroups"); 1230 exit(1); 1231 } 1232 endgrent(); 1233 # ifdef USE_PAM 1234 /* 1235 * PAM credentials may take the form of supplementary groups. 1236 * These will have been wiped by the above initgroups() call. 1237 * Reestablish them here. 1238 */ 1239 do_pam_setcred(0); 1240 # endif /* USE_PAM */ 1241 # if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) 1242 irix_setusercontext(pw); 1243 # endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */ 1244 # ifdef _AIX 1245 /* XXX: Disable tty setting. Enabled if required later */ 1246 aix_usrinfo(pw, &tty, -1); 1247 # endif /* _AIX */ 1248 /* Permanently switch to the desired uid. */ 1249 permanently_set_uid(pw); 1250 #endif 1251 } 1252 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 1253 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); 1254 } 1255 1256 static void 1257 launch_login(struct passwd *pw, const char *hostname) 1258 { 1259 /* Launch login(1). */ 1260 1261 execl(LOGIN_PROGRAM, "login", "-h", hostname, 1262 #ifdef xxxLOGIN_NEEDS_TERM 1263 (s->term ? s->term : "unknown"), 1264 #endif /* LOGIN_NEEDS_TERM */ 1265 #ifdef LOGIN_NO_ENDOPT 1266 "-p", "-f", pw->pw_name, (char *)NULL); 1267 #else 1268 "-p", "-f", "--", pw->pw_name, (char *)NULL); 1269 #endif 1270 1271 /* Login couldn't be executed, die. */ 1272 1273 perror("login"); 1274 exit(1); 1275 } 1276 1277 /* 1278 * Performs common processing for the child, such as setting up the 1279 * environment, closing extra file descriptors, setting the user and group 1280 * ids, and executing the command or shell. 1281 */ 1282 void 1283 do_child(Session *s, const char *command) 1284 { 1285 extern char **environ; 1286 char **env; 1287 char *argv[10]; 1288 const char *shell, *shell0, *hostname = NULL; 1289 struct passwd *pw = s->pw; 1290 u_int i; 1291 1292 /* remove hostkey from the child's memory */ 1293 destroy_sensitive_data(); 1294 1295 /* login(1) is only called if we execute the login shell */ 1296 if (options.use_login && command != NULL) 1297 options.use_login = 0; 1298 1299 /* 1300 * Login(1) does this as well, and it needs uid 0 for the "-h" 1301 * switch, so we let login(1) to this for us. 1302 */ 1303 if (!options.use_login) { 1304 #ifdef HAVE_OSF_SIA 1305 session_setup_sia(pw->pw_name, s->ttyfd == -1 ? NULL : s->tty); 1306 if (!check_quietlogin(s, command)) 1307 do_motd(); 1308 #else /* HAVE_OSF_SIA */ 1309 do_nologin(pw); 1310 do_setusercontext(pw); 1311 #endif /* HAVE_OSF_SIA */ 1312 } 1313 1314 /* 1315 * Get the shell from the password data. An empty shell field is 1316 * legal, and means /bin/sh. 1317 */ 1318 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 1319 #ifdef HAVE_LOGIN_CAP 1320 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); 1321 #endif 1322 1323 env = do_setup_env(s, shell); 1324 1325 /* we have to stash the hostname before we close our socket. */ 1326 if (options.use_login) 1327 hostname = get_remote_name_or_ip(utmp_len, 1328 options.verify_reverse_mapping); 1329 /* 1330 * Close the connection descriptors; note that this is the child, and 1331 * the server will still have the socket open, and it is important 1332 * that we do not shutdown it. Note that the descriptors cannot be 1333 * closed before building the environment, as we call 1334 * get_remote_ipaddr there. 1335 */ 1336 if (packet_get_connection_in() == packet_get_connection_out()) 1337 close(packet_get_connection_in()); 1338 else { 1339 close(packet_get_connection_in()); 1340 close(packet_get_connection_out()); 1341 } 1342 /* 1343 * Close all descriptors related to channels. They will still remain 1344 * open in the parent. 1345 */ 1346 /* XXX better use close-on-exec? -markus */ 1347 channel_close_all(); 1348 1349 /* 1350 * Close any extra file descriptors. Note that there may still be 1351 * descriptors left by system functions. They will be closed later. 1352 */ 1353 endpwent(); 1354 1355 /* 1356 * Close any extra open file descriptors so that we don\'t have them 1357 * hanging around in clients. Note that we want to do this after 1358 * initgroups, because at least on Solaris 2.3 it leaves file 1359 * descriptors open. 1360 */ 1361 for (i = 3; i < 64; i++) 1362 close(i); 1363 1364 /* 1365 * Must take new environment into use so that .ssh/rc, 1366 * /etc/ssh/sshrc and xauth are run in the proper environment. 1367 */ 1368 environ = env; 1369 1370 #ifdef AFS 1371 /* Try to get AFS tokens for the local cell. */ 1372 if (k_hasafs()) { 1373 char cell[64]; 1374 1375 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 1376 krb_afslog(cell, 0); 1377 1378 krb_afslog(0, 0); 1379 } 1380 #endif /* AFS */ 1381 1382 /* Change current directory to the user\'s home directory. */ 1383 if (chdir(pw->pw_dir) < 0) { 1384 fprintf(stderr, "Could not chdir to home directory %s: %s\n", 1385 pw->pw_dir, strerror(errno)); 1386 #ifdef HAVE_LOGIN_CAP 1387 if (login_getcapbool(lc, "requirehome", 0)) 1388 exit(1); 1389 #endif 1390 } 1391 1392 if (!options.use_login) 1393 do_rc_files(s, shell); 1394 1395 /* restore SIGPIPE for child */ 1396 signal(SIGPIPE, SIG_DFL); 1397 1398 if (options.use_login) { 1399 launch_login(pw, hostname); 1400 /* NEVERREACHED */ 1401 } 1402 1403 /* Get the last component of the shell name. */ 1404 if ((shell0 = strrchr(shell, '/')) != NULL) 1405 shell0++; 1406 else 1407 shell0 = shell; 1408 1409 /* 1410 * If we have no command, execute the shell. In this case, the shell 1411 * name to be passed in argv[0] is preceded by '-' to indicate that 1412 * this is a login shell. 1413 */ 1414 if (!command) { 1415 char argv0[256]; 1416 1417 /* Start the shell. Set initial character to '-'. */ 1418 argv0[0] = '-'; 1419 1420 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) 1421 >= sizeof(argv0) - 1) { 1422 errno = EINVAL; 1423 perror(shell); 1424 exit(1); 1425 } 1426 1427 /* Execute the shell. */ 1428 argv[0] = argv0; 1429 argv[1] = NULL; 1430 execve(shell, argv, env); 1431 1432 /* Executing the shell failed. */ 1433 perror(shell); 1434 exit(1); 1435 } 1436 /* 1437 * Execute the command using the user's shell. This uses the -c 1438 * option to execute the command. 1439 */ 1440 argv[0] = (char *) shell0; 1441 argv[1] = "-c"; 1442 argv[2] = (char *) command; 1443 argv[3] = NULL; 1444 execve(shell, argv, env); 1445 perror(shell); 1446 exit(1); 1447 } 1448 1449 Session * 1450 session_new(void) 1451 { 1452 int i; 1453 static int did_init = 0; 1454 if (!did_init) { 1455 debug("session_new: init"); 1456 for (i = 0; i < MAX_SESSIONS; i++) { 1457 sessions[i].used = 0; 1458 } 1459 did_init = 1; 1460 } 1461 for (i = 0; i < MAX_SESSIONS; i++) { 1462 Session *s = &sessions[i]; 1463 if (! s->used) { 1464 memset(s, 0, sizeof(*s)); 1465 s->chanid = -1; 1466 s->ptyfd = -1; 1467 s->ttyfd = -1; 1468 s->used = 1; 1469 s->self = i; 1470 debug("session_new: session %d", i); 1471 return s; 1472 } 1473 } 1474 return NULL; 1475 } 1476 1477 static void 1478 session_dump(void) 1479 { 1480 int i; 1481 for (i = 0; i < MAX_SESSIONS; i++) { 1482 Session *s = &sessions[i]; 1483 debug("dump: used %d session %d %p channel %d pid %ld", 1484 s->used, 1485 s->self, 1486 s, 1487 s->chanid, 1488 (long)s->pid); 1489 } 1490 } 1491 1492 int 1493 session_open(Authctxt *authctxt, int chanid) 1494 { 1495 Session *s = session_new(); 1496 debug("session_open: channel %d", chanid); 1497 if (s == NULL) { 1498 error("no more sessions"); 1499 return 0; 1500 } 1501 s->authctxt = authctxt; 1502 s->pw = authctxt->pw; 1503 if (s->pw == NULL) 1504 fatal("no user for session %d", s->self); 1505 debug("session_open: session %d: link with channel %d", s->self, chanid); 1506 s->chanid = chanid; 1507 return 1; 1508 } 1509 1510 Session * 1511 session_by_tty(char *tty) 1512 { 1513 int i; 1514 for (i = 0; i < MAX_SESSIONS; i++) { 1515 Session *s = &sessions[i]; 1516 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) { 1517 debug("session_by_tty: session %d tty %s", i, tty); 1518 return s; 1519 } 1520 } 1521 debug("session_by_tty: unknown tty %.100s", tty); 1522 session_dump(); 1523 return NULL; 1524 } 1525 1526 static Session * 1527 session_by_channel(int id) 1528 { 1529 int i; 1530 for (i = 0; i < MAX_SESSIONS; i++) { 1531 Session *s = &sessions[i]; 1532 if (s->used && s->chanid == id) { 1533 debug("session_by_channel: session %d channel %d", i, id); 1534 return s; 1535 } 1536 } 1537 debug("session_by_channel: unknown channel %d", id); 1538 session_dump(); 1539 return NULL; 1540 } 1541 1542 static Session * 1543 session_by_pid(pid_t pid) 1544 { 1545 int i; 1546 debug("session_by_pid: pid %ld", (long)pid); 1547 for (i = 0; i < MAX_SESSIONS; i++) { 1548 Session *s = &sessions[i]; 1549 if (s->used && s->pid == pid) 1550 return s; 1551 } 1552 error("session_by_pid: unknown pid %ld", (long)pid); 1553 session_dump(); 1554 return NULL; 1555 } 1556 1557 static int 1558 session_window_change_req(Session *s) 1559 { 1560 s->col = packet_get_int(); 1561 s->row = packet_get_int(); 1562 s->xpixel = packet_get_int(); 1563 s->ypixel = packet_get_int(); 1564 packet_check_eom(); 1565 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1566 return 1; 1567 } 1568 1569 static int 1570 session_pty_req(Session *s) 1571 { 1572 u_int len; 1573 int n_bytes; 1574 1575 if (no_pty_flag) { 1576 debug("Allocating a pty not permitted for this authentication."); 1577 return 0; 1578 } 1579 if (s->ttyfd != -1) { 1580 packet_disconnect("Protocol error: you already have a pty."); 1581 return 0; 1582 } 1583 /* Get the time and hostname when the user last logged in. */ 1584 if (options.print_lastlog) { 1585 s->hostname[0] = '\0'; 1586 s->last_login_time = get_last_login_time(s->pw->pw_uid, 1587 s->pw->pw_name, s->hostname, sizeof(s->hostname)); 1588 } 1589 1590 s->term = packet_get_string(&len); 1591 1592 if (compat20) { 1593 s->col = packet_get_int(); 1594 s->row = packet_get_int(); 1595 } else { 1596 s->row = packet_get_int(); 1597 s->col = packet_get_int(); 1598 } 1599 s->xpixel = packet_get_int(); 1600 s->ypixel = packet_get_int(); 1601 1602 if (strcmp(s->term, "") == 0) { 1603 xfree(s->term); 1604 s->term = NULL; 1605 } 1606 1607 /* Allocate a pty and open it. */ 1608 debug("Allocating pty."); 1609 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) { 1610 if (s->term) 1611 xfree(s->term); 1612 s->term = NULL; 1613 s->ptyfd = -1; 1614 s->ttyfd = -1; 1615 error("session_pty_req: session %d alloc failed", s->self); 1616 return 0; 1617 } 1618 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 1619 1620 /* for SSH1 the tty modes length is not given */ 1621 if (!compat20) 1622 n_bytes = packet_remaining(); 1623 tty_parse_modes(s->ttyfd, &n_bytes); 1624 1625 /* 1626 * Add a cleanup function to clear the utmp entry and record logout 1627 * time in case we call fatal() (e.g., the connection gets closed). 1628 */ 1629 fatal_add_cleanup(session_pty_cleanup, (void *)s); 1630 if (!use_privsep) 1631 pty_setowner(s->pw, s->tty); 1632 1633 /* Set window size from the packet. */ 1634 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1635 1636 packet_check_eom(); 1637 session_proctitle(s); 1638 return 1; 1639 } 1640 1641 static int 1642 session_subsystem_req(Session *s) 1643 { 1644 struct stat st; 1645 u_int len; 1646 int success = 0; 1647 char *cmd, *subsys = packet_get_string(&len); 1648 int i; 1649 1650 packet_check_eom(); 1651 log("subsystem request for %.100s", subsys); 1652 1653 for (i = 0; i < options.num_subsystems; i++) { 1654 if (strcmp(subsys, options.subsystem_name[i]) == 0) { 1655 cmd = options.subsystem_command[i]; 1656 if (stat(cmd, &st) < 0) { 1657 error("subsystem: cannot stat %s: %s", cmd, 1658 strerror(errno)); 1659 break; 1660 } 1661 debug("subsystem: exec() %s", cmd); 1662 s->is_subsystem = 1; 1663 do_exec(s, cmd); 1664 success = 1; 1665 break; 1666 } 1667 } 1668 1669 if (!success) 1670 log("subsystem request for %.100s failed, subsystem not found", 1671 subsys); 1672 1673 xfree(subsys); 1674 return success; 1675 } 1676 1677 static int 1678 session_x11_req(Session *s) 1679 { 1680 int success; 1681 1682 s->single_connection = packet_get_char(); 1683 s->auth_proto = packet_get_string(NULL); 1684 s->auth_data = packet_get_string(NULL); 1685 s->screen = packet_get_int(); 1686 packet_check_eom(); 1687 1688 success = session_setup_x11fwd(s); 1689 if (!success) { 1690 xfree(s->auth_proto); 1691 xfree(s->auth_data); 1692 s->auth_proto = NULL; 1693 s->auth_data = NULL; 1694 } 1695 return success; 1696 } 1697 1698 static int 1699 session_shell_req(Session *s) 1700 { 1701 packet_check_eom(); 1702 do_exec(s, NULL); 1703 return 1; 1704 } 1705 1706 static int 1707 session_exec_req(Session *s) 1708 { 1709 u_int len; 1710 char *command = packet_get_string(&len); 1711 packet_check_eom(); 1712 do_exec(s, command); 1713 xfree(command); 1714 return 1; 1715 } 1716 1717 static int 1718 session_auth_agent_req(Session *s) 1719 { 1720 static int called = 0; 1721 packet_check_eom(); 1722 if (no_agent_forwarding_flag) { 1723 debug("session_auth_agent_req: no_agent_forwarding_flag"); 1724 return 0; 1725 } 1726 if (called) { 1727 return 0; 1728 } else { 1729 called = 1; 1730 return auth_input_request_forwarding(s->pw); 1731 } 1732 } 1733 1734 int 1735 session_input_channel_req(Channel *c, const char *rtype) 1736 { 1737 int success = 0; 1738 Session *s; 1739 1740 if ((s = session_by_channel(c->self)) == NULL) { 1741 log("session_input_channel_req: no session %d req %.100s", 1742 c->self, rtype); 1743 return 0; 1744 } 1745 debug("session_input_channel_req: session %d req %s", s->self, rtype); 1746 1747 /* 1748 * a session is in LARVAL state until a shell, a command 1749 * or a subsystem is executed 1750 */ 1751 if (c->type == SSH_CHANNEL_LARVAL) { 1752 if (strcmp(rtype, "shell") == 0) { 1753 success = session_shell_req(s); 1754 } else if (strcmp(rtype, "exec") == 0) { 1755 success = session_exec_req(s); 1756 } else if (strcmp(rtype, "pty-req") == 0) { 1757 success = session_pty_req(s); 1758 } else if (strcmp(rtype, "x11-req") == 0) { 1759 success = session_x11_req(s); 1760 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) { 1761 success = session_auth_agent_req(s); 1762 } else if (strcmp(rtype, "subsystem") == 0) { 1763 success = session_subsystem_req(s); 1764 } 1765 } 1766 if (strcmp(rtype, "window-change") == 0) { 1767 success = session_window_change_req(s); 1768 } 1769 return success; 1770 } 1771 1772 void 1773 session_set_fds(Session *s, int fdin, int fdout, int fderr) 1774 { 1775 if (!compat20) 1776 fatal("session_set_fds: called for proto != 2.0"); 1777 /* 1778 * now that have a child and a pipe to the child, 1779 * we can activate our channel and register the fd's 1780 */ 1781 if (s->chanid == -1) 1782 fatal("no channel for session %d", s->self); 1783 channel_set_fds(s->chanid, 1784 fdout, fdin, fderr, 1785 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ, 1786 1, 1787 CHAN_SES_WINDOW_DEFAULT); 1788 } 1789 1790 /* 1791 * Function to perform pty cleanup. Also called if we get aborted abnormally 1792 * (e.g., due to a dropped connection). 1793 */ 1794 void 1795 session_pty_cleanup2(void *session) 1796 { 1797 Session *s = session; 1798 1799 if (s == NULL) { 1800 error("session_pty_cleanup: no session"); 1801 return; 1802 } 1803 if (s->ttyfd == -1) 1804 return; 1805 1806 debug("session_pty_cleanup: session %d release %s", s->self, s->tty); 1807 1808 /* Record that the user has logged out. */ 1809 if (s->pid != 0) 1810 record_logout(s->pid, s->tty, s->pw->pw_name); 1811 1812 /* Release the pseudo-tty. */ 1813 if (getuid() == 0) 1814 pty_release(s->tty); 1815 1816 /* 1817 * Close the server side of the socket pairs. We must do this after 1818 * the pty cleanup, so that another process doesn't get this pty 1819 * while we're still cleaning up. 1820 */ 1821 if (close(s->ptymaster) < 0) 1822 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno)); 1823 1824 /* unlink pty from session */ 1825 s->ttyfd = -1; 1826 } 1827 1828 void 1829 session_pty_cleanup(void *session) 1830 { 1831 PRIVSEP(session_pty_cleanup2(session)); 1832 } 1833 1834 static void 1835 session_exit_message(Session *s, int status) 1836 { 1837 Channel *c; 1838 1839 if ((c = channel_lookup(s->chanid)) == NULL) 1840 fatal("session_exit_message: session %d: no channel %d", 1841 s->self, s->chanid); 1842 debug("session_exit_message: session %d channel %d pid %ld", 1843 s->self, s->chanid, (long)s->pid); 1844 1845 if (WIFEXITED(status)) { 1846 channel_request_start(s->chanid, "exit-status", 0); 1847 packet_put_int(WEXITSTATUS(status)); 1848 packet_send(); 1849 } else if (WIFSIGNALED(status)) { 1850 channel_request_start(s->chanid, "exit-signal", 0); 1851 packet_put_int(WTERMSIG(status)); 1852 #ifdef WCOREDUMP 1853 packet_put_char(WCOREDUMP(status)); 1854 #else /* WCOREDUMP */ 1855 packet_put_char(0); 1856 #endif /* WCOREDUMP */ 1857 packet_put_cstring(""); 1858 packet_put_cstring(""); 1859 packet_send(); 1860 } else { 1861 /* Some weird exit cause. Just exit. */ 1862 packet_disconnect("wait returned status %04x.", status); 1863 } 1864 1865 /* disconnect channel */ 1866 debug("session_exit_message: release channel %d", s->chanid); 1867 channel_cancel_cleanup(s->chanid); 1868 /* 1869 * emulate a write failure with 'chan_write_failed', nobody will be 1870 * interested in data we write. 1871 * Note that we must not call 'chan_read_failed', since there could 1872 * be some more data waiting in the pipe. 1873 */ 1874 if (c->ostate != CHAN_OUTPUT_CLOSED) 1875 chan_write_failed(c); 1876 s->chanid = -1; 1877 } 1878 1879 void 1880 session_close(Session *s) 1881 { 1882 debug("session_close: session %d pid %ld", s->self, (long)s->pid); 1883 if (s->ttyfd != -1) { 1884 fatal_remove_cleanup(session_pty_cleanup, (void *)s); 1885 session_pty_cleanup(s); 1886 } 1887 if (s->term) 1888 xfree(s->term); 1889 if (s->display) 1890 xfree(s->display); 1891 if (s->auth_display) 1892 xfree(s->auth_display); 1893 if (s->auth_data) 1894 xfree(s->auth_data); 1895 if (s->auth_proto) 1896 xfree(s->auth_proto); 1897 s->used = 0; 1898 session_proctitle(s); 1899 } 1900 1901 void 1902 session_close_by_pid(pid_t pid, int status) 1903 { 1904 Session *s = session_by_pid(pid); 1905 if (s == NULL) { 1906 debug("session_close_by_pid: no session for pid %ld", 1907 (long)pid); 1908 return; 1909 } 1910 if (s->chanid != -1) 1911 session_exit_message(s, status); 1912 session_close(s); 1913 } 1914 1915 /* 1916 * this is called when a channel dies before 1917 * the session 'child' itself dies 1918 */ 1919 void 1920 session_close_by_channel(int id, void *arg) 1921 { 1922 Session *s = session_by_channel(id); 1923 if (s == NULL) { 1924 debug("session_close_by_channel: no session for id %d", id); 1925 return; 1926 } 1927 debug("session_close_by_channel: channel %d child %ld", 1928 id, (long)s->pid); 1929 if (s->pid != 0) { 1930 debug("session_close_by_channel: channel %d: has child", id); 1931 /* 1932 * delay detach of session, but release pty, since 1933 * the fd's to the child are already closed 1934 */ 1935 if (s->ttyfd != -1) { 1936 fatal_remove_cleanup(session_pty_cleanup, (void *)s); 1937 session_pty_cleanup(s); 1938 } 1939 return; 1940 } 1941 /* detach by removing callback */ 1942 channel_cancel_cleanup(s->chanid); 1943 s->chanid = -1; 1944 session_close(s); 1945 } 1946 1947 void 1948 session_destroy_all(void (*closefunc)(Session *)) 1949 { 1950 int i; 1951 for (i = 0; i < MAX_SESSIONS; i++) { 1952 Session *s = &sessions[i]; 1953 if (s->used) { 1954 if (closefunc != NULL) 1955 closefunc(s); 1956 else 1957 session_close(s); 1958 } 1959 } 1960 } 1961 1962 static char * 1963 session_tty_list(void) 1964 { 1965 static char buf[1024]; 1966 int i; 1967 buf[0] = '\0'; 1968 for (i = 0; i < MAX_SESSIONS; i++) { 1969 Session *s = &sessions[i]; 1970 if (s->used && s->ttyfd != -1) { 1971 if (buf[0] != '\0') 1972 strlcat(buf, ",", sizeof buf); 1973 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf); 1974 } 1975 } 1976 if (buf[0] == '\0') 1977 strlcpy(buf, "notty", sizeof buf); 1978 return buf; 1979 } 1980 1981 void 1982 session_proctitle(Session *s) 1983 { 1984 if (s->pw == NULL) 1985 error("no user for session %d", s->self); 1986 else 1987 setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); 1988 } 1989 1990 int 1991 session_setup_x11fwd(Session *s) 1992 { 1993 struct stat st; 1994 char display[512], auth_display[512]; 1995 char hostname[MAXHOSTNAMELEN]; 1996 1997 if (no_x11_forwarding_flag) { 1998 packet_send_debug("X11 forwarding disabled in user configuration file."); 1999 return 0; 2000 } 2001 if (!options.x11_forwarding) { 2002 debug("X11 forwarding disabled in server configuration file."); 2003 return 0; 2004 } 2005 if (!options.xauth_location || 2006 (stat(options.xauth_location, &st) == -1)) { 2007 packet_send_debug("No xauth program; cannot forward with spoofing."); 2008 return 0; 2009 } 2010 if (options.use_login) { 2011 packet_send_debug("X11 forwarding disabled; " 2012 "not compatible with UseLogin=yes."); 2013 return 0; 2014 } 2015 if (s->display != NULL) { 2016 debug("X11 display already set."); 2017 return 0; 2018 } 2019 if (x11_create_display_inet(options.x11_display_offset, 2020 options.x11_use_localhost, s->single_connection, 2021 &s->display_number) == -1) { 2022 debug("x11_create_display_inet failed."); 2023 return 0; 2024 } 2025 2026 /* Set up a suitable value for the DISPLAY variable. */ 2027 if (gethostname(hostname, sizeof(hostname)) < 0) 2028 fatal("gethostname: %.100s", strerror(errno)); 2029 /* 2030 * auth_display must be used as the displayname when the 2031 * authorization entry is added with xauth(1). This will be 2032 * different than the DISPLAY string for localhost displays. 2033 */ 2034 if (options.x11_use_localhost) { 2035 snprintf(display, sizeof display, "localhost:%u.%u", 2036 s->display_number, s->screen); 2037 snprintf(auth_display, sizeof auth_display, "unix:%u.%u", 2038 s->display_number, s->screen); 2039 s->display = xstrdup(display); 2040 s->auth_display = xstrdup(auth_display); 2041 } else { 2042 #ifdef IPADDR_IN_DISPLAY 2043 struct hostent *he; 2044 struct in_addr my_addr; 2045 2046 he = gethostbyname(hostname); 2047 if (he == NULL) { 2048 error("Can't get IP address for X11 DISPLAY."); 2049 packet_send_debug("Can't get IP address for X11 DISPLAY."); 2050 return 0; 2051 } 2052 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr)); 2053 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr), 2054 s->display_number, s->screen); 2055 #else 2056 snprintf(display, sizeof display, "%.400s:%u.%u", hostname, 2057 s->display_number, s->screen); 2058 #endif 2059 s->display = xstrdup(display); 2060 s->auth_display = xstrdup(display); 2061 } 2062 2063 return 1; 2064 } 2065 2066 static void 2067 do_authenticated2(Authctxt *authctxt) 2068 { 2069 server_loop2(authctxt); 2070 } 2071