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

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