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