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

Annotation of src/usr.bin/ssh/sshconnect.c, Revision 1.2

1.1       deraadt     1: /*
                      2:
                      3: sshconnect.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: Sat Mar 18 22:15:47 1995 ylo
                     11:
                     12: Code to connect to a remote host, and to perform the client side of the
                     13: login (authentication) dialog.
                     14:
                     15: */
                     16:
                     17: #include "includes.h"
1.2     ! deraadt    18: RCSID("$Id: sshconnect.c,v 1.1 1999/09/26 20:53:38 deraadt Exp $");
1.1       deraadt    19:
                     20: #include <gmp.h>
                     21: #include "xmalloc.h"
                     22: #include "randoms.h"
                     23: #include "rsa.h"
                     24: #include "ssh.h"
                     25: #include "packet.h"
                     26: #include "authfd.h"
                     27: #include "cipher.h"
                     28: #include "ssh_md5.h"
                     29: #include "mpaux.h"
                     30: #include "uidswap.h"
                     31:
                     32: #ifdef KRB4
                     33: #include <krb.h>
                     34: #ifdef AFS
                     35: #if defined(HAVE_SYS_IOCTL_H) && SunOS != 4
                     36: #include <sys/ioctl.h>
                     37: #endif
                     38: #ifdef HAVE_SYS_FILIO_H
                     39: #include <sys/filio.h>
                     40: #endif
                     41: #include <kafs.h>
                     42: #endif /* AFS */
                     43: #endif /* KRB4 */
                     44:
                     45: /* Session id for the current session. */
                     46: unsigned char session_id[16];
                     47:
                     48: /* Connect to the given ssh server using a proxy command. */
                     49:
                     50: int ssh_proxy_connect(const char *host, int port, uid_t original_real_uid,
                     51:                      const char *proxy_command, RandomState *random_state)
                     52: {
                     53:   Buffer command;
                     54:   const char *cp;
                     55:   char *command_string;
                     56:   int pin[2], pout[2];
                     57:   int pid;
                     58:   char portstring[100];
                     59:
                     60:   /* Convert the port number into a string. */
                     61:   sprintf(portstring, "%d", port);
                     62:
                     63:   /* Build the final command string in the buffer by making the appropriate
                     64:      substitutions to the given proxy command. */
                     65:   buffer_init(&command);
                     66:   for (cp = proxy_command; *cp; cp++)
                     67:     {
                     68:       if (cp[0] == '%' && cp[1] == '%')
                     69:        {
                     70:          buffer_append(&command, "%", 1);
                     71:          cp++;
                     72:          continue;
                     73:        }
                     74:       if (cp[0] == '%' && cp[1] == 'h')
                     75:        {
                     76:          buffer_append(&command, host, strlen(host));
                     77:          cp++;
                     78:          continue;
                     79:        }
                     80:       if (cp[0] == '%' && cp[1] == 'p')
                     81:        {
                     82:          buffer_append(&command, portstring, strlen(portstring));
                     83:          cp++;
                     84:          continue;
                     85:        }
                     86:       buffer_append(&command, cp, 1);
                     87:     }
                     88:   buffer_append(&command, "\0", 1);
                     89:
                     90:   /* Get the final command string. */
                     91:   command_string = buffer_ptr(&command);
                     92:
                     93:   /* Create pipes for communicating with the proxy. */
                     94:   if (pipe(pin) < 0 || pipe(pout) < 0)
                     95:     fatal("Could not create pipes to communicate with the proxy: %.100s",
                     96:          strerror(errno));
                     97:
                     98:   debug("Executing proxy command: %.500s", command_string);
                     99:
                    100:   /* Fork and execute the proxy command. */
                    101:   if ((pid = fork()) == 0)
                    102:     {
                    103:       char *argv[10];
                    104:
                    105:       /* Child.  Permanently give up superuser privileges. */
                    106:       permanently_set_uid(original_real_uid);
                    107:
                    108:       /* Redirect stdin and stdout. */
                    109:       close(pin[1]);
                    110:       if (pin[0] != 0)
                    111:        {
                    112:          if (dup2(pin[0], 0) < 0)
                    113:            perror("dup2 stdin");
                    114:          close(pin[0]);
                    115:        }
                    116:       close(pout[0]);
                    117:       if (dup2(pout[1], 1) < 0)
                    118:        perror("dup2 stdout");
                    119:       close(pout[1]); /* Cannot be 1 because pin allocated two descriptors. */
                    120:
                    121:       /* Stderr is left as it is so that error messages get printed on
                    122:         the user's terminal. */
                    123:       argv[0] = "/bin/sh";
                    124:       argv[1] = "-c";
                    125:       argv[2] = command_string;
                    126:       argv[3] = NULL;
                    127:
                    128:       /* Execute the proxy command.  Note that we gave up any extra
                    129:         privileges above. */
                    130:       execv("/bin/sh", argv);
                    131:       perror("/bin/sh");
                    132:       exit(1);
                    133:     }
                    134:   /* Parent. */
                    135:   if (pid < 0)
                    136:     fatal("fork failed: %.100s", strerror(errno));
                    137:
                    138:   /* Close child side of the descriptors. */
                    139:   close(pin[0]);
                    140:   close(pout[1]);
                    141:
                    142:   /* Free the command name. */
                    143:   buffer_free(&command);
                    144:
                    145:   /* Set the connection file descriptors. */
                    146:   packet_set_connection(pout[0], pin[1], random_state);
                    147:
                    148:   return 1;
                    149: }
                    150:
                    151: /* Creates a (possibly privileged) socket for use as the ssh connection. */
                    152:
                    153: int ssh_create_socket(uid_t original_real_uid, int privileged)
                    154: {
                    155:   int sock;
                    156:
                    157:   /* If we are running as root and want to connect to a privileged port,
                    158:      bind our own socket to a privileged port. */
                    159:   if (privileged)
                    160:     {
                    161:       struct sockaddr_in sin;
1.2     ! deraadt   162:       int p = IPPORT_RESERVED - 1;
        !           163:
        !           164:       sock = rresvport(&p);
        !           165:       if (sock < 0)
        !           166:         fatal("rresvport: %.100s", strerror(errno));
1.1       deraadt   167:       debug("Allocated local port %d.", p);
                    168:     }
                    169:   else
                    170:     {
                    171:       /* Just create an ordinary socket on arbitrary port.  We use the
                    172:         user's uid to create the socket. */
                    173:       temporarily_use_uid(original_real_uid);
                    174:       sock = socket(AF_INET, SOCK_STREAM, 0);
                    175:       if (sock < 0)
                    176:        fatal("socket: %.100s", strerror(errno));
                    177:       restore_uid();
                    178:     }
                    179:   return sock;
                    180: }
                    181:
                    182: /* Opens a TCP/IP connection to the remote server on the given host.  If
                    183:    port is 0, the default port will be used.  If anonymous is zero,
                    184:    a privileged port will be allocated to make the connection.
                    185:    This requires super-user privileges if anonymous is false.
                    186:    Connection_attempts specifies the maximum number of tries (one per
                    187:    second).  If proxy_command is non-NULL, it specifies the command (with %h
                    188:    and %p substituted for host and port, respectively) to use to contact
                    189:    the daemon. */
                    190:
                    191: int ssh_connect(const char *host, int port, int connection_attempts,
                    192:                int anonymous, uid_t original_real_uid,
                    193:                const char *proxy_command, RandomState *random_state)
                    194: {
                    195:   int sock = -1, attempt, i;
                    196:   int on = 1;
                    197:   struct servent *sp;
                    198:   struct hostent *hp;
                    199:   struct sockaddr_in hostaddr;
                    200: #ifdef SO_LINGER
                    201:   struct linger linger;
                    202: #endif /* SO_LINGER */
                    203:
                    204:   debug("ssh_connect: getuid %d geteuid %d anon %d",
                    205:        (int)getuid(), (int)geteuid(), anonymous);
                    206:
                    207:   /* Get default port if port has not been set. */
                    208:   if (port == 0)
                    209:     {
                    210:       sp = getservbyname(SSH_SERVICE_NAME, "tcp");
                    211:       if (sp)
                    212:        port = ntohs(sp->s_port);
                    213:       else
                    214:        port = SSH_DEFAULT_PORT;
                    215:     }
                    216:
                    217:   /* If a proxy command is given, connect using it. */
                    218:   if (proxy_command != NULL)
                    219:     return ssh_proxy_connect(host, port, original_real_uid, proxy_command,
                    220:                             random_state);
                    221:
                    222:   /* No proxy command. */
                    223:
                    224:   /* No host lookup made yet. */
                    225:   hp = NULL;
                    226:
                    227:   /* Try to connect several times.  On some machines, the first time will
                    228:      sometimes fail.  In general socket code appears to behave quite
                    229:      magically on many machines. */
                    230:   for (attempt = 0; attempt < connection_attempts; attempt++)
                    231:     {
                    232:       if (attempt > 0)
                    233:        debug("Trying again...");
                    234:
                    235:       /* Try to parse the host name as a numeric inet address. */
                    236:       memset(&hostaddr, 0, sizeof(hostaddr));
                    237:       hostaddr.sin_family = AF_INET;
                    238:       hostaddr.sin_port = htons(port);
                    239: #ifdef BROKEN_INET_ADDR
                    240:       hostaddr.sin_addr.s_addr = inet_network(host);
                    241: #else /* BROKEN_INET_ADDR */
                    242:       hostaddr.sin_addr.s_addr = inet_addr(host);
                    243: #endif /* BROKEN_INET_ADDR */
                    244:       if ((hostaddr.sin_addr.s_addr & 0xffffffff) != 0xffffffff)
                    245:        {
                    246:          /* Valid numeric IP address */
                    247:          debug("Connecting to %.100s port %d.",
                    248:                inet_ntoa(hostaddr.sin_addr), port);
                    249:
                    250:          /* Create a socket. */
                    251:          sock = ssh_create_socket(original_real_uid,
                    252:                                   !anonymous && geteuid() == 0 &&
                    253:                                     port < 1024);
                    254:
                    255:          /* Connect to the host.  We use the user's uid in the hope that
                    256:             it will help with the problems of tcp_wrappers showing the
                    257:             remote uid as root. */
                    258:          temporarily_use_uid(original_real_uid);
                    259:          if (connect(sock, (struct sockaddr *)&hostaddr, sizeof(hostaddr))
                    260:              >= 0)
                    261:            {
                    262:              /* Successful connect. */
                    263:              restore_uid();
                    264:              break;
                    265:            }
                    266:          debug("connect: %.100s", strerror(errno));
                    267:          restore_uid();
                    268:
                    269:          /* Destroy the failed socket. */
                    270:          shutdown(sock, 2);
                    271:          close(sock);
                    272:        }
                    273:       else
                    274:        {
                    275:          /* Not a valid numeric inet address. */
                    276:          /* Map host name to an address. */
                    277:          if (!hp)
                    278:            hp = gethostbyname(host);
                    279:          if (!hp)
                    280:            fatal("Bad host name: %.100s", host);
                    281:          if (!hp->h_addr_list[0])
                    282:            fatal("Host does not have an IP address: %.100s", host);
                    283:
                    284:          /* Loop through addresses for this host, and try each one in
                    285:             sequence until the connection succeeds. */
                    286:          for (i = 0; hp->h_addr_list[i]; i++)
                    287:            {
                    288:              /* Set the address to connect to. */
                    289:              hostaddr.sin_family = hp->h_addrtype;
                    290:              memcpy(&hostaddr.sin_addr, hp->h_addr_list[i],
                    291:                     sizeof(hostaddr.sin_addr));
                    292:
                    293:              debug("Connecting to %.200s [%.100s] port %d.",
                    294:                    host, inet_ntoa(hostaddr.sin_addr), port);
                    295:
                    296:              /* Create a socket for connecting. */
                    297:              sock = ssh_create_socket(original_real_uid,
                    298:                                       !anonymous && geteuid() == 0 &&
                    299:                                         port < 1024);
                    300:
                    301:              /* Connect to the host.  We use the user's uid in the hope that
                    302:                 it will help with tcp_wrappers showing the remote uid as
                    303:                 root. */
                    304:              temporarily_use_uid(original_real_uid);
                    305:              if (connect(sock, (struct sockaddr *)&hostaddr,
                    306:                          sizeof(hostaddr)) >= 0)
                    307:                {
                    308:                  /* Successful connection. */
                    309:                  restore_uid();
                    310:                  break;
                    311:                }
                    312:              debug("connect: %.100s", strerror(errno));
                    313:              restore_uid();
                    314:
                    315:              /* Close the failed socket; there appear to be some problems
                    316:                 when reusing a socket for which connect() has already
                    317:                 returned an error. */
                    318:              shutdown(sock, 2);
                    319:              close(sock);
                    320:            }
                    321:          if (hp->h_addr_list[i])
                    322:            break; /* Successful connection. */
                    323:        }
                    324:
                    325:       /* Sleep a moment before retrying. */
                    326:       sleep(1);
                    327:     }
                    328:   /* Return failure if we didn't get a successful connection. */
                    329:   if (attempt >= connection_attempts)
                    330:     return 0;
                    331:
                    332:   debug("Connection established.");
                    333:
                    334:   /* Set socket options.  We would like the socket to disappear as soon as
                    335:      it has been closed for whatever reason. */
                    336:   /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
                    337: #ifdef TCP_NODELAY
                    338:   setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on));
                    339: #endif /* TCP_NODELAY */
                    340: #ifdef SO_LINGER
                    341:   linger.l_onoff = 1;
                    342:   linger.l_linger = 5;
                    343:   setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
                    344: #endif /* SO_LINGER */
                    345:
                    346:   /* Set the connection. */
                    347:   packet_set_connection(sock, sock, random_state);
                    348:
                    349:   return 1;
                    350: }
                    351:
                    352: /* Checks if the user has an authentication agent, and if so, tries to
                    353:    authenticate using the agent. */
                    354:
                    355: int try_agent_authentication()
                    356: {
                    357:   int status, type, bits;
                    358:   MP_INT e, n, challenge;
                    359:   char *comment;
                    360:   AuthenticationConnection *auth;
                    361:   unsigned char response[16];
                    362:   unsigned int i;
                    363:
                    364:   /* Get connection to the agent. */
                    365:   auth = ssh_get_authentication_connection();
                    366:   if (!auth)
                    367:     return 0;
                    368:
                    369:   mpz_init(&e);
                    370:   mpz_init(&n);
                    371:   mpz_init(&challenge);
                    372:
                    373:   /* Loop through identities served by the agent. */
                    374:   for (status = ssh_get_first_identity(auth, &bits, &e, &n, &comment);
                    375:        status;
                    376:        status = ssh_get_next_identity(auth, &bits, &e, &n, &comment))
                    377:     {
                    378:       int plen, clen;
                    379:
                    380:       /* Try this identity. */
                    381:       debug("Trying RSA authentication via agent with '%.100s'", comment);
                    382:       xfree(comment);
                    383:
                    384:       /* Tell the server that we are willing to authenticate using this key. */
                    385:       packet_start(SSH_CMSG_AUTH_RSA);
                    386:       packet_put_mp_int(&n);
                    387:       packet_send();
                    388:       packet_write_wait();
                    389:
                    390:       /* Wait for server's response. */
                    391:       type = packet_read(&plen);
                    392:
                    393:       /* The server sends failure if it doesn\'t like our key or does not
                    394:         support RSA authentication. */
                    395:       if (type == SSH_SMSG_FAILURE)
                    396:        {
                    397:          debug("Server refused our key.");
                    398:          continue;
                    399:        }
                    400:
                    401:       /* Otherwise it should have sent a challenge. */
                    402:       if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    403:        packet_disconnect("Protocol error during RSA authentication: %d",
                    404:                          type);
                    405:
                    406:       packet_get_mp_int(&challenge, &clen);
                    407:
                    408:       packet_integrity_check(plen, clen, type);
                    409:
                    410:       debug("Received RSA challenge from server.");
                    411:
                    412:       /* Ask the agent to decrypt the challenge. */
                    413:       if (!ssh_decrypt_challenge(auth, bits, &e, &n, &challenge,
                    414:                                 session_id, 1, response))
                    415:        {
                    416:          /* The agent failed to authenticate this identifier although it
                    417:             advertised it supports this.  Just return a wrong value. */
                    418:          log("Authentication agent failed to decrypt challenge.");
                    419:          memset(response, 0, sizeof(response));
                    420:        }
                    421:
                    422:       debug("Sending response to RSA challenge.");
                    423:
                    424:       /* Send the decrypted challenge back to the server. */
                    425:       packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    426:       for (i = 0; i < 16; i++)
                    427:        packet_put_char(response[i]);
                    428:       packet_send();
                    429:       packet_write_wait();
                    430:
                    431:       /* Wait for response from the server. */
                    432:       type = packet_read(&plen);
                    433:
                    434:       /* The server returns success if it accepted the authentication. */
                    435:       if (type == SSH_SMSG_SUCCESS)
                    436:        {
                    437:          debug("RSA authentication accepted by server.");
                    438:          mpz_clear(&e);
                    439:          mpz_clear(&n);
                    440:          mpz_clear(&challenge);
                    441:          return 1;
                    442:        }
                    443:
                    444:       /* Otherwise it should return failure. */
                    445:       if (type != SSH_SMSG_FAILURE)
                    446:        packet_disconnect("Protocol error waiting RSA auth response: %d",
                    447:                          type);
                    448:     }
                    449:
                    450:   mpz_clear(&e);
                    451:   mpz_clear(&n);
                    452:   mpz_clear(&challenge);
                    453:
                    454:   debug("RSA authentication using agent refused.");
                    455:   return 0;
                    456: }
                    457:
                    458: /* Computes the proper response to a RSA challenge, and sends the response to
                    459:    the server. */
                    460:
                    461: void respond_to_rsa_challenge(MP_INT *challenge, RSAPrivateKey *prv)
                    462: {
                    463:   unsigned char buf[32], response[16];
                    464:   struct MD5Context md;
                    465:   int i;
                    466:
                    467:   /* Decrypt the challenge using the private key. */
                    468:   rsa_private_decrypt(challenge, challenge, prv);
                    469:
                    470:   /* Compute the response. */
                    471:   /* The response is MD5 of decrypted challenge plus session id. */
                    472:   mp_linearize_msb_first(buf, 32, challenge);
                    473:   MD5Init(&md);
                    474:   MD5Update(&md, buf, 32);
                    475:   MD5Update(&md, session_id, 16);
                    476:   MD5Final(response, &md);
                    477:
                    478:   debug("Sending response to host key RSA challenge.");
                    479:
                    480:   /* Send the response back to the server. */
                    481:   packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    482:   for (i = 0; i < 16; i++)
                    483:     packet_put_char(response[i]);
                    484:   packet_send();
                    485:   packet_write_wait();
                    486:
                    487:   memset(buf, 0, sizeof(buf));
                    488:   memset(response, 0, sizeof(response));
                    489:   memset(&md, 0, sizeof(md));
                    490: }
                    491:
                    492: /* Checks if the user has authentication file, and if so, tries to authenticate
                    493:    the user using it. */
                    494:
                    495: int try_rsa_authentication(struct passwd *pw, const char *authfile,
                    496:                           int may_ask_passphrase)
                    497: {
                    498:   MP_INT challenge;
                    499:   RSAPrivateKey private_key;
                    500:   RSAPublicKey public_key;
                    501:   char *passphrase, *comment;
                    502:   int type, i;
                    503:   int plen, clen;
                    504:
                    505:   /* Try to load identification for the authentication key. */
                    506:   if (!load_public_key(authfile, &public_key, &comment))
                    507:     return 0; /* Could not load it.  Fail. */
                    508:
                    509:   debug("Trying RSA authentication with key '%.100s'", comment);
                    510:
                    511:   /* Tell the server that we are willing to authenticate using this key. */
                    512:   packet_start(SSH_CMSG_AUTH_RSA);
                    513:   packet_put_mp_int(&public_key.n);
                    514:   packet_send();
                    515:   packet_write_wait();
                    516:
                    517:   /* We no longer need the public key. */
                    518:   rsa_clear_public_key(&public_key);
                    519:
                    520:   /* Wait for server's response. */
                    521:   type = packet_read(&plen);
                    522:
                    523:   /* The server responds with failure if it doesn\'t like our key or doesn\'t
                    524:      support RSA authentication. */
                    525:   if (type == SSH_SMSG_FAILURE)
                    526:     {
                    527:       debug("Server refused our key.");
                    528:       xfree(comment);
                    529:       return 0; /* Server refuses to authenticate with this key. */
                    530:     }
                    531:
                    532:   /* Otherwise, the server should respond with a challenge. */
                    533:   if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    534:     packet_disconnect("Protocol error during RSA authentication: %d", type);
                    535:
                    536:   /* Get the challenge from the packet. */
                    537:   mpz_init(&challenge);
                    538:   packet_get_mp_int(&challenge, &clen);
                    539:
                    540:   packet_integrity_check(plen, clen, type);
                    541:
                    542:   debug("Received RSA challenge from server.");
                    543:
                    544:   /* Load the private key.  Try first with empty passphrase; if it fails,
                    545:      ask for a passphrase. */
                    546:   if (!load_private_key(authfile, "", &private_key, NULL))
                    547:     {
                    548:       char buf[300];
                    549:       /* Request passphrase from the user.  We read from /dev/tty to make
                    550:          this work even if stdin has been redirected.  If running in
                    551:         batch mode, we just use the empty passphrase, which will fail and
                    552:         return. */
                    553:       sprintf(buf, "Enter passphrase for RSA key '%.100s': ", comment);
                    554:       if (may_ask_passphrase)
                    555:        passphrase = read_passphrase(buf, 0);
                    556:       else
                    557:        {
                    558:          debug("Will not query passphrase for %.100s in batch mode.",
                    559:                comment);
                    560:          passphrase = xstrdup("");
                    561:        }
                    562:
                    563:       /* Load the authentication file using the pasphrase. */
                    564:       if (!load_private_key(authfile, passphrase, &private_key, NULL))
                    565:        {
                    566:          memset(passphrase, 0, strlen(passphrase));
                    567:          xfree(passphrase);
                    568:          error("Bad passphrase.");
                    569:
                    570:          /* Send a dummy response packet to avoid protocol error. */
                    571:          packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
                    572:          for (i = 0; i < 16; i++)
                    573:            packet_put_char(0);
                    574:          packet_send();
                    575:          packet_write_wait();
                    576:
                    577:          /* Expect the server to reject it... */
                    578:          packet_read_expect(&plen, SSH_SMSG_FAILURE);
                    579:          xfree(comment);
                    580:          return 0;
                    581:        }
                    582:
                    583:       /* Destroy the passphrase. */
                    584:       memset(passphrase, 0, strlen(passphrase));
                    585:       xfree(passphrase);
                    586:     }
                    587:
                    588:   /* We no longer need the comment. */
                    589:   xfree(comment);
                    590:
                    591:   /* Compute and send a response to the challenge. */
                    592:   respond_to_rsa_challenge(&challenge, &private_key);
                    593:
                    594:   /* Destroy the private key. */
                    595:   rsa_clear_private_key(&private_key);
                    596:
                    597:   /* We no longer need the challenge. */
                    598:   mpz_clear(&challenge);
                    599:
                    600:   /* Wait for response from the server. */
                    601:   type = packet_read(&plen);
                    602:   if (type == SSH_SMSG_SUCCESS)
                    603:     {
                    604:       debug("RSA authentication accepted by server.");
                    605:       return 1;
                    606:     }
                    607:   if (type != SSH_SMSG_FAILURE)
                    608:     packet_disconnect("Protocol error waiting RSA auth response: %d", type);
                    609:   debug("RSA authentication refused.");
                    610:   return 0;
                    611: }
                    612:
                    613: /* Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
                    614:    authentication and RSA host authentication. */
                    615:
                    616: int try_rhosts_rsa_authentication(const char *local_user,
                    617:                                  RSAPrivateKey *host_key)
                    618: {
                    619:   int type;
                    620:   MP_INT challenge;
                    621:   int plen, clen;
                    622:
                    623:   debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
                    624:
                    625:   /* Tell the server that we are willing to authenticate using this key. */
                    626:   packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
                    627:   packet_put_string(local_user, strlen(local_user));
                    628:   packet_put_int(host_key->bits);
                    629:   packet_put_mp_int(&host_key->e);
                    630:   packet_put_mp_int(&host_key->n);
                    631:   packet_send();
                    632:   packet_write_wait();
                    633:
                    634:   /* Wait for server's response. */
                    635:   type = packet_read(&plen);
                    636:
                    637:   /* The server responds with failure if it doesn't admit our .rhosts
                    638:      authentication or doesn't know our host key. */
                    639:   if (type == SSH_SMSG_FAILURE)
                    640:     {
                    641:       debug("Server refused our rhosts authentication or host key.");
                    642:       return 0; /* Server refuses to authenticate us with this method. */
                    643:     }
                    644:
                    645:   /* Otherwise, the server should respond with a challenge. */
                    646:   if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
                    647:     packet_disconnect("Protocol error during RSA authentication: %d", type);
                    648:
                    649:   /* Get the challenge from the packet. */
                    650:   mpz_init(&challenge);
                    651:   packet_get_mp_int(&challenge, &clen);
                    652:
                    653:   packet_integrity_check(plen, clen, type);
                    654:
                    655:   debug("Received RSA challenge for host key from server.");
                    656:
                    657:   /* Compute a response to the challenge. */
                    658:   respond_to_rsa_challenge(&challenge, host_key);
                    659:
                    660:   /* We no longer need the challenge. */
                    661:   mpz_clear(&challenge);
                    662:
                    663:   /* Wait for response from the server. */
                    664:   type = packet_read(&plen);
                    665:   if (type == SSH_SMSG_SUCCESS)
                    666:     {
                    667:       debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
                    668:       return 1;
                    669:     }
                    670:   if (type != SSH_SMSG_FAILURE)
                    671:     packet_disconnect("Protocol error waiting RSA auth response: %d", type);
                    672:   debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
                    673:   return 0;
                    674: }
                    675:
                    676: #ifdef KRB4
                    677: int try_kerberos_authentication()
                    678: {
                    679:   KTEXT_ST auth;                     /* Kerberos data */
                    680:   char *reply;
                    681:   char inst[INST_SZ];
                    682:   char *realm;
                    683:   CREDENTIALS cred;
                    684:   int r, type;
                    685:   Key_schedule schedule;
                    686:   u_long checksum, cksum;
                    687:   MSG_DAT msg_data;
                    688:   struct sockaddr_in local, foreign;
                    689:   struct stat st;
                    690:   int plen;
                    691:
                    692:   /* Don't do anything if we don't have any tickets. */
                    693:   if (stat(tkt_string(), &st) < 0) return 0;
                    694:
                    695:   debug("Trying Kerberos authentication.");
                    696:   strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
                    697:
                    698:   realm = (char *)krb_realmofhost(get_canonical_hostname());
                    699:   if (!realm) {
                    700:     debug("Kerberos V4: no realm for %.100s", get_canonical_hostname());
                    701:     return 0;
                    702:   }
                    703:   /* This can really be anything. */
                    704:   checksum = (u_long) getpid();
                    705:
                    706:   r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
                    707:   if (r != KSUCCESS) {
                    708:     debug("Kerberos V4 krb_mk_req failed: %.100s", krb_err_txt[r]);
                    709:     return 0;
                    710:   }
                    711:   /* Get session key to decrypt the server's reply with. */
                    712:   r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
                    713:   if (r != KSUCCESS) {
                    714:      debug("get_cred failed: %.100s", krb_err_txt[r]);
                    715:      return 0;
                    716:   }
                    717:   des_key_sched((des_cblock *)cred.session, schedule);
                    718:
                    719:   /* Send authentication info to server. */
                    720:   packet_start(SSH_CMSG_AUTH_KERBEROS);
                    721:   packet_put_string((char *)auth.dat, auth.length);
                    722:   packet_send();
                    723:   packet_write_wait();
                    724:
                    725:   /* zero the buffer */
                    726:   (void) memset(auth.dat, 0, MAX_KTXT_LEN);
                    727:
                    728:   r = sizeof(local);
                    729:   memset(&local, 0, sizeof(local));
                    730:   if (getsockname(packet_get_connection_in(),
                    731:                  (struct sockaddr *) &local, &r) < 0)
                    732:     debug("getsockname failed: %.100s", strerror(errno));
                    733:
                    734:   r = sizeof(foreign);
                    735:   memset(&foreign, 0, sizeof(foreign));
                    736:    if (getpeername(packet_get_connection_in(),
                    737:                   (struct sockaddr *)&foreign, &r) < 0)
                    738:      debug("getpeername failed: %.100s", strerror(errno));
                    739:
                    740:    /* Get server reply. */
                    741:    type = packet_read(&plen);
                    742:    switch(type) {
                    743:
                    744:    case SSH_SMSG_FAILURE: /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
                    745:      debug("Kerberos V4 authentication failed.");
                    746:      return 0;
                    747:      break;
                    748:
                    749:    case SSH_SMSG_AUTH_KERBEROS_RESPONSE: /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
                    750:      debug("Kerberos V4 authentication accepted.");
                    751:
                    752:      /* Get server's response. */
                    753:      reply = packet_get_string((unsigned int *)&auth.length);
                    754:      memcpy(auth.dat, reply, auth.length);
                    755:      xfree(reply);
                    756:
                    757:      packet_integrity_check(plen, 4 + auth.length, type);
                    758:
                    759:      /* If his response isn't properly encrypted with the session key,
                    760:         and the decrypted checksum fails to match, he's bogus. Bail out. */
                    761:      r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
                    762:                     &foreign, &local, &msg_data);
                    763:      if (r != KSUCCESS) {
                    764:        debug("Kerberos V4 krb_rd_priv failed: %.100s", krb_err_txt[r]);
                    765:        packet_disconnect("Kerberos V4 challenge failed!");
                    766:      }
                    767:      /* fetch the (incremented) checksum that we supplied in the request */
                    768:      (void)memcpy((char *)&cksum, (char *)msg_data.app_data, sizeof(cksum));
                    769:      cksum = ntohl(cksum);
                    770:
                    771:      /* If it matches, we're golden. */
                    772:      if (cksum == checksum + 1) {
                    773:        debug("Kerberos V4 challenge successful.");
                    774:        return 1;
                    775:      }
                    776:      else
                    777:        packet_disconnect("Kerberos V4 challenge failed!");
                    778:      break;
                    779:
                    780:    default:
                    781:      packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
                    782:    }
                    783:    return 0;
                    784: }
                    785: #endif /* KRB4 */
                    786:
                    787: #ifdef AFS
                    788:
                    789: #ifdef KERBEROS_TGT_PASSING
                    790: int send_kerberos_tgt()
                    791: {
                    792:   CREDENTIALS *creds;
                    793:   char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
                    794:   int r, plen, type;
                    795:   unsigned char buffer[8192];
                    796:   struct stat st;
                    797:
                    798:   /* Don't do anything if we don't have any tickets. */
                    799:   if (stat(tkt_string(), &st) < 0) return 0;
                    800:
                    801:   creds = xmalloc(sizeof(CREDENTIALS));
                    802:
                    803:   if ((r=krb_get_tf_fullname(TKT_FILE,pname,pinst,prealm)) != KSUCCESS) {
                    804:     debug("Kerberos V4 tf_fullname failed: %.100s",krb_err_txt[r]);
                    805:     return 0;
                    806: }
                    807:   if ((r=krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
                    808:     debug("Kerberos V4 get_cred failed: %.100s", krb_err_txt[r]);
                    809:     return 0;
                    810:   }
                    811:   if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
                    812:     debug("Kerberos V4 ticket expired: %.100s", TKT_FILE);
                    813:     return 0;
                    814:   }
                    815:
                    816:   creds_to_radix(creds, buffer);
                    817:   xfree(creds);
                    818:
                    819:   packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
                    820:   packet_put_string((char *)buffer, strlen(buffer));
                    821:   packet_send();
                    822:   packet_write_wait();
                    823:
                    824:   type = packet_read(&plen);
                    825:
                    826:   if (type == SSH_SMSG_FAILURE)
                    827:     debug("Kerberos TGT for realm %.100s rejected.", prealm);
                    828:   else if (type != SSH_SMSG_SUCCESS)
                    829:     packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
                    830:
                    831:   return 1;
                    832: }
                    833: #endif /* KERBEROS_TGT_PASSING */
                    834:
                    835: /* Forwards our AFS tokens to the server. */
                    836: void send_afs_tokens(void)
                    837: {
                    838:   CREDENTIALS creds;
                    839:   struct ViceIoctl parms;
                    840:   struct ClearToken ct;
                    841:   int i, type;
                    842:   int len, plen;
                    843:   char buf[2048], *p, *server_cell;
                    844:   unsigned char buffer[8192];
                    845:
                    846:   /* Move over ktc_GetToken, here's something leaner. */
                    847:   for (i = 0; i < 100; i++) { /* just in case */
                    848:     parms.in = (char *)&i;
                    849:     parms.in_size = sizeof(i);
                    850:     parms.out = buf;
                    851:     parms.out_size = sizeof(buf);
                    852:     if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0) break;
                    853:     p = buf;
                    854:
                    855:     /* Get secret token. */
                    856:     memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
                    857:     if (creds.ticket_st.length > MAX_KTXT_LEN) break;
                    858:     p += sizeof(unsigned int);
                    859:     memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
                    860:     p += creds.ticket_st.length;
                    861:
                    862:     /* Get clear token. */
                    863:     memcpy(&len, p, sizeof(len));
                    864:     if (len != sizeof(struct ClearToken)) break;
                    865:     p += sizeof(len);
                    866:     memcpy(&ct, p, len);
                    867:     p += len;
                    868:     p += sizeof(len); /* primary flag */
                    869:     server_cell = p;
                    870:
                    871:     /* Flesh out our credentials. */
                    872:     strcpy(creds.service, "afs");
                    873:     creds.instance[0] = '\0';
                    874:     strncpy(creds.realm, server_cell, REALM_SZ);
                    875:     memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
                    876:     creds.issue_date = ct.BeginTimestamp;
                    877:     creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
                    878:     creds.kvno = ct.AuthHandle;
                    879:     sprintf(creds.pname, "AFS ID %d", ct.ViceId);
                    880:     creds.pinst[0] = '\0';
                    881:
                    882:     /* Encode token, ship it off. */
                    883:     if (!creds_to_radix(&creds, buffer)) break;
                    884:     packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
                    885:     packet_put_string((char *)buffer, strlen(buffer));
                    886:     packet_send();
                    887:     packet_write_wait();
                    888:
                    889:     /* Roger, Roger. Clearance, Clarence. What's your vector, Victor? */
                    890:     type = packet_read(&plen);
                    891:
                    892:     if (type == SSH_SMSG_FAILURE)
                    893:       debug("AFS token for cell %.100s rejected.", server_cell);
                    894:     else if (type != SSH_SMSG_SUCCESS)
                    895:       packet_disconnect("Protocol error on AFS token response: %d", type);
                    896:   }
                    897: }
                    898: #endif /* AFS */
                    899:
                    900: /* Waits for the server identification string, and sends our own identification
                    901:    string. */
                    902:
                    903: void ssh_exchange_identification()
                    904: {
                    905:   char buf[256], remote_version[256]; /* must be same size! */
                    906:   int remote_major, remote_minor, i;
                    907:   int connection_in = packet_get_connection_in();
                    908:   int connection_out = packet_get_connection_out();
                    909:
                    910:   /* Read other side\'s version identification. */
                    911:   for (i = 0; i < sizeof(buf) - 1; i++)
                    912:     {
                    913:       if (read(connection_in, &buf[i], 1) != 1)
                    914:        fatal("read: %.100s", strerror(errno));
                    915:       if (buf[i] == '\r')
                    916:        {
                    917:          buf[i] = '\n';
                    918:          buf[i + 1] = 0;
                    919:          break;
                    920:        }
                    921:       if (buf[i] == '\n')
                    922:        {
                    923:          buf[i + 1] = 0;
                    924:          break;
                    925:        }
                    926:     }
                    927:   buf[sizeof(buf) - 1] = 0;
                    928:
                    929:   /* Check that the versions match.  In future this might accept several
                    930:      versions and set appropriate flags to handle them. */
                    931:   if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
                    932:             remote_version) != 3)
                    933:     fatal("Bad remote protocol version identification: '%.100s'", buf);
                    934:   debug("Remote protocol version %d.%d, remote software version %.100s",
                    935:        remote_major, remote_minor, remote_version);
                    936: #if 0
                    937:   /* Removed for now, to permit compatibility with latter versions.  The server
                    938:      will reject our version and disconnect if it doesn't support it. */
                    939:   if (remote_major != PROTOCOL_MAJOR)
                    940:     fatal("Protocol major versions differ: %d vs. %d",
                    941:          PROTOCOL_MAJOR, remote_major);
                    942: #endif
                    943:
                    944:   /* Check if the remote protocol version is too old. */
                    945:   if (remote_major == 1 && remote_minor == 0)
                    946:     fatal("Remote machine has too old SSH software version.");
                    947:
                    948:   /* Send our own protocol version identification. */
                    949:   sprintf(buf, "SSH-%d.%d-%.100s\n",
                    950:          PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
                    951:   if (write(connection_out, buf, strlen(buf)) != strlen(buf))
                    952:     fatal("write: %.100s", strerror(errno));
                    953: }
                    954:
                    955: int ssh_cipher_default = SSH_CIPHER_3DES;
                    956:
                    957: int read_yes_or_no(const char *prompt, int defval)
                    958: {
                    959:   char buf[1024];
                    960:   FILE *f;
                    961:   int retval = -1;
                    962:
                    963:   if (isatty(0))
                    964:     f = stdin;
                    965:   else
                    966:     f = fopen("/dev/tty", "rw");
                    967:
                    968:   if (f == NULL)
                    969:     return 0;
                    970:
                    971:   fflush(stdout);
                    972:
                    973:   while (1)
                    974:     {
                    975:       fprintf(stderr, "%s", prompt);
                    976:       if (fgets(buf, sizeof(buf), f) == NULL)
                    977:        {
                    978:          /* Print a newline (the prompt probably didn\'t have one). */
                    979:          fprintf(stderr, "\n");
                    980:          strcpy(buf, "no");
                    981:        }
                    982:       /* Remove newline from response. */
                    983:       if (strchr(buf, '\n'))
                    984:        *strchr(buf, '\n') = 0;
                    985:
                    986:       if (buf[0] == 0)
                    987:        retval = defval;
                    988:       if (strcmp(buf, "yes") == 0)
                    989:        retval = 1;
                    990:       if (strcmp(buf, "no") == 0)
                    991:        retval = 0;
                    992:
                    993:       if (retval != -1)
                    994:        {
                    995:          if (f != stdin)
                    996:            fclose(f);
                    997:          return retval;
                    998:        }
                    999:     }
                   1000: }
                   1001:
                   1002: /* Starts a dialog with the server, and authenticates the current user on the
                   1003:    server.  This does not need any extra privileges.  The basic connection
                   1004:    to the server must already have been established before this is called.
                   1005:    User is the remote user; if it is NULL, the current local user name will
                   1006:    be used.  Anonymous indicates that no rhosts authentication will be used.
                   1007:    If login fails, this function prints an error and never returns.
                   1008:    This function does not require super-user privileges. */
                   1009:
                   1010: void ssh_login(RandomState *state, int host_key_valid,
                   1011:               RSAPrivateKey *own_host_key,
                   1012:               const char *orighost,
                   1013:               Options *options, uid_t original_real_uid)
                   1014: {
                   1015:   int i, type;
                   1016:   char buf[1024];
                   1017:   char *password;
                   1018:   struct passwd *pw;
                   1019:   MP_INT key;
                   1020:   RSAPublicKey host_key;
                   1021:   RSAPublicKey public_key;
                   1022:   unsigned char session_key[SSH_SESSION_KEY_LENGTH];
                   1023:   const char *server_user, *local_user;
                   1024:   char *cp, *host;
                   1025:   struct stat st;
                   1026:   unsigned char check_bytes[8];
                   1027:   unsigned int supported_ciphers, supported_authentications, protocol_flags;
                   1028:   HostStatus host_status;
                   1029:   int payload_len, clen, sum_len = 0;
                   1030:
                   1031:   /* Convert the user-supplied hostname into all lowercase. */
                   1032:   host = xstrdup(orighost);
                   1033:   for (cp = host; *cp; cp++)
                   1034:     if (isupper(*cp))
                   1035:       *cp = tolower(*cp);
                   1036:
                   1037:   /* Exchange protocol version identification strings with the server. */
                   1038:   ssh_exchange_identification();
                   1039:
                   1040:   /* Put the connection into non-blocking mode. */
                   1041:   packet_set_nonblocking();
                   1042:
                   1043:   /* Get local user name.  Use it as server user if no user name
                   1044:      was given. */
                   1045:   pw = getpwuid(original_real_uid);
                   1046:   if (!pw)
                   1047:     fatal("User id %d not found from user database.", original_real_uid);
                   1048:   local_user = xstrdup(pw->pw_name);
                   1049:   server_user = options->user ? options->user : local_user;
                   1050:
                   1051:   debug("Waiting for server public key.");
                   1052:
                   1053:   /* Wait for a public key packet from the server. */
                   1054:   packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
                   1055:
                   1056:   /* Get check bytes from the packet. */
                   1057:   for (i = 0; i < 8; i++)
                   1058:     check_bytes[i] = packet_get_char();
                   1059:
                   1060:   /* Get the public key. */
                   1061:   public_key.bits = packet_get_int();
                   1062:   mpz_init(&public_key.e);
                   1063:   packet_get_mp_int(&public_key.e, &clen);
                   1064:   sum_len += clen;
                   1065:   mpz_init(&public_key.n);
                   1066:   packet_get_mp_int(&public_key.n, &clen);
                   1067:   sum_len += clen;
                   1068:
                   1069:   /* Get the host key. */
                   1070:   host_key.bits = packet_get_int();
                   1071:   mpz_init(&host_key.e);
                   1072:   packet_get_mp_int(&host_key.e, &clen);
                   1073:   sum_len += clen;
                   1074:   mpz_init(&host_key.n);
                   1075:   packet_get_mp_int(&host_key.n, &clen);
                   1076:   sum_len += clen;
                   1077:
                   1078:   /* Get protocol flags. */
                   1079:   protocol_flags = packet_get_int();
                   1080:   packet_set_protocol_flags(protocol_flags);
                   1081:
                   1082:   /* Get supported cipher types. */
                   1083:   supported_ciphers = packet_get_int();
                   1084:
                   1085:   /* Get supported authentication types. */
                   1086:   supported_authentications = packet_get_int();
                   1087:
                   1088:   debug("Received server public key (%d bits) and host key (%d bits).",
                   1089:        public_key.bits, host_key.bits);
                   1090:
                   1091:   packet_integrity_check(payload_len,
                   1092:                         8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
                   1093:                         SSH_SMSG_PUBLIC_KEY);
                   1094:
                   1095:   /* Compute the session id. */
                   1096:   compute_session_id(session_id, check_bytes, host_key.bits, &host_key.n,
                   1097:                     public_key.bits, &public_key.n);
                   1098:
                   1099:   /* Check if the host key is present in the user\'s list of known hosts
                   1100:      or in the systemwide list. */
                   1101:   host_status = check_host_in_hostfile(options->user_hostfile,
                   1102:                                       host, host_key.bits,
                   1103:                                       &host_key.e, &host_key.n);
                   1104:   if (host_status == HOST_NEW)
                   1105:     host_status = check_host_in_hostfile(options->system_hostfile, host,
                   1106:                                         host_key.bits, &host_key.e,
                   1107:                                         &host_key.n);
                   1108:
                   1109:   /* Force accepting of the host key for localhost and 127.0.0.1.
                   1110:      The problem is that if the home directory is NFS-mounted to multiple
                   1111:      machines, localhost will refer to a different machine in each of them,
                   1112:      and the user will get bogus HOST_CHANGED warnings.  This essentially
                   1113:      disables host authentication for localhost; however, this is probably
                   1114:      not a real problem. */
                   1115:   if (strcmp(host, "localhost") == 0 ||
                   1116:       strcmp(host, "127.0.0.1") == 0)
                   1117:     {
                   1118:       debug("Forcing accepting of host key for localhost.");
                   1119:       host_status = HOST_OK;
                   1120:     }
                   1121:
                   1122:   switch (host_status)
                   1123:     {
                   1124:     case HOST_OK:
                   1125:       /* The host is known and the key matches. */
                   1126:       debug("Host '%.200s' is known and matches the host key.", host);
                   1127:       break;
                   1128:     case HOST_NEW:
                   1129:       /* The host is new. */
                   1130:       if (options->strict_host_key_checking == 1)
                   1131:        { /* User has requested strict host key checking.  We will not
                   1132:             add the host key automatically.  The only alternative left
                   1133:             is to abort. */
                   1134:          fatal("No host key is known for %.200s and you have requested strict checking.", host);
                   1135:        }
                   1136:       else if (options->strict_host_key_checking == 2) /* The default */
                   1137:        {
                   1138:          char prompt[1024];
                   1139:          sprintf(prompt,
                   1140:                  "The authenticity of host '%.200s' can't be established.\n"
                   1141:                  "Are you sure you want to continue connecting (yes/no)? ",
                   1142:                  host);
                   1143:          if (!read_yes_or_no(prompt, -1))
                   1144:            fatal("Aborted by user!\n");
                   1145:        }
                   1146:       /* If not in strict mode, add the key automatically to the local
                   1147:         known_hosts file. */
                   1148:       if (!add_host_to_hostfile(options->user_hostfile, host, host_key.bits,
                   1149:                                &host_key.e, &host_key.n))
                   1150:        log("Failed to add the host to the list of known hosts (%.500s).",
                   1151:            options->user_hostfile);
                   1152:       else
                   1153:        log("Warning: Permanently added host '%.200s' to the list of known hosts.", host);
                   1154:       break;
                   1155:     case HOST_CHANGED:
                   1156:       /* The host key has changed. */
                   1157:       error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1158:       error("@       WARNING: HOST IDENTIFICATION HAS CHANGED!         @");
                   1159:       error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
                   1160:       error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
                   1161:       error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
                   1162:       error("It is also possible that the host key has just been changed.");
                   1163:       error("Please contact your system administrator.");
                   1164:       error("Add correct host key in %.100s to get rid of this message.",
                   1165:            options->user_hostfile);
                   1166:
                   1167:       /* If strict host key checking is in use, the user will have to edit
                   1168:         the key manually and we can only abort. */
                   1169:       if (options->strict_host_key_checking)
                   1170:        fatal("Host key for %.200s has changed and you have requested strict checking.", host);
                   1171:
                   1172:       /* If strict host key checking has not been requested, allow the
                   1173:         connection but without password authentication. */
                   1174:       error("Password authentication is disabled to avoid trojan horses.");
                   1175:       options->password_authentication = 0;
                   1176:       /* XXX Should permit the user to change to use the new id.  This could
                   1177:          be done by converting the host key to an identifying sentence, tell
                   1178:         that the host identifies itself by that sentence, and ask the user
                   1179:         if he/she whishes to accept the authentication. */
                   1180:       break;
                   1181:     }
                   1182:
                   1183:   /* Generate a session key. */
                   1184:
                   1185:   /* Initialize the random number generator. */
                   1186:   sprintf(buf, "%.500s/%.200s", pw->pw_dir, SSH_CLIENT_SEEDFILE);
                   1187:   if (stat(buf, &st) < 0)
                   1188:     log("Creating random seed file ~/%.900s.  This may take a while.",
                   1189:        SSH_CLIENT_SEEDFILE);
                   1190:   else
                   1191:     debug("Initializing random; seed file %.900s", buf);
                   1192:   random_initialize(state, buf);
                   1193:
                   1194:   /* Generate an encryption key for the session.   The key is a 256 bit
                   1195:      random number, interpreted as a 32-byte key, with the least significant
                   1196:      8 bits being the first byte of the key. */
                   1197:   for (i = 0; i < 32; i++)
                   1198:     session_key[i] = random_get_byte(state);
                   1199:
                   1200:   /* Save the new random state. */
                   1201:   random_save(state, buf);
                   1202:   random_stir(state); /* This is supposed to be irreversible. */
                   1203:
                   1204:   /* According to the protocol spec, the first byte of the session key is
                   1205:      the highest byte of the integer.  The session key is xored with the
                   1206:      first 16 bytes of the session id. */
                   1207:   mpz_init_set_ui(&key, 0);
                   1208:   for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++)
                   1209:     {
                   1210:       mpz_mul_2exp(&key, &key, 8);
                   1211:       if (i < 16)
                   1212:        mpz_add_ui(&key, &key, session_key[i] ^ session_id[i]);
                   1213:       else
                   1214:        mpz_add_ui(&key, &key, session_key[i]);
                   1215:     }
                   1216:
                   1217:   /* Encrypt the integer using the public key and host key of the server
                   1218:      (key with smaller modulus first). */
                   1219:   if (mpz_cmp(&public_key.n, &host_key.n) < 0)
                   1220:     {
                   1221:       /* Public key has smaller modulus. */
                   1222:       assert(host_key.bits >= public_key.bits + SSH_KEY_BITS_RESERVED);
                   1223:
                   1224:       rsa_public_encrypt(&key, &key, &public_key, state);
                   1225:       rsa_public_encrypt(&key, &key, &host_key, state);
                   1226:     }
                   1227:   else
                   1228:     {
                   1229:       /* Host key has smaller modulus (or they are equal). */
                   1230:       assert(public_key.bits >= host_key.bits + SSH_KEY_BITS_RESERVED);
                   1231:
                   1232:       rsa_public_encrypt(&key, &key, &host_key, state);
                   1233:       rsa_public_encrypt(&key, &key, &public_key, state);
                   1234:     }
                   1235:
                   1236:   if (options->cipher == SSH_CIPHER_NOT_SET)
                   1237:     if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
                   1238:       options->cipher = ssh_cipher_default;
                   1239:     else
                   1240:       {
                   1241:        debug("Cipher %d not supported, using %.100s instead.",
                   1242:              cipher_name(ssh_cipher_default),
                   1243:              cipher_name(SSH_FALLBACK_CIPHER));
                   1244:        options->cipher = SSH_FALLBACK_CIPHER;
                   1245:       }
                   1246:
                   1247:   /* Check that the selected cipher is supported. */
                   1248:   if (!(supported_ciphers & (1 << options->cipher)))
                   1249:     fatal("Selected cipher type %.100s not supported by server.",
                   1250:          cipher_name(options->cipher));
                   1251:
                   1252:   debug("Encryption type: %.100s", cipher_name(options->cipher));
                   1253:
                   1254:   /* Send the encrypted session key to the server. */
                   1255:   packet_start(SSH_CMSG_SESSION_KEY);
                   1256:   packet_put_char(options->cipher);
                   1257:
                   1258:   /* Send the check bytes back to the server. */
                   1259:   for (i = 0; i < 8; i++)
                   1260:     packet_put_char(check_bytes[i]);
                   1261:
                   1262:   /* Send the encrypted encryption key. */
                   1263:   packet_put_mp_int(&key);
                   1264:
                   1265:   /* Send protocol flags. */
                   1266:   packet_put_int(SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
                   1267:
                   1268:   /* Send the packet now. */
                   1269:   packet_send();
                   1270:   packet_write_wait();
                   1271:
                   1272:   /* Destroy the session key integer and the public keys since we no longer
                   1273:      need them. */
                   1274:   mpz_clear(&key);
                   1275:   rsa_clear_public_key(&public_key);
                   1276:   rsa_clear_public_key(&host_key);
                   1277:
                   1278:   debug("Sent encrypted session key.");
                   1279:
                   1280:   /* Set the encryption key. */
                   1281:   packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH,
                   1282:                            options->cipher, 1);
                   1283:
                   1284:   /* We will no longer need the session key here.  Destroy any extra copies. */
                   1285:   memset(session_key, 0, sizeof(session_key));
                   1286:
                   1287:   /* Expect a success message from the server.  Note that this message will
                   1288:      be received in encrypted form. */
                   1289:   packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
                   1290:
                   1291:   debug("Received encrypted confirmation.");
                   1292:
                   1293:   /* Send the name of the user to log in as on the server. */
                   1294:   packet_start(SSH_CMSG_USER);
                   1295:   packet_put_string(server_user, strlen(server_user));
                   1296:   packet_send();
                   1297:   packet_write_wait();
                   1298:
                   1299:   /* The server should respond with success if no authentication is needed
                   1300:      (the user has no password).  Otherwise the server responds with
                   1301:      failure. */
                   1302:   type = packet_read(&payload_len);
                   1303:   if (type == SSH_SMSG_SUCCESS)
                   1304:     return;  /* Connection was accepted without authentication. */
                   1305:   if (type != SSH_SMSG_FAILURE)
                   1306:     packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
                   1307:                      type);
                   1308:
                   1309: #ifdef KERBEROS_TGT_PASSING
                   1310:   /* Try Kerberos tgt passing if the server supports it. */
                   1311:   if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
                   1312:       options->kerberos_tgt_passing) {
                   1313:     if (options->cipher == SSH_CIPHER_NONE)
                   1314:       log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
                   1315:     (void)send_kerberos_tgt();
                   1316:   }
                   1317: #endif /* KERBEROS_TGT_PASSING */
                   1318:
                   1319: #ifdef AFS
                   1320:   /* Try AFS token passing if the server supports it. */
                   1321:   if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
                   1322:       options->afs_token_passing && k_hasafs())  {
                   1323:     if (options->cipher == SSH_CIPHER_NONE)
                   1324:       log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
                   1325:     send_afs_tokens();
                   1326:   }
                   1327: #endif /* AFS */
                   1328:
                   1329: #if defined(KRB4)
                   1330:   if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
                   1331:       options->kerberos_authentication)
                   1332:     {
                   1333:       if (try_kerberos_authentication()) {
                   1334:         /* The server should respond with success or failure. */
                   1335:         type = packet_read(&payload_len);
                   1336:         if (type == SSH_SMSG_SUCCESS)
                   1337:           return; /* Successful connection. */
                   1338:         if (type != SSH_SMSG_FAILURE)
                   1339:           packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
                   1340:       }
                   1341:     }
                   1342: #endif /* KRB4 */
                   1343:
                   1344:   /* Use rhosts authentication if running in privileged socket and we do not
                   1345:      wish to remain anonymous. */
                   1346:   if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
                   1347:       options->rhosts_authentication)
                   1348:     {
                   1349:       debug("Trying rhosts authentication.");
                   1350:       packet_start(SSH_CMSG_AUTH_RHOSTS);
                   1351:       packet_put_string(local_user, strlen(local_user));
                   1352:       packet_send();
                   1353:       packet_write_wait();
                   1354:
                   1355:       /* The server should respond with success or failure. */
                   1356:       type = packet_read(&payload_len);
                   1357:       if (type == SSH_SMSG_SUCCESS)
                   1358:        return; /* Successful connection. */
                   1359:       if (type != SSH_SMSG_FAILURE)
                   1360:        packet_disconnect("Protocol error: got %d in response to rhosts auth",
                   1361:                          type);
                   1362:     }
                   1363:
                   1364:   /* Try .rhosts or /etc/hosts.equiv authentication with RSA host
                   1365:      authentication. */
                   1366:   if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
                   1367:       options->rhosts_rsa_authentication && host_key_valid)
                   1368:     {
                   1369:       if (try_rhosts_rsa_authentication(local_user, own_host_key))
                   1370:        return; /* Successful authentication. */
                   1371:     }
                   1372:
                   1373:   /* Try RSA authentication if the server supports it. */
                   1374:   if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
                   1375:       options->rsa_authentication)
                   1376:     {
                   1377:       /* Try RSA authentication using the authentication agent.  The agent
                   1378:          is tried first because no passphrase is needed for it, whereas
                   1379:         identity files may require passphrases. */
                   1380:       if (try_agent_authentication())
                   1381:        return; /* Successful connection. */
                   1382:
                   1383:       /* Try RSA authentication for each identity. */
                   1384:       for (i = 0; i < options->num_identity_files; i++)
                   1385:        if (try_rsa_authentication(pw, options->identity_files[i],
                   1386:                                   !options->batch_mode))
                   1387:          return; /* Successful connection. */
                   1388:     }
                   1389:
                   1390:   /* Try password authentication if the server supports it. */
                   1391:   if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
                   1392:       options->password_authentication && !options->batch_mode)
                   1393:     {
                   1394:       debug("Doing password authentication.");
                   1395:       if (options->cipher == SSH_CIPHER_NONE)
                   1396:        log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
                   1397:       password = read_passphrase("Password: ", 0);
                   1398:       packet_start(SSH_CMSG_AUTH_PASSWORD);
                   1399:       packet_put_string(password, strlen(password));
                   1400:       memset(password, 0, strlen(password));
                   1401:       xfree(password);
                   1402:       packet_send();
                   1403:       packet_write_wait();
                   1404:
                   1405:       type = packet_read(&payload_len);
                   1406:       if (type == SSH_SMSG_SUCCESS)
                   1407:        return; /* Successful connection. */
                   1408:       if (type != SSH_SMSG_FAILURE)
                   1409:        packet_disconnect("Protocol error: got %d in response to passwd auth",
                   1410:                          type);
                   1411:     }
                   1412:
                   1413:   /* All authentication methods have failed.  Exit with an error message. */
                   1414:   fatal("Permission denied.");
                   1415:   /*NOTREACHED*/
                   1416: }