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

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