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

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