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

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