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

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