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

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