session.c revision 94657
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 94657 2002-04-14 16:24:36Z 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 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, 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(Session *s, const char *shell) 948{ 949 char buf[256]; 950 u_int i, envsize; 951 char **env; 952 struct passwd *pw = s->pw; 953 954 /* Initialize the environment. */ 955 envsize = 100; 956 env = xmalloc(envsize * sizeof(char *)); 957 env[0] = NULL; 958 959 if (!options.use_login) { 960 /* Set basic environment. */ 961 child_set_env(&env, &envsize, "USER", pw->pw_name); 962 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 963 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 964#ifdef HAVE_LOGIN_CAP 965 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH); 966 child_set_env(&env, &envsize, "PATH", getenv("PATH")); 967#else 968 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 969#endif 970 971 snprintf(buf, sizeof buf, "%.200s/%.50s", 972 _PATH_MAILDIR, pw->pw_name); 973 child_set_env(&env, &envsize, "MAIL", buf); 974 975 /* Normal systems set SHELL by default. */ 976 child_set_env(&env, &envsize, "SHELL", shell); 977 } 978 if (getenv("TZ")) 979 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 980 981 /* Set custom environment options from RSA authentication. */ 982 if (!options.use_login) { 983 while (custom_environment) { 984 struct envstring *ce = custom_environment; 985 char *s = ce->s; 986 987 for (i = 0; s[i] != '=' && s[i]; i++) 988 ; 989 if (s[i] == '=') { 990 s[i] = 0; 991 child_set_env(&env, &envsize, s, s + i + 1); 992 } 993 custom_environment = ce->next; 994 xfree(ce->s); 995 xfree(ce); 996 } 997 } 998 999 snprintf(buf, sizeof buf, "%.50s %d %d", 1000 get_remote_ipaddr(), get_remote_port(), get_local_port()); 1001 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 1002 1003 if (s->ttyfd != -1) 1004 child_set_env(&env, &envsize, "SSH_TTY", s->tty); 1005 if (s->term) 1006 child_set_env(&env, &envsize, "TERM", s->term); 1007 if (s->display) 1008 child_set_env(&env, &envsize, "DISPLAY", s->display); 1009 if (original_command) 1010 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND", 1011 original_command); 1012#ifdef KRB4 1013 if (s->authctxt->krb4_ticket_file) 1014 child_set_env(&env, &envsize, "KRBTKFILE", 1015 s->authctxt->krb4_ticket_file); 1016#endif 1017#ifdef KRB5 1018 if (s->authctxt->krb5_ticket_file) 1019 child_set_env(&env, &envsize, "KRB5CCNAME", 1020 s->authctxt->krb5_ticket_file); 1021#endif 1022 1023#ifdef USE_PAM 1024 /* Pull in any environment variables that may have been set by PAM. */ 1025 do_pam_environment(&env, &envsize); 1026#endif /* USE_PAM */ 1027 1028 if (auth_get_socket_name() != NULL) 1029 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 1030 auth_get_socket_name()); 1031 1032 /* read $HOME/.ssh/environment. */ 1033 if (!options.use_login) { 1034 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", 1035 pw->pw_dir); 1036 read_environment_file(&env, &envsize, buf); 1037 } 1038 if (debug_flag) { 1039 /* dump the environment */ 1040 fprintf(stderr, "Environment:\n"); 1041 for (i = 0; env[i]; i++) 1042 fprintf(stderr, " %.200s\n", env[i]); 1043 } 1044 return env; 1045} 1046 1047/* 1048 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found 1049 * first in this order). 1050 */ 1051static void 1052do_rc_files(Session *s, const char *shell) 1053{ 1054 FILE *f = NULL; 1055 char cmd[1024]; 1056 int do_xauth; 1057 struct stat st; 1058 1059 do_xauth = 1060 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL; 1061 1062 /* ignore _PATH_SSH_USER_RC for subsystems */ 1063 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) { 1064 snprintf(cmd, sizeof cmd, "%s -c '%s %s'", 1065 shell, _PATH_BSHELL, _PATH_SSH_USER_RC); 1066 if (debug_flag) 1067 fprintf(stderr, "Running %s\n", cmd); 1068 f = popen(cmd, "w"); 1069 if (f) { 1070 if (do_xauth) 1071 fprintf(f, "%s %s\n", s->auth_proto, 1072 s->auth_data); 1073 pclose(f); 1074 } else 1075 fprintf(stderr, "Could not run %s\n", 1076 _PATH_SSH_USER_RC); 1077 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) { 1078 if (debug_flag) 1079 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, 1080 _PATH_SSH_SYSTEM_RC); 1081 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w"); 1082 if (f) { 1083 if (do_xauth) 1084 fprintf(f, "%s %s\n", s->auth_proto, 1085 s->auth_data); 1086 pclose(f); 1087 } else 1088 fprintf(stderr, "Could not run %s\n", 1089 _PATH_SSH_SYSTEM_RC); 1090 } else if (do_xauth && options.xauth_location != NULL) { 1091 /* Add authority data to .Xauthority if appropriate. */ 1092 if (debug_flag) { 1093 fprintf(stderr, 1094 "Running %.100s add " 1095 "%.100s %.100s %.100s\n", 1096 options.xauth_location, s->auth_display, 1097 s->auth_proto, s->auth_data); 1098 } 1099 snprintf(cmd, sizeof cmd, "%s -q -", 1100 options.xauth_location); 1101 f = popen(cmd, "w"); 1102 if (f) { 1103 fprintf(f, "add %s %s %s\n", 1104 s->auth_display, s->auth_proto, 1105 s->auth_data); 1106 pclose(f); 1107 } else { 1108 fprintf(stderr, "Could not run %s\n", 1109 cmd); 1110 } 1111 } 1112} 1113 1114static void 1115do_nologin(struct passwd *pw) 1116{ 1117 FILE *f = NULL; 1118 char buf[1024]; 1119 1120#ifdef HAVE_LOGIN_CAP 1121 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid) 1122 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN, 1123 _PATH_NOLOGIN), "r"); 1124#else 1125 if (pw->pw_uid) 1126 f = fopen(_PATH_NOLOGIN, "r"); 1127#endif 1128 if (f) { 1129 /* /etc/nologin exists. Print its contents and exit. */ 1130 while (fgets(buf, sizeof(buf), f)) 1131 fputs(buf, stderr); 1132 fclose(f); 1133 exit(254); 1134 } 1135} 1136 1137/* Set login name, uid, gid, and groups. */ 1138static void 1139do_setusercontext(struct passwd *pw) 1140{ 1141 if (getuid() == 0 || geteuid() == 0) { 1142#ifdef HAVE_LOGIN_CAP 1143 if (setusercontext(lc, pw, pw->pw_uid, 1144 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) { 1145 perror("unable to set user context"); 1146 exit(1); 1147 } 1148#else 1149 if (setlogin(pw->pw_name) < 0) 1150 error("setlogin failed: %s", strerror(errno)); 1151 if (setgid(pw->pw_gid) < 0) { 1152 perror("setgid"); 1153 exit(1); 1154 } 1155 /* Initialize the group list. */ 1156 if (initgroups(pw->pw_name, pw->pw_gid) < 0) { 1157 perror("initgroups"); 1158 exit(1); 1159 } 1160 endgrent(); 1161 1162 /* Permanently switch to the desired uid. */ 1163 permanently_set_uid(pw); 1164#endif 1165 } 1166 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 1167 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); 1168} 1169 1170/* 1171 * Performs common processing for the child, such as setting up the 1172 * environment, closing extra file descriptors, setting the user and group 1173 * ids, and executing the command or shell. 1174 */ 1175void 1176do_child(Session *s, const char *command) 1177{ 1178 extern char **environ; 1179 char **env; 1180 char *argv[10]; 1181 const char *shell, *shell0, *hostname = NULL; 1182 struct passwd *pw = s->pw; 1183 u_int i; 1184 1185 /* remove hostkey from the child's memory */ 1186 destroy_sensitive_data(); 1187 1188 /* login(1) is only called if we execute the login shell */ 1189 if (options.use_login && command != NULL) 1190 options.use_login = 0; 1191 1192 /* 1193 * Login(1) does this as well, and it needs uid 0 for the "-h" 1194 * switch, so we let login(1) to this for us. 1195 */ 1196 if (!options.use_login) { 1197 do_nologin(pw); 1198 do_setusercontext(pw); 1199 } 1200 1201 /* 1202 * Get the shell from the password data. An empty shell field is 1203 * legal, and means /bin/sh. 1204 */ 1205 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 1206#ifdef HAVE_LOGIN_CAP 1207 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); 1208#endif 1209 1210 env = do_setup_env(s, shell); 1211 1212 /* we have to stash the hostname before we close our socket. */ 1213 if (options.use_login) 1214 hostname = get_remote_name_or_ip(utmp_len, 1215 options.verify_reverse_mapping); 1216 /* 1217 * Close the connection descriptors; note that this is the child, and 1218 * the server will still have the socket open, and it is important 1219 * that we do not shutdown it. Note that the descriptors cannot be 1220 * closed before building the environment, as we call 1221 * get_remote_ipaddr there. 1222 */ 1223 if (packet_get_connection_in() == packet_get_connection_out()) 1224 close(packet_get_connection_in()); 1225 else { 1226 close(packet_get_connection_in()); 1227 close(packet_get_connection_out()); 1228 } 1229 /* 1230 * Close all descriptors related to channels. They will still remain 1231 * open in the parent. 1232 */ 1233 /* XXX better use close-on-exec? -markus */ 1234 channel_close_all(); 1235 1236 /* 1237 * Close any extra file descriptors. Note that there may still be 1238 * descriptors left by system functions. They will be closed later. 1239 */ 1240 endpwent(); 1241 1242 /* 1243 * Close any extra open file descriptors so that we don\'t have them 1244 * hanging around in clients. Note that we want to do this after 1245 * initgroups, because at least on Solaris 2.3 it leaves file 1246 * descriptors open. 1247 */ 1248 for (i = 3; i < getdtablesize(); i++) 1249 close(i); 1250 1251 /* 1252 * Must take new environment into use so that .ssh/rc, 1253 * /etc/ssh/sshrc and xauth are run in the proper environment. 1254 */ 1255 environ = env; 1256 1257#ifdef AFS 1258 /* Try to get AFS tokens for the local cell. */ 1259 if (k_hasafs()) { 1260 char cell[64]; 1261 1262 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 1263 krb_afslog(cell, 0); 1264 1265 krb_afslog(0, 0); 1266 } 1267#endif /* AFS */ 1268 1269 /* Change current directory to the user\'s home directory. */ 1270 if (chdir(pw->pw_dir) < 0) { 1271 fprintf(stderr, "Could not chdir to home directory %s: %s\n", 1272 pw->pw_dir, strerror(errno)); 1273#ifdef HAVE_LOGIN_CAP 1274 if (login_getcapbool(lc, "requirehome", 0)) 1275 exit(1); 1276#endif 1277 } 1278 1279 if (!options.use_login) 1280 do_rc_files(s, shell); 1281 1282 /* restore SIGPIPE for child */ 1283 signal(SIGPIPE, SIG_DFL); 1284 1285 if (options.use_login) { 1286 /* Launch login(1). */ 1287 1288 execl("/usr/bin/login", "login", "-h", hostname, 1289 "-p", "-f", "--", pw->pw_name, (char *)NULL); 1290 1291 /* Login couldn't be executed, die. */ 1292 1293 perror("login"); 1294 exit(1); 1295 } 1296 1297 /* Get the last component of the shell name. */ 1298 if ((shell0 = strrchr(shell, '/')) != NULL) 1299 shell0++; 1300 else 1301 shell0 = shell; 1302 1303 /* 1304 * If we have no command, execute the shell. In this case, the shell 1305 * name to be passed in argv[0] is preceded by '-' to indicate that 1306 * this is a login shell. 1307 */ 1308 if (!command) { 1309 char argv0[256]; 1310 1311 /* Start the shell. Set initial character to '-'. */ 1312 argv0[0] = '-'; 1313 1314 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) 1315 >= sizeof(argv0) - 1) { 1316 errno = EINVAL; 1317 perror(shell); 1318 exit(1); 1319 } 1320 1321 /* Execute the shell. */ 1322 argv[0] = argv0; 1323 argv[1] = NULL; 1324 execve(shell, argv, env); 1325 1326 /* Executing the shell failed. */ 1327 perror(shell); 1328 exit(1); 1329 } 1330 /* 1331 * Execute the command using the user's shell. This uses the -c 1332 * option to execute the command. 1333 */ 1334 argv[0] = (char *) shell0; 1335 argv[1] = "-c"; 1336 argv[2] = (char *) command; 1337 argv[3] = NULL; 1338 execve(shell, argv, env); 1339 perror(shell); 1340 exit(1); 1341} 1342 1343Session * 1344session_new(void) 1345{ 1346 int i; 1347 static int did_init = 0; 1348 if (!did_init) { 1349 debug("session_new: init"); 1350 for (i = 0; i < MAX_SESSIONS; i++) { 1351 sessions[i].used = 0; 1352 } 1353 did_init = 1; 1354 } 1355 for (i = 0; i < MAX_SESSIONS; i++) { 1356 Session *s = &sessions[i]; 1357 if (! s->used) { 1358 memset(s, 0, sizeof(*s)); 1359 s->chanid = -1; 1360 s->ptyfd = -1; 1361 s->ttyfd = -1; 1362 s->used = 1; 1363 s->self = i; 1364 debug("session_new: session %d", i); 1365 return s; 1366 } 1367 } 1368 return NULL; 1369} 1370 1371static void 1372session_dump(void) 1373{ 1374 int i; 1375 for (i = 0; i < MAX_SESSIONS; i++) { 1376 Session *s = &sessions[i]; 1377 debug("dump: used %d session %d %p channel %d pid %d", 1378 s->used, 1379 s->self, 1380 s, 1381 s->chanid, 1382 s->pid); 1383 } 1384} 1385 1386int 1387session_open(Authctxt *authctxt, int chanid) 1388{ 1389 Session *s = session_new(); 1390 debug("session_open: channel %d", chanid); 1391 if (s == NULL) { 1392 error("no more sessions"); 1393 return 0; 1394 } 1395 s->authctxt = authctxt; 1396 s->pw = authctxt->pw; 1397 if (s->pw == NULL) 1398 fatal("no user for session %d", s->self); 1399 debug("session_open: session %d: link with channel %d", s->self, chanid); 1400 s->chanid = chanid; 1401 return 1; 1402} 1403 1404static Session * 1405session_by_channel(int id) 1406{ 1407 int i; 1408 for (i = 0; i < MAX_SESSIONS; i++) { 1409 Session *s = &sessions[i]; 1410 if (s->used && s->chanid == id) { 1411 debug("session_by_channel: session %d channel %d", i, id); 1412 return s; 1413 } 1414 } 1415 debug("session_by_channel: unknown channel %d", id); 1416 session_dump(); 1417 return NULL; 1418} 1419 1420static Session * 1421session_by_pid(pid_t pid) 1422{ 1423 int i; 1424 debug("session_by_pid: pid %d", pid); 1425 for (i = 0; i < MAX_SESSIONS; i++) { 1426 Session *s = &sessions[i]; 1427 if (s->used && s->pid == pid) 1428 return s; 1429 } 1430 error("session_by_pid: unknown pid %d", pid); 1431 session_dump(); 1432 return NULL; 1433} 1434 1435static int 1436session_window_change_req(Session *s) 1437{ 1438 s->col = packet_get_int(); 1439 s->row = packet_get_int(); 1440 s->xpixel = packet_get_int(); 1441 s->ypixel = packet_get_int(); 1442 packet_check_eom(); 1443 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1444 return 1; 1445} 1446 1447static int 1448session_pty_req(Session *s) 1449{ 1450 u_int len; 1451 int n_bytes; 1452 1453 if (no_pty_flag) { 1454 debug("Allocating a pty not permitted for this authentication."); 1455 return 0; 1456 } 1457 if (s->ttyfd != -1) { 1458 packet_disconnect("Protocol error: you already have a pty."); 1459 return 0; 1460 } 1461 1462 s->term = packet_get_string(&len); 1463 1464 if (compat20) { 1465 s->col = packet_get_int(); 1466 s->row = packet_get_int(); 1467 } else { 1468 s->row = packet_get_int(); 1469 s->col = packet_get_int(); 1470 } 1471 s->xpixel = packet_get_int(); 1472 s->ypixel = packet_get_int(); 1473 1474 if (strcmp(s->term, "") == 0) { 1475 xfree(s->term); 1476 s->term = NULL; 1477 } 1478 1479 /* Allocate a pty and open it. */ 1480 debug("Allocating pty."); 1481 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) { 1482 if (s->term) 1483 xfree(s->term); 1484 s->term = NULL; 1485 s->ptyfd = -1; 1486 s->ttyfd = -1; 1487 error("session_pty_req: session %d alloc failed", s->self); 1488 return 0; 1489 } 1490 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 1491 1492 /* for SSH1 the tty modes length is not given */ 1493 if (!compat20) 1494 n_bytes = packet_remaining(); 1495 tty_parse_modes(s->ttyfd, &n_bytes); 1496 1497 /* 1498 * Add a cleanup function to clear the utmp entry and record logout 1499 * time in case we call fatal() (e.g., the connection gets closed). 1500 */ 1501 fatal_add_cleanup(session_pty_cleanup, (void *)s); 1502 pty_setowner(s->pw, s->tty); 1503 1504 /* Set window size from the packet. */ 1505 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1506 1507 packet_check_eom(); 1508 session_proctitle(s); 1509 return 1; 1510} 1511 1512static int 1513session_subsystem_req(Session *s) 1514{ 1515 struct stat st; 1516 u_int len; 1517 int success = 0; 1518 char *cmd, *subsys = packet_get_string(&len); 1519 int i; 1520 1521 packet_check_eom(); 1522 log("subsystem request for %.100s", subsys); 1523 1524 for (i = 0; i < options.num_subsystems; i++) { 1525 if (strcmp(subsys, options.subsystem_name[i]) == 0) { 1526 cmd = options.subsystem_command[i]; 1527 if (stat(cmd, &st) < 0) { 1528 error("subsystem: cannot stat %s: %s", cmd, 1529 strerror(errno)); 1530 break; 1531 } 1532 debug("subsystem: exec() %s", cmd); 1533 s->is_subsystem = 1; 1534 do_exec(s, cmd); 1535 success = 1; 1536 break; 1537 } 1538 } 1539 1540 if (!success) 1541 log("subsystem request for %.100s failed, subsystem not found", 1542 subsys); 1543 1544 xfree(subsys); 1545 return success; 1546} 1547 1548static int 1549session_x11_req(Session *s) 1550{ 1551 int success; 1552 1553 s->single_connection = packet_get_char(); 1554 s->auth_proto = packet_get_string(NULL); 1555 s->auth_data = packet_get_string(NULL); 1556 s->screen = packet_get_int(); 1557 packet_check_eom(); 1558 1559 success = session_setup_x11fwd(s); 1560 if (!success) { 1561 xfree(s->auth_proto); 1562 xfree(s->auth_data); 1563 s->auth_proto = NULL; 1564 s->auth_data = NULL; 1565 } 1566 return success; 1567} 1568 1569static int 1570session_shell_req(Session *s) 1571{ 1572 packet_check_eom(); 1573 do_exec(s, NULL); 1574 return 1; 1575} 1576 1577static int 1578session_exec_req(Session *s) 1579{ 1580 u_int len; 1581 char *command = packet_get_string(&len); 1582 packet_check_eom(); 1583 do_exec(s, command); 1584 xfree(command); 1585 return 1; 1586} 1587 1588static int 1589session_auth_agent_req(Session *s) 1590{ 1591 static int called = 0; 1592 packet_check_eom(); 1593 if (no_agent_forwarding_flag) { 1594 debug("session_auth_agent_req: no_agent_forwarding_flag"); 1595 return 0; 1596 } 1597 if (called) { 1598 return 0; 1599 } else { 1600 called = 1; 1601 return auth_input_request_forwarding(s->pw); 1602 } 1603} 1604 1605int 1606session_input_channel_req(Channel *c, const char *rtype) 1607{ 1608 int success = 0; 1609 Session *s; 1610 1611 if ((s = session_by_channel(c->self)) == NULL) { 1612 log("session_input_channel_req: no session %d req %.100s", 1613 c->self, rtype); 1614 return 0; 1615 } 1616 debug("session_input_channel_req: session %d req %s", s->self, rtype); 1617 1618 /* 1619 * a session is in LARVAL state until a shell, a command 1620 * or a subsystem is executed 1621 */ 1622 if (c->type == SSH_CHANNEL_LARVAL) { 1623 if (strcmp(rtype, "shell") == 0) { 1624 success = session_shell_req(s); 1625 } else if (strcmp(rtype, "exec") == 0) { 1626 success = session_exec_req(s); 1627 } else if (strcmp(rtype, "pty-req") == 0) { 1628 success = session_pty_req(s); 1629 } else if (strcmp(rtype, "x11-req") == 0) { 1630 success = session_x11_req(s); 1631 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) { 1632 success = session_auth_agent_req(s); 1633 } else if (strcmp(rtype, "subsystem") == 0) { 1634 success = session_subsystem_req(s); 1635 } 1636 } 1637 if (strcmp(rtype, "window-change") == 0) { 1638 success = session_window_change_req(s); 1639 } 1640 return success; 1641} 1642 1643void 1644session_set_fds(Session *s, int fdin, int fdout, int fderr) 1645{ 1646 if (!compat20) 1647 fatal("session_set_fds: called for proto != 2.0"); 1648 /* 1649 * now that have a child and a pipe to the child, 1650 * we can activate our channel and register the fd's 1651 */ 1652 if (s->chanid == -1) 1653 fatal("no channel for session %d", s->self); 1654 channel_set_fds(s->chanid, 1655 fdout, fdin, fderr, 1656 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ, 1657 1, 1658 CHAN_SES_WINDOW_DEFAULT); 1659} 1660 1661/* 1662 * Function to perform pty cleanup. Also called if we get aborted abnormally 1663 * (e.g., due to a dropped connection). 1664 */ 1665static void 1666session_pty_cleanup(void *session) 1667{ 1668 Session *s = session; 1669 1670 if (s == NULL) { 1671 error("session_pty_cleanup: no session"); 1672 return; 1673 } 1674 if (s->ttyfd == -1) 1675 return; 1676 1677 debug("session_pty_cleanup: session %d release %s", s->self, s->tty); 1678 1679 /* Record that the user has logged out. */ 1680 if (s->pid != 0) 1681 record_logout(s->pid, s->tty); 1682 1683 /* Release the pseudo-tty. */ 1684 pty_release(s->tty); 1685 1686 /* 1687 * Close the server side of the socket pairs. We must do this after 1688 * the pty cleanup, so that another process doesn't get this pty 1689 * while we're still cleaning up. 1690 */ 1691 if (close(s->ptymaster) < 0) 1692 error("close(s->ptymaster): %s", strerror(errno)); 1693 1694 /* unlink pty from session */ 1695 s->ttyfd = -1; 1696} 1697 1698static void 1699session_exit_message(Session *s, int status) 1700{ 1701 Channel *c; 1702 1703 if ((c = channel_lookup(s->chanid)) == NULL) 1704 fatal("session_exit_message: session %d: no channel %d", 1705 s->self, s->chanid); 1706 debug("session_exit_message: session %d channel %d pid %d", 1707 s->self, s->chanid, s->pid); 1708 1709 if (WIFEXITED(status)) { 1710 channel_request_start(s->chanid, "exit-status", 0); 1711 packet_put_int(WEXITSTATUS(status)); 1712 packet_send(); 1713 } else if (WIFSIGNALED(status)) { 1714 channel_request_start(s->chanid, "exit-signal", 0); 1715 packet_put_int(WTERMSIG(status)); 1716 packet_put_char(WCOREDUMP(status)); 1717 packet_put_cstring(""); 1718 packet_put_cstring(""); 1719 packet_send(); 1720 } else { 1721 /* Some weird exit cause. Just exit. */ 1722 packet_disconnect("wait returned status %04x.", status); 1723 } 1724 1725 /* disconnect channel */ 1726 debug("session_exit_message: release channel %d", s->chanid); 1727 channel_cancel_cleanup(s->chanid); 1728 /* 1729 * emulate a write failure with 'chan_write_failed', nobody will be 1730 * interested in data we write. 1731 * Note that we must not call 'chan_read_failed', since there could 1732 * be some more data waiting in the pipe. 1733 */ 1734 if (c->ostate != CHAN_OUTPUT_CLOSED) 1735 chan_write_failed(c); 1736 s->chanid = -1; 1737} 1738 1739static void 1740session_close(Session *s) 1741{ 1742 debug("session_close: session %d pid %d", s->self, s->pid); 1743 if (s->ttyfd != -1) { 1744 fatal_remove_cleanup(session_pty_cleanup, (void *)s); 1745 session_pty_cleanup(s); 1746 } 1747 if (s->term) 1748 xfree(s->term); 1749 if (s->display) 1750 xfree(s->display); 1751 if (s->auth_display) 1752 xfree(s->auth_display); 1753 if (s->auth_data) 1754 xfree(s->auth_data); 1755 if (s->auth_proto) 1756 xfree(s->auth_proto); 1757 s->used = 0; 1758 session_proctitle(s); 1759} 1760 1761void 1762session_close_by_pid(pid_t pid, int status) 1763{ 1764 Session *s = session_by_pid(pid); 1765 if (s == NULL) { 1766 debug("session_close_by_pid: no session for pid %d", pid); 1767 return; 1768 } 1769 if (s->chanid != -1) 1770 session_exit_message(s, status); 1771 session_close(s); 1772} 1773 1774/* 1775 * this is called when a channel dies before 1776 * the session 'child' itself dies 1777 */ 1778void 1779session_close_by_channel(int id, void *arg) 1780{ 1781 Session *s = session_by_channel(id); 1782 if (s == NULL) { 1783 debug("session_close_by_channel: no session for id %d", id); 1784 return; 1785 } 1786 debug("session_close_by_channel: channel %d child %d", id, s->pid); 1787 if (s->pid != 0) { 1788 debug("session_close_by_channel: channel %d: has child", id); 1789 /* 1790 * delay detach of session, but release pty, since 1791 * the fd's to the child are already closed 1792 */ 1793 if (s->ttyfd != -1) { 1794 fatal_remove_cleanup(session_pty_cleanup, (void *)s); 1795 session_pty_cleanup(s); 1796 } 1797 return; 1798 } 1799 /* detach by removing callback */ 1800 channel_cancel_cleanup(s->chanid); 1801 s->chanid = -1; 1802 session_close(s); 1803} 1804 1805void 1806session_destroy_all(void) 1807{ 1808 int i; 1809 for (i = 0; i < MAX_SESSIONS; i++) { 1810 Session *s = &sessions[i]; 1811 if (s->used) 1812 session_close(s); 1813 } 1814} 1815 1816static char * 1817session_tty_list(void) 1818{ 1819 static char buf[1024]; 1820 int i; 1821 buf[0] = '\0'; 1822 for (i = 0; i < MAX_SESSIONS; i++) { 1823 Session *s = &sessions[i]; 1824 if (s->used && s->ttyfd != -1) { 1825 if (buf[0] != '\0') 1826 strlcat(buf, ",", sizeof buf); 1827 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf); 1828 } 1829 } 1830 if (buf[0] == '\0') 1831 strlcpy(buf, "notty", sizeof buf); 1832 return buf; 1833} 1834 1835void 1836session_proctitle(Session *s) 1837{ 1838 if (s->pw == NULL) 1839 error("no user for session %d", s->self); 1840 else 1841 setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); 1842} 1843 1844int 1845session_setup_x11fwd(Session *s) 1846{ 1847 struct stat st; 1848 char display[512], auth_display[512]; 1849 char hostname[MAXHOSTNAMELEN]; 1850 1851 if (no_x11_forwarding_flag) { 1852 packet_send_debug("X11 forwarding disabled in user configuration file."); 1853 return 0; 1854 } 1855 if (!options.x11_forwarding) { 1856 debug("X11 forwarding disabled in server configuration file."); 1857 return 0; 1858 } 1859 if (!options.xauth_location || 1860 (stat(options.xauth_location, &st) == -1)) { 1861 packet_send_debug("No xauth program; cannot forward with spoofing."); 1862 return 0; 1863 } 1864 if (options.use_login) { 1865 packet_send_debug("X11 forwarding disabled; " 1866 "not compatible with UseLogin=yes."); 1867 return 0; 1868 } 1869 if (s->display != NULL) { 1870 debug("X11 display already set."); 1871 return 0; 1872 } 1873 s->display_number = x11_create_display_inet(options.x11_display_offset, 1874 options.x11_use_localhost, s->single_connection); 1875 if (s->display_number == -1) { 1876 debug("x11_create_display_inet failed."); 1877 return 0; 1878 } 1879 1880 /* Set up a suitable value for the DISPLAY variable. */ 1881 if (gethostname(hostname, sizeof(hostname)) < 0) 1882 fatal("gethostname: %.100s", strerror(errno)); 1883 /* 1884 * auth_display must be used as the displayname when the 1885 * authorization entry is added with xauth(1). This will be 1886 * different than the DISPLAY string for localhost displays. 1887 */ 1888 if (options.x11_use_localhost) { 1889 snprintf(display, sizeof display, "localhost:%d.%d", 1890 s->display_number, s->screen); 1891 snprintf(auth_display, sizeof auth_display, "unix:%d.%d", 1892 s->display_number, s->screen); 1893 s->display = xstrdup(display); 1894 s->auth_display = xstrdup(auth_display); 1895 } else { 1896 snprintf(display, sizeof display, "%.400s:%d.%d", hostname, 1897 s->display_number, s->screen); 1898 s->display = xstrdup(display); 1899 s->auth_display = xstrdup(display); 1900 } 1901 1902 return 1; 1903} 1904 1905static void 1906do_authenticated2(Authctxt *authctxt) 1907{ 1908 server_loop2(authctxt); 1909} 1910