[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.316

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