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

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