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

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