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

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