2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Created: Sat Mar 18 22:15:47 1995 ylo
6 * Code to connect to a remote host, and to perform the client side of the
7 * login (authentication) dialog.
14 #include <openssl/bn.h>
15 #include <openssl/md5.h>
32 #include "fingerprint.h"
34 /* Session id for the current session. */
35 unsigned char session_id[16];
37 extern Options options;
38 extern char *__progname;
41 * Connect to the given ssh server using a proxy command.
44 ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
45 const char *proxy_command)
52 char strport[NI_MAXSERV];
54 /* Convert the port number into a string. */
55 snprintf(strport, sizeof strport, "%hu", port);
57 /* Build the final command string in the buffer by making the
58 appropriate substitutions to the given proxy command. */
59 buffer_init(&command);
60 for (cp = proxy_command; *cp; cp++) {
61 if (cp[0] == '%' && cp[1] == '%') {
62 buffer_append(&command, "%", 1);
66 if (cp[0] == '%' && cp[1] == 'h') {
67 buffer_append(&command, host, strlen(host));
71 if (cp[0] == '%' && cp[1] == 'p') {
72 buffer_append(&command, strport, strlen(strport));
76 buffer_append(&command, cp, 1);
78 buffer_append(&command, "\0", 1);
80 /* Get the final command string. */
81 command_string = buffer_ptr(&command);
83 /* Create pipes for communicating with the proxy. */
84 if (pipe(pin) < 0 || pipe(pout) < 0)
85 fatal("Could not create pipes to communicate with the proxy: %.100s",
88 debug("Executing proxy command: %.500s", command_string);
90 /* Fork and execute the proxy command. */
91 if ((pid = fork()) == 0) {
94 /* Child. Permanently give up superuser privileges. */
95 permanently_set_uid(original_real_uid);
97 /* Redirect stdin and stdout. */
100 if (dup2(pin[0], 0) < 0)
101 perror("dup2 stdin");
105 if (dup2(pout[1], 1) < 0)
106 perror("dup2 stdout");
107 /* Cannot be 1 because pin allocated two descriptors. */
110 /* Stderr is left as it is so that error messages get
111 printed on the user's terminal. */
114 argv[2] = command_string;
117 /* Execute the proxy command. Note that we gave up any
118 extra privileges above. */
119 execv("/bin/sh", argv);
125 fatal("fork failed: %.100s", strerror(errno));
127 /* Close child side of the descriptors. */
131 /* Free the command name. */
132 buffer_free(&command);
134 /* Set the connection file descriptors. */
135 packet_set_connection(pout[0], pin[1]);
141 * Creates a (possibly privileged) socket for use as the ssh connection.
144 ssh_create_socket(uid_t original_real_uid, int privileged, int family)
149 * If we are running as root and want to connect to a privileged
150 * port, bind our own socket to a privileged port.
153 int p = IPPORT_RESERVED - 1;
154 sock = rresvport_af(&p, family);
156 fatal("rresvport: af=%d %.100s", family, strerror(errno));
157 debug("Allocated local port %d.", p);
160 * Just create an ordinary socket on arbitrary port. We use
161 * the user's uid to create the socket.
163 temporarily_use_uid(original_real_uid);
164 sock = socket(family, SOCK_STREAM, 0);
166 error("socket: %.100s", strerror(errno));
173 * Opens a TCP/IP connection to the remote server on the given host.
174 * The address of the remote host will be returned in hostaddr.
175 * If port is 0, the default port will be used. If anonymous is zero,
176 * a privileged port will be allocated to make the connection.
177 * This requires super-user privileges if anonymous is false.
178 * Connection_attempts specifies the maximum number of tries (one per
179 * second). If proxy_command is non-NULL, it specifies the command (with %h
180 * and %p substituted for host and port, respectively) to use to contact
184 ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
185 u_short port, int connection_attempts,
186 int anonymous, uid_t original_real_uid,
187 const char *proxy_command)
189 int sock = -1, attempt;
191 struct addrinfo hints, *ai, *aitop;
192 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
194 struct linger linger;
196 debug("ssh_connect: getuid %d geteuid %d anon %d",
197 (int) getuid(), (int) geteuid(), anonymous);
199 /* Get default port if port has not been set. */
201 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
203 port = ntohs(sp->s_port);
205 port = SSH_DEFAULT_PORT;
207 /* If a proxy command is given, connect using it. */
208 if (proxy_command != NULL)
209 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
211 /* No proxy command. */
213 memset(&hints, 0, sizeof(hints));
214 hints.ai_family = IPv4or6;
215 hints.ai_socktype = SOCK_STREAM;
216 snprintf(strport, sizeof strport, "%d", port);
217 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
218 fatal("%s: %.100s: %s", __progname, host,
219 gai_strerror(gaierr));
222 * Try to connect several times. On some machines, the first time
223 * will sometimes fail. In general socket code appears to behave
224 * quite magically on many machines.
226 for (attempt = 0; attempt < connection_attempts; attempt++) {
228 debug("Trying again...");
230 /* Loop through addresses for this host, and try each one in
231 sequence until the connection succeeds. */
232 for (ai = aitop; ai; ai = ai->ai_next) {
233 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
235 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
236 ntop, sizeof(ntop), strport, sizeof(strport),
237 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
238 error("ssh_connect: getnameinfo failed");
241 debug("Connecting to %.200s [%.100s] port %s.",
242 host, ntop, strport);
244 /* Create a socket for connecting. */
245 sock = ssh_create_socket(original_real_uid,
246 !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
251 /* Connect to the host. We use the user's uid in the
252 * hope that it will help with tcp_wrappers showing
253 * the remote uid as root.
255 temporarily_use_uid(original_real_uid);
256 if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
257 /* Successful connection. */
258 memcpy(hostaddr, ai->ai_addr, sizeof(*(ai->ai_addr)));
262 debug("connect: %.100s", strerror(errno));
265 * Close the failed socket; there appear to
266 * be some problems when reusing a socket for
267 * which connect() has already returned an
270 shutdown(sock, SHUT_RDWR);
275 break; /* Successful connection. */
277 /* Sleep a moment before retrying. */
283 /* Return failure if we didn't get a successful connection. */
284 if (attempt >= connection_attempts)
287 debug("Connection established.");
290 * Set socket options. We would like the socket to disappear as soon
291 * as it has been closed for whatever reason.
293 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
296 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
298 /* Set the connection. */
299 packet_set_connection(sock, sock);
305 * Checks if the user has an authentication agent, and if so, tries to
306 * authenticate using the agent.
309 try_agent_authentication()
313 AuthenticationConnection *auth;
314 unsigned char response[16];
316 BIGNUM *e, *n, *challenge;
318 /* Get connection to the agent. */
319 auth = ssh_get_authentication_connection();
325 challenge = BN_new();
327 /* Loop through identities served by the agent. */
328 for (status = ssh_get_first_identity(auth, e, n, &comment);
330 status = ssh_get_next_identity(auth, e, n, &comment)) {
333 /* Try this identity. */
334 debug("Trying RSA authentication via agent with '%.100s'", comment);
337 /* Tell the server that we are willing to authenticate using this key. */
338 packet_start(SSH_CMSG_AUTH_RSA);
339 packet_put_bignum(n);
343 /* Wait for server's response. */
344 type = packet_read(&plen);
346 /* The server sends failure if it doesn\'t like our key or
347 does not support RSA authentication. */
348 if (type == SSH_SMSG_FAILURE) {
349 debug("Server refused our key.");
352 /* Otherwise it should have sent a challenge. */
353 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
354 packet_disconnect("Protocol error during RSA authentication: %d",
357 packet_get_bignum(challenge, &clen);
359 packet_integrity_check(plen, clen, type);
361 debug("Received RSA challenge from server.");
363 /* Ask the agent to decrypt the challenge. */
364 if (!ssh_decrypt_challenge(auth, e, n, challenge,
365 session_id, 1, response)) {
366 /* The agent failed to authenticate this identifier although it
367 advertised it supports this. Just return a wrong value. */
368 log("Authentication agent failed to decrypt challenge.");
369 memset(response, 0, sizeof(response));
371 debug("Sending response to RSA challenge.");
373 /* Send the decrypted challenge back to the server. */
374 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
375 for (i = 0; i < 16; i++)
376 packet_put_char(response[i]);
380 /* Wait for response from the server. */
381 type = packet_read(&plen);
383 /* The server returns success if it accepted the authentication. */
384 if (type == SSH_SMSG_SUCCESS) {
385 debug("RSA authentication accepted by server.");
388 BN_clear_free(challenge);
391 /* Otherwise it should return failure. */
392 if (type != SSH_SMSG_FAILURE)
393 packet_disconnect("Protocol error waiting RSA auth response: %d",
399 BN_clear_free(challenge);
401 debug("RSA authentication using agent refused.");
406 * Computes the proper response to a RSA challenge, and sends the response to
410 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
412 unsigned char buf[32], response[16];
416 /* Decrypt the challenge using the private key. */
417 rsa_private_decrypt(challenge, challenge, prv);
419 /* Compute the response. */
420 /* The response is MD5 of decrypted challenge plus session id. */
421 len = BN_num_bytes(challenge);
422 if (len <= 0 || len > sizeof(buf))
423 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
426 memset(buf, 0, sizeof(buf));
427 BN_bn2bin(challenge, buf + sizeof(buf) - len);
429 MD5_Update(&md, buf, 32);
430 MD5_Update(&md, session_id, 16);
431 MD5_Final(response, &md);
433 debug("Sending response to host key RSA challenge.");
435 /* Send the response back to the server. */
436 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
437 for (i = 0; i < 16; i++)
438 packet_put_char(response[i]);
442 memset(buf, 0, sizeof(buf));
443 memset(response, 0, sizeof(response));
444 memset(&md, 0, sizeof(md));
448 * Checks if the user has authentication file, and if so, tries to authenticate
452 try_rsa_authentication(const char *authfile)
457 char *passphrase, *comment;
461 /* Try to load identification for the authentication key. */
462 public_key = RSA_new();
463 if (!load_public_key(authfile, public_key, &comment)) {
464 RSA_free(public_key);
465 /* Could not load it. Fail. */
468 debug("Trying RSA authentication with key '%.100s'", comment);
470 /* Tell the server that we are willing to authenticate using this key. */
471 packet_start(SSH_CMSG_AUTH_RSA);
472 packet_put_bignum(public_key->n);
476 /* We no longer need the public key. */
477 RSA_free(public_key);
479 /* Wait for server's response. */
480 type = packet_read(&plen);
483 * The server responds with failure if it doesn\'t like our key or
484 * doesn\'t support RSA authentication.
486 if (type == SSH_SMSG_FAILURE) {
487 debug("Server refused our key.");
491 /* Otherwise, the server should respond with a challenge. */
492 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
493 packet_disconnect("Protocol error during RSA authentication: %d", type);
495 /* Get the challenge from the packet. */
496 challenge = BN_new();
497 packet_get_bignum(challenge, &clen);
499 packet_integrity_check(plen, clen, type);
501 debug("Received RSA challenge from server.");
503 private_key = RSA_new();
505 * Load the private key. Try first with empty passphrase; if it
506 * fails, ask for a passphrase.
508 if (!load_private_key(authfile, "", private_key, NULL)) {
510 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
512 if (!options.batch_mode)
513 passphrase = read_passphrase(buf, 0);
515 debug("Will not query passphrase for %.100s in batch mode.",
517 passphrase = xstrdup("");
520 /* Load the authentication file using the pasphrase. */
521 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
522 memset(passphrase, 0, strlen(passphrase));
524 error("Bad passphrase.");
526 /* Send a dummy response packet to avoid protocol error. */
527 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
528 for (i = 0; i < 16; i++)
533 /* Expect the server to reject it... */
534 packet_read_expect(&plen, SSH_SMSG_FAILURE);
538 /* Destroy the passphrase. */
539 memset(passphrase, 0, strlen(passphrase));
542 /* We no longer need the comment. */
545 /* Compute and send a response to the challenge. */
546 respond_to_rsa_challenge(challenge, private_key);
548 /* Destroy the private key. */
549 RSA_free(private_key);
551 /* We no longer need the challenge. */
552 BN_clear_free(challenge);
554 /* Wait for response from the server. */
555 type = packet_read(&plen);
556 if (type == SSH_SMSG_SUCCESS) {
557 debug("RSA authentication accepted by server.");
560 if (type != SSH_SMSG_FAILURE)
561 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
562 debug("RSA authentication refused.");
567 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
568 * authentication and RSA host authentication.
571 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
577 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
579 /* Tell the server that we are willing to authenticate using this key. */
580 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
581 packet_put_string(local_user, strlen(local_user));
582 packet_put_int(BN_num_bits(host_key->n));
583 packet_put_bignum(host_key->e);
584 packet_put_bignum(host_key->n);
588 /* Wait for server's response. */
589 type = packet_read(&plen);
591 /* The server responds with failure if it doesn't admit our
592 .rhosts authentication or doesn't know our host key. */
593 if (type == SSH_SMSG_FAILURE) {
594 debug("Server refused our rhosts authentication or host key.");
597 /* Otherwise, the server should respond with a challenge. */
598 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
599 packet_disconnect("Protocol error during RSA authentication: %d", type);
601 /* Get the challenge from the packet. */
602 challenge = BN_new();
603 packet_get_bignum(challenge, &clen);
605 packet_integrity_check(plen, clen, type);
607 debug("Received RSA challenge for host key from server.");
609 /* Compute a response to the challenge. */
610 respond_to_rsa_challenge(challenge, host_key);
612 /* We no longer need the challenge. */
613 BN_clear_free(challenge);
615 /* Wait for response from the server. */
616 type = packet_read(&plen);
617 if (type == SSH_SMSG_SUCCESS) {
618 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
621 if (type != SSH_SMSG_FAILURE)
622 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
623 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
629 try_kerberos_authentication()
631 KTEXT_ST auth; /* Kerberos data */
637 Key_schedule schedule;
638 u_long checksum, cksum;
640 struct sockaddr_in local, foreign;
643 /* Don't do anything if we don't have any tickets. */
644 if (stat(tkt_string(), &st) < 0)
647 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
649 realm = (char *) krb_realmofhost(get_canonical_hostname());
651 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
654 /* This can really be anything. */
655 checksum = (u_long) getpid();
657 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
659 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
662 /* Get session key to decrypt the server's reply with. */
663 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
665 debug("get_cred failed: %s", krb_err_txt[r]);
668 des_key_sched((des_cblock *) cred.session, schedule);
670 /* Send authentication info to server. */
671 packet_start(SSH_CMSG_AUTH_KERBEROS);
672 packet_put_string((char *) auth.dat, auth.length);
676 /* Zero the buffer. */
677 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
680 memset(&local, 0, sizeof(local));
681 if (getsockname(packet_get_connection_in(),
682 (struct sockaddr *) & local, &r) < 0)
683 debug("getsockname failed: %s", strerror(errno));
686 memset(&foreign, 0, sizeof(foreign));
687 if (getpeername(packet_get_connection_in(),
688 (struct sockaddr *) & foreign, &r) < 0) {
689 debug("getpeername failed: %s", strerror(errno));
692 /* Get server reply. */
693 type = packet_read(&plen);
695 case SSH_SMSG_FAILURE:
696 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
697 debug("Kerberos V4 authentication failed.");
701 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
702 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
703 debug("Kerberos V4 authentication accepted.");
705 /* Get server's response. */
706 reply = packet_get_string((unsigned int *) &auth.length);
707 memcpy(auth.dat, reply, auth.length);
710 packet_integrity_check(plen, 4 + auth.length, type);
713 * If his response isn't properly encrypted with the session
714 * key, and the decrypted checksum fails to match, he's
717 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
718 &foreign, &local, &msg_data);
720 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
721 packet_disconnect("Kerberos V4 challenge failed!");
723 /* Fetch the (incremented) checksum that we supplied in the request. */
724 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
725 cksum = ntohl(cksum);
727 /* If it matches, we're golden. */
728 if (cksum == checksum + 1) {
729 debug("Kerberos V4 challenge successful.");
732 packet_disconnect("Kerberos V4 challenge failed!");
736 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
748 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
750 unsigned char buffer[8192];
753 /* Don't do anything if we don't have any tickets. */
754 if (stat(tkt_string(), &st) < 0)
757 creds = xmalloc(sizeof(*creds));
759 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
760 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
763 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
764 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
767 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
768 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
771 creds_to_radix(creds, buffer);
774 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
775 packet_put_string((char *) buffer, strlen(buffer));
779 type = packet_read(&plen);
781 if (type == SSH_SMSG_FAILURE)
782 debug("Kerberos TGT for realm %s rejected.", prealm);
783 else if (type != SSH_SMSG_SUCCESS)
784 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
790 send_afs_tokens(void)
793 struct ViceIoctl parms;
794 struct ClearToken ct;
795 int i, type, len, plen;
796 char buf[2048], *p, *server_cell;
797 unsigned char buffer[8192];
799 /* Move over ktc_GetToken, here's something leaner. */
800 for (i = 0; i < 100; i++) { /* just in case */
801 parms.in = (char *) &i;
802 parms.in_size = sizeof(i);
804 parms.out_size = sizeof(buf);
805 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
809 /* Get secret token. */
810 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
811 if (creds.ticket_st.length > MAX_KTXT_LEN)
813 p += sizeof(unsigned int);
814 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
815 p += creds.ticket_st.length;
817 /* Get clear token. */
818 memcpy(&len, p, sizeof(len));
819 if (len != sizeof(struct ClearToken))
824 p += sizeof(len); /* primary flag */
827 /* Flesh out our credentials. */
828 strlcpy(creds.service, "afs", sizeof creds.service);
829 creds.instance[0] = '\0';
830 strlcpy(creds.realm, server_cell, REALM_SZ);
831 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
832 creds.issue_date = ct.BeginTimestamp;
833 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
834 creds.kvno = ct.AuthHandle;
835 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
836 creds.pinst[0] = '\0';
838 /* Encode token, ship it off. */
839 if (!creds_to_radix(&creds, buffer))
841 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
842 packet_put_string((char *) buffer, strlen(buffer));
846 /* Roger, Roger. Clearance, Clarence. What's your vector,
848 type = packet_read(&plen);
850 if (type == SSH_SMSG_FAILURE)
851 debug("AFS token for cell %s rejected.", server_cell);
852 else if (type != SSH_SMSG_SUCCESS)
853 packet_disconnect("Protocol error on AFS token response: %d", type);
860 * Tries to authenticate with any string-based challenge/response system.
861 * Note that the client code is not tied to s/key or TIS.
864 try_skey_authentication()
866 int type, i, payload_len;
867 char *challenge, *response;
869 debug("Doing skey authentication.");
871 /* request a challenge */
872 packet_start(SSH_CMSG_AUTH_TIS);
876 type = packet_read(&payload_len);
877 if (type != SSH_SMSG_FAILURE &&
878 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
879 packet_disconnect("Protocol error: got %d in response "
880 "to skey-auth", type);
882 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
883 debug("No challenge for skey authentication.");
886 challenge = packet_get_string(&payload_len);
887 if (options.cipher == SSH_CIPHER_NONE)
888 log("WARNING: Encryption is disabled! "
889 "Reponse will be transmitted in clear text.");
890 fprintf(stderr, "%s\n", challenge);
892 for (i = 0; i < options.number_of_password_prompts; i++) {
894 error("Permission denied, please try again.");
895 response = read_passphrase("Response: ", 0);
896 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
897 packet_put_string(response, strlen(response));
898 memset(response, 0, strlen(response));
902 type = packet_read(&payload_len);
903 if (type == SSH_SMSG_SUCCESS)
905 if (type != SSH_SMSG_FAILURE)
906 packet_disconnect("Protocol error: got %d in response "
907 "to skey-auth-reponse", type);
914 * Tries to authenticate with plain passwd authentication.
917 try_password_authentication(char *prompt)
919 int type, i, payload_len;
922 debug("Doing password authentication.");
923 if (options.cipher == SSH_CIPHER_NONE)
924 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
925 for (i = 0; i < options.number_of_password_prompts; i++) {
927 error("Permission denied, please try again.");
928 password = read_passphrase(prompt, 0);
929 packet_start(SSH_CMSG_AUTH_PASSWORD);
930 packet_put_string(password, strlen(password));
931 memset(password, 0, strlen(password));
936 type = packet_read(&payload_len);
937 if (type == SSH_SMSG_SUCCESS)
939 if (type != SSH_SMSG_FAILURE)
940 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
947 * Waits for the server identification string, and sends our own
948 * identification string.
951 ssh_exchange_identification()
953 char buf[256], remote_version[256]; /* must be same size! */
954 int remote_major, remote_minor, i;
955 int connection_in = packet_get_connection_in();
956 int connection_out = packet_get_connection_out();
958 /* Read other side\'s version identification. */
959 for (i = 0; i < sizeof(buf) - 1; i++) {
960 if (read(connection_in, &buf[i], 1) != 1)
961 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
962 if (buf[i] == '\r') {
967 if (buf[i] == '\n') {
972 buf[sizeof(buf) - 1] = 0;
975 * Check that the versions match. In future this might accept
976 * several versions and set appropriate flags to handle them.
978 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
979 remote_version) != 3)
980 fatal("Bad remote protocol version identification: '%.100s'", buf);
981 debug("Remote protocol version %d.%d, remote software version %.100s",
982 remote_major, remote_minor, remote_version);
984 /* Check if the remote protocol version is too old. */
985 if (remote_major == 1 && remote_minor < 3)
986 fatal("Remote machine has too old SSH software version.");
988 /* We speak 1.3, too. */
989 if (remote_major == 1 && remote_minor == 3) {
991 if (options.forward_agent && strcmp(remote_version, "OpenSSH-1.1") != 0) {
992 log("Agent forwarding disabled, remote version '%s' is not compatible.",
994 options.forward_agent = 0;
999 * Removed for now, to permit compatibility with latter versions. The
1000 * server will reject our version and disconnect if it doesn't
1003 if (remote_major != PROTOCOL_MAJOR)
1004 fatal("Protocol major versions differ: %d vs. %d",
1005 PROTOCOL_MAJOR, remote_major);
1008 /* Send our own protocol version identification. */
1009 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1010 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1011 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1012 fatal("write: %.100s", strerror(errno));
1015 int ssh_cipher_default = SSH_CIPHER_3DES;
1018 read_yes_or_no(const char *prompt, int defval)
1027 f = fopen("/dev/tty", "rw");
1035 fprintf(stderr, "%s", prompt);
1036 if (fgets(buf, sizeof(buf), f) == NULL) {
1037 /* Print a newline (the prompt probably didn\'t have one). */
1038 fprintf(stderr, "\n");
1039 strlcpy(buf, "no", sizeof buf);
1041 /* Remove newline from response. */
1042 if (strchr(buf, '\n'))
1043 *strchr(buf, '\n') = 0;
1047 if (strcmp(buf, "yes") == 0)
1049 if (strcmp(buf, "no") == 0)
1061 * check whether the supplied host key is valid, return only if ok.
1065 check_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1069 char hostline[1000], *hostp;
1070 HostStatus host_status;
1071 HostStatus ip_status;
1072 int local = 0, host_ip_differ = 0;
1074 char ntop[NI_MAXHOST];
1077 * Force accepting of the host key for loopback/localhost. The
1078 * problem is that if the home directory is NFS-mounted to multiple
1079 * machines, localhost will refer to a different machine in each of
1080 * them, and the user will get bogus HOST_CHANGED warnings. This
1081 * essentially disables host authentication for localhost; however,
1082 * this is probably not a real problem.
1084 switch (hostaddr->sa_family) {
1086 local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1087 salen = sizeof(struct sockaddr_in);
1090 local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
1091 salen = sizeof(struct sockaddr_in6);
1095 salen = sizeof(struct sockaddr_storage);
1099 debug("Forcing accepting of host key for loopback/localhost.");
1104 * Turn off check_host_ip for proxy connects, since
1105 * we don't have the remote ip-address
1107 if (options.proxy_command != NULL && options.check_host_ip)
1108 options.check_host_ip = 0;
1110 if (options.check_host_ip) {
1111 if (getnameinfo(hostaddr, salen, ntop, sizeof(ntop),
1112 NULL, 0, NI_NUMERICHOST) != 0)
1113 fatal("check_host_key: getnameinfo failed");
1118 * Store the host key from the known host file in here so that we can
1119 * compare it with the key for the IP address.
1121 file_key = RSA_new();
1122 file_key->n = BN_new();
1123 file_key->e = BN_new();
1126 * Check if the host key is present in the user\'s list of known
1127 * hosts or in the systemwide list.
1129 host_status = check_host_in_hostfile(options.user_hostfile, host,
1130 host_key->e, host_key->n,
1131 file_key->e, file_key->n);
1132 if (host_status == HOST_NEW)
1133 host_status = check_host_in_hostfile(options.system_hostfile, host,
1134 host_key->e, host_key->n,
1135 file_key->e, file_key->n);
1137 * Also perform check for the ip address, skip the check if we are
1138 * localhost or the hostname was an ip address to begin with
1140 if (options.check_host_ip && !local && strcmp(host, ip)) {
1141 RSA *ip_key = RSA_new();
1142 ip_key->n = BN_new();
1143 ip_key->e = BN_new();
1144 ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1145 host_key->e, host_key->n,
1146 ip_key->e, ip_key->n);
1148 if (ip_status == HOST_NEW)
1149 ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1150 host_key->e, host_key->n,
1151 ip_key->e, ip_key->n);
1152 if (host_status == HOST_CHANGED &&
1153 (ip_status != HOST_CHANGED ||
1154 (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1159 ip_status = host_status;
1163 switch (host_status) {
1165 /* The host is known and the key matches. */
1166 debug("Host '%.200s' is known and matches the host key.", host);
1167 if (options.check_host_ip) {
1168 if (ip_status == HOST_NEW) {
1169 if (!add_host_to_hostfile(options.user_hostfile, ip,
1170 host_key->e, host_key->n))
1171 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1172 ip, options.user_hostfile);
1174 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1176 } else if (ip_status != HOST_OK)
1177 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1182 /* The host is new. */
1183 if (options.strict_host_key_checking == 1) {
1184 /* User has requested strict host key checking. We will not add the host key
1185 automatically. The only alternative left is to abort. */
1186 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1187 } else if (options.strict_host_key_checking == 2) {
1190 char *fp = fingerprint(host_key->e, host_key->n);
1191 snprintf(prompt, sizeof(prompt),
1192 "The authenticity of host '%.200s' can't be established.\n"
1193 "Key fingerprint is %d %s.\n"
1194 "Are you sure you want to continue connecting (yes/no)? ",
1195 host, BN_num_bits(host_key->n), fp);
1196 if (!read_yes_or_no(prompt, -1))
1197 fatal("Aborted by user!\n");
1199 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1200 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1205 /* If not in strict mode, add the key automatically to the local known_hosts file. */
1206 if (!add_host_to_hostfile(options.user_hostfile, hostp,
1207 host_key->e, host_key->n))
1208 log("Failed to add the host to the list of known hosts (%.500s).",
1209 options.user_hostfile);
1211 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1215 if (options.check_host_ip && host_ip_differ) {
1217 if (ip_status == HOST_NEW)
1219 else if (ip_status == HOST_OK)
1220 msg = "is unchanged";
1222 msg = "has a different value";
1223 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1224 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1225 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1226 error("The host key for %s has changed,", host);
1227 error("and the key for the according IP address %s", ip);
1228 error("%s. This could either mean that", msg);
1229 error("DNS SPOOFING is happening or the IP address for the host");
1230 error("and its host key have changed at the same time");
1232 /* The host key has changed. */
1233 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1234 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1235 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1236 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1237 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1238 error("It is also possible that the host key has just been changed.");
1239 error("Please contact your system administrator.");
1240 error("Add correct host key in %.100s to get rid of this message.",
1241 options.user_hostfile);
1244 * If strict host key checking is in use, the user will have
1245 * to edit the key manually and we can only abort.
1247 if (options.strict_host_key_checking)
1248 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1251 * If strict host key checking has not been requested, allow
1252 * the connection but without password authentication or
1255 if (options.password_authentication) {
1256 error("Password authentication is disabled to avoid trojan horses.");
1257 options.password_authentication = 0;
1259 if (options.forward_agent) {
1260 error("Agent forwarding is disabled to avoid trojan horses.");
1261 options.forward_agent = 0;
1264 * XXX Should permit the user to change to use the new id.
1265 * This could be done by converting the host key to an
1266 * identifying sentence, tell that the host identifies itself
1267 * by that sentence, and ask the user if he/she whishes to
1268 * accept the authentication.
1272 if (options.check_host_ip)
1277 * Starts a dialog with the server, and authenticates the current user on the
1278 * server. This does not need any extra privileges. The basic connection
1279 * to the server must already have been established before this is called.
1280 * User is the remote user; if it is NULL, the current local user name will
1281 * be used. Anonymous indicates that no rhosts authentication will be used.
1282 * If login fails, this function prints an error and never returns.
1283 * This function does not require super-user privileges.
1286 ssh_login(int host_key_valid,
1288 const char *orighost,
1289 struct sockaddr *hostaddr,
1290 uid_t original_real_uid)
1298 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1299 const char *server_user, *local_user;
1301 unsigned char check_bytes[8];
1302 unsigned int supported_ciphers, supported_authentications;
1303 unsigned int server_flags, client_flags;
1304 int payload_len, clen, sum_len = 0;
1307 /* Convert the user-supplied hostname into all lowercase. */
1308 host = xstrdup(orighost);
1309 for (cp = host; *cp; cp++)
1313 /* Exchange protocol version identification strings with the server. */
1314 ssh_exchange_identification();
1316 /* Put the connection into non-blocking mode. */
1317 packet_set_nonblocking();
1319 /* Get local user name. Use it as server user if no user name was given. */
1320 pw = getpwuid(original_real_uid);
1322 fatal("User id %d not found from user database.", original_real_uid);
1323 local_user = xstrdup(pw->pw_name);
1324 server_user = options.user ? options.user : local_user;
1326 debug("Waiting for server public key.");
1328 /* Wait for a public key packet from the server. */
1329 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1331 /* Get check bytes from the packet. */
1332 for (i = 0; i < 8; i++)
1333 check_bytes[i] = packet_get_char();
1335 /* Get the public key. */
1336 public_key = RSA_new();
1337 bits = packet_get_int();/* bits */
1338 public_key->e = BN_new();
1339 packet_get_bignum(public_key->e, &clen);
1341 public_key->n = BN_new();
1342 packet_get_bignum(public_key->n, &clen);
1345 rbits = BN_num_bits(public_key->n);
1346 if (bits != rbits) {
1347 log("Warning: Server lies about size of server public key: "
1348 "actual size is %d bits vs. announced %d.", rbits, bits);
1349 log("Warning: This may be due to an old implementation of ssh.");
1351 /* Get the host key. */
1352 host_key = RSA_new();
1353 bits = packet_get_int();/* bits */
1354 host_key->e = BN_new();
1355 packet_get_bignum(host_key->e, &clen);
1357 host_key->n = BN_new();
1358 packet_get_bignum(host_key->n, &clen);
1361 rbits = BN_num_bits(host_key->n);
1362 if (bits != rbits) {
1363 log("Warning: Server lies about size of server host key: "
1364 "actual size is %d bits vs. announced %d.", rbits, bits);
1365 log("Warning: This may be due to an old implementation of ssh.");
1368 /* Get protocol flags. */
1369 server_flags = packet_get_int();
1370 packet_set_protocol_flags(server_flags);
1372 supported_ciphers = packet_get_int();
1373 supported_authentications = packet_get_int();
1375 debug("Received server public key (%d bits) and host key (%d bits).",
1376 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1378 packet_integrity_check(payload_len,
1379 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1380 SSH_SMSG_PUBLIC_KEY);
1382 check_host_key(host, hostaddr, host_key);
1384 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1386 compute_session_id(session_id, check_bytes, host_key->n, public_key->n);
1388 /* Generate a session key. */
1392 * Generate an encryption key for the session. The key is a 256 bit
1393 * random number, interpreted as a 32-byte key, with the least
1394 * significant 8 bits being the first byte of the key.
1396 for (i = 0; i < 32; i++) {
1398 rand = arc4random();
1399 session_key[i] = rand & 0xff;
1404 * According to the protocol spec, the first byte of the session key
1405 * is the highest byte of the integer. The session key is xored with
1406 * the first 16 bytes of the session id.
1409 BN_set_word(key, 0);
1410 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1411 BN_lshift(key, key, 8);
1413 BN_add_word(key, session_key[i] ^ session_id[i]);
1415 BN_add_word(key, session_key[i]);
1419 * Encrypt the integer using the public key and host key of the
1420 * server (key with smaller modulus first).
1422 if (BN_cmp(public_key->n, host_key->n) < 0) {
1423 /* Public key has smaller modulus. */
1424 if (BN_num_bits(host_key->n) <
1425 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1426 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1427 "SSH_KEY_BITS_RESERVED %d",
1428 BN_num_bits(host_key->n),
1429 BN_num_bits(public_key->n),
1430 SSH_KEY_BITS_RESERVED);
1432 rsa_public_encrypt(key, key, public_key);
1433 rsa_public_encrypt(key, key, host_key);
1435 /* Host key has smaller modulus (or they are equal). */
1436 if (BN_num_bits(public_key->n) <
1437 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1438 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1439 "SSH_KEY_BITS_RESERVED %d",
1440 BN_num_bits(public_key->n),
1441 BN_num_bits(host_key->n),
1442 SSH_KEY_BITS_RESERVED);
1444 rsa_public_encrypt(key, key, host_key);
1445 rsa_public_encrypt(key, key, public_key);
1448 if (options.cipher == SSH_CIPHER_NOT_SET) {
1449 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1450 options.cipher = ssh_cipher_default;
1452 debug("Cipher %s not supported, using %.100s instead.",
1453 cipher_name(ssh_cipher_default),
1454 cipher_name(SSH_FALLBACK_CIPHER));
1455 options.cipher = SSH_FALLBACK_CIPHER;
1458 /* Check that the selected cipher is supported. */
1459 if (!(supported_ciphers & (1 << options.cipher)))
1460 fatal("Selected cipher type %.100s not supported by server.",
1461 cipher_name(options.cipher));
1463 debug("Encryption type: %.100s", cipher_name(options.cipher));
1465 /* Send the encrypted session key to the server. */
1466 packet_start(SSH_CMSG_SESSION_KEY);
1467 packet_put_char(options.cipher);
1469 /* Send the check bytes back to the server. */
1470 for (i = 0; i < 8; i++)
1471 packet_put_char(check_bytes[i]);
1473 /* Send the encrypted encryption key. */
1474 packet_put_bignum(key);
1476 /* Send protocol flags. */
1477 packet_put_int(client_flags);
1479 /* Send the packet now. */
1481 packet_write_wait();
1483 /* Destroy the session key integer and the public keys since we no longer need them. */
1485 RSA_free(public_key);
1488 debug("Sent encrypted session key.");
1490 /* Set the encryption key. */
1491 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1493 /* We will no longer need the session key here. Destroy any extra copies. */
1494 memset(session_key, 0, sizeof(session_key));
1497 * Expect a success message from the server. Note that this message
1498 * will be received in encrypted form.
1500 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1502 debug("Received encrypted confirmation.");
1504 /* Send the name of the user to log in as on the server. */
1505 packet_start(SSH_CMSG_USER);
1506 packet_put_string(server_user, strlen(server_user));
1508 packet_write_wait();
1511 * The server should respond with success if no authentication is
1512 * needed (the user has no password). Otherwise the server responds
1515 type = packet_read(&payload_len);
1517 /* check whether the connection was accepted without authentication. */
1518 if (type == SSH_SMSG_SUCCESS)
1520 if (type != SSH_SMSG_FAILURE)
1521 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1525 /* Try Kerberos tgt passing if the server supports it. */
1526 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1527 options.kerberos_tgt_passing) {
1528 if (options.cipher == SSH_CIPHER_NONE)
1529 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1530 (void) send_kerberos_tgt();
1532 /* Try AFS token passing if the server supports it. */
1533 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1534 options.afs_token_passing && k_hasafs()) {
1535 if (options.cipher == SSH_CIPHER_NONE)
1536 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1542 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1543 options.kerberos_authentication) {
1544 debug("Trying Kerberos authentication.");
1545 if (try_kerberos_authentication()) {
1546 /* The server should respond with success or failure. */
1547 type = packet_read(&payload_len);
1548 if (type == SSH_SMSG_SUCCESS)
1550 if (type != SSH_SMSG_FAILURE)
1551 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1557 * Use rhosts authentication if running in privileged socket and we
1558 * do not wish to remain anonymous.
1560 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1561 options.rhosts_authentication) {
1562 debug("Trying rhosts authentication.");
1563 packet_start(SSH_CMSG_AUTH_RHOSTS);
1564 packet_put_string(local_user, strlen(local_user));
1566 packet_write_wait();
1568 /* The server should respond with success or failure. */
1569 type = packet_read(&payload_len);
1570 if (type == SSH_SMSG_SUCCESS)
1572 if (type != SSH_SMSG_FAILURE)
1573 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1577 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1580 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1581 options.rhosts_rsa_authentication && host_key_valid) {
1582 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1585 /* Try RSA authentication if the server supports it. */
1586 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1587 options.rsa_authentication) {
1589 * Try RSA authentication using the authentication agent. The
1590 * agent is tried first because no passphrase is needed for
1591 * it, whereas identity files may require passphrases.
1593 if (try_agent_authentication())
1596 /* Try RSA authentication for each identity. */
1597 for (i = 0; i < options.num_identity_files; i++)
1598 if (try_rsa_authentication(options.identity_files[i]))
1601 /* Try skey authentication if the server supports it. */
1602 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1603 options.skey_authentication && !options.batch_mode) {
1604 if (try_skey_authentication())
1607 /* Try password authentication if the server supports it. */
1608 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1609 options.password_authentication && !options.batch_mode) {
1612 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1614 if (try_password_authentication(prompt))
1617 /* All authentication methods have failed. Exit with an error message. */
1618 fatal("Permission denied.");