jcs's openbsd hax
openbsd
at jcs 2327 lines 59 kB view raw
1/* $OpenBSD: session.c,v 1.347 2026/02/08 15:28:01 dtucker 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/queue.h> 42 43#include <ctype.h> 44#include <errno.h> 45#include <fcntl.h> 46#include <grp.h> 47#include <login_cap.h> 48#include <netdb.h> 49#include <paths.h> 50#include <pwd.h> 51#include <signal.h> 52#include <stdio.h> 53#include <stdlib.h> 54#include <string.h> 55#include <stdarg.h> 56#include <unistd.h> 57#include <limits.h> 58 59#include "xmalloc.h" 60#include "ssh.h" 61#include "ssh2.h" 62#include "sshpty.h" 63#include "packet.h" 64#include "sshbuf.h" 65#include "ssherr.h" 66#include "match.h" 67#include "uidswap.h" 68#include "channels.h" 69#include "sshkey.h" 70#include "cipher.h" 71#include "kex.h" 72#include "hostfile.h" 73#include "auth.h" 74#include "auth-options.h" 75#include "authfd.h" 76#include "pathnames.h" 77#include "log.h" 78#include "misc.h" 79#include "servconf.h" 80#include "sshlogin.h" 81#include "serverloop.h" 82#include "canohost.h" 83#include "session.h" 84#ifdef GSSAPI 85#include "ssh-gss.h" 86#endif 87#include "monitor_wrap.h" 88#include "sftp.h" 89#include "atomicio.h" 90 91#if defined(KRB5) && defined(USE_AFS) 92#include <kafs.h> 93#endif 94 95#define IS_INTERNAL_SFTP(c) \ 96 (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \ 97 (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \ 98 c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \ 99 c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t')) 100 101/* func */ 102 103Session *session_new(void); 104void session_set_fds(struct ssh *, Session *, int, int, int, int, int); 105void session_pty_cleanup(Session *); 106void session_proctitle(Session *); 107int session_setup_x11fwd(struct ssh *, Session *); 108int do_exec_pty(struct ssh *, Session *, const char *); 109int do_exec_no_pty(struct ssh *, Session *, const char *); 110int do_exec(struct ssh *, Session *, const char *); 111void do_login(struct ssh *, Session *, const char *); 112void do_child(struct ssh *, Session *, const char *); 113void do_motd(void); 114int check_quietlogin(Session *, const char *); 115 116static void do_authenticated2(struct ssh *, Authctxt *); 117 118static int session_pty_req(struct ssh *, Session *); 119 120/* import */ 121extern ServerOptions options; 122extern char *__progname; 123extern int debug_flag; 124extern struct sshbuf *loginmsg; 125extern struct sshauthopt *auth_opts; 126extern char *tun_fwd_ifnames; /* serverloop.c */ 127 128/* original command from peer. */ 129const char *original_command = NULL; 130 131/* data */ 132static int sessions_first_unused = -1; 133static int sessions_nalloc = 0; 134static Session *sessions = NULL; 135 136#define SUBSYSTEM_NONE 0 137#define SUBSYSTEM_EXT 1 138#define SUBSYSTEM_INT_SFTP 2 139#define SUBSYSTEM_INT_SFTP_ERROR 3 140 141login_cap_t *lc; 142 143static int is_child = 0; 144static int in_chroot = 0; 145 146/* File containing userauth info, if ExposeAuthInfo set */ 147static char *auth_info_file = NULL; 148 149/* Name and directory of socket for authentication agent forwarding. */ 150static char *auth_sock_name = NULL; 151 152/* removes the agent forwarding socket */ 153 154static void 155auth_sock_cleanup_proc(struct passwd *pw) 156{ 157 if (auth_sock_name != NULL) { 158 temporarily_use_uid(pw); 159 unlink(auth_sock_name); 160 auth_sock_name = NULL; 161 restore_uid(); 162 } 163} 164 165static int 166auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw) 167{ 168 Channel *nc; 169 int sock = -1; 170 171 if (auth_sock_name != NULL) { 172 error("authentication forwarding requested twice."); 173 return 0; 174 } 175 176 /* Temporarily drop privileged uid for mkdir/bind. */ 177 temporarily_use_uid(pw); 178 179 if (agent_listener(pw->pw_dir, "sshd", &sock, &auth_sock_name) != 0) { 180 /* a more detailed error is already logged */ 181 ssh_packet_send_debug(ssh, "Agent forwarding disabled: " 182 "couldn't create listener socket"); 183 restore_uid(); 184 goto authsock_err; 185 } 186 restore_uid(); 187 188 /* Allocate a channel for the authentication agent socket. */ 189 nc = channel_new(ssh, "auth-listener", 190 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1, 191 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 192 0, "auth socket", 1); 193 nc->path = xstrdup(auth_sock_name); 194 return 1; 195 196 authsock_err: 197 free(auth_sock_name); 198 if (sock != -1) 199 close(sock); 200 auth_sock_name = NULL; 201 return 0; 202} 203 204static void 205display_loginmsg(void) 206{ 207 int r; 208 209 if (sshbuf_len(loginmsg) == 0) 210 return; 211 if ((r = sshbuf_put_u8(loginmsg, 0)) != 0) 212 fatal_fr(r, "sshbuf_put_u8"); 213 printf("%s", (char *)sshbuf_ptr(loginmsg)); 214 sshbuf_reset(loginmsg); 215} 216 217static void 218prepare_auth_info_file(struct passwd *pw, struct sshbuf *info) 219{ 220 int fd = -1, success = 0; 221 222 if (!options.expose_userauth_info || info == NULL) 223 return; 224 225 temporarily_use_uid(pw); 226 auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX"); 227 if ((fd = mkstemp(auth_info_file)) == -1) { 228 error_f("mkstemp: %s", strerror(errno)); 229 goto out; 230 } 231 if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info), 232 sshbuf_len(info)) != sshbuf_len(info)) { 233 error_f("write: %s", strerror(errno)); 234 goto out; 235 } 236 if (close(fd) != 0) { 237 error_f("close: %s", strerror(errno)); 238 goto out; 239 } 240 success = 1; 241 out: 242 if (!success) { 243 if (fd != -1) 244 close(fd); 245 free(auth_info_file); 246 auth_info_file = NULL; 247 } 248 restore_uid(); 249} 250 251static void 252set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts) 253{ 254 char *tmp, *cp, *host; 255 int port; 256 size_t i; 257 258 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) { 259 channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL); 260 for (i = 0; i < auth_opts->npermitopen; i++) { 261 tmp = cp = xstrdup(auth_opts->permitopen[i]); 262 /* This shouldn't fail as it has already been checked */ 263 if ((host = hpdelim2(&cp, NULL)) == NULL) 264 fatal_f("internal error: hpdelim"); 265 host = cleanhostname(host); 266 if (cp == NULL || (port = permitopen_port(cp)) < 0) 267 fatal_f("internal error: permitopen port"); 268 channel_add_permission(ssh, 269 FORWARD_USER, FORWARD_LOCAL, host, port); 270 free(tmp); 271 } 272 } 273 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) { 274 channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE); 275 for (i = 0; i < auth_opts->npermitlisten; i++) { 276 tmp = cp = xstrdup(auth_opts->permitlisten[i]); 277 /* This shouldn't fail as it has already been checked */ 278 if ((host = hpdelim(&cp)) == NULL) 279 fatal_f("internal error: hpdelim"); 280 host = cleanhostname(host); 281 if (cp == NULL || (port = permitopen_port(cp)) < 0) 282 fatal_f("internal error: permitlisten port"); 283 channel_add_permission(ssh, 284 FORWARD_USER, FORWARD_REMOTE, host, port); 285 free(tmp); 286 } 287 } 288} 289 290void 291do_authenticated(struct ssh *ssh, Authctxt *authctxt) 292{ 293 setproctitle("%s", authctxt->pw->pw_name); 294 295 auth_log_authopts("active", auth_opts, 0); 296 297 /* set up the channel layer */ 298 /* XXX - streamlocal? */ 299 set_fwdpermit_from_authopts(ssh, auth_opts); 300 301 if (!auth_opts->permit_port_forwarding_flag || 302 options.disable_forwarding) { 303 channel_disable_admin(ssh, FORWARD_LOCAL); 304 channel_disable_admin(ssh, FORWARD_REMOTE); 305 } else { 306 if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0) 307 channel_disable_admin(ssh, FORWARD_LOCAL); 308 else 309 channel_permit_all(ssh, FORWARD_LOCAL); 310 if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0) 311 channel_disable_admin(ssh, FORWARD_REMOTE); 312 else 313 channel_permit_all(ssh, FORWARD_REMOTE); 314 } 315 auth_debug_send(ssh); 316 317 prepare_auth_info_file(authctxt->pw, authctxt->session_info); 318 319 do_authenticated2(ssh, authctxt); 320 321 do_cleanup(ssh, authctxt); 322} 323 324/* Check untrusted xauth strings for metacharacters */ 325static int 326xauth_valid_string(const char *s) 327{ 328 size_t i; 329 330 for (i = 0; s[i] != '\0'; i++) { 331 if (!isalnum((u_char)s[i]) && 332 s[i] != '.' && s[i] != ':' && s[i] != '/' && 333 s[i] != '-' && s[i] != '_') 334 return 0; 335 } 336 return 1; 337} 338 339#define USE_PIPES 1 340/* 341 * This is called to fork and execute a command when we have no tty. This 342 * will call do_child from the child, and server_loop from the parent after 343 * setting up file descriptors and such. 344 */ 345int 346do_exec_no_pty(struct ssh *ssh, Session *s, const char *command) 347{ 348 pid_t pid; 349#ifdef USE_PIPES 350 int pin[2], pout[2], perr[2]; 351 352 if (s == NULL) 353 fatal("do_exec_no_pty: no session"); 354 355 /* Allocate pipes for communicating with the program. */ 356 if (pipe(pin) == -1) { 357 error_f("pipe in: %.100s", strerror(errno)); 358 return -1; 359 } 360 if (pipe(pout) == -1) { 361 error_f("pipe out: %.100s", strerror(errno)); 362 close(pin[0]); 363 close(pin[1]); 364 return -1; 365 } 366 if (pipe(perr) == -1) { 367 error_f("pipe err: %.100s", strerror(errno)); 368 close(pin[0]); 369 close(pin[1]); 370 close(pout[0]); 371 close(pout[1]); 372 return -1; 373 } 374#else 375 int inout[2], err[2]; 376 377 if (s == NULL) 378 fatal("do_exec_no_pty: no session"); 379 380 /* Uses socket pairs to communicate with the program. */ 381 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) { 382 error_f("socketpair #1: %.100s", strerror(errno)); 383 return -1; 384 } 385 if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) { 386 error_f("socketpair #2: %.100s", strerror(errno)); 387 close(inout[0]); 388 close(inout[1]); 389 return -1; 390 } 391#endif 392 393 session_proctitle(s); 394 395 /* Fork the child. */ 396 switch ((pid = fork())) { 397 case -1: 398 error_f("fork: %.100s", strerror(errno)); 399#ifdef USE_PIPES 400 close(pin[0]); 401 close(pin[1]); 402 close(pout[0]); 403 close(pout[1]); 404 close(perr[0]); 405 close(perr[1]); 406#else 407 close(inout[0]); 408 close(inout[1]); 409 close(err[0]); 410 close(err[1]); 411#endif 412 return -1; 413 case 0: 414 is_child = 1; 415 416 /* 417 * Create a new session and process group since the 4.4BSD 418 * setlogin() affects the entire process group. 419 */ 420 if (setsid() == -1) 421 error("setsid failed: %.100s", strerror(errno)); 422 423#ifdef USE_PIPES 424 /* 425 * Redirect stdin. We close the parent side of the socket 426 * pair, and make the child side the standard input. 427 */ 428 close(pin[1]); 429 if (dup2(pin[0], 0) == -1) 430 perror("dup2 stdin"); 431 close(pin[0]); 432 433 /* Redirect stdout. */ 434 close(pout[0]); 435 if (dup2(pout[1], 1) == -1) 436 perror("dup2 stdout"); 437 close(pout[1]); 438 439 /* Redirect stderr. */ 440 close(perr[0]); 441 if (dup2(perr[1], 2) == -1) 442 perror("dup2 stderr"); 443 close(perr[1]); 444#else 445 /* 446 * Redirect stdin, stdout, and stderr. Stdin and stdout will 447 * use the same socket, as some programs (particularly rdist) 448 * seem to depend on it. 449 */ 450 close(inout[1]); 451 close(err[1]); 452 if (dup2(inout[0], 0) == -1) /* stdin */ 453 perror("dup2 stdin"); 454 if (dup2(inout[0], 1) == -1) /* stdout (same as stdin) */ 455 perror("dup2 stdout"); 456 close(inout[0]); 457 if (dup2(err[0], 2) == -1) /* stderr */ 458 perror("dup2 stderr"); 459 close(err[0]); 460#endif 461 462 /* Do processing for the child (exec command etc). */ 463 do_child(ssh, s, command); 464 /* NOTREACHED */ 465 default: 466 break; 467 } 468 469 s->pid = pid; 470 471#ifdef USE_PIPES 472 /* We are the parent. Close the child sides of the pipes. */ 473 close(pin[0]); 474 close(pout[1]); 475 close(perr[1]); 476 477 session_set_fds(ssh, s, pin[1], pout[0], perr[0], 478 s->is_subsystem, 0); 479#else 480 /* We are the parent. Close the child sides of the socket pairs. */ 481 close(inout[0]); 482 close(err[0]); 483 484 /* 485 * Enter the interactive session. Note: server_loop must be able to 486 * handle the case that fdin and fdout are the same. 487 */ 488 session_set_fds(ssh, s, inout[1], inout[1], err[1], 489 s->is_subsystem, 0); 490#endif 491 return 0; 492} 493 494/* 495 * This is called to fork and execute a command when we have a tty. This 496 * will call do_child from the child, and server_loop from the parent after 497 * setting up file descriptors, controlling tty, updating wtmp, utmp, 498 * lastlog, and other such operations. 499 */ 500int 501do_exec_pty(struct ssh *ssh, Session *s, const char *command) 502{ 503 int fdout, ptyfd, ttyfd, ptymaster; 504 pid_t pid; 505 506 if (s == NULL) 507 fatal("do_exec_pty: no session"); 508 ptyfd = s->ptyfd; 509 ttyfd = s->ttyfd; 510 511 /* 512 * Create another descriptor of the pty master side for use as the 513 * standard input. We could use the original descriptor, but this 514 * simplifies code in server_loop. The descriptor is bidirectional. 515 * Do this before forking (and cleanup in the child) so as to 516 * detect and gracefully fail out-of-fd conditions. 517 */ 518 if ((fdout = dup(ptyfd)) == -1) { 519 error_f("dup #1: %s", strerror(errno)); 520 close(ttyfd); 521 close(ptyfd); 522 return -1; 523 } 524 /* we keep a reference to the pty master */ 525 if ((ptymaster = dup(ptyfd)) == -1) { 526 error_f("dup #2: %s", strerror(errno)); 527 close(ttyfd); 528 close(ptyfd); 529 close(fdout); 530 return -1; 531 } 532 533 /* Fork the child. */ 534 switch ((pid = fork())) { 535 case -1: 536 error_f("fork: %.100s", strerror(errno)); 537 close(fdout); 538 close(ptymaster); 539 close(ttyfd); 540 close(ptyfd); 541 return -1; 542 case 0: 543 is_child = 1; 544 545 close(fdout); 546 close(ptymaster); 547 548 /* Close the master side of the pseudo tty. */ 549 close(ptyfd); 550 551 /* Make the pseudo tty our controlling tty. */ 552 pty_make_controlling_tty(&ttyfd, s->tty); 553 554 /* Redirect stdin/stdout/stderr from the pseudo tty. */ 555 if (dup2(ttyfd, 0) == -1) 556 error("dup2 stdin: %s", strerror(errno)); 557 if (dup2(ttyfd, 1) == -1) 558 error("dup2 stdout: %s", strerror(errno)); 559 if (dup2(ttyfd, 2) == -1) 560 error("dup2 stderr: %s", strerror(errno)); 561 562 /* Close the extra descriptor for the pseudo tty. */ 563 close(ttyfd); 564 565 /* record login, etc. similar to login(1) */ 566 do_login(ssh, s, command); 567 568 /* 569 * Do common processing for the child, such as execing 570 * the command. 571 */ 572 do_child(ssh, s, command); 573 /* NOTREACHED */ 574 default: 575 break; 576 } 577 s->pid = pid; 578 579 /* Parent. Close the slave side of the pseudo tty. */ 580 close(ttyfd); 581 582 /* Enter interactive session. */ 583 s->ptymaster = ptymaster; 584 session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1); 585 return 0; 586} 587 588/* 589 * This is called to fork and execute a command. If another command is 590 * to be forced, execute that instead. 591 */ 592int 593do_exec(struct ssh *ssh, Session *s, const char *command) 594{ 595 int ret; 596 const char *forced = NULL, *tty = NULL; 597 char session_type[1024]; 598 599 if (options.adm_forced_command) { 600 original_command = command; 601 command = options.adm_forced_command; 602 forced = "(config)"; 603 } else if (auth_opts->force_command != NULL) { 604 original_command = command; 605 command = auth_opts->force_command; 606 forced = "(key-option)"; 607 } 608 s->forced = 0; 609 if (forced != NULL) { 610 s->forced = 1; 611 if (IS_INTERNAL_SFTP(command)) { 612 s->is_subsystem = s->is_subsystem ? 613 SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR; 614 } else if (s->is_subsystem) 615 s->is_subsystem = SUBSYSTEM_EXT; 616 snprintf(session_type, sizeof(session_type), 617 "forced-command %s '%.900s'", forced, command); 618 } else if (s->is_subsystem) { 619 snprintf(session_type, sizeof(session_type), 620 "subsystem '%.900s'", s->subsys); 621 } else if (command == NULL) { 622 snprintf(session_type, sizeof(session_type), "shell"); 623 } else { 624 /* NB. we don't log unforced commands to preserve privacy */ 625 snprintf(session_type, sizeof(session_type), "command"); 626 } 627 628 if (s->ttyfd != -1) { 629 tty = s->tty; 630 if (strncmp(tty, "/dev/", 5) == 0) 631 tty += 5; 632 } 633 634 verbose("Starting session: %s%s%s for %s from %.200s port %d id %d", 635 session_type, 636 tty == NULL ? "" : " on ", 637 tty == NULL ? "" : tty, 638 s->pw->pw_name, 639 ssh_remote_ipaddr(ssh), 640 ssh_remote_port(ssh), 641 s->self); 642 643#ifdef GSSAPI 644 if (options.gss_authentication) { 645 temporarily_use_uid(s->pw); 646 ssh_gssapi_storecreds(); 647 restore_uid(); 648 } 649#endif 650 if (s->ttyfd != -1) 651 ret = do_exec_pty(ssh, s, command); 652 else 653 ret = do_exec_no_pty(ssh, s, command); 654 655 original_command = NULL; 656 657 /* 658 * Clear loginmsg: it's the child's responsibility to display 659 * it to the user, otherwise multiple sessions may accumulate 660 * multiple copies of the login messages. 661 */ 662 sshbuf_reset(loginmsg); 663 664 return ret; 665} 666 667 668/* administrative, login(1)-like work */ 669void 670do_login(struct ssh *ssh, Session *s, const char *command) 671{ 672 socklen_t fromlen; 673 struct sockaddr_storage from; 674 675 /* 676 * Get IP address of client. If the connection is not a socket, let 677 * the address be 0.0.0.0. 678 */ 679 memset(&from, 0, sizeof(from)); 680 fromlen = sizeof(from); 681 if (ssh_packet_connection_is_on_socket(ssh)) { 682 if (getpeername(ssh_packet_get_connection_in(ssh), 683 (struct sockaddr *)&from, &fromlen) == -1) { 684 debug("getpeername: %.100s", strerror(errno)); 685 cleanup_exit(255); 686 } 687 } 688 689 if (check_quietlogin(s, command)) 690 return; 691 692 display_loginmsg(); 693 694 do_motd(); 695} 696 697/* 698 * Display the message of the day. 699 */ 700void 701do_motd(void) 702{ 703 FILE *f; 704 char buf[256]; 705 706 if (options.print_motd) { 707 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd", 708 "/etc/motd"), "r"); 709 if (f) { 710 while (fgets(buf, sizeof(buf), f)) 711 fputs(buf, stdout); 712 fclose(f); 713 } 714 } 715} 716 717 718/* 719 * Check for quiet login, either .hushlogin or command given. 720 */ 721int 722check_quietlogin(Session *s, const char *command) 723{ 724 char buf[256]; 725 struct passwd *pw = s->pw; 726 struct stat st; 727 728 /* Return 1 if .hushlogin exists or a command given. */ 729 if (command != NULL) 730 return 1; 731 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir); 732 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0) 733 return 1; 734 return 0; 735} 736 737/* 738 * Reads environment variables from the given file and adds/overrides them 739 * into the environment. If the file does not exist, this does nothing. 740 * Otherwise, it must consist of empty lines, comments (line starts with '#') 741 * and assignments of the form name=value. No other forms are allowed. 742 * If allowlist is not NULL, then it is interpreted as a pattern list and 743 * only variable names that match it will be accepted. 744 */ 745static void 746read_environment_file(char ***env, u_int *envsize, 747 const char *filename, const char *allowlist) 748{ 749 FILE *f; 750 char *line = NULL, *cp, *value; 751 size_t linesize = 0; 752 u_int lineno = 0; 753 754 f = fopen(filename, "r"); 755 if (!f) 756 return; 757 758 while (getline(&line, &linesize, f) != -1) { 759 if (++lineno > 1000) 760 fatal("Too many lines in environment file %s", filename); 761 for (cp = line; *cp == ' ' || *cp == '\t'; cp++) 762 ; 763 if (!*cp || *cp == '#' || *cp == '\n') 764 continue; 765 766 cp[strcspn(cp, "\n")] = '\0'; 767 768 value = strchr(cp, '='); 769 if (value == NULL) { 770 fprintf(stderr, "Bad line %u in %.100s\n", lineno, 771 filename); 772 continue; 773 } 774 /* 775 * Replace the equals sign by nul, and advance value to 776 * the value string. 777 */ 778 *value = '\0'; 779 value++; 780 if (allowlist != NULL && 781 match_pattern_list(cp, allowlist, 0) != 1) 782 continue; 783 child_set_env(env, envsize, cp, value); 784 } 785 free(line); 786 fclose(f); 787} 788 789static char ** 790do_setup_env(struct ssh *ssh, Session *s, const char *shell) 791{ 792 char buf[256]; 793 size_t n; 794 u_int i, envsize; 795 char *ocp, *cp, *value, **env, *laddr; 796 struct passwd *pw = s->pw; 797 798 /* Initialize the environment. */ 799 envsize = 100; 800 env = xcalloc(envsize, sizeof(char *)); 801 env[0] = NULL; 802 803#ifdef GSSAPI 804 /* Allow any GSSAPI methods that we've used to alter 805 * the child's environment as they see fit 806 */ 807 ssh_gssapi_do_child(&env, &envsize); 808#endif 809 810 /* Set basic environment. */ 811 for (i = 0; i < s->num_env; i++) 812 child_set_env(&env, &envsize, s->env[i].name, s->env[i].val); 813 814 child_set_env(&env, &envsize, "USER", pw->pw_name); 815 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 816 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 817 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0) 818 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 819 else 820 child_set_env(&env, &envsize, "PATH", getenv("PATH")); 821 822 snprintf(buf, sizeof buf, "%.200s/%.50s", _PATH_MAILDIR, pw->pw_name); 823 child_set_env(&env, &envsize, "MAIL", buf); 824 825 /* Normal systems set SHELL by default. */ 826 child_set_env(&env, &envsize, "SHELL", shell); 827 828 if (getenv("TZ")) 829 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 830 if (getenv("XDG_RUNTIME_DIR")) { 831 child_set_env(&env, &envsize, "XDG_RUNTIME_DIR", 832 getenv("XDG_RUNTIME_DIR")); 833 } 834 if (s->term) 835 child_set_env(&env, &envsize, "TERM", s->term); 836 if (s->display) 837 child_set_env(&env, &envsize, "DISPLAY", s->display); 838#ifdef KRB5 839 if (s->authctxt->krb5_ticket_file) 840 child_set_env(&env, &envsize, "KRB5CCNAME", 841 s->authctxt->krb5_ticket_file); 842#endif 843 if (auth_sock_name != NULL) 844 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 845 auth_sock_name); 846 847 848 /* Set custom environment options from pubkey authentication. */ 849 if (options.permit_user_env) { 850 for (n = 0 ; n < auth_opts->nenv; n++) { 851 ocp = xstrdup(auth_opts->env[n]); 852 cp = strchr(ocp, '='); 853 if (cp != NULL) { 854 *cp = '\0'; 855 /* Apply PermitUserEnvironment allowlist */ 856 if (options.permit_user_env_allowlist == NULL || 857 match_pattern_list(ocp, 858 options.permit_user_env_allowlist, 0) == 1) 859 child_set_env(&env, &envsize, 860 ocp, cp + 1); 861 } 862 free(ocp); 863 } 864 } 865 866 /* read $HOME/.ssh/environment. */ 867 if (options.permit_user_env) { 868 snprintf(buf, sizeof buf, "%.200s/%s/environment", 869 pw->pw_dir, _PATH_SSH_USER_DIR); 870 read_environment_file(&env, &envsize, buf, 871 options.permit_user_env_allowlist); 872 } 873 874 /* Environment specified by admin */ 875 for (i = 0; i < options.num_setenv; i++) { 876 cp = xstrdup(options.setenv[i]); 877 if ((value = strchr(cp, '=')) == NULL) { 878 /* shouldn't happen; vars are checked in servconf.c */ 879 fatal("Invalid config SetEnv: %s", options.setenv[i]); 880 } 881 *value++ = '\0'; 882 child_set_env(&env, &envsize, cp, value); 883 free(cp); 884 } 885 886 /* SSH_CLIENT deprecated */ 887 snprintf(buf, sizeof buf, "%.50s %d %d", 888 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 889 ssh_local_port(ssh)); 890 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 891 892 laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh)); 893 snprintf(buf, sizeof buf, "%.50s %d %.50s %d", 894 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 895 laddr, ssh_local_port(ssh)); 896 free(laddr); 897 child_set_env(&env, &envsize, "SSH_CONNECTION", buf); 898 899 if (tun_fwd_ifnames != NULL) 900 child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames); 901 if (auth_info_file != NULL) 902 child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file); 903 if (s->ttyfd != -1) 904 child_set_env(&env, &envsize, "SSH_TTY", s->tty); 905 if (original_command) 906 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND", 907 original_command); 908 909 if (debug_flag) { 910 /* dump the environment */ 911 fprintf(stderr, "Environment:\n"); 912 for (i = 0; env[i]; i++) 913 fprintf(stderr, " %.200s\n", env[i]); 914 } 915 return env; 916} 917 918/* 919 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found 920 * first in this order). 921 */ 922static void 923do_rc_files(struct ssh *ssh, Session *s, const char *shell) 924{ 925 FILE *f = NULL; 926 char *cmd = NULL, *user_rc = NULL; 927 int do_xauth; 928 struct stat st; 929 930 do_xauth = 931 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL; 932 xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC); 933 934 /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */ 935 if (!s->is_subsystem && options.adm_forced_command == NULL && 936 auth_opts->permit_user_rc && options.permit_user_rc && 937 stat(user_rc, &st) >= 0) { 938 if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL, 939 user_rc) == -1) 940 fatal_f("xasprintf: %s", strerror(errno)); 941 if (debug_flag) 942 fprintf(stderr, "Running %s\n", cmd); 943 f = popen(cmd, "w"); 944 if (f) { 945 if (do_xauth) 946 fprintf(f, "%s %s\n", s->auth_proto, 947 s->auth_data); 948 pclose(f); 949 } else 950 fprintf(stderr, "Could not run %s\n", 951 user_rc); 952 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) { 953 if (debug_flag) 954 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL, 955 _PATH_SSH_SYSTEM_RC); 956 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w"); 957 if (f) { 958 if (do_xauth) 959 fprintf(f, "%s %s\n", s->auth_proto, 960 s->auth_data); 961 pclose(f); 962 } else 963 fprintf(stderr, "Could not run %s\n", 964 _PATH_SSH_SYSTEM_RC); 965 } else if (do_xauth && options.xauth_location != NULL) { 966 /* Add authority data to .Xauthority if appropriate. */ 967 if (debug_flag) { 968 fprintf(stderr, 969 "Running %.500s remove %.100s\n", 970 options.xauth_location, s->auth_display); 971 fprintf(stderr, 972 "%.500s add %.100s %.100s %.100s\n", 973 options.xauth_location, s->auth_display, 974 s->auth_proto, s->auth_data); 975 } 976 if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1) 977 fatal_f("xasprintf: %s", strerror(errno)); 978 f = popen(cmd, "w"); 979 if (f) { 980 fprintf(f, "remove %s\n", 981 s->auth_display); 982 fprintf(f, "add %s %s %s\n", 983 s->auth_display, s->auth_proto, 984 s->auth_data); 985 pclose(f); 986 } else { 987 fprintf(stderr, "Could not run %s\n", 988 cmd); 989 } 990 } 991 free(cmd); 992 free(user_rc); 993} 994 995static void 996do_nologin(struct passwd *pw) 997{ 998 FILE *f = NULL; 999 char buf[1024], *nl, *def_nl = _PATH_NOLOGIN; 1000 struct stat sb; 1001 1002 if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0) 1003 return; 1004 nl = login_getcapstr(lc, "nologin", def_nl, def_nl); 1005 1006 if (stat(nl, &sb) == -1) { 1007 if (nl != def_nl) 1008 free(nl); 1009 return; 1010 } 1011 1012 /* /etc/nologin exists. Print its contents if we can and exit. */ 1013 logit("User %.100s not allowed because %s exists", pw->pw_name, nl); 1014 if ((f = fopen(nl, "r")) != NULL) { 1015 while (fgets(buf, sizeof(buf), f)) 1016 fputs(buf, stderr); 1017 fclose(f); 1018 } 1019 exit(254); 1020} 1021 1022/* 1023 * Chroot into a directory after checking it for safety: all path components 1024 * must be root-owned directories with strict permissions. 1025 */ 1026static void 1027safely_chroot(const char *path, uid_t uid) 1028{ 1029 const char *cp; 1030 char component[PATH_MAX]; 1031 struct stat st; 1032 1033 if (!path_absolute(path)) 1034 fatal("chroot path does not begin at root"); 1035 if (strlen(path) >= sizeof(component)) 1036 fatal("chroot path too long"); 1037 1038 /* 1039 * Descend the path, checking that each component is a 1040 * root-owned directory with strict permissions. 1041 */ 1042 for (cp = path; cp != NULL;) { 1043 if ((cp = strchr(cp, '/')) == NULL) 1044 strlcpy(component, path, sizeof(component)); 1045 else { 1046 cp++; 1047 memcpy(component, path, cp - path); 1048 component[cp - path] = '\0'; 1049 } 1050 1051 debug3_f("checking '%s'", component); 1052 1053 if (stat(component, &st) != 0) 1054 fatal_f("stat(\"%s\"): %s", 1055 component, strerror(errno)); 1056 if (st.st_uid != 0 || (st.st_mode & 022) != 0) 1057 fatal("bad ownership or modes for chroot " 1058 "directory %s\"%s\"", 1059 cp == NULL ? "" : "component ", component); 1060 if (!S_ISDIR(st.st_mode)) 1061 fatal("chroot path %s\"%s\" is not a directory", 1062 cp == NULL ? "" : "component ", component); 1063 1064 } 1065 1066 if (chdir(path) == -1) 1067 fatal("Unable to chdir to chroot path \"%s\": " 1068 "%s", path, strerror(errno)); 1069 if (chroot(path) == -1) 1070 fatal("chroot(\"%s\"): %s", path, strerror(errno)); 1071 if (chdir("/") == -1) 1072 fatal_f("chdir(/) after chroot: %s", strerror(errno)); 1073 verbose("Changed root directory to \"%s\"", path); 1074} 1075 1076/* Set login name, uid, gid, and groups. */ 1077void 1078do_setusercontext(struct passwd *pw) 1079{ 1080 char uidstr[32], *chroot_path, *tmp; 1081 1082 if (getuid() == 0 || geteuid() == 0) { 1083 /* Prepare groups */ 1084 if (setusercontext(lc, pw, pw->pw_uid, 1085 (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) { 1086 perror("unable to set user context"); 1087 exit(1); 1088 } 1089 1090 if (!in_chroot && options.chroot_directory != NULL && 1091 strcasecmp(options.chroot_directory, "none") != 0) { 1092 tmp = tilde_expand_filename(options.chroot_directory, 1093 pw->pw_uid); 1094 snprintf(uidstr, sizeof(uidstr), "%llu", 1095 (unsigned long long)pw->pw_uid); 1096 chroot_path = percent_expand(tmp, "h", pw->pw_dir, 1097 "u", pw->pw_name, "U", uidstr, (char *)NULL); 1098 safely_chroot(chroot_path, pw->pw_uid); 1099 free(tmp); 1100 free(chroot_path); 1101 /* Make sure we don't attempt to chroot again */ 1102 free(options.chroot_directory); 1103 options.chroot_directory = NULL; 1104 in_chroot = 1; 1105 } 1106 1107 /* Set UID */ 1108 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) { 1109 perror("unable to set user context (setuser)"); 1110 exit(1); 1111 } 1112 } else if (options.chroot_directory != NULL && 1113 strcasecmp(options.chroot_directory, "none") != 0) { 1114 fatal("server lacks privileges to chroot to ChrootDirectory"); 1115 } 1116 1117 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 1118 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid); 1119} 1120 1121static void 1122do_pwchange(Session *s) 1123{ 1124 fflush(NULL); 1125 fprintf(stderr, "WARNING: Your password has expired.\n"); 1126 if (s->ttyfd != -1) { 1127 fprintf(stderr, 1128 "You must change your password now and log in again!\n"); 1129 execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL); 1130 perror("passwd"); 1131 } else { 1132 fprintf(stderr, 1133 "Password change required but no TTY available.\n"); 1134 } 1135 exit(1); 1136} 1137 1138static void 1139child_close_fds(struct ssh *ssh) 1140{ 1141 extern int auth_sock; 1142 1143 if (auth_sock != -1) { 1144 close(auth_sock); 1145 auth_sock = -1; 1146 } 1147 1148 if (ssh_packet_get_connection_in(ssh) == 1149 ssh_packet_get_connection_out(ssh)) 1150 close(ssh_packet_get_connection_in(ssh)); 1151 else { 1152 close(ssh_packet_get_connection_in(ssh)); 1153 close(ssh_packet_get_connection_out(ssh)); 1154 } 1155 /* 1156 * Close all descriptors related to channels. They will still remain 1157 * open in the parent. 1158 */ 1159 /* XXX better use close-on-exec? -markus */ 1160 channel_close_all(ssh); 1161 1162 /* 1163 * Close any extra file descriptors. Note that there may still be 1164 * descriptors left by system functions. They will be closed later. 1165 */ 1166 endpwent(); 1167 1168 /* Stop directing logs to a high-numbered fd before we close it */ 1169 log_redirect_stderr_to(NULL); 1170 1171 /* 1172 * Close any extra open file descriptors so that we don't have them 1173 * hanging around in clients. Note that we want to do this after 1174 * initgroups, because at least on Solaris 2.3 it leaves file 1175 * descriptors open. 1176 */ 1177 closefrom(STDERR_FILENO + 1); 1178} 1179 1180/* 1181 * Performs common processing for the child, such as setting up the 1182 * environment, closing extra file descriptors, setting the user and group 1183 * ids, and executing the command or shell. 1184 */ 1185#define ARGV_MAX 10 1186void 1187do_child(struct ssh *ssh, Session *s, const char *command) 1188{ 1189 extern char **environ; 1190 char **env, *argv[ARGV_MAX], remote_id[512]; 1191 const char *shell, *shell0; 1192 struct passwd *pw = s->pw; 1193 int r = 0; 1194 1195 sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id)); 1196 1197 /* remove keys from memory */ 1198 ssh_packet_clear_keys(ssh); 1199 1200 /* Force a password change */ 1201 if (s->authctxt->force_pwchange) { 1202 do_setusercontext(pw); 1203 child_close_fds(ssh); 1204 do_pwchange(s); 1205 exit(1); 1206 } 1207 1208 /* 1209 * Login(1) does this as well, and it needs uid 0 for the "-h" 1210 * switch, so we let login(1) to this for us. 1211 */ 1212 do_nologin(pw); 1213 do_setusercontext(pw); 1214 1215 /* 1216 * Get the shell from the password data. An empty shell field is 1217 * legal, and means /bin/sh. 1218 */ 1219 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 1220 1221 /* 1222 * Make sure $SHELL points to the shell from the password file, 1223 * even if shell is overridden from login.conf 1224 */ 1225 env = do_setup_env(ssh, s, shell); 1226 1227 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell); 1228 1229 /* 1230 * Close the connection descriptors; note that this is the child, and 1231 * the server will still have the socket open, and it is important 1232 * that we do not shutdown it. Note that the descriptors cannot be 1233 * closed before building the environment, as we call 1234 * ssh_remote_ipaddr there. 1235 */ 1236 child_close_fds(ssh); 1237 1238 /* 1239 * Must take new environment into use so that .ssh/rc, 1240 * /etc/ssh/sshrc and xauth are run in the proper environment. 1241 */ 1242 environ = env; 1243 1244#if defined(KRB5) && defined(USE_AFS) 1245 /* 1246 * At this point, we check to see if AFS is active and if we have 1247 * a valid Kerberos 5 TGT. If so, it seems like a good idea to see 1248 * if we can (and need to) extend the ticket into an AFS token. If 1249 * we don't do this, we run into potential problems if the user's 1250 * home directory is in AFS and it's not world-readable. 1251 */ 1252 1253 if (options.kerberos_get_afs_token && k_hasafs() && 1254 (s->authctxt->krb5_ctx != NULL)) { 1255 char cell[64]; 1256 1257 debug("Getting AFS token"); 1258 1259 k_setpag(); 1260 1261 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 1262 krb5_afslog(s->authctxt->krb5_ctx, 1263 s->authctxt->krb5_fwd_ccache, cell, NULL); 1264 1265 krb5_afslog_home(s->authctxt->krb5_ctx, 1266 s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir); 1267 } 1268#endif 1269 1270 /* Change current directory to the user's home directory. */ 1271 if (chdir(pw->pw_dir) == -1) { 1272 /* Suppress missing homedir warning for chroot case */ 1273 r = login_getcapbool(lc, "requirehome", 0); 1274 if (r || !in_chroot) { 1275 fprintf(stderr, "Could not chdir to home " 1276 "directory %s: %s\n", pw->pw_dir, 1277 strerror(errno)); 1278 } 1279 if (r) 1280 exit(1); 1281 } 1282 1283 closefrom(STDERR_FILENO + 1); 1284 1285 do_rc_files(ssh, s, shell); 1286 1287 /* restore SIGPIPE for child */ 1288 ssh_signal(SIGPIPE, SIG_DFL); 1289 1290 if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) { 1291 error("Connection from %s: refusing non-sftp session", 1292 remote_id); 1293 printf("This service allows sftp connections only.\n"); 1294 fflush(NULL); 1295 exit(1); 1296 } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) { 1297 extern int optind, optreset; 1298 int i; 1299 char *p, *args; 1300 1301 setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME); 1302 args = xstrdup(command ? command : "sftp-server"); 1303 for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " "))) 1304 if (i < ARGV_MAX - 1) 1305 argv[i++] = p; 1306 argv[i] = NULL; 1307 optind = optreset = 1; 1308 __progname = argv[0]; 1309 exit(sftp_server_main(i, argv, s->pw)); 1310 } 1311 1312 fflush(NULL); 1313 1314 /* Get the last component of the shell name. */ 1315 if ((shell0 = strrchr(shell, '/')) != NULL) 1316 shell0++; 1317 else 1318 shell0 = shell; 1319 1320 /* 1321 * If we have no command, execute the shell. In this case, the shell 1322 * name to be passed in argv[0] is preceded by '-' to indicate that 1323 * this is a login shell. 1324 */ 1325 if (!command) { 1326 char argv0[256]; 1327 1328 /* Start the shell. Set initial character to '-'. */ 1329 argv0[0] = '-'; 1330 1331 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1) 1332 >= sizeof(argv0) - 1) { 1333 errno = EINVAL; 1334 perror(shell); 1335 exit(1); 1336 } 1337 1338 /* Execute the shell. */ 1339 argv[0] = argv0; 1340 argv[1] = NULL; 1341 execve(shell, argv, env); 1342 1343 /* Executing the shell failed. */ 1344 perror(shell); 1345 exit(1); 1346 } 1347 /* 1348 * Execute the command using the user's shell. This uses the -c 1349 * option to execute the command. 1350 */ 1351 argv[0] = (char *) shell0; 1352 argv[1] = "-c"; 1353 argv[2] = (char *) command; 1354 argv[3] = NULL; 1355 execve(shell, argv, env); 1356 perror(shell); 1357 exit(1); 1358} 1359 1360void 1361session_unused(int id) 1362{ 1363 debug3_f("session id %d unused", id); 1364 if (id >= options.max_sessions || 1365 id >= sessions_nalloc) { 1366 fatal_f("insane session id %d (max %d nalloc %d)", 1367 id, options.max_sessions, sessions_nalloc); 1368 } 1369 memset(&sessions[id], 0, sizeof(*sessions)); 1370 sessions[id].self = id; 1371 sessions[id].used = 0; 1372 sessions[id].chanid = -1; 1373 sessions[id].ptyfd = -1; 1374 sessions[id].ttyfd = -1; 1375 sessions[id].ptymaster = -1; 1376 sessions[id].x11_chanids = NULL; 1377 sessions[id].next_unused = sessions_first_unused; 1378 sessions_first_unused = id; 1379} 1380 1381Session * 1382session_new(void) 1383{ 1384 Session *s, *tmp; 1385 1386 if (sessions_first_unused == -1) { 1387 if (sessions_nalloc >= options.max_sessions) 1388 return NULL; 1389 debug2_f("allocate (allocated %d max %d)", 1390 sessions_nalloc, options.max_sessions); 1391 tmp = xrecallocarray(sessions, sessions_nalloc, 1392 sessions_nalloc + 1, sizeof(*sessions)); 1393 if (tmp == NULL) { 1394 error_f("cannot allocate %d sessions", 1395 sessions_nalloc + 1); 1396 return NULL; 1397 } 1398 sessions = tmp; 1399 session_unused(sessions_nalloc++); 1400 } 1401 1402 if (sessions_first_unused >= sessions_nalloc || 1403 sessions_first_unused < 0) { 1404 fatal_f("insane first_unused %d max %d nalloc %d", 1405 sessions_first_unused, options.max_sessions, 1406 sessions_nalloc); 1407 } 1408 1409 s = &sessions[sessions_first_unused]; 1410 if (s->used) 1411 fatal_f("session %d already used", sessions_first_unused); 1412 sessions_first_unused = s->next_unused; 1413 s->used = 1; 1414 s->next_unused = -1; 1415 debug("session_new: session %d", s->self); 1416 1417 return s; 1418} 1419 1420static void 1421session_dump(void) 1422{ 1423 int i; 1424 for (i = 0; i < sessions_nalloc; i++) { 1425 Session *s = &sessions[i]; 1426 1427 debug("dump: used %d next_unused %d session %d " 1428 "channel %d pid %ld", 1429 s->used, 1430 s->next_unused, 1431 s->self, 1432 s->chanid, 1433 (long)s->pid); 1434 } 1435} 1436 1437int 1438session_open(Authctxt *authctxt, int chanid) 1439{ 1440 Session *s = session_new(); 1441 debug("session_open: channel %d", chanid); 1442 if (s == NULL) { 1443 error("no more sessions"); 1444 return 0; 1445 } 1446 s->authctxt = authctxt; 1447 s->pw = authctxt->pw; 1448 if (s->pw == NULL || !authctxt->valid) 1449 fatal("no user for session %d", s->self); 1450 debug("session_open: session %d: link with channel %d", s->self, chanid); 1451 s->chanid = chanid; 1452 return 1; 1453} 1454 1455Session * 1456session_by_tty(char *tty) 1457{ 1458 int i; 1459 for (i = 0; i < sessions_nalloc; i++) { 1460 Session *s = &sessions[i]; 1461 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) { 1462 debug("session_by_tty: session %d tty %s", i, tty); 1463 return s; 1464 } 1465 } 1466 debug("session_by_tty: unknown tty %.100s", tty); 1467 session_dump(); 1468 return NULL; 1469} 1470 1471static Session * 1472session_by_channel(int id) 1473{ 1474 int i; 1475 for (i = 0; i < sessions_nalloc; i++) { 1476 Session *s = &sessions[i]; 1477 if (s->used && s->chanid == id) { 1478 debug("session_by_channel: session %d channel %d", 1479 i, id); 1480 return s; 1481 } 1482 } 1483 debug("session_by_channel: unknown channel %d", id); 1484 session_dump(); 1485 return NULL; 1486} 1487 1488static Session * 1489session_by_x11_channel(int id) 1490{ 1491 int i, j; 1492 1493 for (i = 0; i < sessions_nalloc; i++) { 1494 Session *s = &sessions[i]; 1495 1496 if (s->x11_chanids == NULL || !s->used) 1497 continue; 1498 for (j = 0; s->x11_chanids[j] != -1; j++) { 1499 if (s->x11_chanids[j] == id) { 1500 debug("session_by_x11_channel: session %d " 1501 "channel %d", s->self, id); 1502 return s; 1503 } 1504 } 1505 } 1506 debug("session_by_x11_channel: unknown channel %d", id); 1507 session_dump(); 1508 return NULL; 1509} 1510 1511static Session * 1512session_by_pid(pid_t pid) 1513{ 1514 int i; 1515 debug("session_by_pid: pid %ld", (long)pid); 1516 for (i = 0; i < sessions_nalloc; i++) { 1517 Session *s = &sessions[i]; 1518 if (s->used && s->pid == pid) 1519 return s; 1520 } 1521 error("session_by_pid: unknown pid %ld", (long)pid); 1522 session_dump(); 1523 return NULL; 1524} 1525 1526static int 1527session_window_change_req(struct ssh *ssh, Session *s) 1528{ 1529 int r; 1530 1531 if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 || 1532 (r = sshpkt_get_u32(ssh, &s->row)) != 0 || 1533 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 || 1534 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 || 1535 (r = sshpkt_get_end(ssh)) != 0) 1536 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1537 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1538 return 1; 1539} 1540 1541static int 1542session_pty_req(struct ssh *ssh, Session *s) 1543{ 1544 int r; 1545 1546 if (!auth_opts->permit_pty_flag || !options.permit_tty) { 1547 debug("Allocating a pty not permitted for this connection."); 1548 return 0; 1549 } 1550 if (s->ttyfd != -1) { 1551 ssh_packet_disconnect(ssh, "Protocol error: you already have a pty."); 1552 return 0; 1553 } 1554 1555 if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 || 1556 (r = sshpkt_get_u32(ssh, &s->col)) != 0 || 1557 (r = sshpkt_get_u32(ssh, &s->row)) != 0 || 1558 (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 || 1559 (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0) 1560 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1561 1562 if (strcmp(s->term, "") == 0) { 1563 free(s->term); 1564 s->term = NULL; 1565 } 1566 1567 /* Allocate a pty and open it. */ 1568 debug("Allocating pty."); 1569 if (!mm_pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) { 1570 free(s->term); 1571 s->term = NULL; 1572 s->ptyfd = -1; 1573 s->ttyfd = -1; 1574 error("session_pty_req: session %d alloc failed", s->self); 1575 return 0; 1576 } 1577 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 1578 1579 ssh_tty_parse_modes(ssh, s->ttyfd); 1580 1581 if ((r = sshpkt_get_end(ssh)) != 0) 1582 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1583 1584 /* Set window size from the packet. */ 1585 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel); 1586 1587 session_proctitle(s); 1588 return 1; 1589} 1590 1591static int 1592session_subsystem_req(struct ssh *ssh, Session *s) 1593{ 1594 struct stat st; 1595 int r, success = 0; 1596 char *prog, *cmd, *type; 1597 u_int i; 1598 1599 if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 || 1600 (r = sshpkt_get_end(ssh)) != 0) 1601 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1602 debug2("subsystem request for %.100s by user %s", s->subsys, 1603 s->pw->pw_name); 1604 1605 for (i = 0; i < options.num_subsystems; i++) { 1606 if (strcmp(s->subsys, options.subsystem_name[i]) == 0) { 1607 prog = options.subsystem_command[i]; 1608 cmd = options.subsystem_args[i]; 1609 if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) { 1610 s->is_subsystem = SUBSYSTEM_INT_SFTP; 1611 debug("subsystem: %s", prog); 1612 } else { 1613 if (stat(prog, &st) == -1) 1614 debug("subsystem: cannot stat %s: %s", 1615 prog, strerror(errno)); 1616 s->is_subsystem = SUBSYSTEM_EXT; 1617 debug("subsystem: exec() %s", cmd); 1618 } 1619 xasprintf(&type, "session:subsystem:%s", 1620 options.subsystem_name[i]); 1621 channel_set_xtype(ssh, s->chanid, type); 1622 free(type); 1623 success = do_exec(ssh, s, cmd) == 0; 1624 break; 1625 } 1626 } 1627 1628 if (!success) 1629 logit("subsystem request for %.100s by user %s failed, " 1630 "subsystem not found", s->subsys, s->pw->pw_name); 1631 1632 return success; 1633} 1634 1635static int 1636session_x11_req(struct ssh *ssh, Session *s) 1637{ 1638 int r, success; 1639 u_char single_connection = 0; 1640 1641 if (s->auth_proto != NULL || s->auth_data != NULL) { 1642 error("session_x11_req: session %d: " 1643 "x11 forwarding already active", s->self); 1644 return 0; 1645 } 1646 if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 || 1647 (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 || 1648 (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 || 1649 (r = sshpkt_get_u32(ssh, &s->screen)) != 0 || 1650 (r = sshpkt_get_end(ssh)) != 0) 1651 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1652 1653 s->single_connection = single_connection; 1654 1655 if (xauth_valid_string(s->auth_proto) && 1656 xauth_valid_string(s->auth_data)) 1657 success = session_setup_x11fwd(ssh, s); 1658 else { 1659 success = 0; 1660 error("Invalid X11 forwarding data"); 1661 } 1662 if (!success) { 1663 free(s->auth_proto); 1664 free(s->auth_data); 1665 s->auth_proto = NULL; 1666 s->auth_data = NULL; 1667 } 1668 return success; 1669} 1670 1671static int 1672session_shell_req(struct ssh *ssh, Session *s) 1673{ 1674 int r; 1675 1676 if ((r = sshpkt_get_end(ssh)) != 0) 1677 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1678 1679 channel_set_xtype(ssh, s->chanid, "session:shell"); 1680 1681 return do_exec(ssh, s, NULL) == 0; 1682} 1683 1684static int 1685session_exec_req(struct ssh *ssh, Session *s) 1686{ 1687 u_int success; 1688 int r; 1689 char *command = NULL; 1690 1691 if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 || 1692 (r = sshpkt_get_end(ssh)) != 0) 1693 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1694 1695 channel_set_xtype(ssh, s->chanid, "session:command"); 1696 1697 success = do_exec(ssh, s, command) == 0; 1698 free(command); 1699 return success; 1700} 1701 1702static int 1703session_break_req(struct ssh *ssh, Session *s) 1704{ 1705 int r; 1706 1707 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */ 1708 (r = sshpkt_get_end(ssh)) != 0) 1709 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1710 1711 if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1) 1712 return 0; 1713 return 1; 1714} 1715 1716static int 1717session_env_req(struct ssh *ssh, Session *s) 1718{ 1719 char *name, *val; 1720 u_int i; 1721 int r; 1722 1723 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 || 1724 (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 || 1725 (r = sshpkt_get_end(ssh)) != 0) 1726 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1727 1728 /* Don't set too many environment variables */ 1729 if (s->num_env > 128) { 1730 debug2("Ignoring env request %s: too many env vars", name); 1731 goto fail; 1732 } 1733 1734 for (i = 0; i < options.num_accept_env; i++) { 1735 if (match_pattern(name, options.accept_env[i])) { 1736 debug2("Setting env %d: %s=%s", s->num_env, name, val); 1737 s->env = xrecallocarray(s->env, s->num_env, 1738 s->num_env + 1, sizeof(*s->env)); 1739 s->env[s->num_env].name = name; 1740 s->env[s->num_env].val = val; 1741 s->num_env++; 1742 return (1); 1743 } 1744 } 1745 debug2("Ignoring env request %s: disallowed name", name); 1746 1747 fail: 1748 free(name); 1749 free(val); 1750 return (0); 1751} 1752 1753/* 1754 * Conversion of signals from ssh channel request names. 1755 * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as 1756 * local extension. 1757 */ 1758static int 1759name2sig(char *name) 1760{ 1761#define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x 1762 SSH_SIG(HUP); 1763 SSH_SIG(INT); 1764 SSH_SIG(KILL); 1765 SSH_SIG(QUIT); 1766 SSH_SIG(TERM); 1767 SSH_SIG(USR1); 1768 SSH_SIG(USR2); 1769#undef SSH_SIG 1770 if (strcmp(name, "INFO@openssh.com") == 0) 1771 return SIGINFO; 1772 return -1; 1773} 1774 1775static int 1776session_signal_req(struct ssh *ssh, Session *s) 1777{ 1778 char *signame = NULL; 1779 int r, sig, success = 0; 1780 1781 if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 || 1782 (r = sshpkt_get_end(ssh)) != 0) { 1783 error_fr(r, "parse"); 1784 goto out; 1785 } 1786 if ((sig = name2sig(signame)) == -1) { 1787 error_f("unsupported signal \"%s\"", signame); 1788 goto out; 1789 } 1790 if (s->pid <= 0) { 1791 error_f("no pid for session %d", s->self); 1792 goto out; 1793 } 1794 if (s->forced || s->is_subsystem) { 1795 error_f("refusing to send signal %s to %s session", 1796 signame, s->forced ? "forced-command" : "subsystem"); 1797 goto out; 1798 } 1799 1800 debug_f("signal %s, killpg(%ld, %d)", signame, (long)s->pid, sig); 1801 temporarily_use_uid(s->pw); 1802 r = killpg(s->pid, sig); 1803 restore_uid(); 1804 if (r != 0) { 1805 error_f("killpg(%ld, %d): %s", (long)s->pid, 1806 sig, strerror(errno)); 1807 goto out; 1808 } 1809 1810 /* success */ 1811 success = 1; 1812 out: 1813 free(signame); 1814 return success; 1815} 1816 1817static int 1818session_auth_agent_req(struct ssh *ssh, Session *s) 1819{ 1820 static int called = 0; 1821 int r; 1822 1823 if ((r = sshpkt_get_end(ssh)) != 0) 1824 sshpkt_fatal(ssh, r, "%s: parse packet", __func__); 1825 if (!auth_opts->permit_agent_forwarding_flag || 1826 !options.allow_agent_forwarding || 1827 options.disable_forwarding) { 1828 debug_f("agent forwarding disabled"); 1829 return 0; 1830 } 1831 if (called) { 1832 return 0; 1833 } else { 1834 called = 1; 1835 return auth_input_request_forwarding(ssh, s->pw); 1836 } 1837} 1838 1839int 1840session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype) 1841{ 1842 int success = 0; 1843 Session *s; 1844 1845 if ((s = session_by_channel(c->self)) == NULL) { 1846 logit_f("no session %d req %.100s", c->self, rtype); 1847 return 0; 1848 } 1849 debug_f("session %d req %s", s->self, rtype); 1850 1851 /* 1852 * a session is in LARVAL state until a shell, a command 1853 * or a subsystem is executed 1854 */ 1855 if (c->type == SSH_CHANNEL_LARVAL) { 1856 if (strcmp(rtype, "shell") == 0) { 1857 success = session_shell_req(ssh, s); 1858 } else if (strcmp(rtype, "exec") == 0) { 1859 success = session_exec_req(ssh, s); 1860 } else if (strcmp(rtype, "pty-req") == 0) { 1861 success = session_pty_req(ssh, s); 1862 } else if (strcmp(rtype, "x11-req") == 0) { 1863 success = session_x11_req(ssh, s); 1864 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) { 1865 success = session_auth_agent_req(ssh, s); 1866 } else if (strcmp(rtype, "subsystem") == 0) { 1867 success = session_subsystem_req(ssh, s); 1868 } else if (strcmp(rtype, "env") == 0) { 1869 success = session_env_req(ssh, s); 1870 } 1871 } 1872 if (strcmp(rtype, "window-change") == 0) { 1873 success = session_window_change_req(ssh, s); 1874 } else if (strcmp(rtype, "break") == 0) { 1875 success = session_break_req(ssh, s); 1876 } else if (strcmp(rtype, "signal") == 0) { 1877 success = session_signal_req(ssh, s); 1878 } 1879 1880 return success; 1881} 1882 1883void 1884session_set_fds(struct ssh *ssh, Session *s, 1885 int fdin, int fdout, int fderr, int ignore_fderr, int is_tty) 1886{ 1887 /* 1888 * now that have a child and a pipe to the child, 1889 * we can activate our channel and register the fd's 1890 */ 1891 if (s->chanid == -1) 1892 fatal("no channel for session %d", s->self); 1893 channel_set_fds(ssh, s->chanid, 1894 fdout, fdin, fderr, 1895 ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ, 1896 1, is_tty, CHAN_SES_WINDOW_DEFAULT); 1897} 1898 1899/* 1900 * Function to perform pty cleanup. Also called if we get aborted abnormally 1901 * (e.g., due to a dropped connection). 1902 */ 1903void 1904session_pty_cleanup2(Session *s) 1905{ 1906 if (s == NULL) { 1907 error_f("no session"); 1908 return; 1909 } 1910 if (s->ttyfd == -1) 1911 return; 1912 1913 debug_f("session %d release %s", s->self, s->tty); 1914 1915 /* Record that the user has logged out. */ 1916 if (s->pid != 0) 1917 record_logout(s->pid, s->tty); 1918 1919 /* Release the pseudo-tty. */ 1920 if (getuid() == 0) 1921 pty_release(s->tty); 1922 1923 /* 1924 * Close the server side of the socket pairs. We must do this after 1925 * the pty cleanup, so that another process doesn't get this pty 1926 * while we're still cleaning up. 1927 */ 1928 if (s->ptymaster != -1 && close(s->ptymaster) == -1) 1929 error("close(s->ptymaster/%d): %s", 1930 s->ptymaster, strerror(errno)); 1931 1932 /* unlink pty from session */ 1933 s->ttyfd = -1; 1934} 1935 1936void 1937session_pty_cleanup(Session *s) 1938{ 1939 mm_session_pty_cleanup2(s); 1940} 1941 1942static char * 1943sig2name(int sig) 1944{ 1945#define SSH_SIG(x) if (sig == SIG ## x) return #x 1946 SSH_SIG(ABRT); 1947 SSH_SIG(ALRM); 1948 SSH_SIG(FPE); 1949 SSH_SIG(HUP); 1950 SSH_SIG(ILL); 1951 SSH_SIG(INT); 1952 SSH_SIG(KILL); 1953 SSH_SIG(PIPE); 1954 SSH_SIG(QUIT); 1955 SSH_SIG(SEGV); 1956 SSH_SIG(TERM); 1957 SSH_SIG(USR1); 1958 SSH_SIG(USR2); 1959#undef SSH_SIG 1960 return "SIG@openssh.com"; 1961} 1962 1963static void 1964session_close_x11(struct ssh *ssh, int id) 1965{ 1966 Channel *c; 1967 1968 if ((c = channel_by_id(ssh, id)) == NULL) { 1969 debug_f("x11 channel %d missing", id); 1970 } else { 1971 /* Detach X11 listener */ 1972 debug_f("detach x11 channel %d", id); 1973 channel_cancel_cleanup(ssh, id); 1974 if (c->ostate != CHAN_OUTPUT_CLOSED) 1975 chan_mark_dead(ssh, c); 1976 } 1977} 1978 1979static void 1980session_close_single_x11(struct ssh *ssh, int id, int force, void *arg) 1981{ 1982 Session *s; 1983 u_int i; 1984 1985 debug3_f("channel %d", id); 1986 channel_cancel_cleanup(ssh, id); 1987 if ((s = session_by_x11_channel(id)) == NULL) 1988 fatal_f("no x11 channel %d", id); 1989 for (i = 0; s->x11_chanids[i] != -1; i++) { 1990 debug_f("session %d: closing channel %d", 1991 s->self, s->x11_chanids[i]); 1992 /* 1993 * The channel "id" is already closing, but make sure we 1994 * close all of its siblings. 1995 */ 1996 if (s->x11_chanids[i] != id) 1997 session_close_x11(ssh, s->x11_chanids[i]); 1998 } 1999 free(s->x11_chanids); 2000 s->x11_chanids = NULL; 2001 free(s->display); 2002 s->display = NULL; 2003 free(s->auth_proto); 2004 s->auth_proto = NULL; 2005 free(s->auth_data); 2006 s->auth_data = NULL; 2007 free(s->auth_display); 2008 s->auth_display = NULL; 2009} 2010 2011static void 2012session_exit_message(struct ssh *ssh, Session *s, int status) 2013{ 2014 Channel *c; 2015 int r; 2016 char *note = NULL; 2017 2018 if ((c = channel_lookup(ssh, s->chanid)) == NULL) 2019 fatal_f("session %d: no channel %d", s->self, s->chanid); 2020 2021 if (WIFEXITED(status)) { 2022 channel_request_start(ssh, s->chanid, "exit-status", 0); 2023 if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 || 2024 (r = sshpkt_send(ssh)) != 0) 2025 sshpkt_fatal(ssh, r, "%s: exit reply", __func__); 2026 xasprintf(&note, "exit %d", WEXITSTATUS(status)); 2027 } else if (WIFSIGNALED(status)) { 2028 channel_request_start(ssh, s->chanid, "exit-signal", 0); 2029 if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 || 2030 (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 || 2031 (r = sshpkt_put_cstring(ssh, "")) != 0 || 2032 (r = sshpkt_put_cstring(ssh, "")) != 0 || 2033 (r = sshpkt_send(ssh)) != 0) 2034 sshpkt_fatal(ssh, r, "%s: exit reply", __func__); 2035 xasprintf(&note, "signal %d%s", WTERMSIG(status), 2036 WCOREDUMP(status) ? " core dumped" : ""); 2037 } else { 2038 /* Some weird exit cause. Just exit. */ 2039 ssh_packet_disconnect(ssh, "wait returned status %04x.", 2040 status); 2041 } 2042 2043 debug_f("session %d channel %d pid %ld %s", s->self, s->chanid, 2044 (long)s->pid, note == NULL ? "UNKNOWN" : note); 2045 free(note); 2046 2047 /* disconnect channel */ 2048 debug_f("release channel %d", s->chanid); 2049 2050 /* 2051 * Adjust cleanup callback attachment to send close messages when 2052 * the channel gets EOF. The session will be then be closed 2053 * by session_close_by_channel when the child sessions close their fds. 2054 */ 2055 channel_register_cleanup(ssh, c->self, session_close_by_channel, 1); 2056 2057 /* 2058 * emulate a write failure with 'chan_write_failed', nobody will be 2059 * interested in data we write. 2060 * Note that we must not call 'chan_read_failed', since there could 2061 * be some more data waiting in the pipe. 2062 */ 2063 if (c->ostate != CHAN_OUTPUT_CLOSED) 2064 chan_write_failed(ssh, c); 2065} 2066 2067void 2068session_close(struct ssh *ssh, Session *s) 2069{ 2070 u_int i; 2071 2072 verbose("Close session: user %s from %.200s port %d id %d", 2073 s->pw->pw_name, 2074 ssh_remote_ipaddr(ssh), 2075 ssh_remote_port(ssh), 2076 s->self); 2077 2078 if (s->ttyfd != -1) 2079 session_pty_cleanup(s); 2080 free(s->term); 2081 free(s->display); 2082 free(s->x11_chanids); 2083 free(s->auth_display); 2084 free(s->auth_data); 2085 free(s->auth_proto); 2086 free(s->subsys); 2087 if (s->env != NULL) { 2088 for (i = 0; i < s->num_env; i++) { 2089 free(s->env[i].name); 2090 free(s->env[i].val); 2091 } 2092 free(s->env); 2093 } 2094 session_proctitle(s); 2095 session_unused(s->self); 2096} 2097 2098void 2099session_close_by_pid(struct ssh *ssh, pid_t pid, int status) 2100{ 2101 Session *s = session_by_pid(pid); 2102 if (s == NULL) { 2103 debug_f("no session for pid %ld", (long)pid); 2104 return; 2105 } 2106 if (s->chanid != -1) 2107 session_exit_message(ssh, s, status); 2108 if (s->ttyfd != -1) 2109 session_pty_cleanup(s); 2110 s->pid = 0; 2111} 2112 2113/* 2114 * this is called when a channel dies before 2115 * the session 'child' itself dies 2116 */ 2117void 2118session_close_by_channel(struct ssh *ssh, int id, int force, void *arg) 2119{ 2120 Session *s = session_by_channel(id); 2121 u_int i; 2122 2123 if (s == NULL) { 2124 debug_f("no session for id %d", id); 2125 return; 2126 } 2127 debug_f("channel %d child %ld", id, (long)s->pid); 2128 if (s->pid != 0) { 2129 debug_f("channel %d: has child, ttyfd %d", id, s->ttyfd); 2130 /* 2131 * delay detach of session (unless this is a forced close), 2132 * but release pty, since the fd's to the child are already 2133 * closed 2134 */ 2135 if (s->ttyfd != -1) 2136 session_pty_cleanup(s); 2137 if (!force) 2138 return; 2139 } 2140 /* detach by removing callback */ 2141 channel_cancel_cleanup(ssh, s->chanid); 2142 2143 /* Close any X11 listeners associated with this session */ 2144 if (s->x11_chanids != NULL) { 2145 for (i = 0; s->x11_chanids[i] != -1; i++) { 2146 session_close_x11(ssh, s->x11_chanids[i]); 2147 s->x11_chanids[i] = -1; 2148 } 2149 } 2150 2151 s->chanid = -1; 2152 session_close(ssh, s); 2153} 2154 2155void 2156session_destroy_all(struct ssh *ssh, void (*closefunc)(Session *)) 2157{ 2158 int i; 2159 for (i = 0; i < sessions_nalloc; i++) { 2160 Session *s = &sessions[i]; 2161 if (s->used) { 2162 if (closefunc != NULL) 2163 closefunc(s); 2164 else 2165 session_close(ssh, s); 2166 } 2167 } 2168} 2169 2170static char * 2171session_tty_list(void) 2172{ 2173 static char buf[1024]; 2174 int i; 2175 buf[0] = '\0'; 2176 for (i = 0; i < sessions_nalloc; i++) { 2177 Session *s = &sessions[i]; 2178 if (s->used && s->ttyfd != -1) { 2179 if (buf[0] != '\0') 2180 strlcat(buf, ",", sizeof buf); 2181 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf); 2182 } 2183 } 2184 if (buf[0] == '\0') 2185 strlcpy(buf, "notty", sizeof buf); 2186 return buf; 2187} 2188 2189void 2190session_proctitle(Session *s) 2191{ 2192 if (s->pw == NULL) 2193 error("no user for session %d", s->self); 2194 else 2195 setproctitle("%s@%s", s->pw->pw_name, session_tty_list()); 2196} 2197 2198int 2199session_setup_x11fwd(struct ssh *ssh, Session *s) 2200{ 2201 struct stat st; 2202 char display[512], auth_display[512]; 2203 char hostname[NI_MAXHOST]; 2204 u_int i; 2205 2206 if (!auth_opts->permit_x11_forwarding_flag) { 2207 ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options."); 2208 return 0; 2209 } 2210 if (!options.x11_forwarding || options.disable_forwarding) { 2211 debug("X11 forwarding disabled in server configuration file."); 2212 return 0; 2213 } 2214 if (options.xauth_location == NULL || 2215 (stat(options.xauth_location, &st) == -1)) { 2216 ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11."); 2217 return 0; 2218 } 2219 if (s->display != NULL) { 2220 debug("X11 display already set."); 2221 return 0; 2222 } 2223 if (x11_create_display_inet(ssh, options.x11_display_offset, 2224 options.x11_use_localhost, s->single_connection, 2225 &s->display_number, &s->x11_chanids) == -1) { 2226 debug("x11_create_display_inet failed."); 2227 return 0; 2228 } 2229 for (i = 0; s->x11_chanids[i] != -1; i++) { 2230 channel_register_cleanup(ssh, s->x11_chanids[i], 2231 session_close_single_x11, 0); 2232 } 2233 2234 /* Set up a suitable value for the DISPLAY variable. */ 2235 if (gethostname(hostname, sizeof(hostname)) == -1) 2236 fatal("gethostname: %.100s", strerror(errno)); 2237 /* 2238 * auth_display must be used as the displayname when the 2239 * authorization entry is added with xauth(1). This will be 2240 * different than the DISPLAY string for localhost displays. 2241 */ 2242 if (options.x11_use_localhost) { 2243 snprintf(display, sizeof display, "localhost:%u.%u", 2244 s->display_number, s->screen); 2245 snprintf(auth_display, sizeof auth_display, "unix:%u.%u", 2246 s->display_number, s->screen); 2247 s->display = xstrdup(display); 2248 s->auth_display = xstrdup(auth_display); 2249 } else { 2250 snprintf(display, sizeof display, "%.400s:%u.%u", hostname, 2251 s->display_number, s->screen); 2252 s->display = xstrdup(display); 2253 s->auth_display = xstrdup(display); 2254 } 2255 2256 return 1; 2257} 2258 2259static void 2260do_authenticated2(struct ssh *ssh, Authctxt *authctxt) 2261{ 2262 server_loop2(ssh, authctxt); 2263} 2264 2265void 2266do_cleanup(struct ssh *ssh, Authctxt *authctxt) 2267{ 2268 static int called = 0; 2269 2270 debug("do_cleanup"); 2271 2272 /* no cleanup if we're in the child for login shell */ 2273 if (is_child) 2274 return; 2275 2276 /* avoid double cleanup */ 2277 if (called) 2278 return; 2279 called = 1; 2280 2281 if (authctxt == NULL || !authctxt->authenticated) 2282 return; 2283#ifdef KRB5 2284 if (options.kerberos_ticket_cleanup && 2285 authctxt->krb5_ctx) 2286 krb5_cleanup_proc(authctxt); 2287#endif 2288 2289#ifdef GSSAPI 2290 if (options.gss_cleanup_creds) 2291 ssh_gssapi_cleanup_creds(); 2292#endif 2293 2294 /* remove agent socket */ 2295 auth_sock_cleanup_proc(authctxt->pw); 2296 2297 /* remove userauth info */ 2298 if (auth_info_file != NULL) { 2299 temporarily_use_uid(authctxt->pw); 2300 unlink(auth_info_file); 2301 restore_uid(); 2302 free(auth_info_file); 2303 auth_info_file = NULL; 2304 } 2305 2306 /* 2307 * Cleanup ptys/utmp only if privsep is disabled, 2308 * or if running in monitor. 2309 */ 2310 if (mm_is_monitor()) 2311 session_destroy_all(ssh, session_pty_cleanup2); 2312} 2313 2314/* Return a name for the remote host that fits inside utmp_size */ 2315 2316const char * 2317session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns) 2318{ 2319 const char *remote = ""; 2320 2321 if (utmp_size > 0) 2322 remote = auth_get_canonical_hostname(ssh, use_dns); 2323 if (utmp_size == 0 || strlen(remote) > utmp_size) 2324 remote = ssh_remote_ipaddr(ssh); 2325 return remote; 2326} 2327