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

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