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