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