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

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