[BACK]Return to session.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/session.c, Revision 1.277

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