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

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