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

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