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

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