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

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