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