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

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