[BACK]Return to session.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/session.c, Revision 1.334

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