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

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