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

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