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

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