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

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