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

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