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

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