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

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