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

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