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

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