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

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