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

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