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

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