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

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