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

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.172   ! markus     36: RCSID("$OpenBSD: session.c,v 1.171 2004/01/13 19:23:15 markus Exp $");
1.1       markus     37:
1.51      markus     38: #include "ssh.h"
                     39: #include "ssh1.h"
                     40: #include "ssh2.h"
1.1       markus     41: #include "xmalloc.h"
1.59      djm        42: #include "sshpty.h"
1.1       markus     43: #include "packet.h"
                     44: #include "buffer.h"
                     45: #include "mpaux.h"
                     46: #include "uidswap.h"
                     47: #include "compat.h"
1.78      markus     48: #include "channels.h"
1.2       markus     49: #include "bufaux.h"
                     50: #include "auth.h"
1.19      markus     51: #include "auth-options.h"
1.50      markus     52: #include "pathnames.h"
1.51      markus     53: #include "log.h"
                     54: #include "servconf.h"
1.59      djm        55: #include "sshlogin.h"
1.51      markus     56: #include "serverloop.h"
                     57: #include "canohost.h"
1.55      itojun     58: #include "session.h"
1.130     provos     59: #include "monitor_wrap.h"
1.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.64      markus    454:                session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
1.2       markus    455:        } else {
                    456:                /* Enter the interactive session. */
                    457:                server_loop(pid, pin[1], pout[0], perr[0]);
1.64      markus    458:                /* server_loop has closed pin[1], pout[0], and perr[0]. */
1.2       markus    459:        }
1.1       markus    460: #else /* USE_PIPES */
                    461:        /* We are the parent.  Close the child sides of the socket pairs. */
                    462:        close(inout[0]);
                    463:        close(err[0]);
                    464:
                    465:        /*
                    466:         * Enter the interactive session.  Note: server_loop must be able to
                    467:         * handle the case that fdin and fdout are the same.
                    468:         */
1.2       markus    469:        if (compat20) {
1.64      markus    470:                session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
1.2       markus    471:        } else {
                    472:                server_loop(pid, inout[1], inout[1], err[1]);
                    473:                /* server_loop has closed inout[1] and err[1]. */
                    474:        }
1.1       markus    475: #endif /* USE_PIPES */
                    476: }
                    477:
                    478: /*
                    479:  * This is called to fork and execute a command when we have a tty.  This
                    480:  * will call do_child from the child, and server_loop from the parent after
                    481:  * setting up file descriptors, controlling tty, updating wtmp, utmp,
                    482:  * lastlog, and other such operations.
                    483:  */
1.4       markus    484: void
1.63      markus    485: do_exec_pty(Session *s, const char *command)
1.1       markus    486: {
                    487:        int fdout, ptyfd, ttyfd, ptymaster;
                    488:        pid_t pid;
                    489:
                    490:        if (s == NULL)
                    491:                fatal("do_exec_pty: no session");
                    492:        ptyfd = s->ptyfd;
                    493:        ttyfd = s->ttyfd;
                    494:
                    495:        /* Fork the child. */
                    496:        if ((pid = fork()) == 0) {
1.165     markus    497:                is_child = 1;
1.97      markus    498:
1.24      markus    499:                /* Child.  Reinitialize the log because the pid has changed. */
1.1       markus    500:                log_init(__progname, options.log_level, options.log_facility, log_stderr);
                    501:                /* Close the master side of the pseudo tty. */
                    502:                close(ptyfd);
                    503:
                    504:                /* Make the pseudo tty our controlling tty. */
                    505:                pty_make_controlling_tty(&ttyfd, s->tty);
                    506:
1.103     markus    507:                /* Redirect stdin/stdout/stderr from the pseudo tty. */
                    508:                if (dup2(ttyfd, 0) < 0)
                    509:                        error("dup2 stdin: %s", strerror(errno));
                    510:                if (dup2(ttyfd, 1) < 0)
                    511:                        error("dup2 stdout: %s", strerror(errno));
                    512:                if (dup2(ttyfd, 2) < 0)
                    513:                        error("dup2 stderr: %s", strerror(errno));
1.1       markus    514:
                    515:                /* Close the extra descriptor for the pseudo tty. */
                    516:                close(ttyfd);
                    517:
1.24      markus    518:                /* record login, etc. similar to login(1) */
1.41      markus    519:                if (!(options.use_login && command == NULL))
                    520:                        do_login(s, command);
1.1       markus    521:
                    522:                /* Do common processing for the child, such as execing the command. */
1.60      markus    523:                do_child(s, command);
1.1       markus    524:                /* NOTREACHED */
                    525:        }
                    526:        if (pid < 0)
                    527:                packet_disconnect("fork failed: %.100s", strerror(errno));
                    528:        s->pid = pid;
                    529:
                    530:        /* Parent.  Close the slave side of the pseudo tty. */
                    531:        close(ttyfd);
                    532:
                    533:        /*
                    534:         * Create another descriptor of the pty master side for use as the
                    535:         * standard input.  We could use the original descriptor, but this
                    536:         * simplifies code in server_loop.  The descriptor is bidirectional.
                    537:         */
                    538:        fdout = dup(ptyfd);
                    539:        if (fdout < 0)
                    540:                packet_disconnect("dup #1 failed: %.100s", strerror(errno));
                    541:
                    542:        /* we keep a reference to the pty master */
                    543:        ptymaster = dup(ptyfd);
                    544:        if (ptymaster < 0)
                    545:                packet_disconnect("dup #2 failed: %.100s", strerror(errno));
                    546:        s->ptymaster = ptymaster;
                    547:
                    548:        /* Enter interactive session. */
1.47      markus    549:        packet_set_interactive(1);
1.2       markus    550:        if (compat20) {
                    551:                session_set_fds(s, ptyfd, fdout, -1);
                    552:        } else {
                    553:                server_loop(pid, ptyfd, fdout, -1);
                    554:                /* server_loop _has_ closed ptyfd and fdout. */
1.24      markus    555:        }
                    556: }
                    557:
1.90      markus    558: /*
                    559:  * This is called to fork and execute a command.  If another command is
                    560:  * to be forced, execute that instead.
                    561:  */
                    562: void
                    563: do_exec(Session *s, const char *command)
                    564: {
                    565:        if (forced_command) {
                    566:                original_command = command;
                    567:                command = forced_command;
                    568:                debug("Forced command '%.900s'", command);
                    569:        }
1.163     markus    570:
                    571: #ifdef GSSAPI
                    572:        if (options.gss_authentication) {
                    573:                temporarily_use_uid(s->pw);
                    574:                ssh_gssapi_storecreds();
                    575:                restore_uid();
                    576:        }
                    577: #endif
1.90      markus    578:
                    579:        if (s->ttyfd != -1)
                    580:                do_exec_pty(s, command);
                    581:        else
                    582:                do_exec_no_pty(s, command);
                    583:
1.92      markus    584:        original_command = NULL;
1.90      markus    585: }
                    586:
                    587:
1.24      markus    588: /* administrative, login(1)-like work */
                    589: void
1.41      markus    590: do_login(Session *s, const char *command)
1.24      markus    591: {
                    592:        char *time_string;
                    593:        socklen_t fromlen;
                    594:        struct sockaddr_storage from;
                    595:        struct passwd * pw = s->pw;
                    596:        pid_t pid = getpid();
                    597:
                    598:        /*
                    599:         * Get IP address of client. If the connection is not a socket, let
                    600:         * the address be 0.0.0.0.
                    601:         */
                    602:        memset(&from, 0, sizeof(from));
1.148     stevesk   603:        fromlen = sizeof(from);
1.24      markus    604:        if (packet_connection_is_on_socket()) {
                    605:                if (getpeername(packet_get_connection_in(),
1.112     deraadt   606:                    (struct sockaddr *) & from, &fromlen) < 0) {
1.24      markus    607:                        debug("getpeername: %.100s", strerror(errno));
1.165     markus    608:                        cleanup_exit(255);
1.24      markus    609:                }
                    610:        }
1.25      markus    611:
1.24      markus    612:        /* Record that there was a login on that tty from the remote host. */
1.133     markus    613:        if (!use_privsep)
                    614:                record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
                    615:                    get_remote_name_or_ip(utmp_len,
1.158     markus    616:                    options.use_dns),
1.148     stevesk   617:                    (struct sockaddr *)&from, fromlen);
1.24      markus    618:
1.73      djm       619:        if (check_quietlogin(s, command))
1.24      markus    620:                return;
1.73      djm       621:
1.134     markus    622:        if (options.print_lastlog && s->last_login_time != 0) {
                    623:                time_string = ctime(&s->last_login_time);
1.24      markus    624:                if (strchr(time_string, '\n'))
                    625:                        *strchr(time_string, '\n') = 0;
1.134     markus    626:                if (strcmp(s->hostname, "") == 0)
1.24      markus    627:                        printf("Last login: %s\r\n", time_string);
                    628:                else
1.134     markus    629:                        printf("Last login: %s from %s\r\n", time_string,
                    630:                            s->hostname);
1.24      markus    631:        }
1.73      djm       632:
                    633:        do_motd();
                    634: }
                    635:
                    636: /*
                    637:  * Display the message of the day.
                    638:  */
                    639: void
                    640: do_motd(void)
                    641: {
                    642:        FILE *f;
                    643:        char buf[256];
                    644:
1.24      markus    645:        if (options.print_motd) {
1.28      millert   646: #ifdef HAVE_LOGIN_CAP
                    647:                f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
                    648:                    "/etc/motd"), "r");
                    649: #else
1.24      markus    650:                f = fopen("/etc/motd", "r");
1.28      millert   651: #endif
1.24      markus    652:                if (f) {
                    653:                        while (fgets(buf, sizeof(buf), f))
                    654:                                fputs(buf, stdout);
                    655:                        fclose(f);
                    656:                }
1.2       markus    657:        }
1.73      djm       658: }
                    659:
                    660:
                    661: /*
                    662:  * Check for quiet login, either .hushlogin or command given.
                    663:  */
                    664: int
                    665: check_quietlogin(Session *s, const char *command)
                    666: {
                    667:        char buf[256];
1.96      dugsong   668:        struct passwd *pw = s->pw;
1.73      djm       669:        struct stat st;
                    670:
                    671:        /* Return 1 if .hushlogin exists or a command given. */
                    672:        if (command != NULL)
                    673:                return 1;
                    674:        snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
                    675: #ifdef HAVE_LOGIN_CAP
                    676:        if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
                    677:                return 1;
                    678: #else
                    679:        if (stat(buf, &st) >= 0)
                    680:                return 1;
                    681: #endif
                    682:        return 0;
1.1       markus    683: }
                    684:
                    685: /*
                    686:  * Sets the value of the given variable in the environment.  If the variable
                    687:  * already exists, its value is overriden.
                    688:  */
1.161     markus    689: void
1.45      markus    690: child_set_env(char ***envp, u_int *envsizep, const char *name,
1.112     deraadt   691:        const char *value)
1.1       markus    692: {
1.164     markus    693:        char **env;
                    694:        u_int envsize;
1.45      markus    695:        u_int i, namelen;
1.1       markus    696:
                    697:        /*
                    698:         * Find the slot where the value should be stored.  If the variable
                    699:         * already exists, we reuse the slot; otherwise we append a new slot
                    700:         * at the end of the array, expanding if necessary.
                    701:         */
                    702:        env = *envp;
                    703:        namelen = strlen(name);
                    704:        for (i = 0; env[i]; i++)
                    705:                if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
                    706:                        break;
                    707:        if (env[i]) {
                    708:                /* Reuse the slot. */
                    709:                xfree(env[i]);
                    710:        } else {
                    711:                /* New variable.  Expand if necessary. */
1.164     markus    712:                envsize = *envsizep;
                    713:                if (i >= envsize - 1) {
                    714:                        if (envsize >= 1000)
                    715:                                fatal("child_set_env: too many env vars");
                    716:                        envsize += 50;
                    717:                        env = (*envp) = xrealloc(env, envsize * sizeof(char *));
                    718:                        *envsizep = envsize;
1.1       markus    719:                }
                    720:                /* Need to set the NULL pointer at end of array beyond the new slot. */
                    721:                env[i + 1] = NULL;
                    722:        }
                    723:
                    724:        /* Allocate space and format the variable in the appropriate slot. */
                    725:        env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
                    726:        snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
                    727: }
                    728:
                    729: /*
                    730:  * Reads environment variables from the given file and adds/overrides them
                    731:  * into the environment.  If the file does not exist, this does nothing.
                    732:  * Otherwise, it must consist of empty lines, comments (line starts with '#')
                    733:  * and assignments of the form name=value.  No other forms are allowed.
                    734:  */
1.94      itojun    735: static void
1.45      markus    736: read_environment_file(char ***env, u_int *envsize,
1.112     deraadt   737:        const char *filename)
1.1       markus    738: {
                    739:        FILE *f;
                    740:        char buf[4096];
                    741:        char *cp, *value;
1.142     deraadt   742:        u_int lineno = 0;
1.1       markus    743:
                    744:        f = fopen(filename, "r");
                    745:        if (!f)
                    746:                return;
                    747:
                    748:        while (fgets(buf, sizeof(buf), f)) {
1.142     deraadt   749:                if (++lineno > 1000)
                    750:                        fatal("Too many lines in environment file %s", filename);
1.1       markus    751:                for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
                    752:                        ;
                    753:                if (!*cp || *cp == '#' || *cp == '\n')
                    754:                        continue;
                    755:                if (strchr(cp, '\n'))
                    756:                        *strchr(cp, '\n') = '\0';
                    757:                value = strchr(cp, '=');
                    758:                if (value == NULL) {
1.142     deraadt   759:                        fprintf(stderr, "Bad line %u in %.100s\n", lineno,
                    760:                            filename);
1.1       markus    761:                        continue;
                    762:                }
1.14      deraadt   763:                /*
                    764:                 * Replace the equals sign by nul, and advance value to
                    765:                 * the value string.
                    766:                 */
1.1       markus    767:                *value = '\0';
                    768:                value++;
                    769:                child_set_env(env, envsize, cp, value);
                    770:        }
                    771:        fclose(f);
                    772: }
                    773:
1.127     markus    774: static char **
                    775: do_setup_env(Session *s, const char *shell)
1.1       markus    776: {
                    777:        char buf[256];
1.127     markus    778:        u_int i, envsize;
1.154     markus    779:        char **env, *laddr;
1.127     markus    780:        struct passwd *pw = s->pw;
1.1       markus    781:
                    782:        /* Initialize the environment. */
                    783:        envsize = 100;
                    784:        env = xmalloc(envsize * sizeof(char *));
                    785:        env[0] = NULL;
                    786:
1.161     markus    787: #ifdef GSSAPI
1.168     djm       788:        /* Allow any GSSAPI methods that we've used to alter
1.161     markus    789:         * the childs environment as they see fit
                    790:         */
                    791:        ssh_gssapi_do_child(&env, &envsize);
                    792: #endif
                    793:
1.1       markus    794:        if (!options.use_login) {
                    795:                /* Set basic environment. */
                    796:                child_set_env(&env, &envsize, "USER", pw->pw_name);
                    797:                child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
                    798:                child_set_env(&env, &envsize, "HOME", pw->pw_dir);
1.28      millert   799: #ifdef HAVE_LOGIN_CAP
1.145     markus    800:                if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
                    801:                        child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
                    802:                else
                    803:                        child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1.28      millert   804: #else
1.29      millert   805:                child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
1.28      millert   806: #endif
1.1       markus    807:
                    808:                snprintf(buf, sizeof buf, "%.200s/%.50s",
                    809:                         _PATH_MAILDIR, pw->pw_name);
                    810:                child_set_env(&env, &envsize, "MAIL", buf);
                    811:
                    812:                /* Normal systems set SHELL by default. */
                    813:                child_set_env(&env, &envsize, "SHELL", shell);
                    814:        }
                    815:        if (getenv("TZ"))
                    816:                child_set_env(&env, &envsize, "TZ", getenv("TZ"));
                    817:
                    818:        /* Set custom environment options from RSA authentication. */
1.110     markus    819:        if (!options.use_login) {
                    820:                while (custom_environment) {
                    821:                        struct envstring *ce = custom_environment;
1.143     deraadt   822:                        char *str = ce->s;
1.127     markus    823:
1.143     deraadt   824:                        for (i = 0; str[i] != '=' && str[i]; i++)
1.110     markus    825:                                ;
1.143     deraadt   826:                        if (str[i] == '=') {
                    827:                                str[i] = 0;
                    828:                                child_set_env(&env, &envsize, str, str + i + 1);
1.110     markus    829:                        }
                    830:                        custom_environment = ce->next;
                    831:                        xfree(ce->s);
                    832:                        xfree(ce);
1.1       markus    833:                }
                    834:        }
                    835:
1.149     stevesk   836:        /* SSH_CLIENT deprecated */
1.1       markus    837:        snprintf(buf, sizeof buf, "%.50s %d %d",
1.127     markus    838:            get_remote_ipaddr(), get_remote_port(), get_local_port());
1.1       markus    839:        child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1.149     stevesk   840:
1.154     markus    841:        laddr = get_local_ipaddr(packet_get_connection_in());
1.149     stevesk   842:        snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
1.154     markus    843:            get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
                    844:        xfree(laddr);
1.149     stevesk   845:        child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1.1       markus    846:
1.60      markus    847:        if (s->ttyfd != -1)
                    848:                child_set_env(&env, &envsize, "SSH_TTY", s->tty);
                    849:        if (s->term)
                    850:                child_set_env(&env, &envsize, "TERM", s->term);
                    851:        if (s->display)
                    852:                child_set_env(&env, &envsize, "DISPLAY", s->display);
1.34      markus    853:        if (original_command)
                    854:                child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
                    855:                    original_command);
1.96      dugsong   856: #ifdef KRB5
                    857:        if (s->authctxt->krb5_ticket_file)
                    858:                child_set_env(&env, &envsize, "KRB5CCNAME",
1.112     deraadt   859:                    s->authctxt->krb5_ticket_file);
1.96      dugsong   860: #endif
1.136     markus    861:        if (auth_sock_name != NULL)
1.1       markus    862:                child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1.136     markus    863:                    auth_sock_name);
1.1       markus    864:
                    865:        /* read $HOME/.ssh/environment. */
1.146     markus    866:        if (options.permit_user_env && !options.use_login) {
1.14      deraadt   867:                snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
                    868:                    pw->pw_dir);
1.1       markus    869:                read_environment_file(&env, &envsize, buf);
                    870:        }
                    871:        if (debug_flag) {
                    872:                /* dump the environment */
                    873:                fprintf(stderr, "Environment:\n");
                    874:                for (i = 0; env[i]; i++)
                    875:                        fprintf(stderr, "  %.200s\n", env[i]);
                    876:        }
1.127     markus    877:        return env;
                    878: }
                    879:
                    880: /*
                    881:  * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
                    882:  * first in this order).
                    883:  */
                    884: static void
                    885: do_rc_files(Session *s, const char *shell)
                    886: {
                    887:        FILE *f = NULL;
                    888:        char cmd[1024];
                    889:        int do_xauth;
                    890:        struct stat st;
                    891:
                    892:        do_xauth =
                    893:            s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
                    894:
                    895:        /* ignore _PATH_SSH_USER_RC for subsystems */
                    896:        if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
                    897:                snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
                    898:                    shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
                    899:                if (debug_flag)
                    900:                        fprintf(stderr, "Running %s\n", cmd);
                    901:                f = popen(cmd, "w");
                    902:                if (f) {
                    903:                        if (do_xauth)
                    904:                                fprintf(f, "%s %s\n", s->auth_proto,
                    905:                                    s->auth_data);
                    906:                        pclose(f);
                    907:                } else
                    908:                        fprintf(stderr, "Could not run %s\n",
                    909:                            _PATH_SSH_USER_RC);
                    910:        } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
                    911:                if (debug_flag)
                    912:                        fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
                    913:                            _PATH_SSH_SYSTEM_RC);
                    914:                f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
                    915:                if (f) {
                    916:                        if (do_xauth)
                    917:                                fprintf(f, "%s %s\n", s->auth_proto,
                    918:                                    s->auth_data);
                    919:                        pclose(f);
                    920:                } else
                    921:                        fprintf(stderr, "Could not run %s\n",
                    922:                            _PATH_SSH_SYSTEM_RC);
                    923:        } else if (do_xauth && options.xauth_location != NULL) {
                    924:                /* Add authority data to .Xauthority if appropriate. */
                    925:                if (debug_flag) {
                    926:                        fprintf(stderr,
1.151     stevesk   927:                            "Running %.500s remove %.100s\n",
1.165     markus    928:                            options.xauth_location, s->auth_display);
1.151     stevesk   929:                        fprintf(stderr,
                    930:                            "%.500s add %.100s %.100s %.100s\n",
1.127     markus    931:                            options.xauth_location, s->auth_display,
                    932:                            s->auth_proto, s->auth_data);
                    933:                }
                    934:                snprintf(cmd, sizeof cmd, "%s -q -",
                    935:                    options.xauth_location);
                    936:                f = popen(cmd, "w");
                    937:                if (f) {
1.151     stevesk   938:                        fprintf(f, "remove %s\n",
                    939:                            s->auth_display);
1.127     markus    940:                        fprintf(f, "add %s %s %s\n",
                    941:                            s->auth_display, s->auth_proto,
                    942:                            s->auth_data);
                    943:                        pclose(f);
                    944:                } else {
                    945:                        fprintf(stderr, "Could not run %s\n",
                    946:                            cmd);
                    947:                }
                    948:        }
                    949: }
                    950:
                    951: static void
                    952: do_nologin(struct passwd *pw)
                    953: {
                    954:        FILE *f = NULL;
                    955:        char buf[1024];
                    956:
                    957: #ifdef HAVE_LOGIN_CAP
                    958:        if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
                    959:                f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
                    960:                    _PATH_NOLOGIN), "r");
                    961: #else
                    962:        if (pw->pw_uid)
                    963:                f = fopen(_PATH_NOLOGIN, "r");
                    964: #endif
                    965:        if (f) {
                    966:                /* /etc/nologin exists.  Print its contents and exit. */
1.155     itojun    967:                logit("User %.100s not allowed because %s exists",
1.150     stevesk   968:                    pw->pw_name, _PATH_NOLOGIN);
1.127     markus    969:                while (fgets(buf, sizeof(buf), f))
                    970:                        fputs(buf, stderr);
                    971:                fclose(f);
                    972:                exit(254);
                    973:        }
                    974: }
                    975:
                    976: /* Set login name, uid, gid, and groups. */
1.130     provos    977: void
1.127     markus    978: do_setusercontext(struct passwd *pw)
                    979: {
                    980:        if (getuid() == 0 || geteuid() == 0) {
                    981: #ifdef HAVE_LOGIN_CAP
                    982:                if (setusercontext(lc, pw, pw->pw_uid,
                    983:                    (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
                    984:                        perror("unable to set user context");
                    985:                        exit(1);
                    986:                }
                    987: #else
                    988:                if (setlogin(pw->pw_name) < 0)
                    989:                        error("setlogin failed: %s", strerror(errno));
                    990:                if (setgid(pw->pw_gid) < 0) {
                    991:                        perror("setgid");
                    992:                        exit(1);
                    993:                }
                    994:                /* Initialize the group list. */
                    995:                if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
                    996:                        perror("initgroups");
                    997:                        exit(1);
                    998:                }
                    999:                endgrent();
                   1000:
                   1001:                /* Permanently switch to the desired uid. */
                   1002:                permanently_set_uid(pw);
                   1003: #endif
                   1004:        }
                   1005:        if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
                   1006:                fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
                   1007: }
                   1008:
1.131     markus   1009: static void
1.172   ! markus   1010: do_pwchange(Session *s)
        !          1011: {
        !          1012:        fprintf(stderr, "WARNING: Your password has expired.\n");
        !          1013:        if (s->ttyfd != -1) {
        !          1014:                fprintf(stderr,
        !          1015:                    "You must change your password now and login again!\n");
        !          1016:                execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
        !          1017:                perror("passwd");
        !          1018:        } else {
        !          1019:                fprintf(stderr,
        !          1020:                    "Password change required but no TTY available.\n");
        !          1021:        }
        !          1022:        exit(1);
        !          1023: }
        !          1024:
        !          1025: static void
1.130     provos   1026: launch_login(struct passwd *pw, const char *hostname)
                   1027: {
                   1028:        /* Launch login(1). */
                   1029:
                   1030:        execl("/usr/bin/login", "login", "-h", hostname,
                   1031:            "-p", "-f", "--", pw->pw_name, (char *)NULL);
                   1032:
                   1033:        /* Login couldn't be executed, die. */
                   1034:
                   1035:        perror("login");
                   1036:        exit(1);
                   1037: }
                   1038:
1.172   ! markus   1039: static void
        !          1040: child_close_fds(void)
        !          1041: {
        !          1042:        int i;
        !          1043:
        !          1044:        if (packet_get_connection_in() == packet_get_connection_out())
        !          1045:                close(packet_get_connection_in());
        !          1046:        else {
        !          1047:                close(packet_get_connection_in());
        !          1048:                close(packet_get_connection_out());
        !          1049:        }
        !          1050:        /*
        !          1051:         * Close all descriptors related to channels.  They will still remain
        !          1052:         * open in the parent.
        !          1053:         */
        !          1054:        /* XXX better use close-on-exec? -markus */
        !          1055:        channel_close_all();
        !          1056:
        !          1057:        /*
        !          1058:         * Close any extra file descriptors.  Note that there may still be
        !          1059:         * descriptors left by system functions.  They will be closed later.
        !          1060:         */
        !          1061:        endpwent();
        !          1062:
        !          1063:        /*
        !          1064:         * Close any extra open file descriptors so that we don\'t have them
        !          1065:         * hanging around in clients.  Note that we want to do this after
        !          1066:         * initgroups, because at least on Solaris 2.3 it leaves file
        !          1067:         * descriptors open.
        !          1068:         */
        !          1069:        for (i = 3; i < 64; i++)
        !          1070:                close(i);
        !          1071: }
        !          1072:
1.127     markus   1073: /*
                   1074:  * Performs common processing for the child, such as setting up the
                   1075:  * environment, closing extra file descriptors, setting the user and group
                   1076:  * ids, and executing the command or shell.
                   1077:  */
                   1078: void
                   1079: do_child(Session *s, const char *command)
                   1080: {
                   1081:        extern char **environ;
                   1082:        char **env;
                   1083:        char *argv[10];
                   1084:        const char *shell, *shell0, *hostname = NULL;
                   1085:        struct passwd *pw = s->pw;
                   1086:
                   1087:        /* remove hostkey from the child's memory */
                   1088:        destroy_sensitive_data();
                   1089:
1.172   ! markus   1090:        /* Force a password change */
        !          1091:        if (s->authctxt->force_pwchange) {
        !          1092:                do_setusercontext(pw);
        !          1093:                child_close_fds();
        !          1094:                do_pwchange(s);
        !          1095:                exit(1);
        !          1096:        }
        !          1097:
1.127     markus   1098:        /* login(1) is only called if we execute the login shell */
                   1099:        if (options.use_login && command != NULL)
                   1100:                options.use_login = 0;
                   1101:
                   1102:        /*
                   1103:         * Login(1) does this as well, and it needs uid 0 for the "-h"
                   1104:         * switch, so we let login(1) to this for us.
                   1105:         */
                   1106:        if (!options.use_login) {
                   1107:                do_nologin(pw);
                   1108:                do_setusercontext(pw);
                   1109:        }
                   1110:
                   1111:        /*
                   1112:         * Get the shell from the password data.  An empty shell field is
                   1113:         * legal, and means /bin/sh.
                   1114:         */
                   1115:        shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.152     markus   1116:
                   1117:        /*
                   1118:         * Make sure $SHELL points to the shell from the password file,
                   1119:         * even if shell is overridden from login.conf
                   1120:         */
                   1121:        env = do_setup_env(s, shell);
                   1122:
1.127     markus   1123: #ifdef HAVE_LOGIN_CAP
                   1124:        shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
                   1125: #endif
                   1126:
1.26      millert  1127:        /* we have to stash the hostname before we close our socket. */
                   1128:        if (options.use_login)
1.70      stevesk  1129:                hostname = get_remote_name_or_ip(utmp_len,
1.158     markus   1130:                    options.use_dns);
1.1       markus   1131:        /*
                   1132:         * Close the connection descriptors; note that this is the child, and
                   1133:         * the server will still have the socket open, and it is important
                   1134:         * that we do not shutdown it.  Note that the descriptors cannot be
                   1135:         * closed before building the environment, as we call
                   1136:         * get_remote_ipaddr there.
                   1137:         */
1.172   ! markus   1138:        child_close_fds();
1.1       markus   1139:
                   1140:        /*
1.125     deraadt  1141:         * Must take new environment into use so that .ssh/rc,
                   1142:         * /etc/ssh/sshrc and xauth are run in the proper environment.
1.1       markus   1143:         */
                   1144:        environ = env;
1.170     jakob    1145:
                   1146: #ifdef KRB5
                   1147:        /*
                   1148:         * At this point, we check to see if AFS is active and if we have
                   1149:         * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
                   1150:         * if we can (and need to) extend the ticket into an AFS token. If
                   1151:         * we don't do this, we run into potential problems if the user's
                   1152:         * home directory is in AFS and it's not world-readable.
                   1153:         */
                   1154:
                   1155:        if (options.kerberos_get_afs_token && k_hasafs() &&
                   1156:             (s->authctxt->krb5_ctx != NULL)) {
                   1157:                char cell[64];
                   1158:
                   1159:                debug("Getting AFS token");
                   1160:
                   1161:                k_setpag();
                   1162:
                   1163:                if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
                   1164:                        krb5_afslog(s->authctxt->krb5_ctx,
                   1165:                            s->authctxt->krb5_fwd_ccache, cell, NULL);
                   1166:
                   1167:                krb5_afslog_home(s->authctxt->krb5_ctx,
                   1168:                    s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
                   1169:        }
                   1170: #endif
1.104     markus   1171:
                   1172:        /* Change current directory to the user\'s home directory. */
                   1173:        if (chdir(pw->pw_dir) < 0) {
                   1174:                fprintf(stderr, "Could not chdir to home directory %s: %s\n",
                   1175:                    pw->pw_dir, strerror(errno));
                   1176: #ifdef HAVE_LOGIN_CAP
                   1177:                if (login_getcapbool(lc, "requirehome", 0))
                   1178:                        exit(1);
                   1179: #endif
                   1180:        }
1.1       markus   1181:
1.127     markus   1182:        if (!options.use_login)
                   1183:                do_rc_files(s, shell);
1.67      markus   1184:
                   1185:        /* restore SIGPIPE for child */
                   1186:        signal(SIGPIPE,  SIG_DFL);
                   1187:
1.127     markus   1188:        if (options.use_login) {
1.130     provos   1189:                launch_login(pw, hostname);
                   1190:                /* NEVERREACHED */
1.127     markus   1191:        }
                   1192:
                   1193:        /* Get the last component of the shell name. */
                   1194:        if ((shell0 = strrchr(shell, '/')) != NULL)
                   1195:                shell0++;
                   1196:        else
                   1197:                shell0 = shell;
                   1198:
1.1       markus   1199:        /*
                   1200:         * If we have no command, execute the shell.  In this case, the shell
                   1201:         * name to be passed in argv[0] is preceded by '-' to indicate that
                   1202:         * this is a login shell.
                   1203:         */
                   1204:        if (!command) {
1.127     markus   1205:                char argv0[256];
1.1       markus   1206:
1.127     markus   1207:                /* Start the shell.  Set initial character to '-'. */
                   1208:                argv0[0] = '-';
1.1       markus   1209:
1.127     markus   1210:                if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1.128     markus   1211:                    >= sizeof(argv0) - 1) {
1.127     markus   1212:                        errno = EINVAL;
1.1       markus   1213:                        perror(shell);
                   1214:                        exit(1);
1.127     markus   1215:                }
1.1       markus   1216:
1.127     markus   1217:                /* Execute the shell. */
                   1218:                argv[0] = argv0;
                   1219:                argv[1] = NULL;
                   1220:                execve(shell, argv, env);
                   1221:
                   1222:                /* Executing the shell failed. */
                   1223:                perror(shell);
                   1224:                exit(1);
1.1       markus   1225:        }
                   1226:        /*
                   1227:         * Execute the command using the user's shell.  This uses the -c
                   1228:         * option to execute the command.
                   1229:         */
1.127     markus   1230:        argv[0] = (char *) shell0;
1.1       markus   1231:        argv[1] = "-c";
                   1232:        argv[2] = (char *) command;
                   1233:        argv[3] = NULL;
                   1234:        execve(shell, argv, env);
                   1235:        perror(shell);
                   1236:        exit(1);
                   1237: }
                   1238:
                   1239: Session *
                   1240: session_new(void)
                   1241: {
                   1242:        int i;
                   1243:        static int did_init = 0;
                   1244:        if (!did_init) {
                   1245:                debug("session_new: init");
1.112     deraadt  1246:                for (i = 0; i < MAX_SESSIONS; i++) {
1.1       markus   1247:                        sessions[i].used = 0;
                   1248:                }
                   1249:                did_init = 1;
                   1250:        }
1.112     deraadt  1251:        for (i = 0; i < MAX_SESSIONS; i++) {
1.1       markus   1252:                Session *s = &sessions[i];
                   1253:                if (! s->used) {
1.68      djm      1254:                        memset(s, 0, sizeof(*s));
1.1       markus   1255:                        s->chanid = -1;
                   1256:                        s->ptyfd = -1;
                   1257:                        s->ttyfd = -1;
                   1258:                        s->used = 1;
1.85      markus   1259:                        s->self = i;
1.1       markus   1260:                        debug("session_new: session %d", i);
                   1261:                        return s;
                   1262:                }
                   1263:        }
                   1264:        return NULL;
                   1265: }
                   1266:
1.94      itojun   1267: static void
1.1       markus   1268: session_dump(void)
                   1269: {
                   1270:        int i;
1.112     deraadt  1271:        for (i = 0; i < MAX_SESSIONS; i++) {
1.1       markus   1272:                Session *s = &sessions[i];
1.137     mpech    1273:                debug("dump: used %d session %d %p channel %d pid %ld",
1.1       markus   1274:                    s->used,
                   1275:                    s->self,
                   1276:                    s,
                   1277:                    s->chanid,
1.137     mpech    1278:                    (long)s->pid);
1.1       markus   1279:        }
                   1280: }
                   1281:
1.2       markus   1282: int
1.97      markus   1283: session_open(Authctxt *authctxt, int chanid)
1.2       markus   1284: {
                   1285:        Session *s = session_new();
                   1286:        debug("session_open: channel %d", chanid);
                   1287:        if (s == NULL) {
                   1288:                error("no more sessions");
                   1289:                return 0;
                   1290:        }
1.97      markus   1291:        s->authctxt = authctxt;
                   1292:        s->pw = authctxt->pw;
1.167     djm      1293:        if (s->pw == NULL || !authctxt->valid)
1.54      stevesk  1294:                fatal("no user for session %d", s->self);
1.2       markus   1295:        debug("session_open: session %d: link with channel %d", s->self, chanid);
                   1296:        s->chanid = chanid;
                   1297:        return 1;
                   1298: }
                   1299:
1.130     provos   1300: Session *
                   1301: session_by_tty(char *tty)
                   1302: {
                   1303:        int i;
                   1304:        for (i = 0; i < MAX_SESSIONS; i++) {
                   1305:                Session *s = &sessions[i];
                   1306:                if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
                   1307:                        debug("session_by_tty: session %d tty %s", i, tty);
                   1308:                        return s;
                   1309:                }
                   1310:        }
                   1311:        debug("session_by_tty: unknown tty %.100s", tty);
                   1312:        session_dump();
                   1313:        return NULL;
                   1314: }
                   1315:
1.94      itojun   1316: static Session *
1.2       markus   1317: session_by_channel(int id)
                   1318: {
                   1319:        int i;
1.112     deraadt  1320:        for (i = 0; i < MAX_SESSIONS; i++) {
1.2       markus   1321:                Session *s = &sessions[i];
                   1322:                if (s->used && s->chanid == id) {
                   1323:                        debug("session_by_channel: session %d channel %d", i, id);
                   1324:                        return s;
                   1325:                }
                   1326:        }
                   1327:        debug("session_by_channel: unknown channel %d", id);
                   1328:        session_dump();
                   1329:        return NULL;
                   1330: }
                   1331:
1.94      itojun   1332: static Session *
1.2       markus   1333: session_by_pid(pid_t pid)
                   1334: {
                   1335:        int i;
1.137     mpech    1336:        debug("session_by_pid: pid %ld", (long)pid);
1.112     deraadt  1337:        for (i = 0; i < MAX_SESSIONS; i++) {
1.2       markus   1338:                Session *s = &sessions[i];
                   1339:                if (s->used && s->pid == pid)
                   1340:                        return s;
                   1341:        }
1.137     mpech    1342:        error("session_by_pid: unknown pid %ld", (long)pid);
1.2       markus   1343:        session_dump();
                   1344:        return NULL;
                   1345: }
                   1346:
1.94      itojun   1347: static int
1.2       markus   1348: session_window_change_req(Session *s)
                   1349: {
                   1350:        s->col = packet_get_int();
                   1351:        s->row = packet_get_int();
                   1352:        s->xpixel = packet_get_int();
                   1353:        s->ypixel = packet_get_int();
1.116     markus   1354:        packet_check_eom();
1.2       markus   1355:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1356:        return 1;
                   1357: }
                   1358:
1.94      itojun   1359: static int
1.2       markus   1360: session_pty_req(Session *s)
                   1361: {
1.45      markus   1362:        u_int len;
1.72      stevesk  1363:        int n_bytes;
1.132     markus   1364:
1.86      markus   1365:        if (no_pty_flag) {
                   1366:                debug("Allocating a pty not permitted for this authentication.");
1.19      markus   1367:                return 0;
1.86      markus   1368:        }
                   1369:        if (s->ttyfd != -1) {
                   1370:                packet_disconnect("Protocol error: you already have a pty.");
1.3       markus   1371:                return 0;
1.134     markus   1372:        }
                   1373:        /* Get the time and hostname when the user last logged in. */
                   1374:        if (options.print_lastlog) {
                   1375:                s->hostname[0] = '\0';
                   1376:                s->last_login_time = get_last_login_time(s->pw->pw_uid,
                   1377:                    s->pw->pw_name, s->hostname, sizeof(s->hostname));
1.86      markus   1378:        }
                   1379:
1.2       markus   1380:        s->term = packet_get_string(&len);
1.86      markus   1381:
                   1382:        if (compat20) {
                   1383:                s->col = packet_get_int();
                   1384:                s->row = packet_get_int();
                   1385:        } else {
                   1386:                s->row = packet_get_int();
                   1387:                s->col = packet_get_int();
                   1388:        }
1.2       markus   1389:        s->xpixel = packet_get_int();
                   1390:        s->ypixel = packet_get_int();
                   1391:
                   1392:        if (strcmp(s->term, "") == 0) {
                   1393:                xfree(s->term);
                   1394:                s->term = NULL;
                   1395:        }
1.86      markus   1396:
1.2       markus   1397:        /* Allocate a pty and open it. */
1.86      markus   1398:        debug("Allocating pty.");
1.130     provos   1399:        if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
1.86      markus   1400:                if (s->term)
                   1401:                        xfree(s->term);
1.2       markus   1402:                s->term = NULL;
                   1403:                s->ptyfd = -1;
                   1404:                s->ttyfd = -1;
                   1405:                error("session_pty_req: session %d alloc failed", s->self);
1.3       markus   1406:                return 0;
1.2       markus   1407:        }
                   1408:        debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1.86      markus   1409:
                   1410:        /* for SSH1 the tty modes length is not given */
                   1411:        if (!compat20)
                   1412:                n_bytes = packet_remaining();
                   1413:        tty_parse_modes(s->ttyfd, &n_bytes);
                   1414:
1.130     provos   1415:        if (!use_privsep)
                   1416:                pty_setowner(s->pw, s->tty);
1.86      markus   1417:
                   1418:        /* Set window size from the packet. */
1.2       markus   1419:        pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
                   1420:
1.116     markus   1421:        packet_check_eom();
1.9       markus   1422:        session_proctitle(s);
1.2       markus   1423:        return 1;
                   1424: }
                   1425:
1.94      itojun   1426: static int
1.7       markus   1427: session_subsystem_req(Session *s)
                   1428: {
1.105     markus   1429:        struct stat st;
1.45      markus   1430:        u_int len;
1.7       markus   1431:        int success = 0;
1.105     markus   1432:        char *cmd, *subsys = packet_get_string(&len);
1.18      jakob    1433:        int i;
1.7       markus   1434:
1.116     markus   1435:        packet_check_eom();
1.155     itojun   1436:        logit("subsystem request for %.100s", subsys);
1.18      jakob    1437:
                   1438:        for (i = 0; i < options.num_subsystems; i++) {
1.105     markus   1439:                if (strcmp(subsys, options.subsystem_name[i]) == 0) {
                   1440:                        cmd = options.subsystem_command[i];
                   1441:                        if (stat(cmd, &st) < 0) {
                   1442:                                error("subsystem: cannot stat %s: %s", cmd,
                   1443:                                    strerror(errno));
                   1444:                                break;
                   1445:                        }
                   1446:                        debug("subsystem: exec() %s", cmd);
1.64      markus   1447:                        s->is_subsystem = 1;
1.105     markus   1448:                        do_exec(s, cmd);
1.18      jakob    1449:                        success = 1;
1.122     markus   1450:                        break;
1.18      jakob    1451:                }
                   1452:        }
                   1453:
                   1454:        if (!success)
1.155     itojun   1455:                logit("subsystem request for %.100s failed, subsystem not found",
1.105     markus   1456:                    subsys);
1.7       markus   1457:
                   1458:        xfree(subsys);
                   1459:        return success;
                   1460: }
                   1461:
1.94      itojun   1462: static int
1.7       markus   1463: session_x11_req(Session *s)
                   1464: {
1.81      markus   1465:        int success;
1.7       markus   1466:
                   1467:        s->single_connection = packet_get_char();
                   1468:        s->auth_proto = packet_get_string(NULL);
                   1469:        s->auth_data = packet_get_string(NULL);
                   1470:        s->screen = packet_get_int();
1.116     markus   1471:        packet_check_eom();
1.7       markus   1472:
1.81      markus   1473:        success = session_setup_x11fwd(s);
                   1474:        if (!success) {
1.7       markus   1475:                xfree(s->auth_proto);
                   1476:                xfree(s->auth_data);
1.84      markus   1477:                s->auth_proto = NULL;
                   1478:                s->auth_data = NULL;
1.7       markus   1479:        }
1.81      markus   1480:        return success;
1.7       markus   1481: }
                   1482:
1.94      itojun   1483: static int
1.19      markus   1484: session_shell_req(Session *s)
                   1485: {
1.116     markus   1486:        packet_check_eom();
1.90      markus   1487:        do_exec(s, NULL);
1.19      markus   1488:        return 1;
                   1489: }
                   1490:
1.94      itojun   1491: static int
1.19      markus   1492: session_exec_req(Session *s)
                   1493: {
1.45      markus   1494:        u_int len;
1.19      markus   1495:        char *command = packet_get_string(&len);
1.116     markus   1496:        packet_check_eom();
1.90      markus   1497:        do_exec(s, command);
1.92      markus   1498:        xfree(command);
1.19      markus   1499:        return 1;
                   1500: }
                   1501:
1.94      itojun   1502: static int
1.157     markus   1503: session_break_req(Session *s)
                   1504: {
                   1505:        u_int break_length;
                   1506:
1.160     markus   1507:        break_length = packet_get_int();        /* ignored */
1.157     markus   1508:        packet_check_eom();
                   1509:
1.160     markus   1510:        if (s->ttyfd == -1 ||
                   1511:            tcsendbreak(s->ttyfd, 0) < 0)
1.157     markus   1512:                return 0;
                   1513:        return 1;
                   1514: }
                   1515:
                   1516: static int
1.43      markus   1517: session_auth_agent_req(Session *s)
                   1518: {
                   1519:        static int called = 0;
1.116     markus   1520:        packet_check_eom();
1.44      markus   1521:        if (no_agent_forwarding_flag) {
                   1522:                debug("session_auth_agent_req: no_agent_forwarding_flag");
                   1523:                return 0;
                   1524:        }
1.43      markus   1525:        if (called) {
                   1526:                return 0;
                   1527:        } else {
                   1528:                called = 1;
                   1529:                return auth_input_request_forwarding(s->pw);
                   1530:        }
                   1531: }
                   1532:
1.123     markus   1533: int
                   1534: session_input_channel_req(Channel *c, const char *rtype)
1.2       markus   1535: {
                   1536:        int success = 0;
                   1537:        Session *s;
                   1538:
1.123     markus   1539:        if ((s = session_by_channel(c->self)) == NULL) {
1.155     itojun   1540:                logit("session_input_channel_req: no session %d req %.100s",
1.123     markus   1541:                    c->self, rtype);
                   1542:                return 0;
                   1543:        }
                   1544:        debug("session_input_channel_req: session %d req %s", s->self, rtype);
1.2       markus   1545:
                   1546:        /*
1.64      markus   1547:         * a session is in LARVAL state until a shell, a command
                   1548:         * or a subsystem is executed
1.2       markus   1549:         */
                   1550:        if (c->type == SSH_CHANNEL_LARVAL) {
                   1551:                if (strcmp(rtype, "shell") == 0) {
1.19      markus   1552:                        success = session_shell_req(s);
1.2       markus   1553:                } else if (strcmp(rtype, "exec") == 0) {
1.19      markus   1554:                        success = session_exec_req(s);
1.2       markus   1555:                } else if (strcmp(rtype, "pty-req") == 0) {
1.3       markus   1556:                        success =  session_pty_req(s);
1.7       markus   1557:                } else if (strcmp(rtype, "x11-req") == 0) {
                   1558:                        success = session_x11_req(s);
1.43      markus   1559:                } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
                   1560:                        success = session_auth_agent_req(s);
1.7       markus   1561:                } else if (strcmp(rtype, "subsystem") == 0) {
                   1562:                        success = session_subsystem_req(s);
1.157     markus   1563:                } else if (strcmp(rtype, "break") == 0) {
                   1564:                        success = session_break_req(s);
1.2       markus   1565:                }
                   1566:        }
                   1567:        if (strcmp(rtype, "window-change") == 0) {
                   1568:                success = session_window_change_req(s);
                   1569:        }
1.123     markus   1570:        return success;
1.2       markus   1571: }
                   1572:
                   1573: void
                   1574: session_set_fds(Session *s, int fdin, int fdout, int fderr)
                   1575: {
                   1576:        if (!compat20)
                   1577:                fatal("session_set_fds: called for proto != 2.0");
                   1578:        /*
                   1579:         * now that have a child and a pipe to the child,
                   1580:         * we can activate our channel and register the fd's
                   1581:         */
                   1582:        if (s->chanid == -1)
                   1583:                fatal("no channel for session %d", s->self);
                   1584:        channel_set_fds(s->chanid,
                   1585:            fdout, fdin, fderr,
1.42      markus   1586:            fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
1.126     markus   1587:            1,
                   1588:            CHAN_SES_WINDOW_DEFAULT);
1.2       markus   1589: }
                   1590:
1.85      markus   1591: /*
                   1592:  * Function to perform pty cleanup. Also called if we get aborted abnormally
                   1593:  * (e.g., due to a dropped connection).
                   1594:  */
1.130     provos   1595: void
1.165     markus   1596: session_pty_cleanup2(Session *s)
1.1       markus   1597: {
1.85      markus   1598:        if (s == NULL) {
                   1599:                error("session_pty_cleanup: no session");
                   1600:                return;
                   1601:        }
                   1602:        if (s->ttyfd == -1)
1.1       markus   1603:                return;
                   1604:
1.54      stevesk  1605:        debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
1.1       markus   1606:
                   1607:        /* Record that the user has logged out. */
1.85      markus   1608:        if (s->pid != 0)
                   1609:                record_logout(s->pid, s->tty);
1.1       markus   1610:
                   1611:        /* Release the pseudo-tty. */
1.130     provos   1612:        if (getuid() == 0)
                   1613:                pty_release(s->tty);
1.1       markus   1614:
                   1615:        /*
                   1616:         * Close the server side of the socket pairs.  We must do this after
                   1617:         * the pty cleanup, so that another process doesn't get this pty
                   1618:         * while we're still cleaning up.
                   1619:         */
                   1620:        if (close(s->ptymaster) < 0)
1.130     provos   1621:                error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
1.108     markus   1622:
                   1623:        /* unlink pty from session */
                   1624:        s->ttyfd = -1;
1.2       markus   1625: }
                   1626:
1.130     provos   1627: void
1.165     markus   1628: session_pty_cleanup(Session *s)
1.130     provos   1629: {
1.165     markus   1630:        PRIVSEP(session_pty_cleanup2(s));
1.130     provos   1631: }
                   1632:
1.147     markus   1633: static char *
                   1634: sig2name(int sig)
                   1635: {
                   1636: #define SSH_SIG(x) if (sig == SIG ## x) return #x
                   1637:        SSH_SIG(ABRT);
                   1638:        SSH_SIG(ALRM);
                   1639:        SSH_SIG(FPE);
                   1640:        SSH_SIG(HUP);
                   1641:        SSH_SIG(ILL);
                   1642:        SSH_SIG(INT);
                   1643:        SSH_SIG(KILL);
                   1644:        SSH_SIG(PIPE);
                   1645:        SSH_SIG(QUIT);
                   1646:        SSH_SIG(SEGV);
                   1647:        SSH_SIG(TERM);
                   1648:        SSH_SIG(USR1);
                   1649:        SSH_SIG(USR2);
                   1650: #undef SSH_SIG
                   1651:        return "SIG@openssh.com";
                   1652: }
                   1653:
1.94      itojun   1654: static void
1.2       markus   1655: session_exit_message(Session *s, int status)
                   1656: {
                   1657:        Channel *c;
1.124     markus   1658:
                   1659:        if ((c = channel_lookup(s->chanid)) == NULL)
1.85      markus   1660:                fatal("session_exit_message: session %d: no channel %d",
1.2       markus   1661:                    s->self, s->chanid);
1.137     mpech    1662:        debug("session_exit_message: session %d channel %d pid %ld",
                   1663:            s->self, s->chanid, (long)s->pid);
1.2       markus   1664:
                   1665:        if (WIFEXITED(status)) {
1.124     markus   1666:                channel_request_start(s->chanid, "exit-status", 0);
1.2       markus   1667:                packet_put_int(WEXITSTATUS(status));
                   1668:                packet_send();
                   1669:        } else if (WIFSIGNALED(status)) {
1.124     markus   1670:                channel_request_start(s->chanid, "exit-signal", 0);
1.147     markus   1671:                packet_put_cstring(sig2name(WTERMSIG(status)));
1.2       markus   1672:                packet_put_char(WCOREDUMP(status));
                   1673:                packet_put_cstring("");
                   1674:                packet_put_cstring("");
                   1675:                packet_send();
                   1676:        } else {
                   1677:                /* Some weird exit cause.  Just exit. */
                   1678:                packet_disconnect("wait returned status %04x.", status);
                   1679:        }
                   1680:
                   1681:        /* disconnect channel */
                   1682:        debug("session_exit_message: release channel %d", s->chanid);
                   1683:        channel_cancel_cleanup(s->chanid);
1.5       markus   1684:        /*
                   1685:         * emulate a write failure with 'chan_write_failed', nobody will be
                   1686:         * interested in data we write.
                   1687:         * Note that we must not call 'chan_read_failed', since there could
                   1688:         * be some more data waiting in the pipe.
                   1689:         */
1.8       markus   1690:        if (c->ostate != CHAN_OUTPUT_CLOSED)
                   1691:                chan_write_failed(c);
1.2       markus   1692:        s->chanid = -1;
                   1693: }
                   1694:
1.130     provos   1695: void
1.85      markus   1696: session_close(Session *s)
1.2       markus   1697: {
1.137     mpech    1698:        debug("session_close: session %d pid %ld", s->self, (long)s->pid);
1.165     markus   1699:        if (s->ttyfd != -1)
1.85      markus   1700:                session_pty_cleanup(s);
1.2       markus   1701:        if (s->term)
                   1702:                xfree(s->term);
                   1703:        if (s->display)
                   1704:                xfree(s->display);
1.118     stevesk  1705:        if (s->auth_display)
                   1706:                xfree(s->auth_display);
1.2       markus   1707:        if (s->auth_data)
                   1708:                xfree(s->auth_data);
                   1709:        if (s->auth_proto)
                   1710:                xfree(s->auth_proto);
                   1711:        s->used = 0;
1.9       markus   1712:        session_proctitle(s);
1.2       markus   1713: }
                   1714:
                   1715: void
                   1716: session_close_by_pid(pid_t pid, int status)
                   1717: {
                   1718:        Session *s = session_by_pid(pid);
                   1719:        if (s == NULL) {
1.137     mpech    1720:                debug("session_close_by_pid: no session for pid %ld",
                   1721:                    (long)pid);
1.2       markus   1722:                return;
                   1723:        }
                   1724:        if (s->chanid != -1)
                   1725:                session_exit_message(s, status);
                   1726:        session_close(s);
1.98      markus   1727: }
                   1728:
1.2       markus   1729: /*
                   1730:  * this is called when a channel dies before
                   1731:  * the session 'child' itself dies
                   1732:  */
                   1733: void
                   1734: session_close_by_channel(int id, void *arg)
                   1735: {
                   1736:        Session *s = session_by_channel(id);
                   1737:        if (s == NULL) {
1.107     markus   1738:                debug("session_close_by_channel: no session for id %d", id);
1.2       markus   1739:                return;
                   1740:        }
1.137     mpech    1741:        debug("session_close_by_channel: channel %d child %ld",
                   1742:            id, (long)s->pid);
1.107     markus   1743:        if (s->pid != 0) {
                   1744:                debug("session_close_by_channel: channel %d: has child", id);
1.108     markus   1745:                /*
                   1746:                 * delay detach of session, but release pty, since
                   1747:                 * the fd's to the child are already closed
                   1748:                 */
1.165     markus   1749:                if (s->ttyfd != -1)
1.108     markus   1750:                        session_pty_cleanup(s);
1.107     markus   1751:                return;
                   1752:        }
                   1753:        /* detach by removing callback */
1.2       markus   1754:        channel_cancel_cleanup(s->chanid);
                   1755:        s->chanid = -1;
1.106     markus   1756:        session_close(s);
                   1757: }
                   1758:
                   1759: void
1.130     provos   1760: session_destroy_all(void (*closefunc)(Session *))
1.106     markus   1761: {
                   1762:        int i;
1.112     deraadt  1763:        for (i = 0; i < MAX_SESSIONS; i++) {
1.106     markus   1764:                Session *s = &sessions[i];
1.130     provos   1765:                if (s->used) {
                   1766:                        if (closefunc != NULL)
                   1767:                                closefunc(s);
                   1768:                        else
                   1769:                                session_close(s);
                   1770:                }
1.2       markus   1771:        }
1.9       markus   1772: }
                   1773:
1.94      itojun   1774: static char *
1.9       markus   1775: session_tty_list(void)
                   1776: {
                   1777:        static char buf[1024];
                   1778:        int i;
                   1779:        buf[0] = '\0';
1.112     deraadt  1780:        for (i = 0; i < MAX_SESSIONS; i++) {
1.9       markus   1781:                Session *s = &sessions[i];
                   1782:                if (s->used && s->ttyfd != -1) {
                   1783:                        if (buf[0] != '\0')
                   1784:                                strlcat(buf, ",", sizeof buf);
                   1785:                        strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
                   1786:                }
                   1787:        }
                   1788:        if (buf[0] == '\0')
                   1789:                strlcpy(buf, "notty", sizeof buf);
                   1790:        return buf;
                   1791: }
                   1792:
                   1793: void
                   1794: session_proctitle(Session *s)
                   1795: {
                   1796:        if (s->pw == NULL)
                   1797:                error("no user for session %d", s->self);
                   1798:        else
                   1799:                setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1.81      markus   1800: }
                   1801:
                   1802: int
                   1803: session_setup_x11fwd(Session *s)
                   1804: {
                   1805:        struct stat st;
1.109     stevesk  1806:        char display[512], auth_display[512];
                   1807:        char hostname[MAXHOSTNAMELEN];
1.81      markus   1808:
                   1809:        if (no_x11_forwarding_flag) {
                   1810:                packet_send_debug("X11 forwarding disabled in user configuration file.");
                   1811:                return 0;
                   1812:        }
                   1813:        if (!options.x11_forwarding) {
                   1814:                debug("X11 forwarding disabled in server configuration file.");
                   1815:                return 0;
                   1816:        }
                   1817:        if (!options.xauth_location ||
                   1818:            (stat(options.xauth_location, &st) == -1)) {
                   1819:                packet_send_debug("No xauth program; cannot forward with spoofing.");
1.91      markus   1820:                return 0;
                   1821:        }
                   1822:        if (options.use_login) {
                   1823:                packet_send_debug("X11 forwarding disabled; "
                   1824:                    "not compatible with UseLogin=yes.");
1.81      markus   1825:                return 0;
                   1826:        }
1.87      markus   1827:        if (s->display != NULL) {
1.81      markus   1828:                debug("X11 display already set.");
                   1829:                return 0;
                   1830:        }
1.140     deraadt  1831:        if (x11_create_display_inet(options.x11_display_offset,
                   1832:            options.x11_use_localhost, s->single_connection,
                   1833:            &s->display_number) == -1) {
1.87      markus   1834:                debug("x11_create_display_inet failed.");
1.81      markus   1835:                return 0;
                   1836:        }
1.109     stevesk  1837:
                   1838:        /* Set up a suitable value for the DISPLAY variable. */
                   1839:        if (gethostname(hostname, sizeof(hostname)) < 0)
                   1840:                fatal("gethostname: %.100s", strerror(errno));
                   1841:        /*
                   1842:         * auth_display must be used as the displayname when the
                   1843:         * authorization entry is added with xauth(1).  This will be
                   1844:         * different than the DISPLAY string for localhost displays.
                   1845:         */
1.119     stevesk  1846:        if (options.x11_use_localhost) {
1.140     deraadt  1847:                snprintf(display, sizeof display, "localhost:%u.%u",
1.109     stevesk  1848:                    s->display_number, s->screen);
1.140     deraadt  1849:                snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
1.118     stevesk  1850:                    s->display_number, s->screen);
1.109     stevesk  1851:                s->display = xstrdup(display);
1.118     stevesk  1852:                s->auth_display = xstrdup(auth_display);
1.109     stevesk  1853:        } else {
1.140     deraadt  1854:                snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
1.109     stevesk  1855:                    s->display_number, s->screen);
                   1856:                s->display = xstrdup(display);
1.118     stevesk  1857:                s->auth_display = xstrdup(display);
1.109     stevesk  1858:        }
                   1859:
1.81      markus   1860:        return 1;
1.2       markus   1861: }
                   1862:
1.94      itojun   1863: static void
1.49      markus   1864: do_authenticated2(Authctxt *authctxt)
1.2       markus   1865: {
1.97      markus   1866:        server_loop2(authctxt);
1.165     markus   1867: }
                   1868:
                   1869: void
                   1870: do_cleanup(Authctxt *authctxt)
                   1871: {
                   1872:        static int called = 0;
                   1873:
                   1874:        debug("do_cleanup");
                   1875:
                   1876:        /* no cleanup if we're in the child for login shell */
                   1877:        if (is_child)
                   1878:                return;
                   1879:
                   1880:        /* avoid double cleanup */
                   1881:        if (called)
                   1882:                return;
                   1883:        called = 1;
                   1884:
                   1885:        if (authctxt == NULL)
                   1886:                return;
                   1887: #ifdef KRB5
                   1888:        if (options.kerberos_ticket_cleanup &&
                   1889:            authctxt->krb5_ctx)
                   1890:                krb5_cleanup_proc(authctxt);
1.161     markus   1891: #endif
1.165     markus   1892:
                   1893: #ifdef GSSAPI
                   1894:        if (compat20 && options.gss_cleanup_creds)
                   1895:                ssh_gssapi_cleanup_creds();
                   1896: #endif
                   1897:
                   1898:        /* remove agent socket */
                   1899:        auth_sock_cleanup_proc(authctxt->pw);
                   1900:
                   1901:        /*
                   1902:         * Cleanup ptys/utmp only if privsep is disabled,
                   1903:         * or if running in monitor.
                   1904:         */
                   1905:        if (!use_privsep || mm_is_monitor())
                   1906:                session_destroy_all(session_pty_cleanup2);
1.1       markus   1907: }