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

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