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

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