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

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