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.172 2004/01/30 09:48:57 markus 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 "mpaux.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 child_set_env(&env, &envsize, "USER", pw->pw_name); 797 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 798 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 799 #ifdef HAVE_LOGIN_CAP 800 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0) 801 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 802 else 803 child_set_env(&env, &envsize, "PATH", getenv("PATH")); 804 #else 805 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 806 #endif 807 808 snprintf(buf, sizeof buf, "%.200s/%.50s", 809 _PATH_MAILDIR, pw->pw_name); 810 child_set_env(&env, &envsize, "MAIL", buf); 811 812 /* Normal systems set SHELL by default. */ 813 child_set_env(&env, &envsize, "SHELL", shell); 814 } 815 if (getenv("TZ")) 816 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 817 818 /* Set custom environment options from RSA authentication. */ 819 if (!options.use_login) { 820 while (custom_environment) { 821 struct envstring *ce = custom_environment; 822 char *str = ce->s; 823 824 for (i = 0; str[i] != '=' && str[i]; i++) 825 ; 826 if (str[i] == '=') { 827 str[i] = 0; 828 child_set_env(&env, &envsize, str, str + i + 1); 829 } 830 custom_environment = ce->next; 831 xfree(ce->s); 832 xfree(ce); 833 } 834 } 835 836 /* SSH_CLIENT deprecated */ 837 snprintf(buf, sizeof buf, "%.50s %d %d", 838 get_remote_ipaddr(), get_remote_port(), get_local_port()); 839 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 840 841 laddr = get_local_ipaddr(packet_get_connection_in()); 842 snprintf(buf, sizeof buf, "%.50s %d %.50s %d", 843 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port()); 844 xfree(laddr); 845 child_set_env(&env, &envsize, "SSH_CONNECTION", buf); 846 847 if (s->ttyfd != -1) 848 child_set_env(&env, &envsize, "SSH_TTY", s->tty); 849 if (s->term) 850 child_set_env(&env, &envsize, "TERM", s->term); 851 if (s->display) 852 child_set_env(&env, &envsize, "DISPLAY", s->display); 853 if (original_command) 854 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND", 855 original_command); 856 #ifdef KRB5 857 if (s->authctxt->krb5_ticket_file) 858 child_set_env(&env, &envsize, "KRB5CCNAME", 859 s->authctxt->krb5_ticket_file); 860 #endif 861 if (auth_sock_name != NULL) 862 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 863 auth_sock_name); 864 865 /* read $HOME/.ssh/environment. */ 866 if (options.permit_user_env && !options.use_login) { 867 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", 868 pw->pw_dir); 869 read_environment_file(&env, &envsize, buf); 870 } 871 if (debug_flag) { 872 /* dump the environment */ 873 fprintf(stderr, "Environment:\n"); 874 for (i = 0; env[i]; i++) 875 fprintf(stderr, " %.200s\n", env[i]); 876 } 877 return env; 878 } 879 880 /* 881 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found 882 * first in this order). 883 */ 884 static void 885 do_rc_files(Session *s, const char *shell) 886 { 887 FILE *f = NULL; 888 char cmd[1024]; 889 int do_xauth; 890 struct stat st; 891 892 do_xauth = 893 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL; 894 895 /* ignore _PATH_SSH_USER_RC for subsystems */ 896 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) { 897 snprintf(cmd, sizeof cmd, "%s -c '%s %s'", 898 shell, _PATH_BSHELL, _PATH_SSH_USER_RC); 899 if (debug_flag) 900 fprintf(stderr, "Running %s\n", cmd); 901 f = popen(cmd, "w"); 902 if (f) { 903 if (do_xauth) 904 fprintf(f, "%s %s\n", s->auth_proto, 905 s->auth_data); 906 pclose(f); 907 } else 908 fprintf(stderr, "Could not run %s\n", 909 _PATH_SSH_USER_RC); 910 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) { 911 if (debug_flag) 912 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, 913 _PATH_SSH_SYSTEM_RC); 914 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w"); 915 if (f) { 916 if (do_xauth) 917 fprintf(f, "%s %s\n", s->auth_proto, 918 s->auth_data); 919 pclose(f); 920 } else 921 fprintf(stderr, "Could not run %s\n", 922 _PATH_SSH_SYSTEM_RC); 923 } else if (do_xauth && options.xauth_location != NULL) { 924 /* Add authority data to .Xauthority if appropriate. */ 925 if (debug_flag) { 926 fprintf(stderr, 927 "Running %.500s remove %.100s\n", 928 options.xauth_location, s->auth_display); 929 fprintf(stderr, 930 "%.500s add %.100s %.100s %.100s\n", 931 options.xauth_location, s->auth_display, 932 s->auth_proto, s->auth_data); 933 } 934 snprintf(cmd, sizeof cmd, "%s -q -", 935 options.xauth_location); 936 f = popen(cmd, "w"); 937 if (f) { 938 fprintf(f, "remove %s\n", 939 s->auth_display); 940 fprintf(f, "add %s %s %s\n", 941 s->auth_display, s->auth_proto, 942 s->auth_data); 943 pclose(f); 944 } else { 945 fprintf(stderr, "Could not run %s\n", 946 cmd); 947 } 948 } 949 } 950 951 static void 952 do_nologin(struct passwd *pw) 953 { 954 FILE *f = NULL; 955 char buf[1024]; 956 957 #ifdef HAVE_LOGIN_CAP 958 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid) 959 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN, 960 _PATH_NOLOGIN), "r"); 961 #else 962 if (pw->pw_uid) 963 f = fopen(_PATH_NOLOGIN, "r"); 964 #endif 965 if (f) { 966 /* /etc/nologin exists. Print its contents and exit. */ 967 logit("User %.100s not allowed because %s exists", 968 pw->pw_name, _PATH_NOLOGIN); 969 while (fgets(buf, sizeof(buf), f)) 970 fputs(buf, stderr); 971 fclose(f); 972 exit(254); 973 } 974 } 975 976 /* Set login name, uid, gid, and groups. */ 977 void 978 do_setusercontext(struct passwd *pw) 979 { 980 if (getuid() == 0 || geteuid() == 0) { 981 #ifdef HAVE_LOGIN_CAP 982 if (setusercontext(lc, pw, pw->pw_uid, 983 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) { 984 perror("unable to set user context"); 985 exit(1); 986 } 987 #else 988 if (setlogin(pw->pw_name) < 0) 989 error("setlogin failed: %s", strerror(errno)); 990 if (setgid(pw->pw_gid) < 0) { 991 perror("setgid"); 992 exit(1); 993 } 994 /* Initialize the group list. */ 995 if (initgroups(pw->pw_name, pw->pw_gid) < 0) { 996 perror("initgroups"); 997 exit(1); 998 } 999 endgrent(); 1000 1001 /* Permanently switch to the desired uid. */ 1002 permanently_set_uid(pw); 1003 #endif 1004 } 1005 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 1006 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); 1007 } 1008 1009 static void 1010 do_pwchange(Session *s) 1011 { 1012 fprintf(stderr, "WARNING: Your password has expired.\n"); 1013 if (s->ttyfd != -1) { 1014 fprintf(stderr, 1015 "You must change your password now and login again!\n"); 1016 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL); 1017 perror("passwd"); 1018 } else { 1019 fprintf(stderr, 1020 "Password change required but no TTY available.\n"); 1021 } 1022 exit(1); 1023 } 1024 1025 static void 1026 launch_login(struct passwd *pw, const char *hostname) 1027 { 1028 /* Launch login(1). */ 1029 1030 execl("/usr/bin/login", "login", "-h", hostname, 1031 "-p", "-f", "--", pw->pw_name, (char *)NULL); 1032 1033 /* Login couldn't be executed, die. */ 1034 1035 perror("login"); 1036 exit(1); 1037 } 1038 1039 static void 1040 child_close_fds(void) 1041 { 1042 int i; 1043 1044 if (packet_get_connection_in() == packet_get_connection_out()) 1045 close(packet_get_connection_in()); 1046 else { 1047 close(packet_get_connection_in()); 1048 close(packet_get_connection_out()); 1049 } 1050 /* 1051 * Close all descriptors related to channels. They will still remain 1052 * open in the parent. 1053 */ 1054 /* XXX better use close-on-exec? -markus */ 1055 channel_close_all(); 1056 1057 /* 1058 * Close any extra file descriptors. Note that there may still be 1059 * descriptors left by system functions. They will be closed later. 1060 */ 1061 endpwent(); 1062 1063 /* 1064 * Close any extra open file descriptors so that we don\'t have them 1065 * hanging around in clients. Note that we want to do this after 1066 * initgroups, because at least on Solaris 2.3 it leaves file 1067 * descriptors open. 1068 */ 1069 for (i = 3; i < 64; i++) 1070 close(i); 1071 } 1072 1073 /* 1074 * Performs common processing for the child, such as setting up the 1075 * environment, closing extra file descriptors, setting the user and group 1076 * ids, and executing the command or shell. 1077 */ 1078 void 1079 do_child(Session *s, const char *command) 1080 { 1081 extern char **environ; 1082 char **env; 1083 char *argv[10]; 1084 const char *shell, *shell0, *hostname = NULL; 1085 struct passwd *pw = s->pw; 1086 1087 /* remove hostkey from the child's memory */ 1088 destroy_sensitive_data(); 1089 1090 /* Force a password change */ 1091 if (s->authctxt->force_pwchange) { 1092 do_setusercontext(pw); 1093 child_close_fds(); 1094 do_pwchange(s); 1095 exit(1); 1096 } 1097 1098 /* login(1) is only called if we execute the login shell */ 1099 if (options.use_login && command != NULL) 1100 options.use_login = 0; 1101 1102 /* 1103 * Login(1) does this as well, and it needs uid 0 for the "-h" 1104 * switch, so we let login(1) to this for us. 1105 */ 1106 if (!options.use_login) { 1107 do_nologin(pw); 1108 do_setusercontext(pw); 1109 } 1110 1111 /* 1112 * Get the shell from the password data. An empty shell field is 1113 * legal, and means /bin/sh. 1114 */ 1115 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 1116 1117 /* 1118 * Make sure $SHELL points to the shell from the password file, 1119 * even if shell is overridden from login.conf 1120 */ 1121 env = do_setup_env(s, shell); 1122 1123 #ifdef HAVE_LOGIN_CAP 1124 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); 1125 #endif 1126 1127 /* we have to stash the hostname before we close our socket. */ 1128 if (options.use_login) 1129 hostname = get_remote_name_or_ip(utmp_len, 1130 options.use_dns); 1131 /* 1132 * Close the connection descriptors; note that this is the child, and 1133 * the server will still have the socket open, and it is important 1134 * that we do not shutdown it. Note that the descriptors cannot be 1135 * closed before building the environment, as we call 1136 * get_remote_ipaddr there. 1137 */ 1138 child_close_fds(); 1139 1140 /* 1141 * Must take new environment into use so that .ssh/rc, 1142 * /etc/ssh/sshrc and xauth are run in the proper environment. 1143 */ 1144 environ = env; 1145 1146 #ifdef KRB5 1147 /* 1148 * At this point, we check to see if AFS is active and if we have 1149 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see 1150 * if we can (and need to) extend the ticket into an AFS token. If 1151 * we don't do this, we run into potential problems if the user's 1152 * home directory is in AFS and it's not world-readable. 1153 */ 1154 1155 if (options.kerberos_get_afs_token && k_hasafs() && 1156 (s->authctxt->krb5_ctx != NULL)) { 1157 char cell[64]; 1158 1159 debug("Getting AFS token"); 1160 1161 k_setpag(); 1162 1163 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 1164 krb5_afslog(s->authctxt->krb5_ctx, 1165 s->authctxt->krb5_fwd_ccache, cell, NULL); 1166 1167 krb5_afslog_home(s->authctxt->krb5_ctx, 1168 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir); 1169 } 1170 #endif 1171 1172 /* Change current directory to the user\'s home directory. */ 1173 if (chdir(pw->pw_dir) < 0) { 1174 fprintf(stderr, "Could not chdir to home directory %s: %s\n", 1175 pw->pw_dir, strerror(errno)); 1176 #ifdef HAVE_LOGIN_CAP 1177 if (login_getcapbool(lc, "requirehome", 0)) 1178 exit(1); 1179 #endif 1180 } 1181 1182 if (!options.use_login) 1183 do_rc_files(s, shell); 1184 1185 /* restore SIGPIPE for child */ 1186 signal(SIGPIPE, SIG_DFL); 1187 1188 if (options.use_login) { 1189 launch_login(pw, hostname); 1190 /* NEVERREACHED */ 1191 } 1192 1193 /* Get the last component of the shell name. */ 1194 if ((shell0 = strrchr(shell, '/')) != NULL) 1195 shell0++; 1196 else 1197 shell0 = shell; 1198 1199 /* 1200 * If we have no command, execute the shell. In this case, the shell 1201 * name to be passed in argv[0] is preceded by '-' to indicate that 1202 * this is a login shell. 1203 */ 1204 if (!command) { 1205 char argv0[256]; 1206 1207 /* Start the shell. Set initial character to '-'. */ 1208 argv0[0] = '-'; 1209 1210 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) 1211 >= sizeof(argv0) - 1) { 1212 errno = EINVAL; 1213 perror(shell); 1214 exit(1); 1215 } 1216 1217 /* Execute the shell. */ 1218 argv[0] = argv0; 1219 argv[1] = NULL; 1220 execve(shell, argv, env); 1221 1222 /* Executing the shell failed. */ 1223 perror(shell); 1224 exit(1); 1225 } 1226 /* 1227 * Execute the command using the user's shell. This uses the -c 1228 * option to execute the command. 1229 */ 1230 argv[0] = (char *) shell0; 1231 argv[1] = "-c"; 1232 argv[2] = (char *) command; 1233 argv[3] = NULL; 1234 execve(shell, argv, env); 1235 perror(shell); 1236 exit(1); 1237 } 1238 1239 Session * 1240 session_new(void) 1241 { 1242 int i; 1243 static int did_init = 0; 1244 if (!did_init) { 1245 debug("session_new: init"); 1246 for (i = 0; i < MAX_SESSIONS; i++) { 1247 sessions[i].used = 0; 1248 } 1249 did_init = 1; 1250 } 1251 for (i = 0; i < MAX_SESSIONS; i++) { 1252 Session *s = &sessions[i]; 1253 if (! s->used) { 1254 memset(s, 0, sizeof(*s)); 1255 s->chanid = -1; 1256 s->ptyfd = -1; 1257 s->ttyfd = -1; 1258 s->used = 1; 1259 s->self = i; 1260 debug("session_new: session %d", i); 1261 return s; 1262 } 1263 } 1264 return NULL; 1265 } 1266 1267 static void 1268 session_dump(void) 1269 { 1270 int i; 1271 for (i = 0; i < MAX_SESSIONS; i++) { 1272 Session *s = &sessions[i]; 1273 debug("dump: used %d session %d %p channel %d pid %ld", 1274 s->used, 1275 s->self, 1276 s, 1277 s->chanid, 1278 (long)s->pid); 1279 } 1280 } 1281 1282 int 1283 session_open(Authctxt *authctxt, int chanid) 1284 { 1285 Session *s = session_new(); 1286 debug("session_open: channel %d", chanid); 1287 if (s == NULL) { 1288 error("no more sessions"); 1289 return 0; 1290 } 1291 s->authctxt = authctxt; 1292 s->pw = authctxt->pw; 1293 if (s->pw == NULL || !authctxt->valid) 1294 fatal("no user for session %d", s->self); 1295 debug("session_open: session %d: link with channel %d", s->self, chanid); 1296 s->chanid = chanid; 1297 return 1; 1298 } 1299 1300 Session * 1301 session_by_tty(char *tty) 1302 { 1303 int i; 1304 for (i = 0; i < MAX_SESSIONS; i++) { 1305 Session *s = &sessions[i]; 1306 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) { 1307 debug("session_by_tty: session %d tty %s", i, tty); 1308 return s; 1309 } 1310 } 1311 debug("session_by_tty: unknown tty %.100s", tty); 1312 session_dump(); 1313 return NULL; 1314 } 1315 1316 static Session * 1317 session_by_channel(int id) 1318 { 1319 int i; 1320 for (i = 0; i < MAX_SESSIONS; i++) { 1321 Session *s = &sessions[i]; 1322 if (s->used && s->chanid == id) { 1323 debug("session_by_channel: session %d channel %d", i, id); 1324 return s; 1325 } 1326 } 1327 debug("session_by_channel: unknown channel %d", id); 1328 session_dump(); 1329 return NULL; 1330 } 1331 1332 static Session * 1333 session_by_pid(pid_t pid) 1334 { 1335 int i; 1336 debug("session_by_pid: pid %ld", (long)pid); 1337 for (i = 0; i < MAX_SESSIONS; i++) { 1338 Session *s = &sessions[i]; 1339 if (s->used && s->pid == pid) 1340 return s; 1341 } 1342 error("session_by_pid: unknown pid %ld", (long)pid); 1343 session_dump(); 1344 return NULL; 1345 } 1346 1347 static int 1348 session_window_change_req(Session *s) 1349 { 1350 s->col = packet_get_int(); 1351 s->row = packet_get_int(); 1352 s->xpixel = packet_get_int(); 1353 s->ypixel = packet_get_int(); 1354 packet_check_eom(); 1355 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1356 return 1; 1357 } 1358 1359 static int 1360 session_pty_req(Session *s) 1361 { 1362 u_int len; 1363 int n_bytes; 1364 1365 if (no_pty_flag) { 1366 debug("Allocating a pty not permitted for this authentication."); 1367 return 0; 1368 } 1369 if (s->ttyfd != -1) { 1370 packet_disconnect("Protocol error: you already have a pty."); 1371 return 0; 1372 } 1373 /* Get the time and hostname when the user last logged in. */ 1374 if (options.print_lastlog) { 1375 s->hostname[0] = '\0'; 1376 s->last_login_time = get_last_login_time(s->pw->pw_uid, 1377 s->pw->pw_name, s->hostname, sizeof(s->hostname)); 1378 } 1379 1380 s->term = packet_get_string(&len); 1381 1382 if (compat20) { 1383 s->col = packet_get_int(); 1384 s->row = packet_get_int(); 1385 } else { 1386 s->row = packet_get_int(); 1387 s->col = packet_get_int(); 1388 } 1389 s->xpixel = packet_get_int(); 1390 s->ypixel = packet_get_int(); 1391 1392 if (strcmp(s->term, "") == 0) { 1393 xfree(s->term); 1394 s->term = NULL; 1395 } 1396 1397 /* Allocate a pty and open it. */ 1398 debug("Allocating pty."); 1399 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) { 1400 if (s->term) 1401 xfree(s->term); 1402 s->term = NULL; 1403 s->ptyfd = -1; 1404 s->ttyfd = -1; 1405 error("session_pty_req: session %d alloc failed", s->self); 1406 return 0; 1407 } 1408 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 1409 1410 /* for SSH1 the tty modes length is not given */ 1411 if (!compat20) 1412 n_bytes = packet_remaining(); 1413 tty_parse_modes(s->ttyfd, &n_bytes); 1414 1415 if (!use_privsep) 1416 pty_setowner(s->pw, s->tty); 1417 1418 /* Set window size from the packet. */ 1419 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1420 1421 packet_check_eom(); 1422 session_proctitle(s); 1423 return 1; 1424 } 1425 1426 static int 1427 session_subsystem_req(Session *s) 1428 { 1429 struct stat st; 1430 u_int len; 1431 int success = 0; 1432 char *cmd, *subsys = packet_get_string(&len); 1433 int i; 1434 1435 packet_check_eom(); 1436 logit("subsystem request for %.100s", subsys); 1437 1438 for (i = 0; i < options.num_subsystems; i++) { 1439 if (strcmp(subsys, options.subsystem_name[i]) == 0) { 1440 cmd = options.subsystem_command[i]; 1441 if (stat(cmd, &st) < 0) { 1442 error("subsystem: cannot stat %s: %s", cmd, 1443 strerror(errno)); 1444 break; 1445 } 1446 debug("subsystem: exec() %s", cmd); 1447 s->is_subsystem = 1; 1448 do_exec(s, cmd); 1449 success = 1; 1450 break; 1451 } 1452 } 1453 1454 if (!success) 1455 logit("subsystem request for %.100s failed, subsystem not found", 1456 subsys); 1457 1458 xfree(subsys); 1459 return success; 1460 } 1461 1462 static int 1463 session_x11_req(Session *s) 1464 { 1465 int success; 1466 1467 s->single_connection = packet_get_char(); 1468 s->auth_proto = packet_get_string(NULL); 1469 s->auth_data = packet_get_string(NULL); 1470 s->screen = packet_get_int(); 1471 packet_check_eom(); 1472 1473 success = session_setup_x11fwd(s); 1474 if (!success) { 1475 xfree(s->auth_proto); 1476 xfree(s->auth_data); 1477 s->auth_proto = NULL; 1478 s->auth_data = NULL; 1479 } 1480 return success; 1481 } 1482 1483 static int 1484 session_shell_req(Session *s) 1485 { 1486 packet_check_eom(); 1487 do_exec(s, NULL); 1488 return 1; 1489 } 1490 1491 static int 1492 session_exec_req(Session *s) 1493 { 1494 u_int len; 1495 char *command = packet_get_string(&len); 1496 packet_check_eom(); 1497 do_exec(s, command); 1498 xfree(command); 1499 return 1; 1500 } 1501 1502 static int 1503 session_break_req(Session *s) 1504 { 1505 u_int break_length; 1506 1507 break_length = packet_get_int(); /* ignored */ 1508 packet_check_eom(); 1509 1510 if (s->ttyfd == -1 || 1511 tcsendbreak(s->ttyfd, 0) < 0) 1512 return 0; 1513 return 1; 1514 } 1515 1516 static int 1517 session_auth_agent_req(Session *s) 1518 { 1519 static int called = 0; 1520 packet_check_eom(); 1521 if (no_agent_forwarding_flag) { 1522 debug("session_auth_agent_req: no_agent_forwarding_flag"); 1523 return 0; 1524 } 1525 if (called) { 1526 return 0; 1527 } else { 1528 called = 1; 1529 return auth_input_request_forwarding(s->pw); 1530 } 1531 } 1532 1533 int 1534 session_input_channel_req(Channel *c, const char *rtype) 1535 { 1536 int success = 0; 1537 Session *s; 1538 1539 if ((s = session_by_channel(c->self)) == NULL) { 1540 logit("session_input_channel_req: no session %d req %.100s", 1541 c->self, rtype); 1542 return 0; 1543 } 1544 debug("session_input_channel_req: session %d req %s", s->self, rtype); 1545 1546 /* 1547 * a session is in LARVAL state until a shell, a command 1548 * or a subsystem is executed 1549 */ 1550 if (c->type == SSH_CHANNEL_LARVAL) { 1551 if (strcmp(rtype, "shell") == 0) { 1552 success = session_shell_req(s); 1553 } else if (strcmp(rtype, "exec") == 0) { 1554 success = session_exec_req(s); 1555 } else if (strcmp(rtype, "pty-req") == 0) { 1556 success = session_pty_req(s); 1557 } else if (strcmp(rtype, "x11-req") == 0) { 1558 success = session_x11_req(s); 1559 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) { 1560 success = session_auth_agent_req(s); 1561 } else if (strcmp(rtype, "subsystem") == 0) { 1562 success = session_subsystem_req(s); 1563 } else if (strcmp(rtype, "break") == 0) { 1564 success = session_break_req(s); 1565 } 1566 } 1567 if (strcmp(rtype, "window-change") == 0) { 1568 success = session_window_change_req(s); 1569 } 1570 return success; 1571 } 1572 1573 void 1574 session_set_fds(Session *s, int fdin, int fdout, int fderr) 1575 { 1576 if (!compat20) 1577 fatal("session_set_fds: called for proto != 2.0"); 1578 /* 1579 * now that have a child and a pipe to the child, 1580 * we can activate our channel and register the fd's 1581 */ 1582 if (s->chanid == -1) 1583 fatal("no channel for session %d", s->self); 1584 channel_set_fds(s->chanid, 1585 fdout, fdin, fderr, 1586 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ, 1587 1, 1588 CHAN_SES_WINDOW_DEFAULT); 1589 } 1590 1591 /* 1592 * Function to perform pty cleanup. Also called if we get aborted abnormally 1593 * (e.g., due to a dropped connection). 1594 */ 1595 void 1596 session_pty_cleanup2(Session *s) 1597 { 1598 if (s == NULL) { 1599 error("session_pty_cleanup: no session"); 1600 return; 1601 } 1602 if (s->ttyfd == -1) 1603 return; 1604 1605 debug("session_pty_cleanup: session %d release %s", s->self, s->tty); 1606 1607 /* Record that the user has logged out. */ 1608 if (s->pid != 0) 1609 record_logout(s->pid, s->tty); 1610 1611 /* Release the pseudo-tty. */ 1612 if (getuid() == 0) 1613 pty_release(s->tty); 1614 1615 /* 1616 * Close the server side of the socket pairs. We must do this after 1617 * the pty cleanup, so that another process doesn't get this pty 1618 * while we're still cleaning up. 1619 */ 1620 if (close(s->ptymaster) < 0) 1621 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno)); 1622 1623 /* unlink pty from session */ 1624 s->ttyfd = -1; 1625 } 1626 1627 void 1628 session_pty_cleanup(Session *s) 1629 { 1630 PRIVSEP(session_pty_cleanup2(s)); 1631 } 1632 1633 static char * 1634 sig2name(int sig) 1635 { 1636 #define SSH_SIG(x) if (sig == SIG ## x) return #x 1637 SSH_SIG(ABRT); 1638 SSH_SIG(ALRM); 1639 SSH_SIG(FPE); 1640 SSH_SIG(HUP); 1641 SSH_SIG(ILL); 1642 SSH_SIG(INT); 1643 SSH_SIG(KILL); 1644 SSH_SIG(PIPE); 1645 SSH_SIG(QUIT); 1646 SSH_SIG(SEGV); 1647 SSH_SIG(TERM); 1648 SSH_SIG(USR1); 1649 SSH_SIG(USR2); 1650 #undef SSH_SIG 1651 return "SIG@openssh.com"; 1652 } 1653 1654 static void 1655 session_exit_message(Session *s, int status) 1656 { 1657 Channel *c; 1658 1659 if ((c = channel_lookup(s->chanid)) == NULL) 1660 fatal("session_exit_message: session %d: no channel %d", 1661 s->self, s->chanid); 1662 debug("session_exit_message: session %d channel %d pid %ld", 1663 s->self, s->chanid, (long)s->pid); 1664 1665 if (WIFEXITED(status)) { 1666 channel_request_start(s->chanid, "exit-status", 0); 1667 packet_put_int(WEXITSTATUS(status)); 1668 packet_send(); 1669 } else if (WIFSIGNALED(status)) { 1670 channel_request_start(s->chanid, "exit-signal", 0); 1671 packet_put_cstring(sig2name(WTERMSIG(status))); 1672 packet_put_char(WCOREDUMP(status)); 1673 packet_put_cstring(""); 1674 packet_put_cstring(""); 1675 packet_send(); 1676 } else { 1677 /* Some weird exit cause. Just exit. */ 1678 packet_disconnect("wait returned status %04x.", status); 1679 } 1680 1681 /* disconnect channel */ 1682 debug("session_exit_message: release channel %d", s->chanid); 1683 channel_cancel_cleanup(s->chanid); 1684 /* 1685 * emulate a write failure with 'chan_write_failed', nobody will be 1686 * interested in data we write. 1687 * Note that we must not call 'chan_read_failed', since there could 1688 * be some more data waiting in the pipe. 1689 */ 1690 if (c->ostate != CHAN_OUTPUT_CLOSED) 1691 chan_write_failed(c); 1692 s->chanid = -1; 1693 } 1694 1695 void 1696 session_close(Session *s) 1697 { 1698 debug("session_close: session %d pid %ld", s->self, (long)s->pid); 1699 if (s->ttyfd != -1) 1700 session_pty_cleanup(s); 1701 if (s->term) 1702 xfree(s->term); 1703 if (s->display) 1704 xfree(s->display); 1705 if (s->auth_display) 1706 xfree(s->auth_display); 1707 if (s->auth_data) 1708 xfree(s->auth_data); 1709 if (s->auth_proto) 1710 xfree(s->auth_proto); 1711 s->used = 0; 1712 session_proctitle(s); 1713 } 1714 1715 void 1716 session_close_by_pid(pid_t pid, int status) 1717 { 1718 Session *s = session_by_pid(pid); 1719 if (s == NULL) { 1720 debug("session_close_by_pid: no session for pid %ld", 1721 (long)pid); 1722 return; 1723 } 1724 if (s->chanid != -1) 1725 session_exit_message(s, status); 1726 session_close(s); 1727 } 1728 1729 /* 1730 * this is called when a channel dies before 1731 * the session 'child' itself dies 1732 */ 1733 void 1734 session_close_by_channel(int id, void *arg) 1735 { 1736 Session *s = session_by_channel(id); 1737 if (s == NULL) { 1738 debug("session_close_by_channel: no session for id %d", id); 1739 return; 1740 } 1741 debug("session_close_by_channel: channel %d child %ld", 1742 id, (long)s->pid); 1743 if (s->pid != 0) { 1744 debug("session_close_by_channel: channel %d: has child", id); 1745 /* 1746 * delay detach of session, but release pty, since 1747 * the fd's to the child are already closed 1748 */ 1749 if (s->ttyfd != -1) 1750 session_pty_cleanup(s); 1751 return; 1752 } 1753 /* detach by removing callback */ 1754 channel_cancel_cleanup(s->chanid); 1755 s->chanid = -1; 1756 session_close(s); 1757 } 1758 1759 void 1760 session_destroy_all(void (*closefunc)(Session *)) 1761 { 1762 int i; 1763 for (i = 0; i < MAX_SESSIONS; i++) { 1764 Session *s = &sessions[i]; 1765 if (s->used) { 1766 if (closefunc != NULL) 1767 closefunc(s); 1768 else 1769 session_close(s); 1770 } 1771 } 1772 } 1773 1774 static char * 1775 session_tty_list(void) 1776 { 1777 static char buf[1024]; 1778 int i; 1779 buf[0] = '\0'; 1780 for (i = 0; i < MAX_SESSIONS; i++) { 1781 Session *s = &sessions[i]; 1782 if (s->used && s->ttyfd != -1) { 1783 if (buf[0] != '\0') 1784 strlcat(buf, ",", sizeof buf); 1785 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf); 1786 } 1787 } 1788 if (buf[0] == '\0') 1789 strlcpy(buf, "notty", sizeof buf); 1790 return buf; 1791 } 1792 1793 void 1794 session_proctitle(Session *s) 1795 { 1796 if (s->pw == NULL) 1797 error("no user for session %d", s->self); 1798 else 1799 setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); 1800 } 1801 1802 int 1803 session_setup_x11fwd(Session *s) 1804 { 1805 struct stat st; 1806 char display[512], auth_display[512]; 1807 char hostname[MAXHOSTNAMELEN]; 1808 1809 if (no_x11_forwarding_flag) { 1810 packet_send_debug("X11 forwarding disabled in user configuration file."); 1811 return 0; 1812 } 1813 if (!options.x11_forwarding) { 1814 debug("X11 forwarding disabled in server configuration file."); 1815 return 0; 1816 } 1817 if (!options.xauth_location || 1818 (stat(options.xauth_location, &st) == -1)) { 1819 packet_send_debug("No xauth program; cannot forward with spoofing."); 1820 return 0; 1821 } 1822 if (options.use_login) { 1823 packet_send_debug("X11 forwarding disabled; " 1824 "not compatible with UseLogin=yes."); 1825 return 0; 1826 } 1827 if (s->display != NULL) { 1828 debug("X11 display already set."); 1829 return 0; 1830 } 1831 if (x11_create_display_inet(options.x11_display_offset, 1832 options.x11_use_localhost, s->single_connection, 1833 &s->display_number) == -1) { 1834 debug("x11_create_display_inet failed."); 1835 return 0; 1836 } 1837 1838 /* Set up a suitable value for the DISPLAY variable. */ 1839 if (gethostname(hostname, sizeof(hostname)) < 0) 1840 fatal("gethostname: %.100s", strerror(errno)); 1841 /* 1842 * auth_display must be used as the displayname when the 1843 * authorization entry is added with xauth(1). This will be 1844 * different than the DISPLAY string for localhost displays. 1845 */ 1846 if (options.x11_use_localhost) { 1847 snprintf(display, sizeof display, "localhost:%u.%u", 1848 s->display_number, s->screen); 1849 snprintf(auth_display, sizeof auth_display, "unix:%u.%u", 1850 s->display_number, s->screen); 1851 s->display = xstrdup(display); 1852 s->auth_display = xstrdup(auth_display); 1853 } else { 1854 snprintf(display, sizeof display, "%.400s:%u.%u", hostname, 1855 s->display_number, s->screen); 1856 s->display = xstrdup(display); 1857 s->auth_display = xstrdup(display); 1858 } 1859 1860 return 1; 1861 } 1862 1863 static void 1864 do_authenticated2(Authctxt *authctxt) 1865 { 1866 server_loop2(authctxt); 1867 } 1868 1869 void 1870 do_cleanup(Authctxt *authctxt) 1871 { 1872 static int called = 0; 1873 1874 debug("do_cleanup"); 1875 1876 /* no cleanup if we're in the child for login shell */ 1877 if (is_child) 1878 return; 1879 1880 /* avoid double cleanup */ 1881 if (called) 1882 return; 1883 called = 1; 1884 1885 if (authctxt == NULL) 1886 return; 1887 #ifdef KRB5 1888 if (options.kerberos_ticket_cleanup && 1889 authctxt->krb5_ctx) 1890 krb5_cleanup_proc(authctxt); 1891 #endif 1892 1893 #ifdef GSSAPI 1894 if (compat20 && options.gss_cleanup_creds) 1895 ssh_gssapi_cleanup_creds(); 1896 #endif 1897 1898 /* remove agent socket */ 1899 auth_sock_cleanup_proc(authctxt->pw); 1900 1901 /* 1902 * Cleanup ptys/utmp only if privsep is disabled, 1903 * or if running in monitor. 1904 */ 1905 if (!use_privsep || mm_is_monitor()) 1906 session_destroy_all(session_pty_cleanup2); 1907 } 1908