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

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