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

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