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