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