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

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.39    ! markus     36: RCSID("$OpenBSD: session.c,v 1.38 2000/10/11 20:27:23 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.24      markus     92: void   do_login(Session *s);
1.1       markus     93:
                     94: void
                     95: do_child(const char *command, struct passwd * pw, const char *term,
                     96:     const char *display, const char *auth_proto,
                     97:     const char *auth_data, const char *ttyname);
                     98:
                     99: /* import */
                    100: extern ServerOptions options;
                    101: extern char *__progname;
                    102: extern int log_stderr;
                    103: extern int debug_flag;
1.25      markus    104: extern unsigned int utmp_len;
1.1       markus    105:
1.21      markus    106: extern int startup_pipe;
                    107:
1.1       markus    108: /* Local Xauthority file. */
                    109: static char *xauthfile;
                    110:
1.34      markus    111: /* original command from peer. */
                    112: char *original_command = NULL;
                    113:
1.1       markus    114: /* data */
                    115: #define MAX_SESSIONS 10
                    116: Session        sessions[MAX_SESSIONS];
                    117:
1.28      millert   118: #ifdef HAVE_LOGIN_CAP
                    119: static login_cap_t *lc;
                    120: #endif
                    121:
1.1       markus    122: /*
                    123:  * Remove local Xauthority file.
                    124:  */
                    125: void
                    126: xauthfile_cleanup_proc(void *ignore)
                    127: {
                    128:        debug("xauthfile_cleanup_proc called");
                    129:
                    130:        if (xauthfile != NULL) {
                    131:                char *p;
                    132:                unlink(xauthfile);
                    133:                p = strrchr(xauthfile, '/');
                    134:                if (p != NULL) {
                    135:                        *p = '\0';
                    136:                        rmdir(xauthfile);
                    137:                }
                    138:                xfree(xauthfile);
                    139:                xauthfile = NULL;
                    140:        }
                    141: }
                    142:
                    143: /*
                    144:  * Function to perform cleanup if we get aborted abnormally (e.g., due to a
                    145:  * dropped connection).
                    146:  */
1.4       markus    147: void
1.1       markus    148: pty_cleanup_proc(void *session)
                    149: {
                    150:        Session *s=session;
                    151:        if (s == NULL)
                    152:                fatal("pty_cleanup_proc: no session");
                    153:        debug("pty_cleanup_proc: %s", s->tty);
                    154:
                    155:        if (s->pid != 0) {
                    156:                /* Record that the user has logged out. */
                    157:                record_logout(s->pid, s->tty);
                    158:        }
                    159:
                    160:        /* Release the pseudo-tty. */
                    161:        pty_release(s->tty);
                    162: }
                    163:
                    164: /*
                    165:  * Prepares for an interactive session.  This is called after the user has
                    166:  * been successfully authenticated.  During this message exchange, pseudo
                    167:  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
                    168:  * are requested, etc.
                    169:  */
1.4       markus    170: void
1.1       markus    171: do_authenticated(struct passwd * pw)
                    172: {
                    173:        Session *s;
1.33      markus    174:        int type, fd;
1.1       markus    175:        int compression_level = 0, enable_compression_after_reply = 0;
                    176:        int have_pty = 0;
                    177:        char *command;
                    178:        int n_bytes;
                    179:        int plen;
                    180:        unsigned int proto_len, data_len, dlen;
                    181:
                    182:        /*
                    183:         * Cancel the alarm we set to limit the time taken for
                    184:         * authentication.
                    185:         */
                    186:        alarm(0);
1.23      deraadt   187:        if (startup_pipe != -1) {
                    188:                close(startup_pipe);
                    189:                startup_pipe = -1;
                    190:        }
1.1       markus    191:
                    192:        /*
                    193:         * Inform the channel mechanism that we are the server side and that
                    194:         * the client may request to connect to any port at all. (The user
                    195:         * could do it anyway, and we wouldn\'t know what is permitted except
                    196:         * by the client telling us, so we can equally well trust the client
                    197:         * not to request anything bogus.)
                    198:         */
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) */
                    575:                if (command == NULL && !options.use_login)
                    576:                        do_login(s);
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
                    628: do_login(Session *s)
                    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:
                    664:        /* Done if .hushlogin exists. */
                    665:        snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
1.28      millert   666: #ifdef HAVE_LOGIN_CAP
                    667:        if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
                    668: #else
1.24      markus    669:        if (stat(buf, &st) >= 0)
1.28      millert   670: #endif
1.24      markus    671:                return;
                    672:        if (last_login_time != 0) {
                    673:                time_string = ctime(&last_login_time);
                    674:                if (strchr(time_string, '\n'))
                    675:                        *strchr(time_string, '\n') = 0;
                    676:                if (strcmp(buf, "") == 0)
                    677:                        printf("Last login: %s\r\n", time_string);
                    678:                else
1.36      markus    679:                        printf("Last login: %s from %s\r\n", time_string, hostname);
1.24      markus    680:        }
                    681:        if (options.print_motd) {
1.28      millert   682: #ifdef HAVE_LOGIN_CAP
                    683:                f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
                    684:                    "/etc/motd"), "r");
                    685: #else
1.24      markus    686:                f = fopen("/etc/motd", "r");
1.28      millert   687: #endif
1.24      markus    688:                if (f) {
                    689:                        while (fgets(buf, sizeof(buf), f))
                    690:                                fputs(buf, stdout);
                    691:                        fclose(f);
                    692:                }
1.2       markus    693:        }
1.1       markus    694: }
                    695:
                    696: /*
                    697:  * Sets the value of the given variable in the environment.  If the variable
                    698:  * already exists, its value is overriden.
                    699:  */
1.4       markus    700: void
1.1       markus    701: child_set_env(char ***envp, unsigned int *envsizep, const char *name,
                    702:              const char *value)
                    703: {
                    704:        unsigned int i, namelen;
                    705:        char **env;
                    706:
                    707:        /*
                    708:         * Find the slot where the value should be stored.  If the variable
                    709:         * already exists, we reuse the slot; otherwise we append a new slot
                    710:         * at the end of the array, expanding if necessary.
                    711:         */
                    712:        env = *envp;
                    713:        namelen = strlen(name);
                    714:        for (i = 0; env[i]; i++)
                    715:                if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
                    716:                        break;
                    717:        if (env[i]) {
                    718:                /* Reuse the slot. */
                    719:                xfree(env[i]);
                    720:        } else {
                    721:                /* New variable.  Expand if necessary. */
                    722:                if (i >= (*envsizep) - 1) {
                    723:                        (*envsizep) += 50;
                    724:                        env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
                    725:                }
                    726:                /* Need to set the NULL pointer at end of array beyond the new slot. */
                    727:                env[i + 1] = NULL;
                    728:        }
                    729:
                    730:        /* Allocate space and format the variable in the appropriate slot. */
                    731:        env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
                    732:        snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
                    733: }
                    734:
                    735: /*
                    736:  * Reads environment variables from the given file and adds/overrides them
                    737:  * into the environment.  If the file does not exist, this does nothing.
                    738:  * Otherwise, it must consist of empty lines, comments (line starts with '#')
                    739:  * and assignments of the form name=value.  No other forms are allowed.
                    740:  */
1.4       markus    741: void
1.1       markus    742: read_environment_file(char ***env, unsigned int *envsize,
                    743:                      const char *filename)
                    744: {
                    745:        FILE *f;
                    746:        char buf[4096];
                    747:        char *cp, *value;
                    748:
                    749:        f = fopen(filename, "r");
                    750:        if (!f)
                    751:                return;
                    752:
                    753:        while (fgets(buf, sizeof(buf), f)) {
                    754:                for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
                    755:                        ;
                    756:                if (!*cp || *cp == '#' || *cp == '\n')
                    757:                        continue;
                    758:                if (strchr(cp, '\n'))
                    759:                        *strchr(cp, '\n') = '\0';
                    760:                value = strchr(cp, '=');
                    761:                if (value == NULL) {
                    762:                        fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
                    763:                        continue;
                    764:                }
1.14      deraadt   765:                /*
                    766:                 * Replace the equals sign by nul, and advance value to
                    767:                 * the value string.
                    768:                 */
1.1       markus    769:                *value = '\0';
                    770:                value++;
                    771:                child_set_env(env, envsize, cp, value);
                    772:        }
                    773:        fclose(f);
                    774: }
                    775:
                    776: /*
                    777:  * Performs common processing for the child, such as setting up the
                    778:  * environment, closing extra file descriptors, setting the user and group
                    779:  * ids, and executing the command or shell.
                    780:  */
1.4       markus    781: void
1.1       markus    782: do_child(const char *command, struct passwd * pw, const char *term,
                    783:         const char *display, const char *auth_proto,
                    784:         const char *auth_data, const char *ttyname)
                    785: {
1.32      markus    786:        const char *shell, *hostname = NULL, *cp = NULL;
1.1       markus    787:        char buf[256];
1.16      markus    788:        char cmd[1024];
1.27      millert   789:        FILE *f = NULL;
1.1       markus    790:        unsigned int envsize, i;
                    791:        char **env;
                    792:        extern char **environ;
                    793:        struct stat st;
                    794:        char *argv[10];
1.17      markus    795:
                    796:        /* login(1) is only called if we execute the login shell */
                    797:        if (options.use_login && command != NULL)
                    798:                options.use_login = 0;
1.1       markus    799:
1.27      millert   800:        if (!options.use_login) {
1.28      millert   801: #ifdef HAVE_LOGIN_CAP
                    802:                if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
                    803:                        f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
                    804:                            _PATH_NOLOGIN), "r");
                    805: #else
1.27      millert   806:                if (pw->pw_uid)
                    807:                        f = fopen(_PATH_NOLOGIN, "r");
1.28      millert   808: #endif
1.27      millert   809:                if (f) {
                    810:                        /* /etc/nologin exists.  Print its contents and exit. */
                    811:                        while (fgets(buf, sizeof(buf), f))
                    812:                                fputs(buf, stderr);
                    813:                        fclose(f);
1.1       markus    814:                        exit(254);
1.27      millert   815:                }
1.1       markus    816:        }
1.28      millert   817:        /* Set login name, uid, gid, and groups. */
1.1       markus    818:        /* Login(1) does this as well, and it needs uid 0 for the "-h"
                    819:           switch, so we let login(1) to this for us. */
                    820:        if (!options.use_login) {
                    821:                if (getuid() == 0 || geteuid() == 0) {
1.28      millert   822: #ifdef HAVE_LOGIN_CAP
                    823:                        if (setusercontext(lc, pw, pw->pw_uid,
                    824:                            (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
                    825:                                perror("unable to set user context");
                    826:                                exit(1);
                    827:
                    828:                        }
                    829: #else
                    830:                        if (setlogin(pw->pw_name) < 0)
                    831:                                error("setlogin failed: %s", strerror(errno));
1.1       markus    832:                        if (setgid(pw->pw_gid) < 0) {
                    833:                                perror("setgid");
                    834:                                exit(1);
                    835:                        }
                    836:                        /* Initialize the group list. */
                    837:                        if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
                    838:                                perror("initgroups");
                    839:                                exit(1);
                    840:                        }
                    841:                        endgrent();
                    842:
                    843:                        /* Permanently switch to the desired uid. */
                    844:                        permanently_set_uid(pw->pw_uid);
1.28      millert   845: #endif
1.1       markus    846:                }
                    847:                if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1.31      deraadt   848:                        fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1.1       markus    849:        }
                    850:        /*
                    851:         * Get the shell from the password data.  An empty shell field is
                    852:         * legal, and means /bin/sh.
                    853:         */
                    854:        shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.28      millert   855: #ifdef HAVE_LOGIN_CAP
                    856:        shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
                    857: #endif
1.1       markus    858:
                    859: #ifdef AFS
                    860:        /* Try to get AFS tokens for the local cell. */
                    861:        if (k_hasafs()) {
                    862:                char cell[64];
                    863:
                    864:                if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
                    865:                        krb_afslog(cell, 0);
                    866:
                    867:                krb_afslog(0, 0);
                    868:        }
                    869: #endif /* AFS */
                    870:
                    871:        /* Initialize the environment. */
                    872:        envsize = 100;
                    873:        env = xmalloc(envsize * sizeof(char *));
                    874:        env[0] = NULL;
                    875:
                    876:        if (!options.use_login) {
                    877:                /* Set basic environment. */
                    878:                child_set_env(&env, &envsize, "USER", pw->pw_name);
                    879:                child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
                    880:                child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1.28      millert   881: #ifdef HAVE_LOGIN_CAP
1.29      millert   882:                (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
                    883:                child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1.28      millert   884: #else
1.29      millert   885:                child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1.28      millert   886: #endif
1.1       markus    887:
                    888:                snprintf(buf, sizeof buf, "%.200s/%.50s",
                    889:                         _PATH_MAILDIR, pw->pw_name);
                    890:                child_set_env(&env, &envsize, "MAIL", buf);
                    891:
                    892:                /* Normal systems set SHELL by default. */
                    893:                child_set_env(&env, &envsize, "SHELL", shell);
                    894:        }
                    895:        if (getenv("TZ"))
                    896:                child_set_env(&env, &envsize, "TZ", getenv("TZ"));
                    897:
                    898:        /* Set custom environment options from RSA authentication. */
                    899:        while (custom_environment) {
                    900:                struct envstring *ce = custom_environment;
                    901:                char *s = ce->s;
                    902:                int i;
                    903:                for (i = 0; s[i] != '=' && s[i]; i++);
                    904:                if (s[i] == '=') {
                    905:                        s[i] = 0;
                    906:                        child_set_env(&env, &envsize, s, s + i + 1);
                    907:                }
                    908:                custom_environment = ce->next;
                    909:                xfree(ce->s);
                    910:                xfree(ce);
                    911:        }
                    912:
                    913:        snprintf(buf, sizeof buf, "%.50s %d %d",
                    914:                 get_remote_ipaddr(), get_remote_port(), get_local_port());
                    915:        child_set_env(&env, &envsize, "SSH_CLIENT", buf);
                    916:
                    917:        if (ttyname)
                    918:                child_set_env(&env, &envsize, "SSH_TTY", ttyname);
                    919:        if (term)
                    920:                child_set_env(&env, &envsize, "TERM", term);
                    921:        if (display)
                    922:                child_set_env(&env, &envsize, "DISPLAY", display);
1.34      markus    923:        if (original_command)
                    924:                child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
                    925:                    original_command);
1.1       markus    926:
                    927: #ifdef KRB4
                    928:        {
                    929:                extern char *ticket;
                    930:
                    931:                if (ticket)
                    932:                        child_set_env(&env, &envsize, "KRBTKFILE", ticket);
                    933:        }
                    934: #endif /* KRB4 */
                    935:
                    936:        if (xauthfile)
                    937:                child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
                    938:        if (auth_get_socket_name() != NULL)
                    939:                child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
                    940:                              auth_get_socket_name());
                    941:
                    942:        /* read $HOME/.ssh/environment. */
                    943:        if (!options.use_login) {
1.14      deraadt   944:                snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
                    945:                    pw->pw_dir);
1.1       markus    946:                read_environment_file(&env, &envsize, buf);
                    947:        }
                    948:        if (debug_flag) {
                    949:                /* dump the environment */
                    950:                fprintf(stderr, "Environment:\n");
                    951:                for (i = 0; env[i]; i++)
                    952:                        fprintf(stderr, "  %.200s\n", env[i]);
                    953:        }
1.26      millert   954:        /* we have to stash the hostname before we close our socket. */
                    955:        if (options.use_login)
                    956:                hostname = get_remote_name_or_ip();
1.1       markus    957:        /*
                    958:         * Close the connection descriptors; note that this is the child, and
                    959:         * the server will still have the socket open, and it is important
                    960:         * that we do not shutdown it.  Note that the descriptors cannot be
                    961:         * closed before building the environment, as we call
                    962:         * get_remote_ipaddr there.
                    963:         */
                    964:        if (packet_get_connection_in() == packet_get_connection_out())
                    965:                close(packet_get_connection_in());
                    966:        else {
                    967:                close(packet_get_connection_in());
                    968:                close(packet_get_connection_out());
                    969:        }
                    970:        /*
                    971:         * Close all descriptors related to channels.  They will still remain
                    972:         * open in the parent.
                    973:         */
                    974:        /* XXX better use close-on-exec? -markus */
                    975:        channel_close_all();
                    976:
                    977:        /*
                    978:         * Close any extra file descriptors.  Note that there may still be
                    979:         * descriptors left by system functions.  They will be closed later.
                    980:         */
                    981:        endpwent();
                    982:
                    983:        /*
                    984:         * Close any extra open file descriptors so that we don\'t have them
                    985:         * hanging around in clients.  Note that we want to do this after
                    986:         * initgroups, because at least on Solaris 2.3 it leaves file
                    987:         * descriptors open.
                    988:         */
                    989:        for (i = 3; i < 64; i++)
                    990:                close(i);
                    991:
                    992:        /* Change current directory to the user\'s home directory. */
1.28      millert   993:        if (chdir(pw->pw_dir) < 0) {
1.1       markus    994:                fprintf(stderr, "Could not chdir to home directory %s: %s\n",
                    995:                        pw->pw_dir, strerror(errno));
1.28      millert   996: #ifdef HAVE_LOGIN_CAP
                    997:                if (login_getcapbool(lc, "requirehome", 0))
                    998:                        exit(1);
                    999: #endif
                   1000:        }
1.1       markus   1001:
                   1002:        /*
                   1003:         * Must take new environment into use so that .ssh/rc, /etc/sshrc and
                   1004:         * xauth are run in the proper environment.
                   1005:         */
                   1006:        environ = env;
                   1007:
                   1008:        /*
                   1009:         * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
                   1010:         * in this order).
                   1011:         */
                   1012:        if (!options.use_login) {
                   1013:                if (stat(SSH_USER_RC, &st) >= 0) {
                   1014:                        if (debug_flag)
                   1015:                                fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
                   1016:
                   1017:                        f = popen("/bin/sh " SSH_USER_RC, "w");
                   1018:                        if (f) {
                   1019:                                if (auth_proto != NULL && auth_data != NULL)
                   1020:                                        fprintf(f, "%s %s\n", auth_proto, auth_data);
                   1021:                                pclose(f);
                   1022:                        } else
                   1023:                                fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
                   1024:                } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
                   1025:                        if (debug_flag)
                   1026:                                fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
                   1027:
                   1028:                        f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
                   1029:                        if (f) {
                   1030:                                if (auth_proto != NULL && auth_data != NULL)
                   1031:                                        fprintf(f, "%s %s\n", auth_proto, auth_data);
                   1032:                                pclose(f);
                   1033:                        } else
                   1034:                                fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
1.16      markus   1035:                } else if (options.xauth_location != NULL) {
1.1       markus   1036:                        /* Add authority data to .Xauthority if appropriate. */
                   1037:                        if (auth_proto != NULL && auth_data != NULL) {
1.13      markus   1038:                                char *screen = strchr(display, ':');
                   1039:                                if (debug_flag) {
1.14      deraadt  1040:                                        fprintf(stderr,
                   1041:                                            "Running %.100s add %.100s %.100s %.100s\n",
1.16      markus   1042:                                            options.xauth_location, display,
                   1043:                                            auth_proto, auth_data);
1.13      markus   1044:                                        if (screen != NULL)
1.14      deraadt  1045:                                                fprintf(stderr,
                   1046:                                                    "Adding %.*s/unix%s %s %s\n",
1.30      deraadt  1047:                                                    (int)(screen-display), display,
1.14      deraadt  1048:                                                    screen, auth_proto, auth_data);
1.13      markus   1049:                                }
1.16      markus   1050:                                snprintf(cmd, sizeof cmd, "%s -q -",
                   1051:                                    options.xauth_location);
                   1052:                                f = popen(cmd, "w");
1.1       markus   1053:                                if (f) {
1.14      deraadt  1054:                                        fprintf(f, "add %s %s %s\n", display,
                   1055:                                            auth_proto, auth_data);
1.13      markus   1056:                                        if (screen != NULL)
                   1057:                                                fprintf(f, "add %.*s/unix%s %s %s\n",
1.30      deraadt  1058:                                                    (int)(screen-display), display,
1.14      deraadt  1059:                                                    screen, auth_proto, auth_data);
1.1       markus   1060:                                        pclose(f);
1.16      markus   1061:                                } else {
                   1062:                                        fprintf(stderr, "Could not run %s\n",
                   1063:                                            cmd);
                   1064:                                }
1.1       markus   1065:                        }
                   1066:                }
                   1067:                /* Get the last component of the shell name. */
                   1068:                cp = strrchr(shell, '/');
                   1069:                if (cp)
                   1070:                        cp++;
                   1071:                else
                   1072:                        cp = shell;
                   1073:        }
                   1074:        /*
                   1075:         * If we have no command, execute the shell.  In this case, the shell
                   1076:         * name to be passed in argv[0] is preceded by '-' to indicate that
                   1077:         * this is a login shell.
                   1078:         */
                   1079:        if (!command) {
                   1080:                if (!options.use_login) {
                   1081:                        char buf[256];
                   1082:
                   1083:                        /*
                   1084:                         * Check for mail if we have a tty and it was enabled
                   1085:                         * in server options.
                   1086:                         */
                   1087:                        if (ttyname && options.check_mail) {
                   1088:                                char *mailbox;
                   1089:                                struct stat mailstat;
                   1090:                                mailbox = getenv("MAIL");
                   1091:                                if (mailbox != NULL) {
1.14      deraadt  1092:                                        if (stat(mailbox, &mailstat) != 0 ||
                   1093:                                            mailstat.st_size == 0)
1.1       markus   1094:                                                printf("No mail.\n");
                   1095:                                        else if (mailstat.st_mtime < mailstat.st_atime)
                   1096:                                                printf("You have mail.\n");
                   1097:                                        else
                   1098:                                                printf("You have new mail.\n");
                   1099:                                }
                   1100:                        }
                   1101:                        /* Start the shell.  Set initial character to '-'. */
                   1102:                        buf[0] = '-';
                   1103:                        strncpy(buf + 1, cp, sizeof(buf) - 1);
                   1104:                        buf[sizeof(buf) - 1] = 0;
                   1105:
                   1106:                        /* Execute the shell. */
                   1107:                        argv[0] = buf;
                   1108:                        argv[1] = NULL;
                   1109:                        execve(shell, argv, env);
                   1110:
                   1111:                        /* Executing the shell failed. */
                   1112:                        perror(shell);
                   1113:                        exit(1);
                   1114:
                   1115:                } else {
                   1116:                        /* Launch login(1). */
                   1117:
1.26      millert  1118:                        execl("/usr/bin/login", "login", "-h", hostname,
1.25      markus   1119:                             "-p", "-f", "--", pw->pw_name, NULL);
1.1       markus   1120:
                   1121:                        /* Login couldn't be executed, die. */
                   1122:
                   1123:                        perror("login");
                   1124:                        exit(1);
                   1125:                }
                   1126:        }
                   1127:        /*
                   1128:         * Execute the command using the user's shell.  This uses the -c
                   1129:         * option to execute the command.
                   1130:         */
                   1131:        argv[0] = (char *) cp;
                   1132:        argv[1] = "-c";
                   1133:        argv[2] = (char *) command;
                   1134:        argv[3] = NULL;
                   1135:        execve(shell, argv, env);
                   1136:        perror(shell);
                   1137:        exit(1);
                   1138: }
                   1139:
                   1140: Session *
                   1141: session_new(void)
                   1142: {
                   1143:        int i;
                   1144:        static int did_init = 0;
                   1145:        if (!did_init) {
                   1146:                debug("session_new: init");
                   1147:                for(i = 0; i < MAX_SESSIONS; i++) {
                   1148:                        sessions[i].used = 0;
                   1149:                        sessions[i].self = i;
                   1150:                }
                   1151:                did_init = 1;
                   1152:        }
                   1153:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1154:                Session *s = &sessions[i];
                   1155:                if (! s->used) {
                   1156:                        s->pid = 0;
1.7       markus   1157:                        s->extended = 0;
1.1       markus   1158:                        s->chanid = -1;
                   1159:                        s->ptyfd = -1;
                   1160:                        s->ttyfd = -1;
                   1161:                        s->term = NULL;
                   1162:                        s->pw = NULL;
                   1163:                        s->display = NULL;
                   1164:                        s->screen = 0;
                   1165:                        s->auth_data = NULL;
                   1166:                        s->auth_proto = NULL;
                   1167:                        s->used = 1;
1.7       markus   1168:                        s->pw = NULL;
1.1       markus   1169:                        debug("session_new: session %d", i);
                   1170:                        return s;
                   1171:                }
                   1172:        }
                   1173:        return NULL;
                   1174: }
                   1175:
                   1176: void
                   1177: session_dump(void)
                   1178: {
                   1179:        int i;
                   1180:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1181:                Session *s = &sessions[i];
                   1182:                debug("dump: used %d session %d %p channel %d pid %d",
                   1183:                    s->used,
                   1184:                    s->self,
                   1185:                    s,
                   1186:                    s->chanid,
                   1187:                    s->pid);
                   1188:        }
                   1189: }
                   1190:
1.2       markus   1191: int
                   1192: session_open(int chanid)
                   1193: {
                   1194:        Session *s = session_new();
                   1195:        debug("session_open: channel %d", chanid);
                   1196:        if (s == NULL) {
                   1197:                error("no more sessions");
                   1198:                return 0;
                   1199:        }
1.7       markus   1200:        s->pw = auth_get_user();
                   1201:        if (s->pw == NULL)
                   1202:                fatal("no user for session %i", s->self);
1.2       markus   1203:        debug("session_open: session %d: link with channel %d", s->self, chanid);
                   1204:        s->chanid = chanid;
                   1205:        return 1;
                   1206: }
                   1207:
                   1208: Session *
                   1209: session_by_channel(int id)
                   1210: {
                   1211:        int i;
                   1212:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1213:                Session *s = &sessions[i];
                   1214:                if (s->used && s->chanid == id) {
                   1215:                        debug("session_by_channel: session %d channel %d", i, id);
                   1216:                        return s;
                   1217:                }
                   1218:        }
                   1219:        debug("session_by_channel: unknown channel %d", id);
                   1220:        session_dump();
                   1221:        return NULL;
                   1222: }
                   1223:
                   1224: Session *
                   1225: session_by_pid(pid_t pid)
                   1226: {
                   1227:        int i;
                   1228:        debug("session_by_pid: pid %d", pid);
                   1229:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1230:                Session *s = &sessions[i];
                   1231:                if (s->used && s->pid == pid)
                   1232:                        return s;
                   1233:        }
                   1234:        error("session_by_pid: unknown pid %d", pid);
                   1235:        session_dump();
                   1236:        return NULL;
                   1237: }
                   1238:
                   1239: int
                   1240: session_window_change_req(Session *s)
                   1241: {
                   1242:        s->col = packet_get_int();
                   1243:        s->row = packet_get_int();
                   1244:        s->xpixel = packet_get_int();
                   1245:        s->ypixel = packet_get_int();
1.3       markus   1246:        packet_done();
1.2       markus   1247:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1248:        return 1;
                   1249: }
                   1250:
                   1251: int
                   1252: session_pty_req(Session *s)
                   1253: {
                   1254:        unsigned int len;
1.3       markus   1255:        char *term_modes;       /* encoded terminal modes */
1.2       markus   1256:
1.19      markus   1257:        if (no_pty_flag)
                   1258:                return 0;
1.2       markus   1259:        if (s->ttyfd != -1)
1.3       markus   1260:                return 0;
1.2       markus   1261:        s->term = packet_get_string(&len);
                   1262:        s->col = packet_get_int();
                   1263:        s->row = packet_get_int();
                   1264:        s->xpixel = packet_get_int();
                   1265:        s->ypixel = packet_get_int();
1.3       markus   1266:        term_modes = packet_get_string(&len);
                   1267:        packet_done();
1.2       markus   1268:
                   1269:        if (strcmp(s->term, "") == 0) {
                   1270:                xfree(s->term);
                   1271:                s->term = NULL;
                   1272:        }
                   1273:        /* Allocate a pty and open it. */
                   1274:        if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
                   1275:                xfree(s->term);
                   1276:                s->term = NULL;
                   1277:                s->ptyfd = -1;
                   1278:                s->ttyfd = -1;
                   1279:                error("session_pty_req: session %d alloc failed", s->self);
1.3       markus   1280:                xfree(term_modes);
                   1281:                return 0;
1.2       markus   1282:        }
                   1283:        debug("session_pty_req: session %d alloc %s", s->self, s->tty);
                   1284:        /*
                   1285:         * Add a cleanup function to clear the utmp entry and record logout
                   1286:         * time in case we call fatal() (e.g., the connection gets closed).
                   1287:         */
                   1288:        fatal_add_cleanup(pty_cleanup_proc, (void *)s);
                   1289:        pty_setowner(s->pw, s->tty);
                   1290:        /* Get window size from the packet. */
                   1291:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1292:
1.9       markus   1293:        session_proctitle(s);
                   1294:
1.3       markus   1295:        /* XXX parse and set terminal modes */
                   1296:        xfree(term_modes);
1.2       markus   1297:        return 1;
                   1298: }
                   1299:
1.7       markus   1300: int
                   1301: session_subsystem_req(Session *s)
                   1302: {
                   1303:        unsigned int len;
                   1304:        int success = 0;
                   1305:        char *subsys = packet_get_string(&len);
1.18      jakob    1306:        int i;
1.7       markus   1307:
                   1308:        packet_done();
                   1309:        log("subsystem request for %s", subsys);
1.18      jakob    1310:
                   1311:        for (i = 0; i < options.num_subsystems; i++) {
                   1312:                if(strcmp(subsys, options.subsystem_name[i]) == 0) {
                   1313:                        debug("subsystem: exec() %s", options.subsystem_command[i]);
                   1314:                        do_exec_no_pty(s, options.subsystem_command[i], s->pw);
                   1315:                        success = 1;
                   1316:                }
                   1317:        }
                   1318:
                   1319:        if (!success)
                   1320:                log("subsystem request for %s failed, subsystem not found", subsys);
1.7       markus   1321:
                   1322:        xfree(subsys);
                   1323:        return success;
                   1324: }
                   1325:
                   1326: int
                   1327: session_x11_req(Session *s)
                   1328: {
1.33      markus   1329:        int fd;
1.22      deraadt  1330:        if (no_x11_forwarding_flag) {
1.19      markus   1331:                debug("X11 forwarding disabled in user configuration file.");
                   1332:                return 0;
                   1333:        }
1.7       markus   1334:        if (!options.x11_forwarding) {
                   1335:                debug("X11 forwarding disabled in server configuration file.");
                   1336:                return 0;
                   1337:        }
                   1338:        if (xauthfile != NULL) {
                   1339:                debug("X11 fwd already started.");
                   1340:                return 0;
                   1341:        }
                   1342:
                   1343:        debug("Received request for X11 forwarding with auth spoofing.");
                   1344:        if (s->display != NULL)
                   1345:                packet_disconnect("Protocol error: X11 display already set.");
                   1346:
                   1347:        s->single_connection = packet_get_char();
                   1348:        s->auth_proto = packet_get_string(NULL);
                   1349:        s->auth_data = packet_get_string(NULL);
                   1350:        s->screen = packet_get_int();
                   1351:        packet_done();
                   1352:
                   1353:        s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
                   1354:        if (s->display == NULL) {
                   1355:                xfree(s->auth_proto);
                   1356:                xfree(s->auth_data);
                   1357:                return 0;
                   1358:        }
                   1359:        xauthfile = xmalloc(MAXPATHLEN);
                   1360:        strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
                   1361:        temporarily_use_uid(s->pw->pw_uid);
                   1362:        if (mkdtemp(xauthfile) == NULL) {
                   1363:                restore_uid();
                   1364:                error("private X11 dir: mkdtemp %s failed: %s",
                   1365:                    xauthfile, strerror(errno));
                   1366:                xfree(xauthfile);
                   1367:                xauthfile = NULL;
                   1368:                xfree(s->auth_proto);
                   1369:                xfree(s->auth_data);
                   1370:                /* XXXX remove listening channels */
                   1371:                return 0;
                   1372:        }
                   1373:        strlcat(xauthfile, "/cookies", MAXPATHLEN);
1.33      markus   1374:        fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
                   1375:        if (fd >= 0)
                   1376:                close(fd);
1.7       markus   1377:        restore_uid();
                   1378:        fatal_add_cleanup(xauthfile_cleanup_proc, s);
                   1379:        return 1;
                   1380: }
                   1381:
1.19      markus   1382: int
                   1383: session_shell_req(Session *s)
                   1384: {
                   1385:        /* if forced_command == NULL, the shell is execed */
                   1386:        char *shell = forced_command;
                   1387:        packet_done();
                   1388:        s->extended = 1;
                   1389:        if (s->ttyfd == -1)
                   1390:                do_exec_no_pty(s, shell, s->pw);
                   1391:        else
                   1392:                do_exec_pty(s, shell, s->pw);
                   1393:        return 1;
                   1394: }
                   1395:
                   1396: int
                   1397: session_exec_req(Session *s)
                   1398: {
1.20      markus   1399:        unsigned int len;
1.19      markus   1400:        char *command = packet_get_string(&len);
                   1401:        packet_done();
                   1402:        if (forced_command) {
1.34      markus   1403:                original_command = command;
1.19      markus   1404:                command = forced_command;
                   1405:                debug("Forced command '%.500s'", forced_command);
                   1406:        }
                   1407:        s->extended = 1;
                   1408:        if (s->ttyfd == -1)
                   1409:                do_exec_no_pty(s, command, s->pw);
                   1410:        else
                   1411:                do_exec_pty(s, command, s->pw);
                   1412:        if (forced_command == NULL)
                   1413:                xfree(command);
                   1414:        return 1;
                   1415: }
                   1416:
1.2       markus   1417: void
                   1418: session_input_channel_req(int id, void *arg)
                   1419: {
                   1420:        unsigned int len;
                   1421:        int reply;
                   1422:        int success = 0;
                   1423:        char *rtype;
                   1424:        Session *s;
                   1425:        Channel *c;
                   1426:
                   1427:        rtype = packet_get_string(&len);
                   1428:        reply = packet_get_char();
                   1429:
                   1430:        s = session_by_channel(id);
                   1431:        if (s == NULL)
                   1432:                fatal("session_input_channel_req: channel %d: no session", id);
                   1433:        c = channel_lookup(id);
                   1434:        if (c == NULL)
                   1435:                fatal("session_input_channel_req: channel %d: bad channel", id);
                   1436:
                   1437:        debug("session_input_channel_req: session %d channel %d request %s reply %d",
                   1438:            s->self, id, rtype, reply);
                   1439:
                   1440:        /*
                   1441:         * a session is in LARVAL state until a shell
                   1442:         * or programm is executed
                   1443:         */
                   1444:        if (c->type == SSH_CHANNEL_LARVAL) {
                   1445:                if (strcmp(rtype, "shell") == 0) {
1.19      markus   1446:                        success = session_shell_req(s);
1.2       markus   1447:                } else if (strcmp(rtype, "exec") == 0) {
1.19      markus   1448:                        success = session_exec_req(s);
1.2       markus   1449:                } else if (strcmp(rtype, "pty-req") == 0) {
1.3       markus   1450:                        success =  session_pty_req(s);
1.7       markus   1451:                } else if (strcmp(rtype, "x11-req") == 0) {
                   1452:                        success = session_x11_req(s);
                   1453:                } else if (strcmp(rtype, "subsystem") == 0) {
                   1454:                        success = session_subsystem_req(s);
1.2       markus   1455:                }
                   1456:        }
                   1457:        if (strcmp(rtype, "window-change") == 0) {
                   1458:                success = session_window_change_req(s);
                   1459:        }
                   1460:
                   1461:        if (reply) {
                   1462:                packet_start(success ?
                   1463:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
                   1464:                packet_put_int(c->remote_id);
                   1465:                packet_send();
                   1466:        }
                   1467:        xfree(rtype);
                   1468: }
                   1469:
                   1470: void
                   1471: session_set_fds(Session *s, int fdin, int fdout, int fderr)
                   1472: {
                   1473:        if (!compat20)
                   1474:                fatal("session_set_fds: called for proto != 2.0");
                   1475:        /*
                   1476:         * now that have a child and a pipe to the child,
                   1477:         * we can activate our channel and register the fd's
                   1478:         */
                   1479:        if (s->chanid == -1)
                   1480:                fatal("no channel for session %d", s->self);
                   1481:        channel_set_fds(s->chanid,
                   1482:            fdout, fdin, fderr,
                   1483:            fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
                   1484: }
                   1485:
1.1       markus   1486: void
                   1487: session_pty_cleanup(Session *s)
                   1488: {
                   1489:        if (s == NULL || s->ttyfd == -1)
                   1490:                return;
                   1491:
                   1492:        debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
                   1493:
                   1494:        /* Cancel the cleanup function. */
                   1495:        fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
                   1496:
                   1497:        /* Record that the user has logged out. */
                   1498:        record_logout(s->pid, s->tty);
                   1499:
                   1500:        /* Release the pseudo-tty. */
                   1501:        pty_release(s->tty);
                   1502:
                   1503:        /*
                   1504:         * Close the server side of the socket pairs.  We must do this after
                   1505:         * the pty cleanup, so that another process doesn't get this pty
                   1506:         * while we're still cleaning up.
                   1507:         */
                   1508:        if (close(s->ptymaster) < 0)
                   1509:                error("close(s->ptymaster): %s", strerror(errno));
1.2       markus   1510: }
                   1511:
                   1512: void
                   1513: session_exit_message(Session *s, int status)
                   1514: {
                   1515:        Channel *c;
                   1516:        if (s == NULL)
                   1517:                fatal("session_close: no session");
                   1518:        c = channel_lookup(s->chanid);
                   1519:        if (c == NULL)
                   1520:                fatal("session_close: session %d: no channel %d",
                   1521:                    s->self, s->chanid);
                   1522:        debug("session_exit_message: session %d channel %d pid %d",
                   1523:            s->self, s->chanid, s->pid);
                   1524:
                   1525:        if (WIFEXITED(status)) {
                   1526:                channel_request_start(s->chanid,
                   1527:                    "exit-status", 0);
                   1528:                packet_put_int(WEXITSTATUS(status));
                   1529:                packet_send();
                   1530:        } else if (WIFSIGNALED(status)) {
                   1531:                channel_request_start(s->chanid,
                   1532:                    "exit-signal", 0);
                   1533:                packet_put_int(WTERMSIG(status));
                   1534:                packet_put_char(WCOREDUMP(status));
                   1535:                packet_put_cstring("");
                   1536:                packet_put_cstring("");
                   1537:                packet_send();
                   1538:        } else {
                   1539:                /* Some weird exit cause.  Just exit. */
                   1540:                packet_disconnect("wait returned status %04x.", status);
                   1541:        }
                   1542:
                   1543:        /* disconnect channel */
                   1544:        debug("session_exit_message: release channel %d", s->chanid);
                   1545:        channel_cancel_cleanup(s->chanid);
1.5       markus   1546:        /*
                   1547:         * emulate a write failure with 'chan_write_failed', nobody will be
                   1548:         * interested in data we write.
                   1549:         * Note that we must not call 'chan_read_failed', since there could
                   1550:         * be some more data waiting in the pipe.
                   1551:         */
1.8       markus   1552:        if (c->ostate != CHAN_OUTPUT_CLOSED)
                   1553:                chan_write_failed(c);
1.2       markus   1554:        s->chanid = -1;
                   1555: }
                   1556:
                   1557: void
                   1558: session_free(Session *s)
                   1559: {
                   1560:        debug("session_free: session %d pid %d", s->self, s->pid);
                   1561:        if (s->term)
                   1562:                xfree(s->term);
                   1563:        if (s->display)
                   1564:                xfree(s->display);
                   1565:        if (s->auth_data)
                   1566:                xfree(s->auth_data);
                   1567:        if (s->auth_proto)
                   1568:                xfree(s->auth_proto);
                   1569:        s->used = 0;
                   1570: }
                   1571:
                   1572: void
                   1573: session_close(Session *s)
                   1574: {
                   1575:        session_pty_cleanup(s);
                   1576:        session_free(s);
1.9       markus   1577:        session_proctitle(s);
1.2       markus   1578: }
                   1579:
                   1580: void
                   1581: session_close_by_pid(pid_t pid, int status)
                   1582: {
                   1583:        Session *s = session_by_pid(pid);
                   1584:        if (s == NULL) {
                   1585:                debug("session_close_by_pid: no session for pid %d", s->pid);
                   1586:                return;
                   1587:        }
                   1588:        if (s->chanid != -1)
                   1589:                session_exit_message(s, status);
                   1590:        session_close(s);
                   1591: }
                   1592:
                   1593: /*
                   1594:  * this is called when a channel dies before
                   1595:  * the session 'child' itself dies
                   1596:  */
                   1597: void
                   1598: session_close_by_channel(int id, void *arg)
                   1599: {
                   1600:        Session *s = session_by_channel(id);
                   1601:        if (s == NULL) {
                   1602:                debug("session_close_by_channel: no session for channel %d", id);
                   1603:                return;
                   1604:        }
                   1605:        /* disconnect channel */
                   1606:        channel_cancel_cleanup(s->chanid);
                   1607:        s->chanid = -1;
                   1608:
                   1609:        debug("session_close_by_channel: channel %d kill %d", id, s->pid);
                   1610:        if (s->pid == 0) {
                   1611:                /* close session immediately */
                   1612:                session_close(s);
                   1613:        } else {
                   1614:                /* notify child, delay session cleanup */
                   1615:                if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
                   1616:                        error("session_close_by_channel: kill %d: %s",
                   1617:                            s->pid, strerror(errno));
                   1618:        }
1.9       markus   1619: }
                   1620:
                   1621: char *
                   1622: session_tty_list(void)
                   1623: {
                   1624:        static char buf[1024];
                   1625:        int i;
                   1626:        buf[0] = '\0';
                   1627:        for(i = 0; i < MAX_SESSIONS; i++) {
                   1628:                Session *s = &sessions[i];
                   1629:                if (s->used && s->ttyfd != -1) {
                   1630:                        if (buf[0] != '\0')
                   1631:                                strlcat(buf, ",", sizeof buf);
                   1632:                        strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
                   1633:                }
                   1634:        }
                   1635:        if (buf[0] == '\0')
                   1636:                strlcpy(buf, "notty", sizeof buf);
                   1637:        return buf;
                   1638: }
                   1639:
                   1640: void
                   1641: session_proctitle(Session *s)
                   1642: {
                   1643:        if (s->pw == NULL)
                   1644:                error("no user for session %d", s->self);
                   1645:        else
                   1646:                setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1.2       markus   1647: }
                   1648:
                   1649: void
                   1650: do_authenticated2(void)
                   1651: {
1.28      millert  1652:        struct passwd *pw;
                   1653:
1.2       markus   1654:        /*
                   1655:         * Cancel the alarm we set to limit the time taken for
                   1656:         * authentication.
                   1657:         */
                   1658:        alarm(0);
1.23      deraadt  1659:        if (startup_pipe != -1) {
                   1660:                close(startup_pipe);
                   1661:                startup_pipe = -1;
                   1662:        }
1.28      millert  1663: #ifdef HAVE_LOGIN_CAP
                   1664:        pw = auth_get_user();
                   1665:        if ((lc = login_getclass(pw->pw_class)) == NULL) {
                   1666:                error("unable to get login class");
                   1667:                return;
                   1668:        }
                   1669: #endif
1.2       markus   1670:        server_loop2();
1.7       markus   1671:        if (xauthfile)
                   1672:                xauthfile_cleanup_proc(NULL);
1.1       markus   1673: }