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