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

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