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