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

1.1       markus      1: /*
                      2:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      3:  *                    All rights reserved
1.37      deraadt     4:  *
                      5:  * As far as I am concerned, the code I have written for this software
                      6:  * can be used freely for any purpose.  Any derived versions of this
                      7:  * software must be clearly marked as such, and if the derived work is
                      8:  * incompatible with the protocol description in the RFC file, it must be
                      9:  * called by a name other than "ssh" or "Secure Shell".
                     10:  *
1.2       markus     11:  * SSH2 support by Markus Friedl.
1.58      deraadt    12:  * Copyright (c) 2000 Markus Friedl.  All rights reserved.
1.37      deraadt    13:  *
                     14:  * Redistribution and use in source and binary forms, with or without
                     15:  * modification, are permitted provided that the following conditions
                     16:  * are met:
                     17:  * 1. Redistributions of source code must retain the above copyright
                     18:  *    notice, this list of conditions and the following disclaimer.
                     19:  * 2. Redistributions in binary form must reproduce the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer in the
                     21:  *    documentation and/or other materials provided with the distribution.
                     22:  *
                     23:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     24:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     25:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     26:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     27:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     28:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     29:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     30:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     31:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     32:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.2       markus     33:  */
1.1       markus     34:
                     35: #include "includes.h"
1.90    ! markus     36: RCSID("$OpenBSD: session.c,v 1.89 2001/06/13 09:10:31 markus Exp $");
1.1       markus     37:
1.51      markus     38: #include "ssh.h"
                     39: #include "ssh1.h"
                     40: #include "ssh2.h"
1.1       markus     41: #include "xmalloc.h"
1.59      djm        42: #include "sshpty.h"
1.1       markus     43: #include "packet.h"
                     44: #include "buffer.h"
                     45: #include "mpaux.h"
                     46: #include "uidswap.h"
                     47: #include "compat.h"
1.78      markus     48: #include "channels.h"
1.2       markus     49: #include "bufaux.h"
                     50: #include "auth.h"
1.19      markus     51: #include "auth-options.h"
1.50      markus     52: #include "pathnames.h"
1.51      markus     53: #include "log.h"
                     54: #include "servconf.h"
1.59      djm        55: #include "sshlogin.h"
1.51      markus     56: #include "serverloop.h"
                     57: #include "canohost.h"
1.55      itojun     58: #include "session.h"
1.2       markus     59:
1.1       markus     60: /* types */
                     61:
                     62: #define TTYSZ 64
                     63: typedef struct Session Session;
                     64: struct Session {
                     65:        int     used;
                     66:        int     self;
                     67:        struct  passwd *pw;
                     68:        pid_t   pid;
                     69:        /* tty */
                     70:        char    *term;
                     71:        int     ptyfd, ttyfd, ptymaster;
                     72:        int     row, col, xpixel, ypixel;
                     73:        char    tty[TTYSZ];
                     74:        /* X11 */
                     75:        char    *display;
                     76:        int     screen;
                     77:        char    *auth_proto;
                     78:        char    *auth_data;
1.7       markus     79:        int     single_connection;
1.1       markus     80:        /* proto 2 */
                     81:        int     chanid;
1.64      markus     82:        int     is_subsystem;
1.1       markus     83: };
                     84:
                     85: /* func */
                     86:
                     87: Session *session_new(void);
                     88: void   session_set_fds(Session *s, int fdin, int fdout, int fderr);
1.85      markus     89: void   session_pty_cleanup(void *session);
1.86      markus     90: int    session_pty_req(Session *s);
1.9       markus     91: void   session_proctitle(Session *s);
1.81      markus     92: int    session_setup_x11fwd(Session *s);
1.82      markus     93: void   session_close(Session *s);
1.63      markus     94: void   do_exec_pty(Session *s, const char *command);
                     95: void   do_exec_no_pty(Session *s, const char *command);
1.90    ! markus     96: void   do_exec(Session *s, const char *command);
1.41      markus     97: void   do_login(Session *s, const char *command);
1.60      markus     98: void   do_child(Session *s, const char *command);
1.73      djm        99: void   do_motd(void);
                    100: int    check_quietlogin(Session *s, const char *command);
1.1       markus    101:
1.65      markus    102: void   do_authenticated1(Authctxt *authctxt);
                    103: void   do_authenticated2(Authctxt *authctxt);
                    104:
1.1       markus    105: /* import */
                    106: extern ServerOptions options;
                    107: extern char *__progname;
                    108: extern int log_stderr;
                    109: extern int debug_flag;
1.45      markus    110: extern u_int utmp_len;
1.21      markus    111: extern int startup_pipe;
1.74      markus    112: extern void destroy_sensitive_data(void);
1.21      markus    113:
1.34      markus    114: /* original command from peer. */
1.53      stevesk   115: char *original_command = NULL;
1.34      markus    116:
1.1       markus    117: /* data */
                    118: #define MAX_SESSIONS 10
                    119: Session        sessions[MAX_SESSIONS];
                    120:
1.28      millert   121: #ifdef HAVE_LOGIN_CAP
                    122: static login_cap_t *lc;
                    123: #endif
                    124:
1.65      markus    125: void
                    126: do_authenticated(Authctxt *authctxt)
                    127: {
                    128:        /*
                    129:         * Cancel the alarm we set to limit the time taken for
                    130:         * authentication.
                    131:         */
                    132:        alarm(0);
                    133:        if (startup_pipe != -1) {
                    134:                close(startup_pipe);
                    135:                startup_pipe = -1;
                    136:        }
                    137: #ifdef HAVE_LOGIN_CAP
                    138:        if ((lc = login_getclass(authctxt->pw->pw_class)) == NULL) {
                    139:                error("unable to get login class");
                    140:                return;
                    141:        }
1.74      markus    142: #ifdef BSD_AUTH
                    143:        if (auth_approval(NULL, lc, authctxt->pw->pw_name, "ssh") <= 0) {
                    144:                packet_disconnect("Approval failure for %s",
                    145:                    authctxt->pw->pw_name);
                    146:        }
                    147: #endif
1.65      markus    148: #endif
                    149:        /* setup the channel layer */
                    150:        if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
                    151:                channel_permit_all_opens();
                    152:
                    153:        if (compat20)
                    154:                do_authenticated2(authctxt);
                    155:        else
                    156:                do_authenticated1(authctxt);
1.79      markus    157:
1.87      markus    158:        /* remove agent socket */
1.79      markus    159:        if (auth_get_socket_name())
1.80      markus    160:                auth_sock_cleanup_proc(authctxt->pw);
1.65      markus    161: }
                    162:
1.1       markus    163: /*
                    164:  * Prepares for an interactive session.  This is called after the user has
                    165:  * been successfully authenticated.  During this message exchange, pseudo
                    166:  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
                    167:  * are requested, etc.
                    168:  */
1.4       markus    169: void
1.65      markus    170: do_authenticated1(Authctxt *authctxt)
1.1       markus    171: {
                    172:        Session *s;
1.65      markus    173:        char *command;
1.86      markus    174:        int success, type, plen, screen_flag;
1.1       markus    175:        int compression_level = 0, enable_compression_after_reply = 0;
1.45      markus    176:        u_int proto_len, data_len, dlen;
1.1       markus    177:
1.61      markus    178:        s = session_new();
1.65      markus    179:        s->pw = authctxt->pw;
1.28      millert   180:
1.1       markus    181:        /*
                    182:         * We stay in this loop until the client requests to execute a shell
                    183:         * or a command.
                    184:         */
                    185:        for (;;) {
1.65      markus    186:                success = 0;
1.1       markus    187:
                    188:                /* Get a packet from the client. */
                    189:                type = packet_read(&plen);
                    190:
                    191:                /* Process the packet. */
                    192:                switch (type) {
                    193:                case SSH_CMSG_REQUEST_COMPRESSION:
                    194:                        packet_integrity_check(plen, 4, type);
                    195:                        compression_level = packet_get_int();
                    196:                        if (compression_level < 1 || compression_level > 9) {
                    197:                                packet_send_debug("Received illegal compression level %d.",
                    198:                                     compression_level);
                    199:                                break;
                    200:                        }
                    201:                        /* Enable compression after we have responded with SUCCESS. */
                    202:                        enable_compression_after_reply = 1;
                    203:                        success = 1;
                    204:                        break;
                    205:
                    206:                case SSH_CMSG_REQUEST_PTY:
1.86      markus    207:                        success = session_pty_req(s);
1.1       markus    208:                        break;
                    209:
                    210:                case SSH_CMSG_X11_REQUEST_FORWARDING:
                    211:                        s->auth_proto = packet_get_string(&proto_len);
                    212:                        s->auth_data = packet_get_string(&data_len);
                    213:
1.57      markus    214:                        screen_flag = packet_get_protocol_flags() &
                    215:                            SSH_PROTOFLAG_SCREEN_NUMBER;
                    216:                        debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
                    217:
                    218:                        if (packet_remaining() == 4) {
                    219:                                if (!screen_flag)
                    220:                                        debug2("Buggy client: "
                    221:                                            "X11 screen flag missing");
1.1       markus    222:                                s->screen = packet_get_int();
1.56      markus    223:                        } else {
1.1       markus    224:                                s->screen = 0;
1.56      markus    225:                        }
1.81      markus    226:                        packet_done();
                    227:                        success = session_setup_x11fwd(s);
                    228:                        if (!success) {
                    229:                                xfree(s->auth_proto);
                    230:                                xfree(s->auth_data);
1.84      markus    231:                                s->auth_proto = NULL;
                    232:                                s->auth_data = NULL;
1.1       markus    233:                        }
                    234:                        break;
                    235:
                    236:                case SSH_CMSG_AGENT_REQUEST_FORWARDING:
                    237:                        if (no_agent_forwarding_flag || compat13) {
                    238:                                debug("Authentication agent forwarding not permitted for this authentication.");
                    239:                                break;
                    240:                        }
                    241:                        debug("Received authentication agent forwarding request.");
1.65      markus    242:                        success = auth_input_request_forwarding(s->pw);
1.1       markus    243:                        break;
                    244:
                    245:                case SSH_CMSG_PORT_FORWARD_REQUEST:
                    246:                        if (no_port_forwarding_flag) {
                    247:                                debug("Port forwarding not permitted for this authentication.");
1.39      markus    248:                                break;
                    249:                        }
                    250:                        if (!options.allow_tcp_forwarding) {
                    251:                                debug("Port forwarding not permitted.");
1.1       markus    252:                                break;
                    253:                        }
                    254:                        debug("Received TCP/IP port forwarding request.");
1.65      markus    255:                        channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
1.1       markus    256:                        success = 1;
                    257:                        break;
                    258:
                    259:                case SSH_CMSG_MAX_PACKET_SIZE:
                    260:                        if (packet_set_maxsize(packet_get_int()) > 0)
                    261:                                success = 1;
                    262:                        break;
                    263:
                    264:                case SSH_CMSG_EXEC_SHELL:
                    265:                case SSH_CMSG_EXEC_CMD:
                    266:                        if (type == SSH_CMSG_EXEC_CMD) {
                    267:                                command = packet_get_string(&dlen);
                    268:                                debug("Exec command '%.500s'", command);
                    269:                                packet_integrity_check(plen, 4 + dlen, type);
                    270:                        } else {
                    271:                                command = NULL;
                    272:                                packet_integrity_check(plen, 0, type);
                    273:                        }
1.90    ! markus    274:                        do_exec(s, command);
1.82      markus    275:                        session_close(s);
1.1       markus    276:                        return;
                    277:
                    278:                default:
                    279:                        /*
                    280:                         * Any unknown messages in this phase are ignored,
                    281:                         * and a failure message is returned.
                    282:                         */
                    283:                        log("Unknown packet type received after authentication: %d", type);
                    284:                }
                    285:                packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
                    286:                packet_send();
                    287:                packet_write_wait();
                    288:
                    289:                /* Enable compression now that we have replied if appropriate. */
                    290:                if (enable_compression_after_reply) {
                    291:                        enable_compression_after_reply = 0;
                    292:                        packet_start_compression(compression_level);
                    293:                }
                    294:        }
                    295: }
                    296:
                    297: /*
                    298:  * This is called to fork and execute a command when we have no tty.  This
                    299:  * will call do_child from the child, and server_loop from the parent after
                    300:  * setting up file descriptors and such.
                    301:  */
1.4       markus    302: void
1.63      markus    303: do_exec_no_pty(Session *s, const char *command)
1.1       markus    304: {
                    305:        int pid;
                    306:
                    307: #ifdef USE_PIPES
                    308:        int pin[2], pout[2], perr[2];
                    309:        /* Allocate pipes for communicating with the program. */
                    310:        if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
                    311:                packet_disconnect("Could not create pipes: %.100s",
                    312:                                  strerror(errno));
                    313: #else /* USE_PIPES */
                    314:        int inout[2], err[2];
                    315:        /* Uses socket pairs to communicate with the program. */
                    316:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
                    317:            socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
                    318:                packet_disconnect("Could not create socket pairs: %.100s",
                    319:                                  strerror(errno));
                    320: #endif /* USE_PIPES */
                    321:        if (s == NULL)
                    322:                fatal("do_exec_no_pty: no session");
                    323:
1.9       markus    324:        session_proctitle(s);
1.1       markus    325:
                    326:        /* Fork the child. */
                    327:        if ((pid = fork()) == 0) {
                    328:                /* Child.  Reinitialize the log since the pid has changed. */
                    329:                log_init(__progname, options.log_level, options.log_facility, log_stderr);
                    330:
                    331:                /*
                    332:                 * Create a new session and process group since the 4.4BSD
                    333:                 * setlogin() affects the entire process group.
                    334:                 */
                    335:                if (setsid() < 0)
                    336:                        error("setsid failed: %.100s", strerror(errno));
                    337:
                    338: #ifdef USE_PIPES
                    339:                /*
                    340:                 * Redirect stdin.  We close the parent side of the socket
                    341:                 * pair, and make the child side the standard input.
                    342:                 */
                    343:                close(pin[1]);
                    344:                if (dup2(pin[0], 0) < 0)
                    345:                        perror("dup2 stdin");
                    346:                close(pin[0]);
                    347:
                    348:                /* Redirect stdout. */
                    349:                close(pout[0]);
                    350:                if (dup2(pout[1], 1) < 0)
                    351:                        perror("dup2 stdout");
                    352:                close(pout[1]);
                    353:
                    354:                /* Redirect stderr. */
                    355:                close(perr[0]);
                    356:                if (dup2(perr[1], 2) < 0)
                    357:                        perror("dup2 stderr");
                    358:                close(perr[1]);
                    359: #else /* USE_PIPES */
                    360:                /*
                    361:                 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
                    362:                 * use the same socket, as some programs (particularly rdist)
                    363:                 * seem to depend on it.
                    364:                 */
                    365:                close(inout[1]);
                    366:                close(err[1]);
                    367:                if (dup2(inout[0], 0) < 0)      /* stdin */
                    368:                        perror("dup2 stdin");
                    369:                if (dup2(inout[0], 1) < 0)      /* stdout.  Note: same socket as stdin. */
                    370:                        perror("dup2 stdout");
                    371:                if (dup2(err[0], 2) < 0)        /* stderr */
                    372:                        perror("dup2 stderr");
                    373: #endif /* USE_PIPES */
                    374:
                    375:                /* Do processing for the child (exec command etc). */
1.60      markus    376:                do_child(s, command);
1.1       markus    377:                /* NOTREACHED */
                    378:        }
                    379:        if (pid < 0)
                    380:                packet_disconnect("fork failed: %.100s", strerror(errno));
                    381:        s->pid = pid;
1.47      markus    382:        /* Set interactive/non-interactive mode. */
1.48      markus    383:        packet_set_interactive(s->display != NULL);
1.1       markus    384: #ifdef USE_PIPES
                    385:        /* We are the parent.  Close the child sides of the pipes. */
                    386:        close(pin[0]);
                    387:        close(pout[1]);
                    388:        close(perr[1]);
                    389:
1.2       markus    390:        if (compat20) {
1.64      markus    391:                session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
1.2       markus    392:        } else {
                    393:                /* Enter the interactive session. */
                    394:                server_loop(pid, pin[1], pout[0], perr[0]);
1.64      markus    395:                /* server_loop has closed pin[1], pout[0], and perr[0]. */
1.2       markus    396:        }
1.1       markus    397: #else /* USE_PIPES */
                    398:        /* We are the parent.  Close the child sides of the socket pairs. */
                    399:        close(inout[0]);
                    400:        close(err[0]);
                    401:
                    402:        /*
                    403:         * Enter the interactive session.  Note: server_loop must be able to
                    404:         * handle the case that fdin and fdout are the same.
                    405:         */
1.2       markus    406:        if (compat20) {
1.64      markus    407:                session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
1.2       markus    408:        } else {
                    409:                server_loop(pid, inout[1], inout[1], err[1]);
                    410:                /* server_loop has closed inout[1] and err[1]. */
                    411:        }
1.1       markus    412: #endif /* USE_PIPES */
                    413: }
                    414:
                    415: /*
                    416:  * This is called to fork and execute a command when we have a tty.  This
                    417:  * will call do_child from the child, and server_loop from the parent after
                    418:  * setting up file descriptors, controlling tty, updating wtmp, utmp,
                    419:  * lastlog, and other such operations.
                    420:  */
1.4       markus    421: void
1.63      markus    422: do_exec_pty(Session *s, const char *command)
1.1       markus    423: {
                    424:        int fdout, ptyfd, ttyfd, ptymaster;
                    425:        pid_t pid;
                    426:
                    427:        if (s == NULL)
                    428:                fatal("do_exec_pty: no session");
                    429:        ptyfd = s->ptyfd;
                    430:        ttyfd = s->ttyfd;
                    431:
                    432:        /* Fork the child. */
                    433:        if ((pid = fork()) == 0) {
1.24      markus    434:                /* Child.  Reinitialize the log because the pid has changed. */
1.1       markus    435:                log_init(__progname, options.log_level, options.log_facility, log_stderr);
                    436:
                    437:                /* Close the master side of the pseudo tty. */
                    438:                close(ptyfd);
                    439:
                    440:                /* Make the pseudo tty our controlling tty. */
                    441:                pty_make_controlling_tty(&ttyfd, s->tty);
                    442:
                    443:                /* Redirect stdin from the pseudo tty. */
                    444:                if (dup2(ttyfd, fileno(stdin)) < 0)
                    445:                        error("dup2 stdin failed: %.100s", strerror(errno));
                    446:
                    447:                /* Redirect stdout to the pseudo tty. */
                    448:                if (dup2(ttyfd, fileno(stdout)) < 0)
                    449:                        error("dup2 stdin failed: %.100s", strerror(errno));
                    450:
                    451:                /* Redirect stderr to the pseudo tty. */
                    452:                if (dup2(ttyfd, fileno(stderr)) < 0)
                    453:                        error("dup2 stdin failed: %.100s", strerror(errno));
                    454:
                    455:                /* Close the extra descriptor for the pseudo tty. */
                    456:                close(ttyfd);
                    457:
1.24      markus    458:                /* record login, etc. similar to login(1) */
1.41      markus    459:                if (!(options.use_login && command == NULL))
                    460:                        do_login(s, command);
1.1       markus    461:
                    462:                /* Do common processing for the child, such as execing the command. */
1.60      markus    463:                do_child(s, command);
1.1       markus    464:                /* NOTREACHED */
                    465:        }
                    466:        if (pid < 0)
                    467:                packet_disconnect("fork failed: %.100s", strerror(errno));
                    468:        s->pid = pid;
                    469:
                    470:        /* Parent.  Close the slave side of the pseudo tty. */
                    471:        close(ttyfd);
                    472:
                    473:        /*
                    474:         * Create another descriptor of the pty master side for use as the
                    475:         * standard input.  We could use the original descriptor, but this
                    476:         * simplifies code in server_loop.  The descriptor is bidirectional.
                    477:         */
                    478:        fdout = dup(ptyfd);
                    479:        if (fdout < 0)
                    480:                packet_disconnect("dup #1 failed: %.100s", strerror(errno));
                    481:
                    482:        /* we keep a reference to the pty master */
                    483:        ptymaster = dup(ptyfd);
                    484:        if (ptymaster < 0)
                    485:                packet_disconnect("dup #2 failed: %.100s", strerror(errno));
                    486:        s->ptymaster = ptymaster;
                    487:
                    488:        /* Enter interactive session. */
1.47      markus    489:        packet_set_interactive(1);
1.2       markus    490:        if (compat20) {
                    491:                session_set_fds(s, ptyfd, fdout, -1);
                    492:        } else {
                    493:                server_loop(pid, ptyfd, fdout, -1);
                    494:                /* server_loop _has_ closed ptyfd and fdout. */
1.24      markus    495:        }
                    496: }
                    497:
1.90    ! markus    498: /*
        !           499:  * This is called to fork and execute a command.  If another command is
        !           500:  * to be forced, execute that instead.
        !           501:  */
        !           502: void
        !           503: do_exec(Session *s, const char *command)
        !           504: {
        !           505:        if (forced_command) {
        !           506:                original_command = command;
        !           507:                command = forced_command;
        !           508:                forced_command = NULL;
        !           509:                debug("Forced command '%.900s'", command);
        !           510:        }
        !           511:
        !           512:        if (s->ttyfd != -1)
        !           513:                do_exec_pty(s, command);
        !           514:        else
        !           515:                do_exec_no_pty(s, command);
        !           516:
        !           517:        if (command != NULL)
        !           518:                xfree(command);
        !           519:
        !           520:        if (original_command != NULL) {
        !           521:                xfree(original_command);
        !           522:                original_command = NULL;
        !           523:        }
        !           524: }
        !           525:
        !           526:
1.24      markus    527: /* administrative, login(1)-like work */
                    528: void
1.41      markus    529: do_login(Session *s, const char *command)
1.24      markus    530: {
                    531:        char *time_string;
1.35      markus    532:        char hostname[MAXHOSTNAMELEN];
1.24      markus    533:        socklen_t fromlen;
                    534:        struct sockaddr_storage from;
                    535:        time_t last_login_time;
                    536:        struct passwd * pw = s->pw;
                    537:        pid_t pid = getpid();
                    538:
                    539:        /*
                    540:         * Get IP address of client. If the connection is not a socket, let
                    541:         * the address be 0.0.0.0.
                    542:         */
                    543:        memset(&from, 0, sizeof(from));
                    544:        if (packet_connection_is_on_socket()) {
                    545:                fromlen = sizeof(from);
                    546:                if (getpeername(packet_get_connection_in(),
                    547:                     (struct sockaddr *) & from, &fromlen) < 0) {
                    548:                        debug("getpeername: %.100s", strerror(errno));
                    549:                        fatal_cleanup();
                    550:                }
                    551:        }
1.25      markus    552:
1.35      markus    553:        /* Get the time and hostname when the user last logged in. */
1.69      stevesk   554:        if (options.print_lastlog) {
                    555:                hostname[0] = '\0';
                    556:                last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
                    557:                    hostname, sizeof(hostname));
                    558:        }
1.35      markus    559:
1.24      markus    560:        /* Record that there was a login on that tty from the remote host. */
                    561:        record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
1.70      stevesk   562:            get_remote_name_or_ip(utmp_len, options.reverse_mapping_check),
                    563:            (struct sockaddr *)&from);
1.24      markus    564:
1.73      djm       565:        if (check_quietlogin(s, command))
1.24      markus    566:                return;
1.73      djm       567:
1.69      stevesk   568:        if (options.print_lastlog && last_login_time != 0) {
1.24      markus    569:                time_string = ctime(&last_login_time);
                    570:                if (strchr(time_string, '\n'))
                    571:                        *strchr(time_string, '\n') = 0;
1.40      markus    572:                if (strcmp(hostname, "") == 0)
1.24      markus    573:                        printf("Last login: %s\r\n", time_string);
                    574:                else
1.36      markus    575:                        printf("Last login: %s from %s\r\n", time_string, hostname);
1.24      markus    576:        }
1.73      djm       577:
                    578:        do_motd();
                    579: }
                    580:
                    581: /*
                    582:  * Display the message of the day.
                    583:  */
                    584: void
                    585: do_motd(void)
                    586: {
                    587:        FILE *f;
                    588:        char buf[256];
                    589:
1.24      markus    590:        if (options.print_motd) {
1.28      millert   591: #ifdef HAVE_LOGIN_CAP
                    592:                f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
                    593:                    "/etc/motd"), "r");
                    594: #else
1.24      markus    595:                f = fopen("/etc/motd", "r");
1.28      millert   596: #endif
1.24      markus    597:                if (f) {
                    598:                        while (fgets(buf, sizeof(buf), f))
                    599:                                fputs(buf, stdout);
                    600:                        fclose(f);
                    601:                }
1.2       markus    602:        }
1.73      djm       603: }
                    604:
                    605:
                    606: /*
                    607:  * Check for quiet login, either .hushlogin or command given.
                    608:  */
                    609: int
                    610: check_quietlogin(Session *s, const char *command)
                    611: {
                    612:        char buf[256];
                    613:        struct passwd * pw = s->pw;
                    614:        struct stat st;
                    615:
                    616:        /* Return 1 if .hushlogin exists or a command given. */
                    617:        if (command != NULL)
                    618:                return 1;
                    619:        snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
                    620: #ifdef HAVE_LOGIN_CAP
                    621:        if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
                    622:                return 1;
                    623: #else
                    624:        if (stat(buf, &st) >= 0)
                    625:                return 1;
                    626: #endif
                    627:        return 0;
1.1       markus    628: }
                    629:
                    630: /*
                    631:  * Sets the value of the given variable in the environment.  If the variable
                    632:  * already exists, its value is overriden.
                    633:  */
1.4       markus    634: void
1.45      markus    635: child_set_env(char ***envp, u_int *envsizep, const char *name,
1.1       markus    636:              const char *value)
                    637: {
1.45      markus    638:        u_int i, namelen;
1.1       markus    639:        char **env;
                    640:
                    641:        /*
                    642:         * Find the slot where the value should be stored.  If the variable
                    643:         * already exists, we reuse the slot; otherwise we append a new slot
                    644:         * at the end of the array, expanding if necessary.
                    645:         */
                    646:        env = *envp;
                    647:        namelen = strlen(name);
                    648:        for (i = 0; env[i]; i++)
                    649:                if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
                    650:                        break;
                    651:        if (env[i]) {
                    652:                /* Reuse the slot. */
                    653:                xfree(env[i]);
                    654:        } else {
                    655:                /* New variable.  Expand if necessary. */
                    656:                if (i >= (*envsizep) - 1) {
                    657:                        (*envsizep) += 50;
                    658:                        env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
                    659:                }
                    660:                /* Need to set the NULL pointer at end of array beyond the new slot. */
                    661:                env[i + 1] = NULL;
                    662:        }
                    663:
                    664:        /* Allocate space and format the variable in the appropriate slot. */
                    665:        env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
                    666:        snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
                    667: }
                    668:
                    669: /*
                    670:  * Reads environment variables from the given file and adds/overrides them
                    671:  * into the environment.  If the file does not exist, this does nothing.
                    672:  * Otherwise, it must consist of empty lines, comments (line starts with '#')
                    673:  * and assignments of the form name=value.  No other forms are allowed.
                    674:  */
1.4       markus    675: void
1.45      markus    676: read_environment_file(char ***env, u_int *envsize,
1.1       markus    677:                      const char *filename)
                    678: {
                    679:        FILE *f;
                    680:        char buf[4096];
                    681:        char *cp, *value;
                    682:
                    683:        f = fopen(filename, "r");
                    684:        if (!f)
                    685:                return;
                    686:
                    687:        while (fgets(buf, sizeof(buf), f)) {
                    688:                for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
                    689:                        ;
                    690:                if (!*cp || *cp == '#' || *cp == '\n')
                    691:                        continue;
                    692:                if (strchr(cp, '\n'))
                    693:                        *strchr(cp, '\n') = '\0';
                    694:                value = strchr(cp, '=');
                    695:                if (value == NULL) {
                    696:                        fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
                    697:                        continue;
                    698:                }
1.14      deraadt   699:                /*
                    700:                 * Replace the equals sign by nul, and advance value to
                    701:                 * the value string.
                    702:                 */
1.1       markus    703:                *value = '\0';
                    704:                value++;
                    705:                child_set_env(env, envsize, cp, value);
                    706:        }
                    707:        fclose(f);
                    708: }
                    709:
                    710: /*
                    711:  * Performs common processing for the child, such as setting up the
                    712:  * environment, closing extra file descriptors, setting the user and group
                    713:  * ids, and executing the command or shell.
                    714:  */
1.4       markus    715: void
1.60      markus    716: do_child(Session *s, const char *command)
1.1       markus    717: {
1.32      markus    718:        const char *shell, *hostname = NULL, *cp = NULL;
1.60      markus    719:        struct passwd * pw = s->pw;
1.1       markus    720:        char buf[256];
1.16      markus    721:        char cmd[1024];
1.27      millert   722:        FILE *f = NULL;
1.45      markus    723:        u_int envsize, i;
1.1       markus    724:        char **env;
                    725:        extern char **environ;
                    726:        struct stat st;
                    727:        char *argv[10];
1.84      markus    728:        int do_xauth;
                    729:
                    730:        do_xauth =
                    731:            s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1.17      markus    732:
1.74      markus    733:        /* remove hostkey from the child's memory */
                    734:        destroy_sensitive_data();
                    735:
1.17      markus    736:        /* login(1) is only called if we execute the login shell */
                    737:        if (options.use_login && command != NULL)
                    738:                options.use_login = 0;
1.1       markus    739:
1.27      millert   740:        if (!options.use_login) {
1.28      millert   741: #ifdef HAVE_LOGIN_CAP
                    742:                if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
                    743:                        f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
                    744:                            _PATH_NOLOGIN), "r");
                    745: #else
1.27      millert   746:                if (pw->pw_uid)
                    747:                        f = fopen(_PATH_NOLOGIN, "r");
1.28      millert   748: #endif
1.27      millert   749:                if (f) {
                    750:                        /* /etc/nologin exists.  Print its contents and exit. */
                    751:                        while (fgets(buf, sizeof(buf), f))
                    752:                                fputs(buf, stderr);
                    753:                        fclose(f);
1.1       markus    754:                        exit(254);
1.27      millert   755:                }
1.1       markus    756:        }
1.28      millert   757:        /* Set login name, uid, gid, and groups. */
1.1       markus    758:        /* Login(1) does this as well, and it needs uid 0 for the "-h"
                    759:           switch, so we let login(1) to this for us. */
                    760:        if (!options.use_login) {
                    761:                if (getuid() == 0 || geteuid() == 0) {
1.28      millert   762: #ifdef HAVE_LOGIN_CAP
                    763:                        if (setusercontext(lc, pw, pw->pw_uid,
                    764:                            (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
                    765:                                perror("unable to set user context");
                    766:                                exit(1);
                    767:                        }
                    768: #else
                    769:                        if (setlogin(pw->pw_name) < 0)
                    770:                                error("setlogin failed: %s", strerror(errno));
1.1       markus    771:                        if (setgid(pw->pw_gid) < 0) {
                    772:                                perror("setgid");
                    773:                                exit(1);
                    774:                        }
                    775:                        /* Initialize the group list. */
                    776:                        if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
                    777:                                perror("initgroups");
                    778:                                exit(1);
                    779:                        }
                    780:                        endgrent();
                    781:
                    782:                        /* Permanently switch to the desired uid. */
1.71      markus    783:                        permanently_set_uid(pw);
1.28      millert   784: #endif
1.1       markus    785:                }
                    786:                if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1.31      deraadt   787:                        fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1.1       markus    788:        }
                    789:        /*
                    790:         * Get the shell from the password data.  An empty shell field is
                    791:         * legal, and means /bin/sh.
                    792:         */
                    793:        shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.28      millert   794: #ifdef HAVE_LOGIN_CAP
                    795:        shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
                    796: #endif
1.1       markus    797:
                    798: #ifdef AFS
                    799:        /* Try to get AFS tokens for the local cell. */
                    800:        if (k_hasafs()) {
                    801:                char cell[64];
                    802:
                    803:                if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
                    804:                        krb_afslog(cell, 0);
                    805:
                    806:                krb_afslog(0, 0);
                    807:        }
                    808: #endif /* AFS */
                    809:
                    810:        /* Initialize the environment. */
                    811:        envsize = 100;
                    812:        env = xmalloc(envsize * sizeof(char *));
                    813:        env[0] = NULL;
                    814:
                    815:        if (!options.use_login) {
                    816:                /* Set basic environment. */
                    817:                child_set_env(&env, &envsize, "USER", pw->pw_name);
                    818:                child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
                    819:                child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1.28      millert   820: #ifdef HAVE_LOGIN_CAP
1.29      millert   821:                (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
                    822:                child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1.28      millert   823: #else
1.29      millert   824:                child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1.28      millert   825: #endif
1.1       markus    826:
                    827:                snprintf(buf, sizeof buf, "%.200s/%.50s",
                    828:                         _PATH_MAILDIR, pw->pw_name);
                    829:                child_set_env(&env, &envsize, "MAIL", buf);
                    830:
                    831:                /* Normal systems set SHELL by default. */
                    832:                child_set_env(&env, &envsize, "SHELL", shell);
                    833:        }
                    834:        if (getenv("TZ"))
                    835:                child_set_env(&env, &envsize, "TZ", getenv("TZ"));
                    836:
                    837:        /* Set custom environment options from RSA authentication. */
                    838:        while (custom_environment) {
                    839:                struct envstring *ce = custom_environment;
                    840:                char *s = ce->s;
                    841:                int i;
                    842:                for (i = 0; s[i] != '=' && s[i]; i++);
                    843:                if (s[i] == '=') {
                    844:                        s[i] = 0;
                    845:                        child_set_env(&env, &envsize, s, s + i + 1);
                    846:                }
                    847:                custom_environment = ce->next;
                    848:                xfree(ce->s);
                    849:                xfree(ce);
                    850:        }
                    851:
                    852:        snprintf(buf, sizeof buf, "%.50s %d %d",
                    853:                 get_remote_ipaddr(), get_remote_port(), get_local_port());
                    854:        child_set_env(&env, &envsize, "SSH_CLIENT", buf);
                    855:
1.60      markus    856:        if (s->ttyfd != -1)
                    857:                child_set_env(&env, &envsize, "SSH_TTY", s->tty);
                    858:        if (s->term)
                    859:                child_set_env(&env, &envsize, "TERM", s->term);
                    860:        if (s->display)
                    861:                child_set_env(&env, &envsize, "DISPLAY", s->display);
1.34      markus    862:        if (original_command)
                    863:                child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
                    864:                    original_command);
1.1       markus    865:
                    866: #ifdef KRB4
                    867:        {
                    868:                extern char *ticket;
                    869:
                    870:                if (ticket)
                    871:                        child_set_env(&env, &envsize, "KRBTKFILE", ticket);
                    872:        }
                    873: #endif /* KRB4 */
                    874:
                    875:        if (auth_get_socket_name() != NULL)
                    876:                child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
                    877:                              auth_get_socket_name());
                    878:
                    879:        /* read $HOME/.ssh/environment. */
                    880:        if (!options.use_login) {
1.14      deraadt   881:                snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
                    882:                    pw->pw_dir);
1.1       markus    883:                read_environment_file(&env, &envsize, buf);
                    884:        }
                    885:        if (debug_flag) {
                    886:                /* dump the environment */
                    887:                fprintf(stderr, "Environment:\n");
                    888:                for (i = 0; env[i]; i++)
                    889:                        fprintf(stderr, "  %.200s\n", env[i]);
                    890:        }
1.26      millert   891:        /* we have to stash the hostname before we close our socket. */
                    892:        if (options.use_login)
1.70      stevesk   893:                hostname = get_remote_name_or_ip(utmp_len,
                    894:                    options.reverse_mapping_check);
1.1       markus    895:        /*
                    896:         * Close the connection descriptors; note that this is the child, and
                    897:         * the server will still have the socket open, and it is important
                    898:         * that we do not shutdown it.  Note that the descriptors cannot be
                    899:         * closed before building the environment, as we call
                    900:         * get_remote_ipaddr there.
                    901:         */
                    902:        if (packet_get_connection_in() == packet_get_connection_out())
                    903:                close(packet_get_connection_in());
                    904:        else {
                    905:                close(packet_get_connection_in());
                    906:                close(packet_get_connection_out());
                    907:        }
                    908:        /*
                    909:         * Close all descriptors related to channels.  They will still remain
                    910:         * open in the parent.
                    911:         */
                    912:        /* XXX better use close-on-exec? -markus */
                    913:        channel_close_all();
                    914:
                    915:        /*
                    916:         * Close any extra file descriptors.  Note that there may still be
                    917:         * descriptors left by system functions.  They will be closed later.
                    918:         */
                    919:        endpwent();
                    920:
                    921:        /*
                    922:         * Close any extra open file descriptors so that we don\'t have them
                    923:         * hanging around in clients.  Note that we want to do this after
                    924:         * initgroups, because at least on Solaris 2.3 it leaves file
                    925:         * descriptors open.
                    926:         */
                    927:        for (i = 3; i < 64; i++)
                    928:                close(i);
                    929:
                    930:        /* Change current directory to the user\'s home directory. */
1.28      millert   931:        if (chdir(pw->pw_dir) < 0) {
1.1       markus    932:                fprintf(stderr, "Could not chdir to home directory %s: %s\n",
                    933:                        pw->pw_dir, strerror(errno));
1.28      millert   934: #ifdef HAVE_LOGIN_CAP
                    935:                if (login_getcapbool(lc, "requirehome", 0))
                    936:                        exit(1);
                    937: #endif
                    938:        }
1.1       markus    939:
                    940:        /*
                    941:         * Must take new environment into use so that .ssh/rc, /etc/sshrc and
                    942:         * xauth are run in the proper environment.
                    943:         */
                    944:        environ = env;
                    945:
                    946:        /*
                    947:         * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
                    948:         * in this order).
                    949:         */
                    950:        if (!options.use_login) {
1.74      markus    951:                /* ignore _PATH_SSH_USER_RC for subsystems */
                    952:                if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1.75      markus    953:                        snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
                    954:                            shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1.1       markus    955:                        if (debug_flag)
1.75      markus    956:                                fprintf(stderr, "Running %s\n", cmd);
                    957:                        f = popen(cmd, "w");
1.1       markus    958:                        if (f) {
1.60      markus    959:                                if (do_xauth)
                    960:                                        fprintf(f, "%s %s\n", s->auth_proto,
                    961:                                            s->auth_data);
1.1       markus    962:                                pclose(f);
                    963:                        } else
1.60      markus    964:                                fprintf(stderr, "Could not run %s\n",
                    965:                                    _PATH_SSH_USER_RC);
1.50      markus    966:                } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1.1       markus    967:                        if (debug_flag)
1.60      markus    968:                                fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
                    969:                                    _PATH_SSH_SYSTEM_RC);
1.50      markus    970:                        f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1.1       markus    971:                        if (f) {
1.60      markus    972:                                if (do_xauth)
                    973:                                        fprintf(f, "%s %s\n", s->auth_proto,
                    974:                                            s->auth_data);
1.1       markus    975:                                pclose(f);
                    976:                        } else
1.60      markus    977:                                fprintf(stderr, "Could not run %s\n",
                    978:                                    _PATH_SSH_SYSTEM_RC);
                    979:                } else if (do_xauth && options.xauth_location != NULL) {
1.1       markus    980:                        /* Add authority data to .Xauthority if appropriate. */
1.60      markus    981:                        char *screen = strchr(s->display, ':');
                    982:
                    983:                        if (debug_flag) {
                    984:                                fprintf(stderr,
                    985:                                    "Running %.100s add "
                    986:                                    "%.100s %.100s %.100s\n",
                    987:                                    options.xauth_location, s->display,
                    988:                                    s->auth_proto, s->auth_data);
                    989:                                if (screen != NULL)
1.14      deraadt   990:                                        fprintf(stderr,
1.60      markus    991:                                            "Adding %.*s/unix%s %s %s\n",
                    992:                                            (int)(screen - s->display),
                    993:                                            s->display, screen,
                    994:                                            s->auth_proto, s->auth_data);
                    995:                        }
                    996:                        snprintf(cmd, sizeof cmd, "%s -q -",
                    997:                            options.xauth_location);
                    998:                        f = popen(cmd, "w");
                    999:                        if (f) {
                   1000:                                fprintf(f, "add %s %s %s\n", s->display,
                   1001:                                    s->auth_proto, s->auth_data);
                   1002:                                if (screen != NULL)
                   1003:                                        fprintf(f, "add %.*s/unix%s %s %s\n",
                   1004:                                            (int)(screen - s->display),
                   1005:                                            s->display, screen,
                   1006:                                            s->auth_proto,
                   1007:                                            s->auth_data);
                   1008:                                pclose(f);
                   1009:                        } else {
                   1010:                                fprintf(stderr, "Could not run %s\n",
                   1011:                                    cmd);
1.1       markus   1012:                        }
                   1013:                }
                   1014:                /* Get the last component of the shell name. */
                   1015:                cp = strrchr(shell, '/');
                   1016:                if (cp)
                   1017:                        cp++;
                   1018:                else
                   1019:                        cp = shell;
                   1020:        }
1.67      markus   1021:
                   1022:        /* restore SIGPIPE for child */
                   1023:        signal(SIGPIPE,  SIG_DFL);
                   1024:
1.1       markus   1025:        /*
                   1026:         * If we have no command, execute the shell.  In this case, the shell
                   1027:         * name to be passed in argv[0] is preceded by '-' to indicate that
                   1028:         * this is a login shell.
                   1029:         */
                   1030:        if (!command) {
                   1031:                if (!options.use_login) {
                   1032:                        char buf[256];
                   1033:
                   1034:                        /*
                   1035:                         * Check for mail if we have a tty and it was enabled
                   1036:                         * in server options.
                   1037:                         */
1.60      markus   1038:                        if (s->ttyfd != -1 && options.check_mail) {
1.1       markus   1039:                                char *mailbox;
                   1040:                                struct stat mailstat;
1.60      markus   1041:
1.1       markus   1042:                                mailbox = getenv("MAIL");
                   1043:                                if (mailbox != NULL) {
1.14      deraadt  1044:                                        if (stat(mailbox, &mailstat) != 0 ||
                   1045:                                            mailstat.st_size == 0)
1.1       markus   1046:                                                printf("No mail.\n");
                   1047:                                        else if (mailstat.st_mtime < mailstat.st_atime)
                   1048:                                                printf("You have mail.\n");
                   1049:                                        else
                   1050:                                                printf("You have new mail.\n");
                   1051:                                }
                   1052:                        }
                   1053:                        /* Start the shell.  Set initial character to '-'. */
                   1054:                        buf[0] = '-';
                   1055:                        strncpy(buf + 1, cp, sizeof(buf) - 1);
                   1056:                        buf[sizeof(buf) - 1] = 0;
                   1057:
                   1058:                        /* Execute the shell. */
                   1059:                        argv[0] = buf;
                   1060:                        argv[1] = NULL;
                   1061:                        execve(shell, argv, env);
                   1062:
                   1063:                        /* Executing the shell failed. */
                   1064:                        perror(shell);
                   1065:                        exit(1);
                   1066:
                   1067:                } else {
                   1068:                        /* Launch login(1). */
                   1069:
1.26      millert  1070:                        execl("/usr/bin/login", "login", "-h", hostname,
1.25      markus   1071:                             "-p", "-f", "--", pw->pw_name, NULL);
1.1       markus   1072:
                   1073:                        /* Login couldn't be executed, die. */
                   1074:
                   1075:                        perror("login");
                   1076:                        exit(1);
                   1077:                }
                   1078:        }
                   1079:        /*
                   1080:         * Execute the command using the user's shell.  This uses the -c
                   1081:         * option to execute the command.
                   1082:         */
                   1083:        argv[0] = (char *) cp;
                   1084:        argv[1] = "-c";
                   1085:        argv[2] = (char *) command;
                   1086:        argv[3] = NULL;
                   1087:        execve(shell, argv, env);
                   1088:        perror(shell);
                   1089:        exit(1);
                   1090: }
                   1091:
                   1092: Session *
                   1093: session_new(void)
                   1094: {
                   1095:        int i;
                   1096:        static int did_init = 0;
                   1097:        if (!did_init) {
                   1098:                debug("session_new: init");
                   1099:                for(i = 0; i < MAX_SESSIONS; i++) {
                   1100:                        sessions[i].used = 0;
                   1101:                }
                   1102:                did_init = 1;
                   1103:        }
                   1104:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1105:                Session *s = &sessions[i];
                   1106:                if (! s->used) {
1.68      djm      1107:                        memset(s, 0, sizeof(*s));
1.1       markus   1108:                        s->chanid = -1;
                   1109:                        s->ptyfd = -1;
                   1110:                        s->ttyfd = -1;
                   1111:                        s->used = 1;
1.85      markus   1112:                        s->self = i;
1.1       markus   1113:                        debug("session_new: session %d", i);
                   1114:                        return s;
                   1115:                }
                   1116:        }
                   1117:        return NULL;
                   1118: }
                   1119:
                   1120: void
                   1121: session_dump(void)
                   1122: {
                   1123:        int i;
                   1124:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1125:                Session *s = &sessions[i];
                   1126:                debug("dump: used %d session %d %p channel %d pid %d",
                   1127:                    s->used,
                   1128:                    s->self,
                   1129:                    s,
                   1130:                    s->chanid,
                   1131:                    s->pid);
                   1132:        }
                   1133: }
                   1134:
1.2       markus   1135: int
                   1136: session_open(int chanid)
                   1137: {
                   1138:        Session *s = session_new();
                   1139:        debug("session_open: channel %d", chanid);
                   1140:        if (s == NULL) {
                   1141:                error("no more sessions");
                   1142:                return 0;
                   1143:        }
1.7       markus   1144:        s->pw = auth_get_user();
                   1145:        if (s->pw == NULL)
1.54      stevesk  1146:                fatal("no user for session %d", s->self);
1.2       markus   1147:        debug("session_open: session %d: link with channel %d", s->self, chanid);
                   1148:        s->chanid = chanid;
                   1149:        return 1;
                   1150: }
                   1151:
                   1152: Session *
                   1153: session_by_channel(int id)
                   1154: {
                   1155:        int i;
                   1156:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1157:                Session *s = &sessions[i];
                   1158:                if (s->used && s->chanid == id) {
                   1159:                        debug("session_by_channel: session %d channel %d", i, id);
                   1160:                        return s;
                   1161:                }
                   1162:        }
                   1163:        debug("session_by_channel: unknown channel %d", id);
                   1164:        session_dump();
                   1165:        return NULL;
                   1166: }
                   1167:
                   1168: Session *
                   1169: session_by_pid(pid_t pid)
                   1170: {
                   1171:        int i;
                   1172:        debug("session_by_pid: pid %d", pid);
                   1173:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1174:                Session *s = &sessions[i];
                   1175:                if (s->used && s->pid == pid)
                   1176:                        return s;
                   1177:        }
                   1178:        error("session_by_pid: unknown pid %d", pid);
                   1179:        session_dump();
                   1180:        return NULL;
                   1181: }
                   1182:
                   1183: int
                   1184: session_window_change_req(Session *s)
                   1185: {
                   1186:        s->col = packet_get_int();
                   1187:        s->row = packet_get_int();
                   1188:        s->xpixel = packet_get_int();
                   1189:        s->ypixel = packet_get_int();
1.3       markus   1190:        packet_done();
1.2       markus   1191:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1192:        return 1;
                   1193: }
                   1194:
                   1195: int
                   1196: session_pty_req(Session *s)
                   1197: {
1.45      markus   1198:        u_int len;
1.72      stevesk  1199:        int n_bytes;
1.2       markus   1200:
1.86      markus   1201:        if (no_pty_flag) {
                   1202:                debug("Allocating a pty not permitted for this authentication.");
1.19      markus   1203:                return 0;
1.86      markus   1204:        }
                   1205:        if (s->ttyfd != -1) {
                   1206:                packet_disconnect("Protocol error: you already have a pty.");
1.3       markus   1207:                return 0;
1.86      markus   1208:        }
                   1209:
1.2       markus   1210:        s->term = packet_get_string(&len);
1.86      markus   1211:
                   1212:        if (compat20) {
                   1213:                s->col = packet_get_int();
                   1214:                s->row = packet_get_int();
                   1215:        } else {
                   1216:                s->row = packet_get_int();
                   1217:                s->col = packet_get_int();
                   1218:        }
1.2       markus   1219:        s->xpixel = packet_get_int();
                   1220:        s->ypixel = packet_get_int();
                   1221:
                   1222:        if (strcmp(s->term, "") == 0) {
                   1223:                xfree(s->term);
                   1224:                s->term = NULL;
                   1225:        }
1.86      markus   1226:
1.2       markus   1227:        /* Allocate a pty and open it. */
1.86      markus   1228:        debug("Allocating pty.");
1.2       markus   1229:        if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1.86      markus   1230:                if (s->term)
                   1231:                        xfree(s->term);
1.2       markus   1232:                s->term = NULL;
                   1233:                s->ptyfd = -1;
                   1234:                s->ttyfd = -1;
                   1235:                error("session_pty_req: session %d alloc failed", s->self);
1.3       markus   1236:                return 0;
1.2       markus   1237:        }
                   1238:        debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1.86      markus   1239:
                   1240:        /* for SSH1 the tty modes length is not given */
                   1241:        if (!compat20)
                   1242:                n_bytes = packet_remaining();
                   1243:        tty_parse_modes(s->ttyfd, &n_bytes);
                   1244:
1.2       markus   1245:        /*
                   1246:         * Add a cleanup function to clear the utmp entry and record logout
                   1247:         * time in case we call fatal() (e.g., the connection gets closed).
                   1248:         */
1.85      markus   1249:        fatal_add_cleanup(session_pty_cleanup, (void *)s);
1.2       markus   1250:        pty_setowner(s->pw, s->tty);
1.86      markus   1251:
                   1252:        /* Set window size from the packet. */
1.2       markus   1253:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1254:
1.72      stevesk  1255:        packet_done();
1.9       markus   1256:        session_proctitle(s);
1.2       markus   1257:        return 1;
                   1258: }
                   1259:
1.7       markus   1260: int
                   1261: session_subsystem_req(Session *s)
                   1262: {
1.45      markus   1263:        u_int len;
1.7       markus   1264:        int success = 0;
                   1265:        char *subsys = packet_get_string(&len);
1.18      jakob    1266:        int i;
1.7       markus   1267:
                   1268:        packet_done();
                   1269:        log("subsystem request for %s", subsys);
1.18      jakob    1270:
                   1271:        for (i = 0; i < options.num_subsystems; i++) {
                   1272:                if(strcmp(subsys, options.subsystem_name[i]) == 0) {
                   1273:                        debug("subsystem: exec() %s", options.subsystem_command[i]);
1.64      markus   1274:                        s->is_subsystem = 1;
1.63      markus   1275:                        do_exec_no_pty(s, options.subsystem_command[i]);
1.18      jakob    1276:                        success = 1;
                   1277:                }
                   1278:        }
                   1279:
                   1280:        if (!success)
                   1281:                log("subsystem request for %s failed, subsystem not found", subsys);
1.7       markus   1282:
                   1283:        xfree(subsys);
                   1284:        return success;
                   1285: }
                   1286:
                   1287: int
                   1288: session_x11_req(Session *s)
                   1289: {
1.81      markus   1290:        int success;
1.7       markus   1291:
                   1292:        s->single_connection = packet_get_char();
                   1293:        s->auth_proto = packet_get_string(NULL);
                   1294:        s->auth_data = packet_get_string(NULL);
                   1295:        s->screen = packet_get_int();
                   1296:        packet_done();
                   1297:
1.81      markus   1298:        success = session_setup_x11fwd(s);
                   1299:        if (!success) {
1.7       markus   1300:                xfree(s->auth_proto);
                   1301:                xfree(s->auth_data);
1.84      markus   1302:                s->auth_proto = NULL;
                   1303:                s->auth_data = NULL;
1.7       markus   1304:        }
1.81      markus   1305:        return success;
1.7       markus   1306: }
                   1307:
1.19      markus   1308: int
                   1309: session_shell_req(Session *s)
                   1310: {
                   1311:        packet_done();
1.90    ! markus   1312:        do_exec(s, NULL);
1.19      markus   1313:        return 1;
                   1314: }
                   1315:
                   1316: int
                   1317: session_exec_req(Session *s)
                   1318: {
1.45      markus   1319:        u_int len;
1.19      markus   1320:        char *command = packet_get_string(&len);
                   1321:        packet_done();
1.90    ! markus   1322:        do_exec(s, command);
1.19      markus   1323:        return 1;
                   1324: }
                   1325:
1.43      markus   1326: int
                   1327: session_auth_agent_req(Session *s)
                   1328: {
                   1329:        static int called = 0;
                   1330:        packet_done();
1.44      markus   1331:        if (no_agent_forwarding_flag) {
                   1332:                debug("session_auth_agent_req: no_agent_forwarding_flag");
                   1333:                return 0;
                   1334:        }
1.43      markus   1335:        if (called) {
                   1336:                return 0;
                   1337:        } else {
                   1338:                called = 1;
                   1339:                return auth_input_request_forwarding(s->pw);
                   1340:        }
                   1341: }
                   1342:
1.2       markus   1343: void
                   1344: session_input_channel_req(int id, void *arg)
                   1345: {
1.45      markus   1346:        u_int len;
1.2       markus   1347:        int reply;
                   1348:        int success = 0;
                   1349:        char *rtype;
                   1350:        Session *s;
                   1351:        Channel *c;
                   1352:
                   1353:        rtype = packet_get_string(&len);
                   1354:        reply = packet_get_char();
                   1355:
                   1356:        s = session_by_channel(id);
                   1357:        if (s == NULL)
                   1358:                fatal("session_input_channel_req: channel %d: no session", id);
                   1359:        c = channel_lookup(id);
                   1360:        if (c == NULL)
                   1361:                fatal("session_input_channel_req: channel %d: bad channel", id);
                   1362:
                   1363:        debug("session_input_channel_req: session %d channel %d request %s reply %d",
                   1364:            s->self, id, rtype, reply);
                   1365:
                   1366:        /*
1.64      markus   1367:         * a session is in LARVAL state until a shell, a command
                   1368:         * or a subsystem is executed
1.2       markus   1369:         */
                   1370:        if (c->type == SSH_CHANNEL_LARVAL) {
                   1371:                if (strcmp(rtype, "shell") == 0) {
1.19      markus   1372:                        success = session_shell_req(s);
1.2       markus   1373:                } else if (strcmp(rtype, "exec") == 0) {
1.19      markus   1374:                        success = session_exec_req(s);
1.2       markus   1375:                } else if (strcmp(rtype, "pty-req") == 0) {
1.3       markus   1376:                        success =  session_pty_req(s);
1.7       markus   1377:                } else if (strcmp(rtype, "x11-req") == 0) {
                   1378:                        success = session_x11_req(s);
1.43      markus   1379:                } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
                   1380:                        success = session_auth_agent_req(s);
1.7       markus   1381:                } else if (strcmp(rtype, "subsystem") == 0) {
                   1382:                        success = session_subsystem_req(s);
1.2       markus   1383:                }
                   1384:        }
                   1385:        if (strcmp(rtype, "window-change") == 0) {
                   1386:                success = session_window_change_req(s);
                   1387:        }
                   1388:
                   1389:        if (reply) {
                   1390:                packet_start(success ?
                   1391:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
                   1392:                packet_put_int(c->remote_id);
                   1393:                packet_send();
                   1394:        }
                   1395:        xfree(rtype);
                   1396: }
                   1397:
                   1398: void
                   1399: session_set_fds(Session *s, int fdin, int fdout, int fderr)
                   1400: {
                   1401:        if (!compat20)
                   1402:                fatal("session_set_fds: called for proto != 2.0");
                   1403:        /*
                   1404:         * now that have a child and a pipe to the child,
                   1405:         * we can activate our channel and register the fd's
                   1406:         */
                   1407:        if (s->chanid == -1)
                   1408:                fatal("no channel for session %d", s->self);
                   1409:        channel_set_fds(s->chanid,
                   1410:            fdout, fdin, fderr,
1.42      markus   1411:            fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
                   1412:            1);
1.2       markus   1413: }
                   1414:
1.85      markus   1415: /*
                   1416:  * Function to perform pty cleanup. Also called if we get aborted abnormally
                   1417:  * (e.g., due to a dropped connection).
                   1418:  */
1.1       markus   1419: void
1.85      markus   1420: session_pty_cleanup(void *session)
1.1       markus   1421: {
1.85      markus   1422:        Session *s = session;
                   1423:
                   1424:        if (s == NULL) {
                   1425:                error("session_pty_cleanup: no session");
                   1426:                return;
                   1427:        }
                   1428:        if (s->ttyfd == -1)
1.1       markus   1429:                return;
                   1430:
1.54      stevesk  1431:        debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1.1       markus   1432:
                   1433:        /* Record that the user has logged out. */
1.85      markus   1434:        if (s->pid != 0)
                   1435:                record_logout(s->pid, s->tty);
1.1       markus   1436:
                   1437:        /* Release the pseudo-tty. */
                   1438:        pty_release(s->tty);
                   1439:
                   1440:        /*
                   1441:         * Close the server side of the socket pairs.  We must do this after
                   1442:         * the pty cleanup, so that another process doesn't get this pty
                   1443:         * while we're still cleaning up.
                   1444:         */
                   1445:        if (close(s->ptymaster) < 0)
                   1446:                error("close(s->ptymaster): %s", strerror(errno));
1.2       markus   1447: }
                   1448:
                   1449: void
                   1450: session_exit_message(Session *s, int status)
                   1451: {
                   1452:        Channel *c;
                   1453:        if (s == NULL)
                   1454:                fatal("session_close: no session");
                   1455:        c = channel_lookup(s->chanid);
                   1456:        if (c == NULL)
1.85      markus   1457:                fatal("session_exit_message: session %d: no channel %d",
1.2       markus   1458:                    s->self, s->chanid);
                   1459:        debug("session_exit_message: session %d channel %d pid %d",
                   1460:            s->self, s->chanid, s->pid);
                   1461:
                   1462:        if (WIFEXITED(status)) {
                   1463:                channel_request_start(s->chanid,
                   1464:                    "exit-status", 0);
                   1465:                packet_put_int(WEXITSTATUS(status));
                   1466:                packet_send();
                   1467:        } else if (WIFSIGNALED(status)) {
                   1468:                channel_request_start(s->chanid,
                   1469:                    "exit-signal", 0);
                   1470:                packet_put_int(WTERMSIG(status));
                   1471:                packet_put_char(WCOREDUMP(status));
                   1472:                packet_put_cstring("");
                   1473:                packet_put_cstring("");
                   1474:                packet_send();
                   1475:        } else {
                   1476:                /* Some weird exit cause.  Just exit. */
                   1477:                packet_disconnect("wait returned status %04x.", status);
                   1478:        }
                   1479:
                   1480:        /* disconnect channel */
                   1481:        debug("session_exit_message: release channel %d", s->chanid);
                   1482:        channel_cancel_cleanup(s->chanid);
1.5       markus   1483:        /*
                   1484:         * emulate a write failure with 'chan_write_failed', nobody will be
                   1485:         * interested in data we write.
                   1486:         * Note that we must not call 'chan_read_failed', since there could
                   1487:         * be some more data waiting in the pipe.
                   1488:         */
1.8       markus   1489:        if (c->ostate != CHAN_OUTPUT_CLOSED)
                   1490:                chan_write_failed(c);
1.2       markus   1491:        s->chanid = -1;
                   1492: }
                   1493:
                   1494: void
1.85      markus   1495: session_close(Session *s)
1.2       markus   1496: {
1.85      markus   1497:        debug("session_close: session %d pid %d", s->self, s->pid);
                   1498:        if (s->ttyfd != -1) {
                   1499:                fatal_remove_cleanup(session_pty_cleanup, (void *)s);
                   1500:                session_pty_cleanup(s);
                   1501:        }
1.2       markus   1502:        if (s->term)
                   1503:                xfree(s->term);
                   1504:        if (s->display)
                   1505:                xfree(s->display);
                   1506:        if (s->auth_data)
                   1507:                xfree(s->auth_data);
                   1508:        if (s->auth_proto)
                   1509:                xfree(s->auth_proto);
                   1510:        s->used = 0;
1.9       markus   1511:        session_proctitle(s);
1.2       markus   1512: }
                   1513:
                   1514: void
                   1515: session_close_by_pid(pid_t pid, int status)
                   1516: {
                   1517:        Session *s = session_by_pid(pid);
                   1518:        if (s == NULL) {
1.89      markus   1519:                debug("session_close_by_pid: no session for pid %d", pid);
1.2       markus   1520:                return;
                   1521:        }
                   1522:        if (s->chanid != -1)
                   1523:                session_exit_message(s, status);
                   1524:        session_close(s);
                   1525: }
                   1526:
                   1527: /*
                   1528:  * this is called when a channel dies before
                   1529:  * the session 'child' itself dies
                   1530:  */
                   1531: void
                   1532: session_close_by_channel(int id, void *arg)
                   1533: {
                   1534:        Session *s = session_by_channel(id);
                   1535:        if (s == NULL) {
                   1536:                debug("session_close_by_channel: no session for channel %d", id);
                   1537:                return;
                   1538:        }
                   1539:        /* disconnect channel */
                   1540:        channel_cancel_cleanup(s->chanid);
                   1541:        s->chanid = -1;
                   1542:
                   1543:        debug("session_close_by_channel: channel %d kill %d", id, s->pid);
                   1544:        if (s->pid == 0) {
                   1545:                /* close session immediately */
                   1546:                session_close(s);
                   1547:        } else {
                   1548:                /* notify child, delay session cleanup */
                   1549:                if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
                   1550:                        error("session_close_by_channel: kill %d: %s",
                   1551:                            s->pid, strerror(errno));
                   1552:        }
1.9       markus   1553: }
                   1554:
                   1555: char *
                   1556: session_tty_list(void)
                   1557: {
                   1558:        static char buf[1024];
                   1559:        int i;
                   1560:        buf[0] = '\0';
                   1561:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1562:                Session *s = &sessions[i];
                   1563:                if (s->used && s->ttyfd != -1) {
                   1564:                        if (buf[0] != '\0')
                   1565:                                strlcat(buf, ",", sizeof buf);
                   1566:                        strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
                   1567:                }
                   1568:        }
                   1569:        if (buf[0] == '\0')
                   1570:                strlcpy(buf, "notty", sizeof buf);
                   1571:        return buf;
                   1572: }
                   1573:
                   1574: void
                   1575: session_proctitle(Session *s)
                   1576: {
                   1577:        if (s->pw == NULL)
                   1578:                error("no user for session %d", s->self);
                   1579:        else
                   1580:                setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1.81      markus   1581: }
                   1582:
                   1583: int
                   1584: session_setup_x11fwd(Session *s)
                   1585: {
                   1586:        struct stat st;
                   1587:
                   1588:        if (no_x11_forwarding_flag) {
                   1589:                packet_send_debug("X11 forwarding disabled in user configuration file.");
                   1590:                return 0;
                   1591:        }
                   1592:        if (!options.x11_forwarding) {
                   1593:                debug("X11 forwarding disabled in server configuration file.");
                   1594:                return 0;
                   1595:        }
                   1596:        if (!options.xauth_location ||
                   1597:            (stat(options.xauth_location, &st) == -1)) {
                   1598:                packet_send_debug("No xauth program; cannot forward with spoofing.");
                   1599:                return 0;
                   1600:        }
1.87      markus   1601:        if (s->display != NULL) {
1.81      markus   1602:                debug("X11 display already set.");
                   1603:                return 0;
                   1604:        }
                   1605:        s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
                   1606:        if (s->display == NULL) {
1.87      markus   1607:                debug("x11_create_display_inet failed.");
1.81      markus   1608:                return 0;
                   1609:        }
                   1610:        return 1;
1.2       markus   1611: }
                   1612:
                   1613: void
1.49      markus   1614: do_authenticated2(Authctxt *authctxt)
1.2       markus   1615: {
                   1616:        server_loop2();
1.1       markus   1617: }