[BACK]Return to sshd.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/sshd.c, Revision 1.71

1.1       deraadt     1: /*
1.65      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
                      5:  * Created: Fri Mar 17 17:09:28 1995 ylo
                      6:  * This program is the ssh daemon.  It listens for connections from clients, and
                      7:  * performs authentication, executes use commands or shell, and forwards
                      8:  * information to/from the application to the user client over an encrypted
                      9:  * connection.  This can also handle forwarding of X11, TCP/IP, and authentication
                     10:  * agent connections.
                     11:  */
1.1       deraadt    12:
                     13: #include "includes.h"
1.71    ! provos     14: RCSID("$Id: sshd.c,v 1.70 1999/12/07 23:14:36 provos Exp $");
1.1       deraadt    15:
                     16: #include "xmalloc.h"
                     17: #include "rsa.h"
                     18: #include "ssh.h"
                     19: #include "pty.h"
                     20: #include "packet.h"
                     21: #include "buffer.h"
                     22: #include "cipher.h"
                     23: #include "mpaux.h"
                     24: #include "servconf.h"
                     25: #include "uidswap.h"
1.33      markus     26: #include "compat.h"
1.1       deraadt    27:
                     28: #ifdef LIBWRAP
                     29: #include <tcpd.h>
                     30: #include <syslog.h>
                     31: int allow_severity = LOG_INFO;
                     32: int deny_severity = LOG_WARNING;
                     33: #endif /* LIBWRAP */
                     34:
                     35: #ifndef O_NOCTTY
                     36: #define O_NOCTTY       0
                     37: #endif
                     38:
                     39: /* Local Xauthority file. */
1.46      markus     40: static char *xauthfile = NULL;
1.1       deraadt    41:
                     42: /* Server configuration options. */
                     43: ServerOptions options;
                     44:
                     45: /* Name of the server configuration file. */
                     46: char *config_file_name = SERVER_CONFIG_FILE;
                     47:
1.65      deraadt    48: /*
                     49:  * Debug mode flag.  This can be set on the command line.  If debug
                     50:  * mode is enabled, extra debugging output will be sent to the system
                     51:  * log, the daemon will not go to background, and will exit after processing
                     52:  * the first connection.
                     53:  */
1.1       deraadt    54: int debug_flag = 0;
                     55:
                     56: /* Flag indicating that the daemon is being started from inetd. */
                     57: int inetd_flag = 0;
                     58:
1.47      markus     59: /* debug goes to stderr unless inetd_flag is set */
                     60: int log_stderr = 0;
                     61:
1.1       deraadt    62: /* argv[0] without path. */
                     63: char *av0;
                     64:
                     65: /* Saved arguments to main(). */
                     66: char **saved_argv;
                     67:
1.66      markus     68: /*
                     69:  * This is set to the socket that the server is listening; this is used in
                     70:  * the SIGHUP signal handler.
                     71:  */
1.1       deraadt    72: int listen_sock;
                     73:
1.66      markus     74: /*
                     75:  * the client's version string, passed by sshd2 in compat mode. if != NULL,
                     76:  * sshd will skip the version-number exchange
                     77:  */
1.61      markus     78: char *client_version_string = NULL;
                     79:
1.64      markus     80: /* Flags set in auth-rsa from authorized_keys flags.  These are set in auth-rsa.c. */
1.1       deraadt    81: int no_port_forwarding_flag = 0;
                     82: int no_agent_forwarding_flag = 0;
                     83: int no_x11_forwarding_flag = 0;
                     84: int no_pty_flag = 0;
1.64      markus     85:
                     86: /* RSA authentication "command=" option. */
                     87: char *forced_command = NULL;
                     88:
                     89: /* RSA authentication "environment=" options. */
                     90: struct envstring *custom_environment = NULL;
1.1       deraadt    91:
                     92: /* Session id for the current session. */
                     93: unsigned char session_id[16];
                     94:
1.66      markus     95: /*
                     96:  * Any really sensitive data in the application is contained in this
                     97:  * structure. The idea is that this structure could be locked into memory so
                     98:  * that the pages do not get written into swap.  However, there are some
                     99:  * problems. The private key contains BIGNUMs, and we do not (in principle)
                    100:  * have access to the internals of them, and locking just the structure is
                    101:  * not very useful.  Currently, memory locking is not implemented.
                    102:  */
1.64      markus    103: struct {
                    104:        RSA *private_key;        /* Private part of server key. */
                    105:        RSA *host_key;           /* Private part of host key. */
1.1       deraadt   106: } sensitive_data;
                    107:
1.66      markus    108: /*
                    109:  * Flag indicating whether the current session key has been used.  This flag
                    110:  * is set whenever the key is used, and cleared when the key is regenerated.
                    111:  */
1.1       deraadt   112: int key_used = 0;
                    113:
                    114: /* This is set to true when SIGHUP is received. */
                    115: int received_sighup = 0;
                    116:
                    117: /* Public side of the server key.  This value is regenerated regularly with
                    118:    the private key. */
1.2       provos    119: RSA *public_key;
1.1       deraadt   120:
                    121: /* Prototypes for various functions defined later in this file. */
1.52      markus    122: void do_connection();
                    123: void do_authentication(char *user);
1.64      markus    124: void do_authloop(struct passwd * pw);
1.52      markus    125: void do_fake_authloop(char *user);
1.64      markus    126: void do_authenticated(struct passwd * pw);
                    127: void do_exec_pty(const char *command, int ptyfd, int ttyfd,
                    128:                 const char *ttyname, struct passwd * pw, const char *term,
                    129:                 const char *display, const char *auth_proto,
                    130:                 const char *auth_data);
                    131: void do_exec_no_pty(const char *command, struct passwd * pw,
                    132:                    const char *display, const char *auth_proto,
                    133:                    const char *auth_data);
                    134: void do_child(const char *command, struct passwd * pw, const char *term,
1.1       deraadt   135:              const char *display, const char *auth_proto,
                    136:              const char *auth_data, const char *ttyname);
                    137:
1.65      deraadt   138: /*
                    139:  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
                    140:  * the effect is to reread the configuration file (and to regenerate
                    141:  * the server key).
                    142:  */
1.64      markus    143: void
                    144: sighup_handler(int sig)
1.1       deraadt   145: {
1.64      markus    146:        received_sighup = 1;
                    147:        signal(SIGHUP, sighup_handler);
1.1       deraadt   148: }
                    149:
1.65      deraadt   150: /*
                    151:  * Called from the main program after receiving SIGHUP.
                    152:  * Restarts the server.
                    153:  */
1.64      markus    154: void
                    155: sighup_restart()
1.1       deraadt   156: {
1.64      markus    157:        log("Received SIGHUP; restarting.");
                    158:        close(listen_sock);
                    159:        execv(saved_argv[0], saved_argv);
                    160:        log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
                    161:        exit(1);
1.1       deraadt   162: }
                    163:
1.65      deraadt   164: /*
                    165:  * Generic signal handler for terminating signals in the master daemon.
                    166:  * These close the listen socket; not closing it seems to cause "Address
                    167:  * already in use" problems on some machines, which is inconvenient.
                    168:  */
1.64      markus    169: void
                    170: sigterm_handler(int sig)
1.1       deraadt   171: {
1.64      markus    172:        log("Received signal %d; terminating.", sig);
                    173:        close(listen_sock);
                    174:        exit(255);
1.1       deraadt   175: }
                    176:
1.65      deraadt   177: /*
                    178:  * SIGCHLD handler.  This is called whenever a child dies.  This will then
                    179:  * reap any zombies left by exited c.
                    180:  */
1.64      markus    181: void
                    182: main_sigchld_handler(int sig)
1.1       deraadt   183: {
1.64      markus    184:        int save_errno = errno;
                    185:        int status;
1.60      deraadt   186:
1.64      markus    187:        while (waitpid(-1, &status, WNOHANG) > 0)
                    188:                ;
1.60      deraadt   189:
1.64      markus    190:        signal(SIGCHLD, main_sigchld_handler);
                    191:        errno = save_errno;
1.1       deraadt   192: }
                    193:
1.65      deraadt   194: /*
                    195:  * Signal handler for the alarm after the login grace period has expired.
                    196:  */
1.64      markus    197: void
                    198: grace_alarm_handler(int sig)
1.1       deraadt   199: {
1.64      markus    200:        /* Close the connection. */
                    201:        packet_close();
                    202:
                    203:        /* Log error and exit. */
                    204:        fatal("Timeout before authentication for %s.", get_remote_ipaddr());
1.62      markus    205: }
                    206:
1.65      deraadt   207: /*
                    208:  * convert ssh auth msg type into description
                    209:  */
1.62      markus    210: char *
                    211: get_authname(int type)
                    212: {
1.64      markus    213:        switch (type) {
                    214:        case SSH_CMSG_AUTH_PASSWORD:
                    215:                return "password";
                    216:        case SSH_CMSG_AUTH_RSA:
                    217:                return "rsa";
                    218:        case SSH_CMSG_AUTH_RHOSTS_RSA:
                    219:                return "rhosts-rsa";
                    220:        case SSH_CMSG_AUTH_RHOSTS:
                    221:                return "rhosts";
1.62      markus    222: #ifdef KRB4
1.64      markus    223:        case SSH_CMSG_AUTH_KERBEROS:
                    224:                return "kerberos";
1.62      markus    225: #endif
1.63      markus    226: #ifdef SKEY
1.64      markus    227:        case SSH_CMSG_AUTH_TIS_RESPONSE:
                    228:                return "s/key";
1.63      markus    229: #endif
1.64      markus    230:        }
                    231:        fatal("get_authname: unknown auth %d: internal error", type);
                    232:        return NULL;
1.1       deraadt   233: }
                    234:
1.65      deraadt   235: /*
                    236:  * Signal handler for the key regeneration alarm.  Note that this
                    237:  * alarm only occurs in the daemon waiting for connections, and it does not
                    238:  * do anything with the private key or random state before forking.
                    239:  * Thus there should be no concurrency control/asynchronous execution
                    240:  * problems.
                    241:  */
1.64      markus    242: void
                    243: key_regeneration_alarm(int sig)
1.1       deraadt   244: {
1.64      markus    245:        int save_errno = errno;
1.18      deraadt   246:
1.64      markus    247:        /* Check if we should generate a new key. */
                    248:        if (key_used) {
                    249:                /* This should really be done in the background. */
                    250:                log("Generating new %d bit RSA key.", options.server_key_bits);
                    251:
                    252:                if (sensitive_data.private_key != NULL)
                    253:                        RSA_free(sensitive_data.private_key);
                    254:                sensitive_data.private_key = RSA_new();
                    255:
                    256:                if (public_key != NULL)
                    257:                        RSA_free(public_key);
                    258:                public_key = RSA_new();
                    259:
                    260:                rsa_generate_key(sensitive_data.private_key, public_key,
                    261:                                 options.server_key_bits);
                    262:                arc4random_stir();
                    263:                key_used = 0;
                    264:                log("RSA key generation complete.");
                    265:        }
                    266:        /* Reschedule the alarm. */
                    267:        signal(SIGALRM, key_regeneration_alarm);
                    268:        alarm(options.key_regeneration_time);
                    269:        errno = save_errno;
1.1       deraadt   270: }
                    271:
1.65      deraadt   272: /*
                    273:  * Main program for the daemon.
                    274:  */
1.2       provos    275: int
                    276: main(int ac, char **av)
1.1       deraadt   277: {
1.64      markus    278:        extern char *optarg;
                    279:        extern int optind;
                    280:        int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
                    281:        int remote_major, remote_minor;
                    282:        int silentrsa = 0;
1.70      provos    283:        struct pollfd fds;
1.64      markus    284:        struct sockaddr_in sin;
                    285:        char buf[100];                  /* Must not be larger than remote_version. */
                    286:        char remote_version[100];       /* Must be at least as big as buf. */
                    287:        const char *remote_ip;
                    288:        int remote_port;
                    289:        char *comment;
                    290:        FILE *f;
                    291:        struct linger linger;
                    292:
                    293:        /* Save argv[0]. */
                    294:        saved_argv = av;
                    295:        if (strchr(av[0], '/'))
                    296:                av0 = strrchr(av[0], '/') + 1;
                    297:        else
                    298:                av0 = av[0];
                    299:
                    300:        /* Initialize configuration options to their default values. */
                    301:        initialize_server_options(&options);
                    302:
                    303:        /* Parse command-line arguments. */
                    304:        while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ")) != EOF) {
                    305:                switch (opt) {
                    306:                case 'f':
                    307:                        config_file_name = optarg;
                    308:                        break;
                    309:                case 'd':
                    310:                        debug_flag = 1;
                    311:                        options.log_level = SYSLOG_LEVEL_DEBUG;
                    312:                        break;
                    313:                case 'i':
                    314:                        inetd_flag = 1;
                    315:                        break;
                    316:                case 'Q':
                    317:                        silentrsa = 1;
                    318:                        break;
                    319:                case 'q':
                    320:                        options.log_level = SYSLOG_LEVEL_QUIET;
                    321:                        break;
                    322:                case 'b':
                    323:                        options.server_key_bits = atoi(optarg);
                    324:                        break;
                    325:                case 'p':
                    326:                        options.port = atoi(optarg);
                    327:                        break;
                    328:                case 'g':
                    329:                        options.login_grace_time = atoi(optarg);
                    330:                        break;
                    331:                case 'k':
                    332:                        options.key_regeneration_time = atoi(optarg);
                    333:                        break;
                    334:                case 'h':
                    335:                        options.host_key_file = optarg;
                    336:                        break;
                    337:                case 'V':
                    338:                        client_version_string = optarg;
                    339:                        /* only makes sense with inetd_flag, i.e. no listen() */
                    340:                        inetd_flag = 1;
                    341:                        break;
                    342:                case '?':
                    343:                default:
                    344:                        fprintf(stderr, "sshd version %s\n", SSH_VERSION);
                    345:                        fprintf(stderr, "Usage: %s [options]\n", av0);
                    346:                        fprintf(stderr, "Options:\n");
1.66      markus    347:                        fprintf(stderr, "  -f file    Configuration file (default %s)\n", SERVER_CONFIG_FILE);
1.64      markus    348:                        fprintf(stderr, "  -d         Debugging mode\n");
                    349:                        fprintf(stderr, "  -i         Started from inetd\n");
                    350:                        fprintf(stderr, "  -q         Quiet (no logging)\n");
                    351:                        fprintf(stderr, "  -p port    Listen on the specified port (default: 22)\n");
                    352:                        fprintf(stderr, "  -k seconds Regenerate server key every this many seconds (default: 3600)\n");
                    353:                        fprintf(stderr, "  -g seconds Grace period for authentication (default: 300)\n");
                    354:                        fprintf(stderr, "  -b bits    Size of server RSA key (default: 768 bits)\n");
                    355:                        fprintf(stderr, "  -h file    File from which to read host key (default: %s)\n",
                    356:                                HOST_KEY_FILE);
                    357:                        exit(1);
                    358:                }
                    359:        }
                    360:
                    361:        /* check if RSA support exists */
                    362:        if (rsa_alive() == 0) {
                    363:                if (silentrsa == 0)
                    364:                        printf("sshd: no RSA support in libssl and libcrypto -- exiting.  See ssl(8)\n");
                    365:                log("no RSA support in libssl and libcrypto -- exiting.  See ssl(8)");
                    366:                exit(1);
                    367:        }
                    368:        /* Read server configuration options from the configuration file. */
                    369:        read_server_config(&options, config_file_name);
                    370:
                    371:        /* Fill in default values for those options not explicitly set. */
                    372:        fill_default_server_options(&options);
                    373:
                    374:        /* Check certain values for sanity. */
                    375:        if (options.server_key_bits < 512 ||
                    376:            options.server_key_bits > 32768) {
                    377:                fprintf(stderr, "Bad server key size.\n");
                    378:                exit(1);
                    379:        }
                    380:        if (options.port < 1 || options.port > 65535) {
                    381:                fprintf(stderr, "Bad port number.\n");
                    382:                exit(1);
                    383:        }
                    384:        /* Check that there are no remaining arguments. */
                    385:        if (optind < ac) {
                    386:                fprintf(stderr, "Extra argument %s.\n", av[optind]);
                    387:                exit(1);
                    388:        }
                    389:        /* Force logging to stderr while loading the private host key
                    390:           unless started from inetd */
                    391:        log_init(av0, options.log_level, options.log_facility, !inetd_flag);
                    392:
                    393:        debug("sshd version %.100s", SSH_VERSION);
                    394:
                    395:        sensitive_data.host_key = RSA_new();
                    396:        errno = 0;
                    397:        /* Load the host key.  It must have empty passphrase. */
                    398:        if (!load_private_key(options.host_key_file, "",
                    399:                              sensitive_data.host_key, &comment)) {
                    400:                error("Could not load host key: %.200s: %.100s",
                    401:                      options.host_key_file, strerror(errno));
                    402:                exit(1);
                    403:        }
                    404:        xfree(comment);
                    405:
                    406:        /* Initialize the log (it is reinitialized below in case we
                    407:           forked). */
                    408:        if (debug_flag && !inetd_flag)
                    409:                log_stderr = 1;
                    410:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    411:
                    412:        /* If not in debugging mode, and not started from inetd,
                    413:           disconnect from the controlling terminal, and fork.  The
                    414:           original process exits. */
                    415:        if (!debug_flag && !inetd_flag) {
1.1       deraadt   416: #ifdef TIOCNOTTY
1.64      markus    417:                int fd;
1.1       deraadt   418: #endif /* TIOCNOTTY */
1.64      markus    419:                if (daemon(0, 0) < 0)
                    420:                        fatal("daemon() failed: %.200s", strerror(errno));
                    421:
                    422:                /* Disconnect from the controlling tty. */
1.1       deraadt   423: #ifdef TIOCNOTTY
1.64      markus    424:                fd = open("/dev/tty", O_RDWR | O_NOCTTY);
                    425:                if (fd >= 0) {
                    426:                        (void) ioctl(fd, TIOCNOTTY, NULL);
                    427:                        close(fd);
                    428:                }
                    429: #endif /* TIOCNOTTY */
                    430:        }
                    431:        /* Reinitialize the log (because of the fork above). */
                    432:        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    433:
                    434:        /* Check that server and host key lengths differ sufficiently.
                    435:           This is necessary to make double encryption work with rsaref.
                    436:           Oh, I hate software patents. I dont know if this can go? Niels */
                    437:        if (options.server_key_bits >
                    438:        BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
                    439:            options.server_key_bits <
                    440:        BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                    441:                options.server_key_bits =
                    442:                        BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
                    443:                debug("Forcing server key to %d bits to make it differ from host key.",
                    444:                      options.server_key_bits);
1.1       deraadt   445:        }
1.64      markus    446:        /* Do not display messages to stdout in RSA code. */
                    447:        rsa_set_verbose(0);
                    448:
                    449:        /* Initialize the random number generator. */
                    450:        arc4random_stir();
                    451:
                    452:        /* Chdir to the root directory so that the current disk can be
                    453:           unmounted if desired. */
                    454:        chdir("/");
                    455:
                    456:        /* Close connection cleanly after attack. */
                    457:        cipher_attack_detected = packet_disconnect;
                    458:
                    459:        /* Start listening for a socket, unless started from inetd. */
                    460:        if (inetd_flag) {
                    461:                int s1, s2;
                    462:                s1 = dup(0);    /* Make sure descriptors 0, 1, and 2 are in use. */
                    463:                s2 = dup(s1);
                    464:                sock_in = dup(0);
                    465:                sock_out = dup(1);
                    466:                /* We intentionally do not close the descriptors 0, 1, and 2
                    467:                   as our code for setting the descriptors won\'t work
                    468:                   if ttyfd happens to be one of those. */
                    469:                debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
                    470:
                    471:                public_key = RSA_new();
                    472:                sensitive_data.private_key = RSA_new();
                    473:
                    474:                log("Generating %d bit RSA key.", options.server_key_bits);
                    475:                rsa_generate_key(sensitive_data.private_key, public_key,
                    476:                                 options.server_key_bits);
                    477:                arc4random_stir();
                    478:                log("RSA key generation complete.");
                    479:        } else {
                    480:                /* Create socket for listening. */
                    481:                listen_sock = socket(AF_INET, SOCK_STREAM, 0);
                    482:                if (listen_sock < 0)
                    483:                        fatal("socket: %.100s", strerror(errno));
                    484:
                    485:                /* Set socket options.  We try to make the port reusable
                    486:                   and have it close as fast as possible without waiting
                    487:                   in unnecessary wait states on close. */
                    488:                setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on,
                    489:                           sizeof(on));
                    490:                linger.l_onoff = 1;
                    491:                linger.l_linger = 5;
                    492:                setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *) &linger,
                    493:                           sizeof(linger));
                    494:
                    495:                memset(&sin, 0, sizeof(sin));
                    496:                sin.sin_family = AF_INET;
                    497:                sin.sin_addr = options.listen_addr;
                    498:                sin.sin_port = htons(options.port);
                    499:
                    500:                if (bind(listen_sock, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
                    501:                        error("bind: %.100s", strerror(errno));
                    502:                        shutdown(listen_sock, SHUT_RDWR);
                    503:                        close(listen_sock);
                    504:                        fatal("Bind to port %d failed.", options.port);
                    505:                }
                    506:                if (!debug_flag) {
1.66      markus    507:                        /*
                    508:                         * Record our pid in /etc/sshd_pid to make it easier
                    509:                         * to kill the correct sshd.  We don\'t want to do
                    510:                         * this before the bind above because the bind will
                    511:                         * fail if there already is a daemon, and this will
                    512:                         * overwrite any old pid in the file.
                    513:                         */
1.64      markus    514:                        f = fopen(SSH_DAEMON_PID_FILE, "w");
                    515:                        if (f) {
                    516:                                fprintf(f, "%u\n", (unsigned int) getpid());
                    517:                                fclose(f);
                    518:                        }
                    519:                }
                    520:
                    521:                log("Server listening on port %d.", options.port);
                    522:                if (listen(listen_sock, 5) < 0)
                    523:                        fatal("listen: %.100s", strerror(errno));
                    524:
                    525:                public_key = RSA_new();
                    526:                sensitive_data.private_key = RSA_new();
                    527:
                    528:                log("Generating %d bit RSA key.", options.server_key_bits);
                    529:                rsa_generate_key(sensitive_data.private_key, public_key,
                    530:                                 options.server_key_bits);
                    531:                arc4random_stir();
                    532:                log("RSA key generation complete.");
                    533:
                    534:                /* Schedule server key regeneration alarm. */
                    535:                signal(SIGALRM, key_regeneration_alarm);
                    536:                alarm(options.key_regeneration_time);
                    537:
                    538:                /* Arrange to restart on SIGHUP.  The handler needs listen_sock. */
                    539:                signal(SIGHUP, sighup_handler);
                    540:                signal(SIGTERM, sigterm_handler);
                    541:                signal(SIGQUIT, sigterm_handler);
                    542:
                    543:                /* Arrange SIGCHLD to be caught. */
                    544:                signal(SIGCHLD, main_sigchld_handler);
                    545:
1.66      markus    546:                /*
                    547:                 * Stay listening for connections until the system crashes or
                    548:                 * the daemon is killed with a signal.
                    549:                 */
1.64      markus    550:                for (;;) {
                    551:                        if (received_sighup)
                    552:                                sighup_restart();
1.70      provos    553:                        /* Wait in poll until there is a connection. */
                    554:                        memset(&fds, 0, sizeof(fds));
                    555:                        fds.fd = listen_sock;
                    556:                        fds.events = POLLIN;
                    557:                        if (poll(&fds, 1, -1) == -1) {
                    558:                                if (errno == EINTR)
                    559:                                        continue;
1.71    ! provos    560:                                fatal("poll: %.100s", strerror(errno));
1.70      provos    561:                                /*NOTREACHED*/
                    562:                        }
                    563:                        if (fds.revents == 0)
                    564:                                continue;
1.64      markus    565:                        aux = sizeof(sin);
                    566:                        newsock = accept(listen_sock, (struct sockaddr *) & sin, &aux);
                    567:                        if (received_sighup)
                    568:                                sighup_restart();
                    569:                        if (newsock < 0) {
                    570:                                if (errno == EINTR)
                    571:                                        continue;
                    572:                                error("accept: %.100s", strerror(errno));
                    573:                                continue;
                    574:                        }
1.66      markus    575:                        /*
                    576:                         * Got connection.  Fork a child to handle it, unless
                    577:                         * we are in debugging mode.
                    578:                         */
1.64      markus    579:                        if (debug_flag) {
1.66      markus    580:                                /*
                    581:                                 * In debugging mode.  Close the listening
                    582:                                 * socket, and start processing the
                    583:                                 * connection without forking.
                    584:                                 */
1.64      markus    585:                                debug("Server will not fork when running in debugging mode.");
                    586:                                close(listen_sock);
                    587:                                sock_in = newsock;
                    588:                                sock_out = newsock;
                    589:                                pid = getpid();
                    590:                                break;
                    591:                        } else {
1.66      markus    592:                                /*
                    593:                                 * Normal production daemon.  Fork, and have
                    594:                                 * the child process the connection. The
                    595:                                 * parent continues listening.
                    596:                                 */
1.64      markus    597:                                if ((pid = fork()) == 0) {
1.66      markus    598:                                        /*
                    599:                                         * Child.  Close the listening socket, and start using the
                    600:                                         * accepted socket.  Reinitialize logging (since our pid has
                    601:                                         * changed).  We break out of the loop to handle the connection.
                    602:                                         */
1.64      markus    603:                                        close(listen_sock);
                    604:                                        sock_in = newsock;
                    605:                                        sock_out = newsock;
                    606:                                        log_init(av0, options.log_level, options.log_facility, log_stderr);
                    607:                                        break;
                    608:                                }
                    609:                        }
                    610:
                    611:                        /* Parent.  Stay in the loop. */
                    612:                        if (pid < 0)
                    613:                                error("fork: %.100s", strerror(errno));
                    614:                        else
                    615:                                debug("Forked child %d.", pid);
1.1       deraadt   616:
1.64      markus    617:                        /* Mark that the key has been used (it was "given" to the child). */
                    618:                        key_used = 1;
1.1       deraadt   619:
1.64      markus    620:                        arc4random_stir();
1.1       deraadt   621:
1.64      markus    622:                        /* Close the new socket (the child is now taking care of it). */
                    623:                        close(newsock);
                    624:                }
1.1       deraadt   625:        }
                    626:
1.64      markus    627:        /* This is the child processing a new connection. */
                    628:
1.66      markus    629:        /*
                    630:         * Disable the key regeneration alarm.  We will not regenerate the
                    631:         * key since we are no longer in a position to give it to anyone. We
                    632:         * will not restart on SIGHUP since it no longer makes sense.
                    633:         */
1.64      markus    634:        alarm(0);
                    635:        signal(SIGALRM, SIG_DFL);
                    636:        signal(SIGHUP, SIG_DFL);
                    637:        signal(SIGTERM, SIG_DFL);
                    638:        signal(SIGQUIT, SIG_DFL);
                    639:        signal(SIGCHLD, SIG_DFL);
                    640:
1.66      markus    641:        /*
                    642:         * Set socket options for the connection.  We want the socket to
                    643:         * close as fast as possible without waiting for anything.  If the
                    644:         * connection is not a socket, these will do nothing.
                    645:         */
                    646:        /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1.64      markus    647:        linger.l_onoff = 1;
                    648:        linger.l_linger = 5;
                    649:        setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
                    650:
1.66      markus    651:        /*
                    652:         * Register our connection.  This turns encryption off because we do
                    653:         * not have a key.
                    654:         */
1.64      markus    655:        packet_set_connection(sock_in, sock_out);
1.1       deraadt   656:
1.64      markus    657:        remote_port = get_remote_port();
                    658:        remote_ip = get_remote_ipaddr();
1.52      markus    659:
1.64      markus    660:        /* Check whether logins are denied from this host. */
1.37      dugsong   661: #ifdef LIBWRAP
1.64      markus    662:        {
                    663:                struct request_info req;
1.37      dugsong   664:
1.64      markus    665:                request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
                    666:                fromhost(&req);
1.37      dugsong   667:
1.64      markus    668:                if (!hosts_access(&req)) {
                    669:                        close(sock_in);
                    670:                        close(sock_out);
                    671:                        refuse(&req);
                    672:                }
                    673:                verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
                    674:        }
1.37      dugsong   675: #else
1.64      markus    676:        /* Log the connection. */
                    677:        verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.37      dugsong   678: #endif /* LIBWRAP */
1.1       deraadt   679:
1.66      markus    680:        /*
                    681:         * We don\'t want to listen forever unless the other side
                    682:         * successfully authenticates itself.  So we set up an alarm which is
                    683:         * cleared after successful authentication.  A limit of zero
                    684:         * indicates no limit. Note that we don\'t set the alarm in debugging
                    685:         * mode; it is just annoying to have the server exit just when you
                    686:         * are about to discover the bug.
                    687:         */
1.64      markus    688:        signal(SIGALRM, grace_alarm_handler);
                    689:        if (!debug_flag)
                    690:                alarm(options.login_grace_time);
                    691:
                    692:        if (client_version_string != NULL) {
                    693:                /* we are exec'ed by sshd2, so skip exchange of protocol version */
                    694:                strlcpy(buf, client_version_string, sizeof(buf));
                    695:        } else {
                    696:                /* Send our protocol version identification. */
                    697:                snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
                    698:                         PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1.68      deraadt   699:                if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf))
1.64      markus    700:                        fatal("Could not write ident string to %s.", get_remote_ipaddr());
                    701:
                    702:                /* Read other side\'s version identification. */
                    703:                for (i = 0; i < sizeof(buf) - 1; i++) {
                    704:                        if (read(sock_in, &buf[i], 1) != 1)
                    705:                                fatal("Did not receive ident string from %s.", get_remote_ipaddr());
                    706:                        if (buf[i] == '\r') {
                    707:                                buf[i] = '\n';
                    708:                                buf[i + 1] = 0;
                    709:                                break;
                    710:                        }
                    711:                        if (buf[i] == '\n') {
                    712:                                /* buf[i] == '\n' */
                    713:                                buf[i + 1] = 0;
                    714:                                break;
                    715:                        }
                    716:                }
                    717:                buf[sizeof(buf) - 1] = 0;
                    718:        }
                    719:
1.66      markus    720:        /*
                    721:         * Check that the versions match.  In future this might accept
                    722:         * several versions and set appropriate flags to handle them.
                    723:         */
1.64      markus    724:        if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
1.68      deraadt   725:            remote_version) != 3) {
                    726:                char *s = "Protocol mismatch.\n";
                    727:
                    728:                (void) atomicio(write, sock_out, s, strlen(s));
1.64      markus    729:                close(sock_in);
                    730:                close(sock_out);
                    731:                fatal("Bad protocol version identification '%.100s' from %s",
                    732:                      buf, get_remote_ipaddr());
                    733:        }
                    734:        debug("Client protocol version %d.%d; client software version %.100s",
                    735:              remote_major, remote_minor, remote_version);
                    736:        if (remote_major != PROTOCOL_MAJOR) {
1.68      deraadt   737:                char *s = "Protocol major versions differ.\n";
                    738:
                    739:                (void) atomicio(write, sock_out, s, strlen(s));
1.64      markus    740:                close(sock_in);
                    741:                close(sock_out);
                    742:                fatal("Protocol major versions differ for %s: %d vs. %d",
                    743:                      get_remote_ipaddr(),
                    744:                      PROTOCOL_MAJOR, remote_major);
                    745:        }
                    746:        /* Check that the client has sufficiently high software version. */
                    747:        if (remote_major == 1 && remote_minor < 3)
                    748:                packet_disconnect("Your ssh version is too old and is no longer supported.  Please install a newer version.");
                    749:
                    750:        if (remote_major == 1 && remote_minor == 3) {
                    751:                enable_compat13();
                    752:                if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
                    753:                        debug("Agent forwarding disabled, remote version is not compatible.");
                    754:                        no_agent_forwarding_flag = 1;
                    755:                }
                    756:        }
1.66      markus    757:        /*
                    758:         * Check that the connection comes from a privileged port.  Rhosts-
                    759:         * and Rhosts-RSA-Authentication only make sense from priviledged
                    760:         * programs.  Of course, if the intruder has root access on his local
                    761:         * machine, he can connect from any port.  So do not use these
                    762:         * authentication methods from machines that you do not trust.
                    763:         */
1.64      markus    764:        if (remote_port >= IPPORT_RESERVED ||
                    765:            remote_port < IPPORT_RESERVED / 2) {
                    766:                options.rhosts_authentication = 0;
                    767:                options.rhosts_rsa_authentication = 0;
                    768:        }
                    769:        packet_set_nonblocking();
1.1       deraadt   770:
1.64      markus    771:        /* Handle the connection. */
                    772:        do_connection();
1.1       deraadt   773:
                    774: #ifdef KRB4
1.64      markus    775:        /* Cleanup user's ticket cache file. */
                    776:        if (options.kerberos_ticket_cleanup)
                    777:                (void) dest_tkt();
1.1       deraadt   778: #endif /* KRB4 */
                    779:
1.64      markus    780:        /* Cleanup user's local Xauthority file. */
                    781:        if (xauthfile)
                    782:                unlink(xauthfile);
                    783:
                    784:        /* The connection has been terminated. */
                    785:        verbose("Closing connection to %.100s", remote_ip);
                    786:        packet_close();
                    787:        exit(0);
1.1       deraadt   788: }
                    789:
1.65      deraadt   790: /*
                    791:  * Process an incoming connection.  Protocol version identifiers have already
                    792:  * been exchanged.  This sends server key and performs the key exchange.
                    793:  * Server and host keys will no longer be needed after this functions.
                    794:  */
1.52      markus    795: void
                    796: do_connection()
1.1       deraadt   797: {
1.64      markus    798:        int i, len;
                    799:        BIGNUM *session_key_int;
                    800:        unsigned char session_key[SSH_SESSION_KEY_LENGTH];
                    801:        unsigned char check_bytes[8];
                    802:        char *user;
                    803:        unsigned int cipher_type, auth_mask, protocol_flags;
                    804:        int plen, slen;
                    805:        u_int32_t rand = 0;
                    806:
1.66      markus    807:        /*
                    808:         * Generate check bytes that the client must send back in the user
                    809:         * packet in order for it to be accepted; this is used to defy ip
                    810:         * spoofing attacks.  Note that this only works against somebody
                    811:         * doing IP spoofing from a remote machine; any machine on the local
                    812:         * network can still see outgoing packets and catch the random
                    813:         * cookie.  This only affects rhosts authentication, and this is one
                    814:         * of the reasons why it is inherently insecure.
                    815:         */
1.64      markus    816:        for (i = 0; i < 8; i++) {
                    817:                if (i % 4 == 0)
                    818:                        rand = arc4random();
                    819:                check_bytes[i] = rand & 0xff;
                    820:                rand >>= 8;
                    821:        }
                    822:
1.66      markus    823:        /*
                    824:         * Send our public key.  We include in the packet 64 bits of random
                    825:         * data that must be matched in the reply in order to prevent IP
                    826:         * spoofing.
                    827:         */
1.64      markus    828:        packet_start(SSH_SMSG_PUBLIC_KEY);
                    829:        for (i = 0; i < 8; i++)
                    830:                packet_put_char(check_bytes[i]);
                    831:
                    832:        /* Store our public server RSA key. */
                    833:        packet_put_int(BN_num_bits(public_key->n));
                    834:        packet_put_bignum(public_key->e);
                    835:        packet_put_bignum(public_key->n);
                    836:
                    837:        /* Store our public host RSA key. */
                    838:        packet_put_int(BN_num_bits(sensitive_data.host_key->n));
                    839:        packet_put_bignum(sensitive_data.host_key->e);
                    840:        packet_put_bignum(sensitive_data.host_key->n);
                    841:
                    842:        /* Put protocol flags. */
                    843:        packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                    844:
                    845:        /* Declare which ciphers we support. */
                    846:        packet_put_int(cipher_mask());
                    847:
                    848:        /* Declare supported authentication types. */
                    849:        auth_mask = 0;
                    850:        if (options.rhosts_authentication)
                    851:                auth_mask |= 1 << SSH_AUTH_RHOSTS;
                    852:        if (options.rhosts_rsa_authentication)
                    853:                auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
                    854:        if (options.rsa_authentication)
                    855:                auth_mask |= 1 << SSH_AUTH_RSA;
1.1       deraadt   856: #ifdef KRB4
1.64      markus    857:        if (options.kerberos_authentication)
                    858:                auth_mask |= 1 << SSH_AUTH_KERBEROS;
1.1       deraadt   859: #endif
1.5       dugsong   860: #ifdef AFS
1.64      markus    861:        if (options.kerberos_tgt_passing)
                    862:                auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
                    863:        if (options.afs_token_passing)
                    864:                auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1.1       deraadt   865: #endif
1.63      markus    866: #ifdef SKEY
1.64      markus    867:        if (options.skey_authentication == 1)
                    868:                auth_mask |= 1 << SSH_AUTH_TIS;
1.63      markus    869: #endif
1.64      markus    870:        if (options.password_authentication)
                    871:                auth_mask |= 1 << SSH_AUTH_PASSWORD;
                    872:        packet_put_int(auth_mask);
                    873:
                    874:        /* Send the packet and wait for it to be sent. */
                    875:        packet_send();
                    876:        packet_write_wait();
                    877:
                    878:        debug("Sent %d bit public key and %d bit host key.",
                    879:              BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
                    880:
                    881:        /* Read clients reply (cipher type and session key). */
                    882:        packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
                    883:
1.69      markus    884:        /* Get cipher type and check whether we accept this. */
1.64      markus    885:        cipher_type = packet_get_char();
1.69      markus    886:
                    887:         if (!(cipher_mask() & (1 << cipher_type)))
                    888:                packet_disconnect("Warning: client selects unsupported cipher.");
1.64      markus    889:
                    890:        /* Get check bytes from the packet.  These must match those we
                    891:           sent earlier with the public key packet. */
                    892:        for (i = 0; i < 8; i++)
                    893:                if (check_bytes[i] != packet_get_char())
                    894:                        packet_disconnect("IP Spoofing check bytes do not match.");
                    895:
                    896:        debug("Encryption type: %.200s", cipher_name(cipher_type));
                    897:
                    898:        /* Get the encrypted integer. */
                    899:        session_key_int = BN_new();
                    900:        packet_get_bignum(session_key_int, &slen);
                    901:
                    902:        protocol_flags = packet_get_int();
                    903:        packet_set_protocol_flags(protocol_flags);
                    904:
                    905:        packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
                    906:
1.66      markus    907:        /*
                    908:         * Decrypt it using our private server key and private host key (key
                    909:         * with larger modulus first).
                    910:         */
1.64      markus    911:        if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
                    912:                /* Private key has bigger modulus. */
                    913:                if (BN_num_bits(sensitive_data.private_key->n) <
                    914:                    BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
                    915:                        fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
                    916:                              get_remote_ipaddr(),
                    917:                              BN_num_bits(sensitive_data.private_key->n),
                    918:                              BN_num_bits(sensitive_data.host_key->n),
                    919:                              SSH_KEY_BITS_RESERVED);
                    920:                }
                    921:                rsa_private_decrypt(session_key_int, session_key_int,
                    922:                                    sensitive_data.private_key);
                    923:                rsa_private_decrypt(session_key_int, session_key_int,
                    924:                                    sensitive_data.host_key);
                    925:        } else {
                    926:                /* Host key has bigger modulus (or they are equal). */
                    927:                if (BN_num_bits(sensitive_data.host_key->n) <
                    928:                    BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
                    929:                        fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
                    930:                              get_remote_ipaddr(),
                    931:                              BN_num_bits(sensitive_data.host_key->n),
                    932:                              BN_num_bits(sensitive_data.private_key->n),
                    933:                              SSH_KEY_BITS_RESERVED);
                    934:                }
                    935:                rsa_private_decrypt(session_key_int, session_key_int,
                    936:                                    sensitive_data.host_key);
                    937:                rsa_private_decrypt(session_key_int, session_key_int,
                    938:                                    sensitive_data.private_key);
                    939:        }
                    940:
                    941:        compute_session_id(session_id, check_bytes,
                    942:                           sensitive_data.host_key->n,
                    943:                           sensitive_data.private_key->n);
                    944:
1.66      markus    945:        /*
                    946:         * Extract session key from the decrypted integer.  The key is in the
                    947:         * least significant 256 bits of the integer; the first byte of the
                    948:         * key is in the highest bits.
                    949:         */
1.64      markus    950:        BN_mask_bits(session_key_int, sizeof(session_key) * 8);
                    951:        len = BN_num_bytes(session_key_int);
                    952:        if (len < 0 || len > sizeof(session_key))
                    953:                fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
                    954:                      get_remote_ipaddr(),
                    955:                      len, sizeof(session_key));
                    956:        memset(session_key, 0, sizeof(session_key));
                    957:        BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
                    958:
                    959:        /* Xor the first 16 bytes of the session key with the session id. */
                    960:        for (i = 0; i < 16; i++)
                    961:                session_key[i] ^= session_id[i];
                    962:
                    963:        /* Destroy the decrypted integer.  It is no longer needed. */
                    964:        BN_clear_free(session_key_int);
                    965:
                    966:        /* Set the session key.  From this on all communications will be encrypted. */
                    967:        packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
                    968:
                    969:        /* Destroy our copy of the session key.  It is no longer needed. */
                    970:        memset(session_key, 0, sizeof(session_key));
                    971:
                    972:        debug("Received session key; encryption turned on.");
                    973:
                    974:        /* Send an acknowledgement packet.  Note that this packet is sent encrypted. */
                    975:        packet_start(SSH_SMSG_SUCCESS);
                    976:        packet_send();
                    977:        packet_write_wait();
                    978:
                    979:        /* Get the name of the user that we wish to log in as. */
                    980:        packet_read_expect(&plen, SSH_CMSG_USER);
                    981:
                    982:        /* Get the user name. */
                    983:        {
                    984:                int ulen;
                    985:                user = packet_get_string(&ulen);
                    986:                packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
                    987:        }
                    988:
                    989:        /* Destroy the private and public keys.  They will no longer be needed. */
                    990:        RSA_free(public_key);
                    991:        RSA_free(sensitive_data.private_key);
                    992:        RSA_free(sensitive_data.host_key);
                    993:
                    994:        setproctitle("%s", user);
                    995:        /* Do the authentication. */
                    996:        do_authentication(user);
1.1       deraadt   997: }
                    998:
1.65      deraadt   999: /*
                   1000:  * Check if the user is allowed to log in via ssh. If user is listed in
                   1001:  * DenyUsers or user's primary group is listed in DenyGroups, false will
                   1002:  * be returned. If AllowUsers isn't empty and user isn't listed there, or
                   1003:  * if AllowGroups isn't empty and user isn't listed there, false will be
                   1004:  * returned. Otherwise true is returned.
                   1005:  * XXX This function should also check if user has a valid shell
                   1006:  */
1.28      markus   1007: static int
1.64      markus   1008: allowed_user(struct passwd * pw)
1.28      markus   1009: {
1.64      markus   1010:        struct group *grp;
                   1011:        int i;
1.28      markus   1012:
1.64      markus   1013:        /* Shouldn't be called if pw is NULL, but better safe than sorry... */
                   1014:        if (!pw)
                   1015:                return 0;
                   1016:
                   1017:        /* XXX Should check for valid login shell */
                   1018:
                   1019:        /* Return false if user is listed in DenyUsers */
                   1020:        if (options.num_deny_users > 0) {
                   1021:                if (!pw->pw_name)
                   1022:                        return 0;
                   1023:                for (i = 0; i < options.num_deny_users; i++)
                   1024:                        if (match_pattern(pw->pw_name, options.deny_users[i]))
                   1025:                                return 0;
                   1026:        }
1.66      markus   1027:        /* Return false if AllowUsers isn't empty and user isn't listed there */
1.64      markus   1028:        if (options.num_allow_users > 0) {
                   1029:                if (!pw->pw_name)
                   1030:                        return 0;
                   1031:                for (i = 0; i < options.num_allow_users; i++)
                   1032:                        if (match_pattern(pw->pw_name, options.allow_users[i]))
                   1033:                                break;
                   1034:                /* i < options.num_allow_users iff we break for loop */
                   1035:                if (i >= options.num_allow_users)
                   1036:                        return 0;
                   1037:        }
                   1038:        /* Get the primary group name if we need it. Return false if it fails */
                   1039:        if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
                   1040:                grp = getgrgid(pw->pw_gid);
                   1041:                if (!grp)
                   1042:                        return 0;
                   1043:
                   1044:                /* Return false if user's group is listed in DenyGroups */
                   1045:                if (options.num_deny_groups > 0) {
                   1046:                        if (!grp->gr_name)
                   1047:                                return 0;
                   1048:                        for (i = 0; i < options.num_deny_groups; i++)
                   1049:                                if (match_pattern(grp->gr_name, options.deny_groups[i]))
                   1050:                                        return 0;
                   1051:                }
1.66      markus   1052:                /*
                   1053:                 * Return false if AllowGroups isn't empty and user's group
                   1054:                 * isn't listed there
                   1055:                 */
1.64      markus   1056:                if (options.num_allow_groups > 0) {
                   1057:                        if (!grp->gr_name)
                   1058:                                return 0;
                   1059:                        for (i = 0; i < options.num_allow_groups; i++)
                   1060:                                if (match_pattern(grp->gr_name, options.allow_groups[i]))
                   1061:                                        break;
                   1062:                        /* i < options.num_allow_groups iff we break for
                   1063:                           loop */
                   1064:                        if (i >= options.num_allow_groups)
                   1065:                                return 0;
                   1066:                }
                   1067:        }
                   1068:        /* We found no reason not to let this user try to log on... */
                   1069:        return 1;
1.28      markus   1070: }
                   1071:
1.65      deraadt  1072: /*
                   1073:  * Performs authentication of an incoming connection.  Session key has already
                   1074:  * been exchanged and encryption is enabled.  User is the user name to log
                   1075:  * in as (received from the client).
                   1076:  */
1.2       provos   1077: void
1.52      markus   1078: do_authentication(char *user)
1.1       deraadt  1079: {
1.64      markus   1080:        struct passwd *pw, pwcopy;
1.52      markus   1081:
1.1       deraadt  1082: #ifdef AFS
1.64      markus   1083:        /* If machine has AFS, set process authentication group. */
                   1084:        if (k_hasafs()) {
                   1085:                k_setpag();
                   1086:                k_unlog();
                   1087:        }
1.1       deraadt  1088: #endif /* AFS */
                   1089:
1.64      markus   1090:        /* Verify that the user is a valid user. */
                   1091:        pw = getpwnam(user);
                   1092:        if (!pw || !allowed_user(pw))
                   1093:                do_fake_authloop(user);
                   1094:
                   1095:        /* Take a copy of the returned structure. */
                   1096:        memset(&pwcopy, 0, sizeof(pwcopy));
                   1097:        pwcopy.pw_name = xstrdup(pw->pw_name);
                   1098:        pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
                   1099:        pwcopy.pw_uid = pw->pw_uid;
                   1100:        pwcopy.pw_gid = pw->pw_gid;
                   1101:        pwcopy.pw_dir = xstrdup(pw->pw_dir);
                   1102:        pwcopy.pw_shell = xstrdup(pw->pw_shell);
                   1103:        pw = &pwcopy;
                   1104:
1.66      markus   1105:        /*
                   1106:         * If we are not running as root, the user must have the same uid as
                   1107:         * the server.
                   1108:         */
1.64      markus   1109:        if (getuid() != 0 && pw->pw_uid != getuid())
                   1110:                packet_disconnect("Cannot change user when server not running as root.");
                   1111:
                   1112:        debug("Attempting authentication for %.100s.", user);
1.1       deraadt  1113:
1.64      markus   1114:        /* If the user has no password, accept authentication immediately. */
                   1115:        if (options.password_authentication &&
1.1       deraadt  1116: #ifdef KRB4
1.64      markus   1117:            (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1.1       deraadt  1118: #endif /* KRB4 */
1.64      markus   1119:            auth_password(pw, "")) {
                   1120:                /* Authentication with empty password succeeded. */
                   1121:                log("Login for user %s from %.100s, accepted without authentication.",
                   1122:                    pw->pw_name, get_remote_ipaddr());
                   1123:        } else {
                   1124:                /* Loop until the user has been authenticated or the
                   1125:                   connection is closed, do_authloop() returns only if
                   1126:                   authentication is successfull */
                   1127:                do_authloop(pw);
                   1128:        }
1.52      markus   1129:
1.64      markus   1130:        /* Check if the user is logging in as root and root logins are disallowed. */
                   1131:        if (pw->pw_uid == 0 && !options.permit_root_login) {
                   1132:                if (forced_command)
                   1133:                        log("Root login accepted for forced command.");
                   1134:                else
                   1135:                        packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
                   1136:                                          get_canonical_hostname());
                   1137:        }
                   1138:        /* The user has been authenticated and accepted. */
                   1139:        packet_start(SSH_SMSG_SUCCESS);
                   1140:        packet_send();
                   1141:        packet_write_wait();
                   1142:
                   1143:        /* Perform session preparation. */
                   1144:        do_authenticated(pw);
1.52      markus   1145: }
                   1146:
1.62      markus   1147: #define AUTH_FAIL_MAX 6
                   1148: #define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
                   1149: #define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
1.52      markus   1150:
1.65      deraadt  1151: /*
                   1152:  * read packets and try to authenticate local user *pw.
                   1153:  * return if authentication is successfull
                   1154:  */
1.52      markus   1155: void
1.64      markus   1156: do_authloop(struct passwd * pw)
1.52      markus   1157: {
1.64      markus   1158:        int attempt = 0;
                   1159:        unsigned int bits;
                   1160:        BIGNUM *client_host_key_e, *client_host_key_n;
                   1161:        BIGNUM *n;
                   1162:        char *client_user, *password;
                   1163:        char user[1024];
                   1164:        int plen, dlen, nlen, ulen, elen;
                   1165:        int type = 0;
                   1166:        void (*authlog) (const char *fmt,...) = verbose;
                   1167:
                   1168:        /* Indicate that authentication is needed. */
                   1169:        packet_start(SSH_SMSG_FAILURE);
                   1170:        packet_send();
                   1171:        packet_write_wait();
                   1172:
                   1173:        for (attempt = 1;; attempt++) {
                   1174:                int authenticated = 0;
                   1175:                strlcpy(user, "", sizeof user);
                   1176:
                   1177:                /* Get a packet from the client. */
                   1178:                type = packet_read(&plen);
                   1179:
                   1180:                /* Process the packet. */
                   1181:                switch (type) {
1.5       dugsong  1182: #ifdef AFS
1.64      markus   1183:                case SSH_CMSG_HAVE_KERBEROS_TGT:
                   1184:                        if (!options.kerberos_tgt_passing) {
                   1185:                                /* packet_get_all(); */
                   1186:                                verbose("Kerberos tgt passing disabled.");
                   1187:                                break;
                   1188:                        } else {
                   1189:                                /* Accept Kerberos tgt. */
                   1190:                                char *tgt = packet_get_string(&dlen);
                   1191:                                packet_integrity_check(plen, 4 + dlen, type);
                   1192:                                if (!auth_kerberos_tgt(pw, tgt))
                   1193:                                        verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
                   1194:                                xfree(tgt);
                   1195:                        }
                   1196:                        continue;
                   1197:
                   1198:                case SSH_CMSG_HAVE_AFS_TOKEN:
                   1199:                        if (!options.afs_token_passing || !k_hasafs()) {
                   1200:                                /* packet_get_all(); */
                   1201:                                verbose("AFS token passing disabled.");
                   1202:                                break;
                   1203:                        } else {
                   1204:                                /* Accept AFS token. */
                   1205:                                char *token_string = packet_get_string(&dlen);
                   1206:                                packet_integrity_check(plen, 4 + dlen, type);
                   1207:                                if (!auth_afs_token(pw, token_string))
                   1208:                                        verbose("AFS token REFUSED for %s", pw->pw_name);
                   1209:                                xfree(token_string);
                   1210:                        }
                   1211:                        continue;
1.1       deraadt  1212: #endif /* AFS */
                   1213: #ifdef KRB4
1.64      markus   1214:                case SSH_CMSG_AUTH_KERBEROS:
                   1215:                        if (!options.kerberos_authentication) {
                   1216:                                /* packet_get_all(); */
                   1217:                                verbose("Kerberos authentication disabled.");
                   1218:                                break;
                   1219:                        } else {
                   1220:                                /* Try Kerberos v4 authentication. */
                   1221:                                KTEXT_ST auth;
                   1222:                                char *tkt_user = NULL;
                   1223:                                char *kdata = packet_get_string((unsigned int *) &auth.length);
                   1224:                                packet_integrity_check(plen, 4 + auth.length, type);
                   1225:
                   1226:                                if (auth.length < MAX_KTXT_LEN)
                   1227:                                        memcpy(auth.dat, kdata, auth.length);
                   1228:                                xfree(kdata);
                   1229:
                   1230:                                authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
                   1231:
                   1232:                                if (authenticated) {
                   1233:                                        snprintf(user, sizeof user, " tktuser %s", tkt_user);
                   1234:                                        xfree(tkt_user);
                   1235:                                }
                   1236:                        }
                   1237:                        break;
1.52      markus   1238: #endif /* KRB4 */
1.64      markus   1239:
                   1240:                case SSH_CMSG_AUTH_RHOSTS:
                   1241:                        if (!options.rhosts_authentication) {
                   1242:                                verbose("Rhosts authentication disabled.");
                   1243:                                break;
                   1244:                        }
1.66      markus   1245:                        /*
                   1246:                         * Get client user name.  Note that we just have to
                   1247:                         * trust the client; this is one reason why rhosts
                   1248:                         * authentication is insecure. (Another is
                   1249:                         * IP-spoofing on a local network.)
                   1250:                         */
1.64      markus   1251:                        client_user = packet_get_string(&ulen);
                   1252:                        packet_integrity_check(plen, 4 + ulen, type);
                   1253:
                   1254:                        /* Try to authenticate using /etc/hosts.equiv and
                   1255:                           .rhosts. */
                   1256:                        authenticated = auth_rhosts(pw, client_user);
                   1257:
                   1258:                        snprintf(user, sizeof user, " ruser %s", client_user);
                   1259:                        xfree(client_user);
                   1260:                        break;
                   1261:
                   1262:                case SSH_CMSG_AUTH_RHOSTS_RSA:
                   1263:                        if (!options.rhosts_rsa_authentication) {
                   1264:                                verbose("Rhosts with RSA authentication disabled.");
                   1265:                                break;
                   1266:                        }
1.66      markus   1267:                        /*
                   1268:                         * Get client user name.  Note that we just have to
                   1269:                         * trust the client; root on the client machine can
                   1270:                         * claim to be any user.
                   1271:                         */
1.64      markus   1272:                        client_user = packet_get_string(&ulen);
                   1273:
                   1274:                        /* Get the client host key. */
                   1275:                        client_host_key_e = BN_new();
                   1276:                        client_host_key_n = BN_new();
                   1277:                        bits = packet_get_int();
                   1278:                        packet_get_bignum(client_host_key_e, &elen);
                   1279:                        packet_get_bignum(client_host_key_n, &nlen);
                   1280:
                   1281:                        if (bits != BN_num_bits(client_host_key_n))
                   1282:                                error("Warning: keysize mismatch for client_host_key: "
                   1283:                                      "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
                   1284:                        packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
                   1285:
                   1286:                        authenticated = auth_rhosts_rsa(pw, client_user,
                   1287:                                   client_host_key_e, client_host_key_n);
                   1288:                        BN_clear_free(client_host_key_e);
                   1289:                        BN_clear_free(client_host_key_n);
                   1290:
                   1291:                        snprintf(user, sizeof user, " ruser %s", client_user);
                   1292:                        xfree(client_user);
                   1293:                        break;
                   1294:
                   1295:                case SSH_CMSG_AUTH_RSA:
                   1296:                        if (!options.rsa_authentication) {
                   1297:                                verbose("RSA authentication disabled.");
                   1298:                                break;
                   1299:                        }
                   1300:                        /* RSA authentication requested. */
                   1301:                        n = BN_new();
                   1302:                        packet_get_bignum(n, &nlen);
                   1303:                        packet_integrity_check(plen, nlen, type);
                   1304:                        authenticated = auth_rsa(pw, n);
                   1305:                        BN_clear_free(n);
                   1306:                        break;
                   1307:
                   1308:                case SSH_CMSG_AUTH_PASSWORD:
                   1309:                        if (!options.password_authentication) {
                   1310:                                verbose("Password authentication disabled.");
                   1311:                                break;
                   1312:                        }
1.66      markus   1313:                        /*
                   1314:                         * Read user password.  It is in plain text, but was
                   1315:                         * transmitted over the encrypted channel so it is
                   1316:                         * not visible to an outside observer.
                   1317:                         */
1.64      markus   1318:                        password = packet_get_string(&dlen);
                   1319:                        packet_integrity_check(plen, 4 + dlen, type);
                   1320:
                   1321:                        /* Try authentication with the password. */
                   1322:                        authenticated = auth_password(pw, password);
                   1323:
                   1324:                        memset(password, 0, strlen(password));
                   1325:                        xfree(password);
                   1326:                        break;
                   1327:
1.63      markus   1328: #ifdef SKEY
1.64      markus   1329:                case SSH_CMSG_AUTH_TIS:
                   1330:                        debug("rcvd SSH_CMSG_AUTH_TIS");
                   1331:                        if (options.skey_authentication == 1) {
                   1332:                                char *skeyinfo = skey_keyinfo(pw->pw_name);
                   1333:                                if (skeyinfo == NULL) {
                   1334:                                        debug("generating fake skeyinfo for %.100s.", pw->pw_name);
                   1335:                                        skeyinfo = skey_fake_keyinfo(pw->pw_name);
                   1336:                                }
                   1337:                                if (skeyinfo != NULL) {
1.66      markus   1338:                                        /* we send our s/key- in tis-challenge messages */
1.64      markus   1339:                                        debug("sending challenge '%s'", skeyinfo);
                   1340:                                        packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
                   1341:                                        packet_put_string(skeyinfo, strlen(skeyinfo));
                   1342:                                        packet_send();
                   1343:                                        packet_write_wait();
                   1344:                                        continue;
                   1345:                                }
                   1346:                        }
                   1347:                        break;
                   1348:                case SSH_CMSG_AUTH_TIS_RESPONSE:
                   1349:                        debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
                   1350:                        if (options.skey_authentication == 1) {
                   1351:                                char *response = packet_get_string(&dlen);
                   1352:                                debug("skey response == '%s'", response);
                   1353:                                packet_integrity_check(plen, 4 + dlen, type);
                   1354:                                authenticated = (skey_haskey(pw->pw_name) == 0 &&
                   1355:                                                 skey_passcheck(pw->pw_name, response) != -1);
                   1356:                                xfree(response);
                   1357:                        }
                   1358:                        break;
1.63      markus   1359: #else
1.64      markus   1360:                case SSH_CMSG_AUTH_TIS:
                   1361:                        /* TIS Authentication is unsupported */
                   1362:                        log("TIS authentication unsupported.");
                   1363:                        break;
1.63      markus   1364: #endif
1.64      markus   1365:
                   1366:                default:
1.66      markus   1367:                        /*
                   1368:                         * Any unknown messages will be ignored (and failure
                   1369:                         * returned) during authentication.
                   1370:                         */
1.64      markus   1371:                        log("Unknown message during authentication: type %d", type);
                   1372:                        break;
                   1373:                }
                   1374:
                   1375:                /* Raise logging level */
                   1376:                if (authenticated ||
                   1377:                    attempt == AUTH_FAIL_LOG ||
                   1378:                    type == SSH_CMSG_AUTH_PASSWORD)
                   1379:                        authlog = log;
                   1380:
                   1381:                authlog("%s %s for %.200s from %.200s port %d%s",
                   1382:                        authenticated ? "Accepted" : "Failed",
                   1383:                        get_authname(type),
                   1384:                        pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
                   1385:                        get_remote_ipaddr(),
                   1386:                        get_remote_port(),
                   1387:                        user);
                   1388:
                   1389:                if (authenticated)
                   1390:                        return;
                   1391:
                   1392:                if (attempt > AUTH_FAIL_MAX)
                   1393:                        packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
                   1394:
                   1395:                /* Send a message indicating that the authentication attempt failed. */
                   1396:                packet_start(SSH_SMSG_FAILURE);
                   1397:                packet_send();
                   1398:                packet_write_wait();
                   1399:        }
1.52      markus   1400: }
1.1       deraadt  1401:
1.65      deraadt  1402: /*
                   1403:  * The user does not exist or access is denied,
                   1404:  * but fake indication that authentication is needed.
                   1405:  */
1.52      markus   1406: void
                   1407: do_fake_authloop(char *user)
                   1408: {
1.64      markus   1409:        int attempt = 0;
                   1410:
                   1411:        log("Faking authloop for illegal user %.200s from %.200s port %d",
                   1412:            user,
                   1413:            get_remote_ipaddr(),
                   1414:            get_remote_port());
1.62      markus   1415:
1.64      markus   1416:        /* Indicate that authentication is needed. */
                   1417:        packet_start(SSH_SMSG_FAILURE);
                   1418:        packet_send();
                   1419:        packet_write_wait();
                   1420:
1.66      markus   1421:        /*
                   1422:         * Keep reading packets, and always respond with a failure.  This is
                   1423:         * to avoid disclosing whether such a user really exists.
                   1424:         */
1.64      markus   1425:        for (attempt = 1;; attempt++) {
1.66      markus   1426:                /* Read a packet.  This will not return if the client disconnects. */
1.64      markus   1427:                int plen;
                   1428:                int type = packet_read(&plen);
1.52      markus   1429: #ifdef SKEY
1.64      markus   1430:                int dlen;
                   1431:                char *password, *skeyinfo;
                   1432:                if (options.password_authentication &&
                   1433:                    options.skey_authentication == 1 &&
                   1434:                    type == SSH_CMSG_AUTH_PASSWORD &&
                   1435:                    (password = packet_get_string(&dlen)) != NULL &&
                   1436:                    dlen == 5 &&
                   1437:                    strncasecmp(password, "s/key", 5) == 0 &&
                   1438:                    (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
                   1439:                        /* Send a fake s/key challenge. */
                   1440:                        packet_send_debug(skeyinfo);
                   1441:                }
1.52      markus   1442: #endif
1.64      markus   1443:                if (attempt > AUTH_FAIL_MAX)
                   1444:                        packet_disconnect(AUTH_FAIL_MSG, user);
1.62      markus   1445:
1.66      markus   1446:                /*
                   1447:                 * Send failure.  This should be indistinguishable from a
                   1448:                 * failed authentication.
                   1449:                 */
1.64      markus   1450:                packet_start(SSH_SMSG_FAILURE);
                   1451:                packet_send();
                   1452:                packet_write_wait();
                   1453:        }
                   1454:        /* NOTREACHED */
                   1455:        abort();
1.52      markus   1456: }
1.1       deraadt  1457:
                   1458:
1.65      deraadt  1459: /*
                   1460:  * Remove local Xauthority file.
                   1461:  */
1.46      markus   1462: static void
                   1463: xauthfile_cleanup_proc(void *ignore)
                   1464: {
1.64      markus   1465:        debug("xauthfile_cleanup_proc called");
1.46      markus   1466:
1.64      markus   1467:        if (xauthfile != NULL) {
                   1468:                unlink(xauthfile);
                   1469:                xfree(xauthfile);
                   1470:                xauthfile = NULL;
                   1471:        }
1.46      markus   1472: }
                   1473:
1.65      deraadt  1474: /*
                   1475:  * Prepares for an interactive session.  This is called after the user has
                   1476:  * been successfully authenticated.  During this message exchange, pseudo
                   1477:  * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
                   1478:  * are requested, etc.
                   1479:  */
1.64      markus   1480: void
                   1481: do_authenticated(struct passwd * pw)
1.1       deraadt  1482: {
1.64      markus   1483:        int type;
                   1484:        int compression_level = 0, enable_compression_after_reply = 0;
                   1485:        int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
                   1486:        int row, col, xpixel, ypixel, screen;
                   1487:        char ttyname[64];
                   1488:        char *command, *term = NULL, *display = NULL, *proto = NULL,
                   1489:        *data = NULL;
                   1490:        struct group *grp;
                   1491:        gid_t tty_gid;
                   1492:        mode_t tty_mode;
                   1493:        int n_bytes;
                   1494:
1.66      markus   1495:        /*
                   1496:         * Cancel the alarm we set to limit the time taken for
                   1497:         * authentication.
                   1498:         */
1.64      markus   1499:        alarm(0);
                   1500:
1.66      markus   1501:        /*
                   1502:         * Inform the channel mechanism that we are the server side and that
                   1503:         * the client may request to connect to any port at all. (The user
                   1504:         * could do it anyway, and we wouldn\'t know what is permitted except
                   1505:         * by the client telling us, so we can equally well trust the client
                   1506:         * not to request anything bogus.)
                   1507:         */
1.64      markus   1508:        channel_permit_all_opens();
                   1509:
1.66      markus   1510:        /*
                   1511:         * We stay in this loop until the client requests to execute a shell
                   1512:         * or a command.
                   1513:         */
1.64      markus   1514:        while (1) {
                   1515:                int plen, dlen;
                   1516:
                   1517:                /* Get a packet from the client. */
                   1518:                type = packet_read(&plen);
                   1519:
                   1520:                /* Process the packet. */
                   1521:                switch (type) {
                   1522:                case SSH_CMSG_REQUEST_COMPRESSION:
                   1523:                        packet_integrity_check(plen, 4, type);
                   1524:                        compression_level = packet_get_int();
                   1525:                        if (compression_level < 1 || compression_level > 9) {
                   1526:                                packet_send_debug("Received illegal compression level %d.",
                   1527:                                                  compression_level);
                   1528:                                goto fail;
                   1529:                        }
                   1530:                        /* Enable compression after we have responded with SUCCESS. */
                   1531:                        enable_compression_after_reply = 1;
                   1532:                        break;
                   1533:
                   1534:                case SSH_CMSG_REQUEST_PTY:
                   1535:                        if (no_pty_flag) {
                   1536:                                debug("Allocating a pty not permitted for this authentication.");
                   1537:                                goto fail;
                   1538:                        }
                   1539:                        if (have_pty)
                   1540:                                packet_disconnect("Protocol error: you already have a pty.");
                   1541:
                   1542:                        debug("Allocating pty.");
                   1543:
                   1544:                        /* Allocate a pty and open it. */
1.67      deraadt  1545:                        if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
                   1546:                            sizeof(ttyname))) {
1.64      markus   1547:                                error("Failed to allocate pty.");
                   1548:                                goto fail;
                   1549:                        }
                   1550:                        /* Determine the group to make the owner of the tty. */
                   1551:                        grp = getgrnam("tty");
                   1552:                        if (grp) {
                   1553:                                tty_gid = grp->gr_gid;
                   1554:                                tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
                   1555:                        } else {
                   1556:                                tty_gid = pw->pw_gid;
                   1557:                                tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
                   1558:                        }
                   1559:
                   1560:                        /* Change ownership of the tty. */
                   1561:                        if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
                   1562:                                fatal("chown(%.100s, %d, %d) failed: %.100s",
                   1563:                                      ttyname, pw->pw_uid, tty_gid, strerror(errno));
                   1564:                        if (chmod(ttyname, tty_mode) < 0)
                   1565:                                fatal("chmod(%.100s, 0%o) failed: %.100s",
                   1566:                                      ttyname, tty_mode, strerror(errno));
                   1567:
                   1568:                        /* Get TERM from the packet.  Note that the value may be of arbitrary length. */
                   1569:                        term = packet_get_string(&dlen);
                   1570:                        packet_integrity_check(dlen, strlen(term), type);
                   1571:                        /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
                   1572:                        /* Remaining bytes */
                   1573:                        n_bytes = plen - (4 + dlen + 4 * 4);
                   1574:
                   1575:                        if (strcmp(term, "") == 0)
                   1576:                                term = NULL;
                   1577:
                   1578:                        /* Get window size from the packet. */
                   1579:                        row = packet_get_int();
                   1580:                        col = packet_get_int();
                   1581:                        xpixel = packet_get_int();
                   1582:                        ypixel = packet_get_int();
                   1583:                        pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
                   1584:
                   1585:                        /* Get tty modes from the packet. */
                   1586:                        tty_parse_modes(ttyfd, &n_bytes);
                   1587:                        packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
                   1588:
                   1589:                        /* Indicate that we now have a pty. */
                   1590:                        have_pty = 1;
                   1591:                        break;
                   1592:
                   1593:                case SSH_CMSG_X11_REQUEST_FORWARDING:
                   1594:                        if (!options.x11_forwarding) {
                   1595:                                packet_send_debug("X11 forwarding disabled in server configuration file.");
                   1596:                                goto fail;
                   1597:                        }
1.1       deraadt  1598: #ifdef XAUTH_PATH
1.64      markus   1599:                        if (no_x11_forwarding_flag) {
                   1600:                                packet_send_debug("X11 forwarding not permitted for this authentication.");
                   1601:                                goto fail;
                   1602:                        }
                   1603:                        debug("Received request for X11 forwarding with auth spoofing.");
                   1604:                        if (display)
                   1605:                                packet_disconnect("Protocol error: X11 display already set.");
                   1606:                        {
                   1607:                                int proto_len, data_len;
                   1608:                                proto = packet_get_string(&proto_len);
                   1609:                                data = packet_get_string(&data_len);
                   1610:                                packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
                   1611:                        }
                   1612:                        if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
                   1613:                                screen = packet_get_int();
                   1614:                        else
                   1615:                                screen = 0;
                   1616:                        display = x11_create_display_inet(screen);
                   1617:                        if (!display)
                   1618:                                goto fail;
                   1619:
                   1620:                        /* Setup to always have a local .Xauthority. */
                   1621:                        xauthfile = xmalloc(MAXPATHLEN);
                   1622:                        snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
                   1623:
                   1624:                        if ((xauthfd = mkstemp(xauthfile)) != -1) {
                   1625:                                fchown(xauthfd, pw->pw_uid, pw->pw_gid);
                   1626:                                close(xauthfd);
                   1627:                                fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
                   1628:                        } else {
                   1629:                                xfree(xauthfile);
                   1630:                                xauthfile = NULL;
                   1631:                        }
                   1632:                        break;
1.1       deraadt  1633: #else /* XAUTH_PATH */
1.64      markus   1634:                        packet_send_debug("No xauth program; cannot forward with spoofing.");
                   1635:                        goto fail;
1.1       deraadt  1636: #endif /* XAUTH_PATH */
                   1637:
1.64      markus   1638:                case SSH_CMSG_AGENT_REQUEST_FORWARDING:
                   1639:                        if (no_agent_forwarding_flag) {
                   1640:                                debug("Authentication agent forwarding not permitted for this authentication.");
                   1641:                                goto fail;
                   1642:                        }
                   1643:                        debug("Received authentication agent forwarding request.");
                   1644:                        auth_input_request_forwarding(pw);
                   1645:                        break;
                   1646:
                   1647:                case SSH_CMSG_PORT_FORWARD_REQUEST:
                   1648:                        if (no_port_forwarding_flag) {
                   1649:                                debug("Port forwarding not permitted for this authentication.");
                   1650:                                goto fail;
                   1651:                        }
                   1652:                        debug("Received TCP/IP port forwarding request.");
                   1653:                        channel_input_port_forward_request(pw->pw_uid == 0);
                   1654:                        break;
                   1655:
                   1656:                case SSH_CMSG_MAX_PACKET_SIZE:
                   1657:                        if (packet_set_maxsize(packet_get_int()) < 0)
                   1658:                                goto fail;
                   1659:                        break;
                   1660:
                   1661:                case SSH_CMSG_EXEC_SHELL:
                   1662:                        /* Set interactive/non-interactive mode. */
                   1663:                        packet_set_interactive(have_pty || display != NULL,
                   1664:                                               options.keepalives);
                   1665:
                   1666:                        if (forced_command != NULL)
                   1667:                                goto do_forced_command;
                   1668:                        debug("Forking shell.");
                   1669:                        packet_integrity_check(plen, 0, type);
                   1670:                        if (have_pty)
                   1671:                                do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
                   1672:                        else
                   1673:                                do_exec_no_pty(NULL, pw, display, proto, data);
                   1674:                        return;
                   1675:
                   1676:                case SSH_CMSG_EXEC_CMD:
                   1677:                        /* Set interactive/non-interactive mode. */
                   1678:                        packet_set_interactive(have_pty || display != NULL,
                   1679:                                               options.keepalives);
                   1680:
                   1681:                        if (forced_command != NULL)
                   1682:                                goto do_forced_command;
                   1683:                        /* Get command from the packet. */
                   1684:                        {
                   1685:                                int dlen;
                   1686:                                command = packet_get_string(&dlen);
                   1687:                                debug("Executing command '%.500s'", command);
                   1688:                                packet_integrity_check(plen, 4 + dlen, type);
                   1689:                        }
                   1690:                        if (have_pty)
                   1691:                                do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
                   1692:                        else
                   1693:                                do_exec_no_pty(command, pw, display, proto, data);
                   1694:                        xfree(command);
                   1695:                        return;
                   1696:
                   1697:                default:
1.66      markus   1698:                        /*
                   1699:                         * Any unknown messages in this phase are ignored,
                   1700:                         * and a failure message is returned.
                   1701:                         */
1.64      markus   1702:                        log("Unknown packet type received after authentication: %d", type);
                   1703:                        goto fail;
                   1704:                }
1.1       deraadt  1705:
1.64      markus   1706:                /* The request was successfully processed. */
                   1707:                packet_start(SSH_SMSG_SUCCESS);
                   1708:                packet_send();
                   1709:                packet_write_wait();
                   1710:
                   1711:                /* Enable compression now that we have replied if appropriate. */
                   1712:                if (enable_compression_after_reply) {
                   1713:                        enable_compression_after_reply = 0;
                   1714:                        packet_start_compression(compression_level);
                   1715:                }
                   1716:                continue;
1.1       deraadt  1717:
1.64      markus   1718: fail:
                   1719:                /* The request failed. */
                   1720:                packet_start(SSH_SMSG_FAILURE);
                   1721:                packet_send();
                   1722:                packet_write_wait();
                   1723:                continue;
1.1       deraadt  1724:
1.64      markus   1725: do_forced_command:
1.66      markus   1726:                /*
                   1727:                 * There is a forced command specified for this login.
                   1728:                 * Execute it.
                   1729:                 */
1.64      markus   1730:                debug("Executing forced command: %.900s", forced_command);
                   1731:                if (have_pty)
                   1732:                        do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
                   1733:                else
                   1734:                        do_exec_no_pty(forced_command, pw, display, proto, data);
                   1735:                return;
                   1736:        }
1.1       deraadt  1737: }
                   1738:
1.65      deraadt  1739: /*
                   1740:  * This is called to fork and execute a command when we have no tty.  This
                   1741:  * will call do_child from the child, and server_loop from the parent after
                   1742:  * setting up file descriptors and such.
                   1743:  */
1.64      markus   1744: void
                   1745: do_exec_no_pty(const char *command, struct passwd * pw,
                   1746:               const char *display, const char *auth_proto,
                   1747:               const char *auth_data)
                   1748: {
                   1749:        int pid;
1.1       deraadt  1750:
                   1751: #ifdef USE_PIPES
1.64      markus   1752:        int pin[2], pout[2], perr[2];
                   1753:        /* Allocate pipes for communicating with the program. */
                   1754:        if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
                   1755:                packet_disconnect("Could not create pipes: %.100s",
                   1756:                                  strerror(errno));
1.1       deraadt  1757: #else /* USE_PIPES */
1.64      markus   1758:        int inout[2], err[2];
                   1759:        /* Uses socket pairs to communicate with the program. */
                   1760:        if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
                   1761:            socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
                   1762:                packet_disconnect("Could not create socket pairs: %.100s",
                   1763:                                  strerror(errno));
1.1       deraadt  1764: #endif /* USE_PIPES */
1.16      deraadt  1765:
1.64      markus   1766:        setproctitle("%s@notty", pw->pw_name);
                   1767:
                   1768:        /* Fork the child. */
                   1769:        if ((pid = fork()) == 0) {
                   1770:                /* Child.  Reinitialize the log since the pid has changed. */
                   1771:                log_init(av0, options.log_level, options.log_facility, log_stderr);
                   1772:
1.66      markus   1773:                /*
                   1774:                 * Create a new session and process group since the 4.4BSD
                   1775:                 * setlogin() affects the entire process group.
                   1776:                 */
1.64      markus   1777:                if (setsid() < 0)
                   1778:                        error("setsid failed: %.100s", strerror(errno));
1.29      deraadt  1779:
1.1       deraadt  1780: #ifdef USE_PIPES
1.66      markus   1781:                /*
                   1782:                 * Redirect stdin.  We close the parent side of the socket
                   1783:                 * pair, and make the child side the standard input.
                   1784:                 */
1.64      markus   1785:                close(pin[1]);
                   1786:                if (dup2(pin[0], 0) < 0)
                   1787:                        perror("dup2 stdin");
                   1788:                close(pin[0]);
                   1789:
                   1790:                /* Redirect stdout. */
                   1791:                close(pout[0]);
                   1792:                if (dup2(pout[1], 1) < 0)
                   1793:                        perror("dup2 stdout");
                   1794:                close(pout[1]);
                   1795:
                   1796:                /* Redirect stderr. */
                   1797:                close(perr[0]);
                   1798:                if (dup2(perr[1], 2) < 0)
                   1799:                        perror("dup2 stderr");
                   1800:                close(perr[1]);
1.1       deraadt  1801: #else /* USE_PIPES */
1.66      markus   1802:                /*
                   1803:                 * Redirect stdin, stdout, and stderr.  Stdin and stdout will
                   1804:                 * use the same socket, as some programs (particularly rdist)
                   1805:                 * seem to depend on it.
                   1806:                 */
1.64      markus   1807:                close(inout[1]);
                   1808:                close(err[1]);
                   1809:                if (dup2(inout[0], 0) < 0)      /* stdin */
                   1810:                        perror("dup2 stdin");
                   1811:                if (dup2(inout[0], 1) < 0)      /* stdout.  Note: same socket as stdin. */
                   1812:                        perror("dup2 stdout");
                   1813:                if (dup2(err[0], 2) < 0)        /* stderr */
                   1814:                        perror("dup2 stderr");
1.1       deraadt  1815: #endif /* USE_PIPES */
                   1816:
1.64      markus   1817:                /* Do processing for the child (exec command etc). */
                   1818:                do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
                   1819:                /* NOTREACHED */
                   1820:        }
                   1821:        if (pid < 0)
                   1822:                packet_disconnect("fork failed: %.100s", strerror(errno));
1.1       deraadt  1823: #ifdef USE_PIPES
1.64      markus   1824:        /* We are the parent.  Close the child sides of the pipes. */
                   1825:        close(pin[0]);
                   1826:        close(pout[1]);
                   1827:        close(perr[1]);
                   1828:
                   1829:        /* Enter the interactive session. */
                   1830:        server_loop(pid, pin[1], pout[0], perr[0]);
                   1831:        /* server_loop has closed pin[1], pout[1], and perr[1]. */
1.1       deraadt  1832: #else /* USE_PIPES */
1.64      markus   1833:        /* We are the parent.  Close the child sides of the socket pairs. */
                   1834:        close(inout[0]);
                   1835:        close(err[0]);
                   1836:
1.66      markus   1837:        /*
                   1838:         * Enter the interactive session.  Note: server_loop must be able to
                   1839:         * handle the case that fdin and fdout are the same.
                   1840:         */
1.64      markus   1841:        server_loop(pid, inout[1], inout[1], err[1]);
                   1842:        /* server_loop has closed inout[1] and err[1]. */
1.1       deraadt  1843: #endif /* USE_PIPES */
                   1844: }
                   1845:
1.64      markus   1846: struct pty_cleanup_context {
                   1847:        const char *ttyname;
                   1848:        int pid;
1.1       deraadt  1849: };
                   1850:
1.65      deraadt  1851: /*
                   1852:  * Function to perform cleanup if we get aborted abnormally (e.g., due to a
                   1853:  * dropped connection).
                   1854:  */
1.64      markus   1855: void
                   1856: pty_cleanup_proc(void *context)
1.1       deraadt  1857: {
1.64      markus   1858:        struct pty_cleanup_context *cu = context;
1.1       deraadt  1859:
1.64      markus   1860:        debug("pty_cleanup_proc called");
1.1       deraadt  1861:
1.64      markus   1862:        /* Record that the user has logged out. */
                   1863:        record_logout(cu->pid, cu->ttyname);
1.1       deraadt  1864:
1.64      markus   1865:        /* Release the pseudo-tty. */
                   1866:        pty_release(cu->ttyname);
1.1       deraadt  1867: }
                   1868:
1.65      deraadt  1869: /*
                   1870:  * This is called to fork and execute a command when we have a tty.  This
                   1871:  * will call do_child from the child, and server_loop from the parent after
                   1872:  * setting up file descriptors, controlling tty, updating wtmp, utmp,
                   1873:  * lastlog, and other such operations.
                   1874:  */
1.64      markus   1875: void
                   1876: do_exec_pty(const char *command, int ptyfd, int ttyfd,
                   1877:            const char *ttyname, struct passwd * pw, const char *term,
                   1878:            const char *display, const char *auth_proto,
                   1879:            const char *auth_data)
                   1880: {
                   1881:        int pid, fdout;
                   1882:        const char *hostname;
                   1883:        time_t last_login_time;
                   1884:        char buf[100], *time_string;
                   1885:        FILE *f;
                   1886:        char line[256];
                   1887:        struct stat st;
                   1888:        int quiet_login;
                   1889:        struct sockaddr_in from;
                   1890:        int fromlen;
                   1891:        struct pty_cleanup_context cleanup_context;
                   1892:
                   1893:        /* Get remote host name. */
                   1894:        hostname = get_canonical_hostname();
                   1895:
1.66      markus   1896:        /*
                   1897:         * Get the time when the user last logged in.  Buf will be set to
                   1898:         * contain the hostname the last login was from.
                   1899:         */
1.64      markus   1900:        if (!options.use_login) {
                   1901:                last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
                   1902:                                                      buf, sizeof(buf));
                   1903:        }
                   1904:        setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
                   1905:
                   1906:        /* Fork the child. */
                   1907:        if ((pid = fork()) == 0) {
                   1908:                pid = getpid();
                   1909:
                   1910:                /* Child.  Reinitialize the log because the pid has
                   1911:                   changed. */
                   1912:                log_init(av0, options.log_level, options.log_facility, log_stderr);
                   1913:
                   1914:                /* Close the master side of the pseudo tty. */
                   1915:                close(ptyfd);
                   1916:
                   1917:                /* Make the pseudo tty our controlling tty. */
                   1918:                pty_make_controlling_tty(&ttyfd, ttyname);
                   1919:
                   1920:                /* Redirect stdin from the pseudo tty. */
                   1921:                if (dup2(ttyfd, fileno(stdin)) < 0)
                   1922:                        error("dup2 stdin failed: %.100s", strerror(errno));
                   1923:
                   1924:                /* Redirect stdout to the pseudo tty. */
                   1925:                if (dup2(ttyfd, fileno(stdout)) < 0)
                   1926:                        error("dup2 stdin failed: %.100s", strerror(errno));
                   1927:
                   1928:                /* Redirect stderr to the pseudo tty. */
                   1929:                if (dup2(ttyfd, fileno(stderr)) < 0)
                   1930:                        error("dup2 stdin failed: %.100s", strerror(errno));
                   1931:
                   1932:                /* Close the extra descriptor for the pseudo tty. */
                   1933:                close(ttyfd);
                   1934:
1.66      markus   1935:                /*
                   1936:                 * Get IP address of client.  This is needed because we want
                   1937:                 * to record where the user logged in from.  If the
                   1938:                 * connection is not a socket, let the ip address be 0.0.0.0.
                   1939:                 */
1.64      markus   1940:                memset(&from, 0, sizeof(from));
                   1941:                if (packet_get_connection_in() == packet_get_connection_out()) {
                   1942:                        fromlen = sizeof(from);
                   1943:                        if (getpeername(packet_get_connection_in(),
                   1944:                             (struct sockaddr *) & from, &fromlen) < 0) {
                   1945:                                debug("getpeername: %.100s", strerror(errno));
                   1946:                                fatal_cleanup();
                   1947:                        }
                   1948:                }
                   1949:                /* Record that there was a login on that terminal. */
                   1950:                record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
                   1951:                             &from);
                   1952:
                   1953:                /* Check if .hushlogin exists. */
                   1954:                snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
                   1955:                quiet_login = stat(line, &st) >= 0;
                   1956:
1.66      markus   1957:                /*
                   1958:                 * If the user has logged in before, display the time of last
                   1959:                 * login. However, don't display anything extra if a command
                   1960:                 * has been specified (so that ssh can be used to execute
                   1961:                 * commands on a remote machine without users knowing they
                   1962:                 * are going to another machine). Login(1) will do this for
                   1963:                 * us as well, so check if login(1) is used
                   1964:                 */
1.64      markus   1965:                if (command == NULL && last_login_time != 0 && !quiet_login &&
                   1966:                    !options.use_login) {
                   1967:                        /* Convert the date to a string. */
                   1968:                        time_string = ctime(&last_login_time);
                   1969:                        /* Remove the trailing newline. */
                   1970:                        if (strchr(time_string, '\n'))
                   1971:                                *strchr(time_string, '\n') = 0;
                   1972:                        /* Display the last login time.  Host if displayed
                   1973:                           if known. */
                   1974:                        if (strcmp(buf, "") == 0)
                   1975:                                printf("Last login: %s\r\n", time_string);
                   1976:                        else
                   1977:                                printf("Last login: %s from %s\r\n", time_string, buf);
                   1978:                }
1.66      markus   1979:                /*
                   1980:                 * Print /etc/motd unless a command was specified or printing
                   1981:                 * it was disabled in server options or login(1) will be
                   1982:                 * used.  Note that some machines appear to print it in
                   1983:                 * /etc/profile or similar.
                   1984:                 */
1.64      markus   1985:                if (command == NULL && options.print_motd && !quiet_login &&
                   1986:                    !options.use_login) {
                   1987:                        /* Print /etc/motd if it exists. */
                   1988:                        f = fopen("/etc/motd", "r");
                   1989:                        if (f) {
                   1990:                                while (fgets(line, sizeof(line), f))
                   1991:                                        fputs(line, stdout);
                   1992:                                fclose(f);
                   1993:                        }
                   1994:                }
                   1995:                /* Do common processing for the child, such as execing the command. */
                   1996:                do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
                   1997:                /* NOTREACHED */
                   1998:        }
                   1999:        if (pid < 0)
                   2000:                packet_disconnect("fork failed: %.100s", strerror(errno));
                   2001:        /* Parent.  Close the slave side of the pseudo tty. */
                   2002:        close(ttyfd);
                   2003:
1.66      markus   2004:        /*
                   2005:         * Create another descriptor of the pty master side for use as the
                   2006:         * standard input.  We could use the original descriptor, but this
                   2007:         * simplifies code in server_loop.  The descriptor is bidirectional.
                   2008:         */
1.64      markus   2009:        fdout = dup(ptyfd);
                   2010:        if (fdout < 0)
                   2011:                packet_disconnect("dup failed: %.100s", strerror(errno));
                   2012:
1.66      markus   2013:        /*
                   2014:         * Add a cleanup function to clear the utmp entry and record logout
                   2015:         * time in case we call fatal() (e.g., the connection gets closed).
                   2016:         */
1.64      markus   2017:        cleanup_context.pid = pid;
                   2018:        cleanup_context.ttyname = ttyname;
                   2019:        fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
                   2020:
                   2021:        /* Enter interactive session. */
                   2022:        server_loop(pid, ptyfd, fdout, -1);
                   2023:        /* server_loop has not closed ptyfd and fdout. */
                   2024:
                   2025:        /* Cancel the cleanup function. */
                   2026:        fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
                   2027:
                   2028:        /* Record that the user has logged out. */
                   2029:        record_logout(pid, ttyname);
                   2030:
                   2031:        /* Release the pseudo-tty. */
                   2032:        pty_release(ttyname);
                   2033:
1.66      markus   2034:        /*
                   2035:         * Close the server side of the socket pairs.  We must do this after
                   2036:         * the pty cleanup, so that another process doesn't get this pty
                   2037:         * while we're still cleaning up.
                   2038:         */
1.64      markus   2039:        close(ptyfd);
                   2040:        close(fdout);
1.1       deraadt  2041: }
                   2042:
1.65      deraadt  2043: /*
                   2044:  * Sets the value of the given variable in the environment.  If the variable
                   2045:  * already exists, its value is overriden.
                   2046:  */
1.64      markus   2047: void
                   2048: child_set_env(char ***envp, unsigned int *envsizep, const char *name,
                   2049:              const char *value)
                   2050: {
                   2051:        unsigned int i, namelen;
                   2052:        char **env;
                   2053:
1.66      markus   2054:        /*
                   2055:         * Find the slot where the value should be stored.  If the variable
                   2056:         * already exists, we reuse the slot; otherwise we append a new slot
                   2057:         * at the end of the array, expanding if necessary.
                   2058:         */
1.64      markus   2059:        env = *envp;
                   2060:        namelen = strlen(name);
                   2061:        for (i = 0; env[i]; i++)
                   2062:                if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
                   2063:                        break;
                   2064:        if (env[i]) {
1.66      markus   2065:                /* Reuse the slot. */
1.64      markus   2066:                xfree(env[i]);
                   2067:        } else {
1.66      markus   2068:                /* New variable.  Expand if necessary. */
1.64      markus   2069:                if (i >= (*envsizep) - 1) {
                   2070:                        (*envsizep) += 50;
                   2071:                        env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
                   2072:                }
                   2073:                /* Need to set the NULL pointer at end of array beyond the new slot. */
                   2074:                env[i + 1] = NULL;
1.1       deraadt  2075:        }
                   2076:
1.64      markus   2077:        /* Allocate space and format the variable in the appropriate slot. */
                   2078:        env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
                   2079:        snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
1.1       deraadt  2080: }
                   2081:
1.65      deraadt  2082: /*
                   2083:  * Reads environment variables from the given file and adds/overrides them
                   2084:  * into the environment.  If the file does not exist, this does nothing.
                   2085:  * Otherwise, it must consist of empty lines, comments (line starts with '#')
                   2086:  * and assignments of the form name=value.  No other forms are allowed.
                   2087:  */
1.64      markus   2088: void
                   2089: read_environment_file(char ***env, unsigned int *envsize,
                   2090:                      const char *filename)
                   2091: {
                   2092:        FILE *f;
                   2093:        char buf[4096];
                   2094:        char *cp, *value;
                   2095:
                   2096:        f = fopen(filename, "r");
                   2097:        if (!f)
                   2098:                return;
                   2099:
                   2100:        while (fgets(buf, sizeof(buf), f)) {
1.66      markus   2101:                for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
                   2102:                        ;
1.64      markus   2103:                if (!*cp || *cp == '#' || *cp == '\n')
                   2104:                        continue;
                   2105:                if (strchr(cp, '\n'))
                   2106:                        *strchr(cp, '\n') = '\0';
                   2107:                value = strchr(cp, '=');
                   2108:                if (value == NULL) {
                   2109:                        fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
                   2110:                        continue;
                   2111:                }
1.66      markus   2112:                /* Replace the equals sign by nul, and advance value to the value string. */
1.64      markus   2113:                *value = '\0';
                   2114:                value++;
                   2115:                child_set_env(env, envsize, cp, value);
1.1       deraadt  2116:        }
1.64      markus   2117:        fclose(f);
1.1       deraadt  2118: }
                   2119:
1.65      deraadt  2120: /*
                   2121:  * Performs common processing for the child, such as setting up the
                   2122:  * environment, closing extra file descriptors, setting the user and group
                   2123:  * ids, and executing the command or shell.
                   2124:  */
1.64      markus   2125: void
                   2126: do_child(const char *command, struct passwd * pw, const char *term,
                   2127:         const char *display, const char *auth_proto,
                   2128:         const char *auth_data, const char *ttyname)
                   2129: {
                   2130:        const char *shell, *cp = NULL;
                   2131:        char buf[256];
                   2132:        FILE *f;
                   2133:        unsigned int envsize, i;
                   2134:        char **env;
                   2135:        extern char **environ;
                   2136:        struct stat st;
                   2137:        char *argv[10];
                   2138:
                   2139:        f = fopen("/etc/nologin", "r");
                   2140:        if (f) {
                   2141:                /* /etc/nologin exists.  Print its contents and exit. */
                   2142:                while (fgets(buf, sizeof(buf), f))
                   2143:                        fputs(buf, stderr);
                   2144:                fclose(f);
                   2145:                if (pw->pw_uid != 0)
                   2146:                        exit(254);
                   2147:        }
                   2148:        /* Set login name in the kernel. */
                   2149:        if (setlogin(pw->pw_name) < 0)
                   2150:                error("setlogin failed: %s", strerror(errno));
                   2151:
                   2152:        /* Set uid, gid, and groups. */
                   2153:        /* Login(1) does this as well, and it needs uid 0 for the "-h"
                   2154:           switch, so we let login(1) to this for us. */
                   2155:        if (!options.use_login) {
                   2156:                if (getuid() == 0 || geteuid() == 0) {
                   2157:                        if (setgid(pw->pw_gid) < 0) {
                   2158:                                perror("setgid");
                   2159:                                exit(1);
                   2160:                        }
                   2161:                        /* Initialize the group list. */
                   2162:                        if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
                   2163:                                perror("initgroups");
                   2164:                                exit(1);
                   2165:                        }
                   2166:                        endgrent();
                   2167:
                   2168:                        /* Permanently switch to the desired uid. */
                   2169:                        permanently_set_uid(pw->pw_uid);
                   2170:                }
                   2171:                if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
                   2172:                        fatal("Failed to set uids to %d.", (int) pw->pw_uid);
                   2173:        }
1.66      markus   2174:        /*
                   2175:         * Get the shell from the password data.  An empty shell field is
                   2176:         * legal, and means /bin/sh.
                   2177:         */
1.64      markus   2178:        shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
1.1       deraadt  2179:
                   2180: #ifdef AFS
1.64      markus   2181:        /* Try to get AFS tokens for the local cell. */
                   2182:        if (k_hasafs()) {
                   2183:                char cell[64];
1.1       deraadt  2184:
1.64      markus   2185:                if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
                   2186:                        krb_afslog(cell, 0);
                   2187:
                   2188:                krb_afslog(0, 0);
                   2189:        }
1.1       deraadt  2190: #endif /* AFS */
1.64      markus   2191:
1.66      markus   2192:        /* Initialize the environment. */
1.64      markus   2193:        envsize = 100;
                   2194:        env = xmalloc(envsize * sizeof(char *));
                   2195:        env[0] = NULL;
                   2196:
                   2197:        if (!options.use_login) {
                   2198:                /* Set basic environment. */
                   2199:                child_set_env(&env, &envsize, "USER", pw->pw_name);
                   2200:                child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
                   2201:                child_set_env(&env, &envsize, "HOME", pw->pw_dir);
                   2202:                child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
                   2203:
                   2204:                snprintf(buf, sizeof buf, "%.200s/%.50s",
                   2205:                         _PATH_MAILDIR, pw->pw_name);
                   2206:                child_set_env(&env, &envsize, "MAIL", buf);
                   2207:
                   2208:                /* Normal systems set SHELL by default. */
                   2209:                child_set_env(&env, &envsize, "SHELL", shell);
                   2210:        }
                   2211:        if (getenv("TZ"))
                   2212:                child_set_env(&env, &envsize, "TZ", getenv("TZ"));
                   2213:
                   2214:        /* Set custom environment options from RSA authentication. */
                   2215:        while (custom_environment) {
                   2216:                struct envstring *ce = custom_environment;
                   2217:                char *s = ce->s;
                   2218:                int i;
                   2219:                for (i = 0; s[i] != '=' && s[i]; i++);
                   2220:                if (s[i] == '=') {
                   2221:                        s[i] = 0;
                   2222:                        child_set_env(&env, &envsize, s, s + i + 1);
                   2223:                }
                   2224:                custom_environment = ce->next;
                   2225:                xfree(ce->s);
                   2226:                xfree(ce);
1.1       deraadt  2227:        }
1.64      markus   2228:
                   2229:        snprintf(buf, sizeof buf, "%.50s %d %d",
                   2230:                 get_remote_ipaddr(), get_remote_port(), options.port);
                   2231:        child_set_env(&env, &envsize, "SSH_CLIENT", buf);
                   2232:
                   2233:        if (ttyname)
                   2234:                child_set_env(&env, &envsize, "SSH_TTY", ttyname);
                   2235:        if (term)
                   2236:                child_set_env(&env, &envsize, "TERM", term);
                   2237:        if (display)
                   2238:                child_set_env(&env, &envsize, "DISPLAY", display);
1.1       deraadt  2239:
1.5       dugsong  2240: #ifdef KRB4
1.64      markus   2241:        {
                   2242:                extern char *ticket;
                   2243:
                   2244:                if (ticket)
                   2245:                        child_set_env(&env, &envsize, "KRBTKFILE", ticket);
                   2246:        }
1.1       deraadt  2247: #endif /* KRB4 */
1.64      markus   2248:
                   2249:        if (xauthfile)
                   2250:                child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
                   2251:        if (auth_get_socket_name() != NULL)
                   2252:                child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
                   2253:                              auth_get_socket_name());
                   2254:
1.66      markus   2255:        /* read $HOME/.ssh/environment. */
1.64      markus   2256:        if (!options.use_login) {
                   2257:                snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
                   2258:                read_environment_file(&env, &envsize, buf);
                   2259:        }
                   2260:        if (debug_flag) {
1.66      markus   2261:                /* dump the environment */
1.64      markus   2262:                fprintf(stderr, "Environment:\n");
                   2263:                for (i = 0; env[i]; i++)
                   2264:                        fprintf(stderr, "  %.200s\n", env[i]);
                   2265:        }
1.66      markus   2266:        /*
                   2267:         * Close the connection descriptors; note that this is the child, and
                   2268:         * the server will still have the socket open, and it is important
                   2269:         * that we do not shutdown it.  Note that the descriptors cannot be
                   2270:         * closed before building the environment, as we call
                   2271:         * get_remote_ipaddr there.
                   2272:         */
1.64      markus   2273:        if (packet_get_connection_in() == packet_get_connection_out())
                   2274:                close(packet_get_connection_in());
                   2275:        else {
                   2276:                close(packet_get_connection_in());
                   2277:                close(packet_get_connection_out());
                   2278:        }
1.66      markus   2279:        /*
                   2280:         * Close all descriptors related to channels.  They will still remain
                   2281:         * open in the parent.
                   2282:         */
                   2283:        /* XXX better use close-on-exec? -markus */
1.64      markus   2284:        channel_close_all();
                   2285:
1.66      markus   2286:        /*
                   2287:         * Close any extra file descriptors.  Note that there may still be
                   2288:         * descriptors left by system functions.  They will be closed later.
                   2289:         */
1.64      markus   2290:        endpwent();
                   2291:        endhostent();
                   2292:
1.66      markus   2293:        /*
                   2294:         * Close any extra open file descriptors so that we don\'t have them
                   2295:         * hanging around in clients.  Note that we want to do this after
                   2296:         * initgroups, because at least on Solaris 2.3 it leaves file
                   2297:         * descriptors open.
                   2298:         */
1.64      markus   2299:        for (i = 3; i < 64; i++)
                   2300:                close(i);
                   2301:
                   2302:        /* Change current directory to the user\'s home directory. */
                   2303:        if (chdir(pw->pw_dir) < 0)
                   2304:                fprintf(stderr, "Could not chdir to home directory %s: %s\n",
                   2305:                        pw->pw_dir, strerror(errno));
                   2306:
1.66      markus   2307:        /*
                   2308:         * Must take new environment into use so that .ssh/rc, /etc/sshrc and
                   2309:         * xauth are run in the proper environment.
                   2310:         */
1.64      markus   2311:        environ = env;
                   2312:
1.66      markus   2313:        /*
                   2314:         * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
                   2315:         * in this order).
                   2316:         */
1.64      markus   2317:        if (!options.use_login) {
                   2318:                if (stat(SSH_USER_RC, &st) >= 0) {
                   2319:                        if (debug_flag)
                   2320:                                fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
                   2321:
                   2322:                        f = popen("/bin/sh " SSH_USER_RC, "w");
                   2323:                        if (f) {
                   2324:                                if (auth_proto != NULL && auth_data != NULL)
                   2325:                                        fprintf(f, "%s %s\n", auth_proto, auth_data);
                   2326:                                pclose(f);
                   2327:                        } else
                   2328:                                fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
                   2329:                } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
                   2330:                        if (debug_flag)
                   2331:                                fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
                   2332:
                   2333:                        f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
                   2334:                        if (f) {
                   2335:                                if (auth_proto != NULL && auth_data != NULL)
                   2336:                                        fprintf(f, "%s %s\n", auth_proto, auth_data);
                   2337:                                pclose(f);
                   2338:                        } else
                   2339:                                fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
                   2340:                }
1.1       deraadt  2341: #ifdef XAUTH_PATH
1.64      markus   2342:                else {
1.66      markus   2343:                        /* Add authority data to .Xauthority if appropriate. */
1.64      markus   2344:                        if (auth_proto != NULL && auth_data != NULL) {
                   2345:                                if (debug_flag)
                   2346:                                        fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
                   2347:                                                XAUTH_PATH, display, auth_proto, auth_data);
                   2348:
                   2349:                                f = popen(XAUTH_PATH " -q -", "w");
                   2350:                                if (f) {
                   2351:                                        fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
                   2352:                                        fclose(f);
                   2353:                                } else
                   2354:                                        fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
                   2355:                        }
                   2356:                }
1.1       deraadt  2357: #endif /* XAUTH_PATH */
                   2358:
1.64      markus   2359:                /* Get the last component of the shell name. */
                   2360:                cp = strrchr(shell, '/');
                   2361:                if (cp)
                   2362:                        cp++;
                   2363:                else
                   2364:                        cp = shell;
                   2365:        }
1.66      markus   2366:        /*
                   2367:         * If we have no command, execute the shell.  In this case, the shell
                   2368:         * name to be passed in argv[0] is preceded by '-' to indicate that
                   2369:         * this is a login shell.
                   2370:         */
1.64      markus   2371:        if (!command) {
                   2372:                if (!options.use_login) {
                   2373:                        char buf[256];
                   2374:
1.66      markus   2375:                        /*
                   2376:                         * Check for mail if we have a tty and it was enabled
                   2377:                         * in server options.
                   2378:                         */
1.64      markus   2379:                        if (ttyname && options.check_mail) {
                   2380:                                char *mailbox;
                   2381:                                struct stat mailstat;
                   2382:                                mailbox = getenv("MAIL");
                   2383:                                if (mailbox != NULL) {
                   2384:                                        if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
                   2385:                                                printf("No mail.\n");
                   2386:                                        else if (mailstat.st_mtime < mailstat.st_atime)
                   2387:                                                printf("You have mail.\n");
                   2388:                                        else
                   2389:                                                printf("You have new mail.\n");
                   2390:                                }
                   2391:                        }
                   2392:                        /* Start the shell.  Set initial character to '-'. */
                   2393:                        buf[0] = '-';
                   2394:                        strncpy(buf + 1, cp, sizeof(buf) - 1);
                   2395:                        buf[sizeof(buf) - 1] = 0;
                   2396:
                   2397:                        /* Execute the shell. */
                   2398:                        argv[0] = buf;
                   2399:                        argv[1] = NULL;
                   2400:                        execve(shell, argv, env);
                   2401:
                   2402:                        /* Executing the shell failed. */
                   2403:                        perror(shell);
                   2404:                        exit(1);
                   2405:
                   2406:                } else {
                   2407:                        /* Launch login(1). */
                   2408:
                   2409:                        execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
                   2410:                              "-p", "-f", "--", pw->pw_name, NULL);
                   2411:
                   2412:                        /* Login couldn't be executed, die. */
                   2413:
                   2414:                        perror("login");
                   2415:                        exit(1);
                   2416:                }
                   2417:        }
1.66      markus   2418:        /*
                   2419:         * Execute the command using the user's shell.  This uses the -c
                   2420:         * option to execute the command.
                   2421:         */
1.64      markus   2422:        argv[0] = (char *) cp;
                   2423:        argv[1] = "-c";
                   2424:        argv[2] = (char *) command;
                   2425:        argv[3] = NULL;
                   2426:        execve(shell, argv, env);
                   2427:        perror(shell);
                   2428:        exit(1);
1.1       deraadt  2429: }