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

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