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

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