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

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