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

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