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

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