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

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