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

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