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

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