[BACK]Return to session.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / crypto / external / bsd / openssh / dist

Annotation of src/crypto/external/bsd/openssh/dist/session.c, Revision 1.34

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

CVSweb <webmaster@jp.NetBSD.org>