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

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

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