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

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