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

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