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

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