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.
11 RCSID("$OpenBSD: sshconnect.c,v 1.53 2000/01/18 09:42:17 markus Exp $");
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 /* authentications supported by server */
38 unsigned int supported_authentications;
40 extern Options options;
41 extern char *__progname;
44 * Connect to the given ssh server using a proxy command.
47 ssh_proxy_connect(const char *host, u_short port, uid_t original_real_uid,
48 const char *proxy_command)
55 char strport[NI_MAXSERV];
57 /* Convert the port number into a string. */
58 snprintf(strport, sizeof strport, "%hu", port);
60 /* Build the final command string in the buffer by making the
61 appropriate substitutions to the given proxy command. */
62 buffer_init(&command);
63 for (cp = proxy_command; *cp; cp++) {
64 if (cp[0] == '%' && cp[1] == '%') {
65 buffer_append(&command, "%", 1);
69 if (cp[0] == '%' && cp[1] == 'h') {
70 buffer_append(&command, host, strlen(host));
74 if (cp[0] == '%' && cp[1] == 'p') {
75 buffer_append(&command, strport, strlen(strport));
79 buffer_append(&command, cp, 1);
81 buffer_append(&command, "\0", 1);
83 /* Get the final command string. */
84 command_string = buffer_ptr(&command);
86 /* Create pipes for communicating with the proxy. */
87 if (pipe(pin) < 0 || pipe(pout) < 0)
88 fatal("Could not create pipes to communicate with the proxy: %.100s",
91 debug("Executing proxy command: %.500s", command_string);
93 /* Fork and execute the proxy command. */
94 if ((pid = fork()) == 0) {
97 /* Child. Permanently give up superuser privileges. */
98 permanently_set_uid(original_real_uid);
100 /* Redirect stdin and stdout. */
103 if (dup2(pin[0], 0) < 0)
104 perror("dup2 stdin");
108 if (dup2(pout[1], 1) < 0)
109 perror("dup2 stdout");
110 /* Cannot be 1 because pin allocated two descriptors. */
113 /* Stderr is left as it is so that error messages get
114 printed on the user's terminal. */
117 argv[2] = command_string;
120 /* Execute the proxy command. Note that we gave up any
121 extra privileges above. */
122 execv("/bin/sh", argv);
128 fatal("fork failed: %.100s", strerror(errno));
130 /* Close child side of the descriptors. */
134 /* Free the command name. */
135 buffer_free(&command);
137 /* Set the connection file descriptors. */
138 packet_set_connection(pout[0], pin[1]);
144 * Creates a (possibly privileged) socket for use as the ssh connection.
147 ssh_create_socket(uid_t original_real_uid, int privileged, int family)
152 * If we are running as root and want to connect to a privileged
153 * port, bind our own socket to a privileged port.
156 int p = IPPORT_RESERVED - 1;
157 sock = rresvport_af(&p, family);
159 fatal("rresvport: af=%d %.100s", family, strerror(errno));
160 debug("Allocated local port %d.", p);
163 * Just create an ordinary socket on arbitrary port. We use
164 * the user's uid to create the socket.
166 temporarily_use_uid(original_real_uid);
167 sock = socket(family, SOCK_STREAM, 0);
169 error("socket: %.100s", strerror(errno));
176 * Opens a TCP/IP connection to the remote server on the given host.
177 * The address of the remote host will be returned in hostaddr.
178 * If port is 0, the default port will be used. If anonymous is zero,
179 * a privileged port will be allocated to make the connection.
180 * This requires super-user privileges if anonymous is false.
181 * Connection_attempts specifies the maximum number of tries (one per
182 * second). If proxy_command is non-NULL, it specifies the command (with %h
183 * and %p substituted for host and port, respectively) to use to contact
187 ssh_connect(const char *host, struct sockaddr_storage * hostaddr,
188 u_short port, int connection_attempts,
189 int anonymous, uid_t original_real_uid,
190 const char *proxy_command)
192 int sock = -1, attempt;
194 struct addrinfo hints, *ai, *aitop;
195 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
197 struct linger linger;
199 debug("ssh_connect: getuid %d geteuid %d anon %d",
200 (int) getuid(), (int) geteuid(), anonymous);
202 /* Get default port if port has not been set. */
204 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
206 port = ntohs(sp->s_port);
208 port = SSH_DEFAULT_PORT;
210 /* If a proxy command is given, connect using it. */
211 if (proxy_command != NULL)
212 return ssh_proxy_connect(host, port, original_real_uid, proxy_command);
214 /* No proxy command. */
216 memset(&hints, 0, sizeof(hints));
217 hints.ai_family = IPv4or6;
218 hints.ai_socktype = SOCK_STREAM;
219 snprintf(strport, sizeof strport, "%d", port);
220 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
221 fatal("%s: %.100s: %s", __progname, host,
222 gai_strerror(gaierr));
225 * Try to connect several times. On some machines, the first time
226 * will sometimes fail. In general socket code appears to behave
227 * quite magically on many machines.
229 for (attempt = 0; attempt < connection_attempts; attempt++) {
231 debug("Trying again...");
233 /* Loop through addresses for this host, and try each one in
234 sequence until the connection succeeds. */
235 for (ai = aitop; ai; ai = ai->ai_next) {
236 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
238 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
239 ntop, sizeof(ntop), strport, sizeof(strport),
240 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
241 error("ssh_connect: getnameinfo failed");
244 debug("Connecting to %.200s [%.100s] port %s.",
245 host, ntop, strport);
247 /* Create a socket for connecting. */
248 sock = ssh_create_socket(original_real_uid,
249 !anonymous && geteuid() == 0 && port < IPPORT_RESERVED,
254 /* Connect to the host. We use the user's uid in the
255 * hope that it will help with tcp_wrappers showing
256 * the remote uid as root.
258 temporarily_use_uid(original_real_uid);
259 if (connect(sock, ai->ai_addr, ai->ai_addrlen) >= 0) {
260 /* Successful connection. */
261 memcpy(hostaddr, ai->ai_addr, sizeof(*(ai->ai_addr)));
265 debug("connect: %.100s", strerror(errno));
268 * Close the failed socket; there appear to
269 * be some problems when reusing a socket for
270 * which connect() has already returned an
273 shutdown(sock, SHUT_RDWR);
278 break; /* Successful connection. */
280 /* Sleep a moment before retrying. */
286 /* Return failure if we didn't get a successful connection. */
287 if (attempt >= connection_attempts)
290 debug("Connection established.");
293 * Set socket options. We would like the socket to disappear as soon
294 * as it has been closed for whatever reason.
296 /* setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
299 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
301 /* Set the connection. */
302 packet_set_connection(sock, sock);
308 * Checks if the user has an authentication agent, and if so, tries to
309 * authenticate using the agent.
312 try_agent_authentication()
316 AuthenticationConnection *auth;
317 unsigned char response[16];
319 BIGNUM *e, *n, *challenge;
321 /* Get connection to the agent. */
322 auth = ssh_get_authentication_connection();
328 challenge = BN_new();
330 /* Loop through identities served by the agent. */
331 for (status = ssh_get_first_identity(auth, e, n, &comment);
333 status = ssh_get_next_identity(auth, e, n, &comment)) {
336 /* Try this identity. */
337 debug("Trying RSA authentication via agent with '%.100s'", comment);
340 /* Tell the server that we are willing to authenticate using this key. */
341 packet_start(SSH_CMSG_AUTH_RSA);
342 packet_put_bignum(n);
346 /* Wait for server's response. */
347 type = packet_read(&plen);
349 /* The server sends failure if it doesn\'t like our key or
350 does not support RSA authentication. */
351 if (type == SSH_SMSG_FAILURE) {
352 debug("Server refused our key.");
355 /* Otherwise it should have sent a challenge. */
356 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
357 packet_disconnect("Protocol error during RSA authentication: %d",
360 packet_get_bignum(challenge, &clen);
362 packet_integrity_check(plen, clen, type);
364 debug("Received RSA challenge from server.");
366 /* Ask the agent to decrypt the challenge. */
367 if (!ssh_decrypt_challenge(auth, e, n, challenge,
368 session_id, 1, response)) {
369 /* The agent failed to authenticate this identifier although it
370 advertised it supports this. Just return a wrong value. */
371 log("Authentication agent failed to decrypt challenge.");
372 memset(response, 0, sizeof(response));
374 debug("Sending response to RSA challenge.");
376 /* Send the decrypted challenge back to the server. */
377 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
378 for (i = 0; i < 16; i++)
379 packet_put_char(response[i]);
383 /* Wait for response from the server. */
384 type = packet_read(&plen);
386 /* The server returns success if it accepted the authentication. */
387 if (type == SSH_SMSG_SUCCESS) {
388 debug("RSA authentication accepted by server.");
391 BN_clear_free(challenge);
394 /* Otherwise it should return failure. */
395 if (type != SSH_SMSG_FAILURE)
396 packet_disconnect("Protocol error waiting RSA auth response: %d",
402 BN_clear_free(challenge);
404 debug("RSA authentication using agent refused.");
409 * Computes the proper response to a RSA challenge, and sends the response to
413 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
415 unsigned char buf[32], response[16];
419 /* Decrypt the challenge using the private key. */
420 rsa_private_decrypt(challenge, challenge, prv);
422 /* Compute the response. */
423 /* The response is MD5 of decrypted challenge plus session id. */
424 len = BN_num_bytes(challenge);
425 if (len <= 0 || len > sizeof(buf))
426 packet_disconnect("respond_to_rsa_challenge: bad challenge length %d",
429 memset(buf, 0, sizeof(buf));
430 BN_bn2bin(challenge, buf + sizeof(buf) - len);
432 MD5_Update(&md, buf, 32);
433 MD5_Update(&md, session_id, 16);
434 MD5_Final(response, &md);
436 debug("Sending response to host key RSA challenge.");
438 /* Send the response back to the server. */
439 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
440 for (i = 0; i < 16; i++)
441 packet_put_char(response[i]);
445 memset(buf, 0, sizeof(buf));
446 memset(response, 0, sizeof(response));
447 memset(&md, 0, sizeof(md));
451 * Checks if the user has authentication file, and if so, tries to authenticate
455 try_rsa_authentication(const char *authfile)
460 char *passphrase, *comment;
464 /* Try to load identification for the authentication key. */
465 public_key = RSA_new();
466 if (!load_public_key(authfile, public_key, &comment)) {
467 RSA_free(public_key);
468 /* Could not load it. Fail. */
471 debug("Trying RSA authentication with key '%.100s'", comment);
473 /* Tell the server that we are willing to authenticate using this key. */
474 packet_start(SSH_CMSG_AUTH_RSA);
475 packet_put_bignum(public_key->n);
479 /* We no longer need the public key. */
480 RSA_free(public_key);
482 /* Wait for server's response. */
483 type = packet_read(&plen);
486 * The server responds with failure if it doesn\'t like our key or
487 * doesn\'t support RSA authentication.
489 if (type == SSH_SMSG_FAILURE) {
490 debug("Server refused our key.");
494 /* Otherwise, the server should respond with a challenge. */
495 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
496 packet_disconnect("Protocol error during RSA authentication: %d", type);
498 /* Get the challenge from the packet. */
499 challenge = BN_new();
500 packet_get_bignum(challenge, &clen);
502 packet_integrity_check(plen, clen, type);
504 debug("Received RSA challenge from server.");
506 private_key = RSA_new();
508 * Load the private key. Try first with empty passphrase; if it
509 * fails, ask for a passphrase.
511 if (!load_private_key(authfile, "", private_key, NULL)) {
513 snprintf(buf, sizeof buf, "Enter passphrase for RSA key '%.100s': ",
515 if (!options.batch_mode)
516 passphrase = read_passphrase(buf, 0);
518 debug("Will not query passphrase for %.100s in batch mode.",
520 passphrase = xstrdup("");
523 /* Load the authentication file using the pasphrase. */
524 if (!load_private_key(authfile, passphrase, private_key, NULL)) {
525 memset(passphrase, 0, strlen(passphrase));
527 error("Bad passphrase.");
529 /* Send a dummy response packet to avoid protocol error. */
530 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
531 for (i = 0; i < 16; i++)
536 /* Expect the server to reject it... */
537 packet_read_expect(&plen, SSH_SMSG_FAILURE);
541 /* Destroy the passphrase. */
542 memset(passphrase, 0, strlen(passphrase));
545 /* We no longer need the comment. */
548 /* Compute and send a response to the challenge. */
549 respond_to_rsa_challenge(challenge, private_key);
551 /* Destroy the private key. */
552 RSA_free(private_key);
554 /* We no longer need the challenge. */
555 BN_clear_free(challenge);
557 /* Wait for response from the server. */
558 type = packet_read(&plen);
559 if (type == SSH_SMSG_SUCCESS) {
560 debug("RSA authentication accepted by server.");
563 if (type != SSH_SMSG_FAILURE)
564 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
565 debug("RSA authentication refused.");
570 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
571 * authentication and RSA host authentication.
574 try_rhosts_rsa_authentication(const char *local_user, RSA * host_key)
580 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
582 /* Tell the server that we are willing to authenticate using this key. */
583 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
584 packet_put_string(local_user, strlen(local_user));
585 packet_put_int(BN_num_bits(host_key->n));
586 packet_put_bignum(host_key->e);
587 packet_put_bignum(host_key->n);
591 /* Wait for server's response. */
592 type = packet_read(&plen);
594 /* The server responds with failure if it doesn't admit our
595 .rhosts authentication or doesn't know our host key. */
596 if (type == SSH_SMSG_FAILURE) {
597 debug("Server refused our rhosts authentication or host key.");
600 /* Otherwise, the server should respond with a challenge. */
601 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
602 packet_disconnect("Protocol error during RSA authentication: %d", type);
604 /* Get the challenge from the packet. */
605 challenge = BN_new();
606 packet_get_bignum(challenge, &clen);
608 packet_integrity_check(plen, clen, type);
610 debug("Received RSA challenge for host key from server.");
612 /* Compute a response to the challenge. */
613 respond_to_rsa_challenge(challenge, host_key);
615 /* We no longer need the challenge. */
616 BN_clear_free(challenge);
618 /* Wait for response from the server. */
619 type = packet_read(&plen);
620 if (type == SSH_SMSG_SUCCESS) {
621 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
624 if (type != SSH_SMSG_FAILURE)
625 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
626 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
632 try_kerberos_authentication()
634 KTEXT_ST auth; /* Kerberos data */
640 Key_schedule schedule;
641 u_long checksum, cksum;
643 struct sockaddr_in local, foreign;
646 /* Don't do anything if we don't have any tickets. */
647 if (stat(tkt_string(), &st) < 0)
650 strncpy(inst, (char *) krb_get_phost(get_canonical_hostname()), INST_SZ);
652 realm = (char *) krb_realmofhost(get_canonical_hostname());
654 debug("Kerberos V4: no realm for %s", get_canonical_hostname());
657 /* This can really be anything. */
658 checksum = (u_long) getpid();
660 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
662 debug("Kerberos V4 krb_mk_req failed: %s", krb_err_txt[r]);
665 /* Get session key to decrypt the server's reply with. */
666 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
668 debug("get_cred failed: %s", krb_err_txt[r]);
671 des_key_sched((des_cblock *) cred.session, schedule);
673 /* Send authentication info to server. */
674 packet_start(SSH_CMSG_AUTH_KERBEROS);
675 packet_put_string((char *) auth.dat, auth.length);
679 /* Zero the buffer. */
680 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
683 memset(&local, 0, sizeof(local));
684 if (getsockname(packet_get_connection_in(),
685 (struct sockaddr *) & local, &r) < 0)
686 debug("getsockname failed: %s", strerror(errno));
689 memset(&foreign, 0, sizeof(foreign));
690 if (getpeername(packet_get_connection_in(),
691 (struct sockaddr *) & foreign, &r) < 0) {
692 debug("getpeername failed: %s", strerror(errno));
695 /* Get server reply. */
696 type = packet_read(&plen);
698 case SSH_SMSG_FAILURE:
699 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
700 debug("Kerberos V4 authentication failed.");
704 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
705 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
706 debug("Kerberos V4 authentication accepted.");
708 /* Get server's response. */
709 reply = packet_get_string((unsigned int *) &auth.length);
710 memcpy(auth.dat, reply, auth.length);
713 packet_integrity_check(plen, 4 + auth.length, type);
716 * If his response isn't properly encrypted with the session
717 * key, and the decrypted checksum fails to match, he's
720 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
721 &foreign, &local, &msg_data);
723 debug("Kerberos V4 krb_rd_priv failed: %s", krb_err_txt[r]);
724 packet_disconnect("Kerberos V4 challenge failed!");
726 /* Fetch the (incremented) checksum that we supplied in the request. */
727 (void) memcpy((char *) &cksum, (char *) msg_data.app_data, sizeof(cksum));
728 cksum = ntohl(cksum);
730 /* If it matches, we're golden. */
731 if (cksum == checksum + 1) {
732 debug("Kerberos V4 challenge successful.");
735 packet_disconnect("Kerberos V4 challenge failed!");
739 packet_disconnect("Protocol error on Kerberos V4 response: %d", type);
751 char pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
753 unsigned char buffer[8192];
756 /* Don't do anything if we don't have any tickets. */
757 if (stat(tkt_string(), &st) < 0)
760 creds = xmalloc(sizeof(*creds));
762 if ((r = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm)) != KSUCCESS) {
763 debug("Kerberos V4 tf_fullname failed: %s", krb_err_txt[r]);
766 if ((r = krb_get_cred("krbtgt", prealm, prealm, creds)) != GC_OK) {
767 debug("Kerberos V4 get_cred failed: %s", krb_err_txt[r]);
770 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
771 debug("Kerberos V4 ticket expired: %s", TKT_FILE);
774 creds_to_radix(creds, buffer);
777 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
778 packet_put_string((char *) buffer, strlen(buffer));
782 type = packet_read(&plen);
784 if (type == SSH_SMSG_FAILURE)
785 debug("Kerberos TGT for realm %s rejected.", prealm);
786 else if (type != SSH_SMSG_SUCCESS)
787 packet_disconnect("Protocol error on Kerberos TGT response: %d", type);
793 send_afs_tokens(void)
796 struct ViceIoctl parms;
797 struct ClearToken ct;
798 int i, type, len, plen;
799 char buf[2048], *p, *server_cell;
800 unsigned char buffer[8192];
802 /* Move over ktc_GetToken, here's something leaner. */
803 for (i = 0; i < 100; i++) { /* just in case */
804 parms.in = (char *) &i;
805 parms.in_size = sizeof(i);
807 parms.out_size = sizeof(buf);
808 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
812 /* Get secret token. */
813 memcpy(&creds.ticket_st.length, p, sizeof(unsigned int));
814 if (creds.ticket_st.length > MAX_KTXT_LEN)
816 p += sizeof(unsigned int);
817 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
818 p += creds.ticket_st.length;
820 /* Get clear token. */
821 memcpy(&len, p, sizeof(len));
822 if (len != sizeof(struct ClearToken))
827 p += sizeof(len); /* primary flag */
830 /* Flesh out our credentials. */
831 strlcpy(creds.service, "afs", sizeof creds.service);
832 creds.instance[0] = '\0';
833 strlcpy(creds.realm, server_cell, REALM_SZ);
834 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
835 creds.issue_date = ct.BeginTimestamp;
836 creds.lifetime = krb_time_to_life(creds.issue_date, ct.EndTimestamp);
837 creds.kvno = ct.AuthHandle;
838 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
839 creds.pinst[0] = '\0';
841 /* Encode token, ship it off. */
842 if (!creds_to_radix(&creds, buffer))
844 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
845 packet_put_string((char *) buffer, strlen(buffer));
849 /* Roger, Roger. Clearance, Clarence. What's your vector,
851 type = packet_read(&plen);
853 if (type == SSH_SMSG_FAILURE)
854 debug("AFS token for cell %s rejected.", server_cell);
855 else if (type != SSH_SMSG_SUCCESS)
856 packet_disconnect("Protocol error on AFS token response: %d", type);
863 * Tries to authenticate with any string-based challenge/response system.
864 * Note that the client code is not tied to s/key or TIS.
867 try_skey_authentication()
869 int type, i, payload_len;
870 char *challenge, *response;
872 debug("Doing skey authentication.");
874 /* request a challenge */
875 packet_start(SSH_CMSG_AUTH_TIS);
879 type = packet_read(&payload_len);
880 if (type != SSH_SMSG_FAILURE &&
881 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
882 packet_disconnect("Protocol error: got %d in response "
883 "to skey-auth", type);
885 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
886 debug("No challenge for skey authentication.");
889 challenge = packet_get_string(&payload_len);
890 if (options.cipher == SSH_CIPHER_NONE)
891 log("WARNING: Encryption is disabled! "
892 "Reponse will be transmitted in clear text.");
893 fprintf(stderr, "%s\n", challenge);
895 for (i = 0; i < options.number_of_password_prompts; i++) {
897 error("Permission denied, please try again.");
898 response = read_passphrase("Response: ", 0);
899 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
900 packet_put_string(response, strlen(response));
901 memset(response, 0, strlen(response));
905 type = packet_read(&payload_len);
906 if (type == SSH_SMSG_SUCCESS)
908 if (type != SSH_SMSG_FAILURE)
909 packet_disconnect("Protocol error: got %d in response "
910 "to skey-auth-reponse", type);
917 * Tries to authenticate with plain passwd authentication.
920 try_password_authentication(char *prompt)
922 int type, i, payload_len;
925 debug("Doing password authentication.");
926 if (options.cipher == SSH_CIPHER_NONE)
927 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
928 for (i = 0; i < options.number_of_password_prompts; i++) {
930 error("Permission denied, please try again.");
931 password = read_passphrase(prompt, 0);
932 packet_start(SSH_CMSG_AUTH_PASSWORD);
933 packet_put_string(password, strlen(password));
934 memset(password, 0, strlen(password));
939 type = packet_read(&payload_len);
940 if (type == SSH_SMSG_SUCCESS)
942 if (type != SSH_SMSG_FAILURE)
943 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
950 * Waits for the server identification string, and sends our own
951 * identification string.
954 ssh_exchange_identification()
956 char buf[256], remote_version[256]; /* must be same size! */
957 int remote_major, remote_minor, i;
958 int connection_in = packet_get_connection_in();
959 int connection_out = packet_get_connection_out();
961 /* Read other side\'s version identification. */
962 for (i = 0; i < sizeof(buf) - 1; i++) {
963 if (read(connection_in, &buf[i], 1) != 1)
964 fatal("ssh_exchange_identification: read: %.100s", strerror(errno));
965 if (buf[i] == '\r') {
970 if (buf[i] == '\n') {
975 buf[sizeof(buf) - 1] = 0;
978 * Check that the versions match. In future this might accept
979 * several versions and set appropriate flags to handle them.
981 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
982 remote_version) != 3)
983 fatal("Bad remote protocol version identification: '%.100s'", buf);
984 debug("Remote protocol version %d.%d, remote software version %.100s",
985 remote_major, remote_minor, remote_version);
987 /* Check if the remote protocol version is too old. */
988 if (remote_major == 1 && remote_minor < 3)
989 fatal("Remote machine has too old SSH software version.");
991 /* We speak 1.3, too. */
992 if (remote_major == 1 && remote_minor == 3) {
994 if (options.forward_agent) {
995 log("Agent forwarding disabled for protocol 1.3");
996 options.forward_agent = 0;
1001 * Removed for now, to permit compatibility with latter versions. The
1002 * server will reject our version and disconnect if it doesn't
1005 if (remote_major != PROTOCOL_MAJOR)
1006 fatal("Protocol major versions differ: %d vs. %d",
1007 PROTOCOL_MAJOR, remote_major);
1010 /* Send our own protocol version identification. */
1011 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
1012 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
1013 if (atomicio(write, connection_out, buf, strlen(buf)) != strlen(buf))
1014 fatal("write: %.100s", strerror(errno));
1017 int ssh_cipher_default = SSH_CIPHER_3DES;
1020 read_yes_or_no(const char *prompt, int defval)
1029 f = fopen("/dev/tty", "rw");
1037 fprintf(stderr, "%s", prompt);
1038 if (fgets(buf, sizeof(buf), f) == NULL) {
1039 /* Print a newline (the prompt probably didn\'t have one). */
1040 fprintf(stderr, "\n");
1041 strlcpy(buf, "no", sizeof buf);
1043 /* Remove newline from response. */
1044 if (strchr(buf, '\n'))
1045 *strchr(buf, '\n') = 0;
1049 if (strcmp(buf, "yes") == 0)
1051 if (strcmp(buf, "no") == 0)
1063 * check whether the supplied host key is valid, return only if ok.
1067 check_host_key(char *host, struct sockaddr *hostaddr, RSA *host_key)
1071 char hostline[1000], *hostp;
1072 HostStatus host_status;
1073 HostStatus ip_status;
1074 int local = 0, host_ip_differ = 0;
1076 char ntop[NI_MAXHOST];
1079 * Force accepting of the host key for loopback/localhost. The
1080 * problem is that if the home directory is NFS-mounted to multiple
1081 * machines, localhost will refer to a different machine in each of
1082 * them, and the user will get bogus HOST_CHANGED warnings. This
1083 * essentially disables host authentication for localhost; however,
1084 * this is probably not a real problem.
1086 switch (hostaddr->sa_family) {
1088 local = (ntohl(((struct sockaddr_in *)hostaddr)->sin_addr.s_addr) >> 24) == IN_LOOPBACKNET;
1089 salen = sizeof(struct sockaddr_in);
1092 local = IN6_IS_ADDR_LOOPBACK(&(((struct sockaddr_in6 *)hostaddr)->sin6_addr));
1093 salen = sizeof(struct sockaddr_in6);
1097 salen = sizeof(struct sockaddr_storage);
1101 debug("Forcing accepting of host key for loopback/localhost.");
1106 * Turn off check_host_ip for proxy connects, since
1107 * we don't have the remote ip-address
1109 if (options.proxy_command != NULL && options.check_host_ip)
1110 options.check_host_ip = 0;
1112 if (options.check_host_ip) {
1113 if (getnameinfo(hostaddr, salen, ntop, sizeof(ntop),
1114 NULL, 0, NI_NUMERICHOST) != 0)
1115 fatal("check_host_key: getnameinfo failed");
1120 * Store the host key from the known host file in here so that we can
1121 * compare it with the key for the IP address.
1123 file_key = RSA_new();
1124 file_key->n = BN_new();
1125 file_key->e = BN_new();
1128 * Check if the host key is present in the user\'s list of known
1129 * hosts or in the systemwide list.
1131 host_status = check_host_in_hostfile(options.user_hostfile, host,
1132 host_key->e, host_key->n,
1133 file_key->e, file_key->n);
1134 if (host_status == HOST_NEW)
1135 host_status = check_host_in_hostfile(options.system_hostfile, host,
1136 host_key->e, host_key->n,
1137 file_key->e, file_key->n);
1139 * Also perform check for the ip address, skip the check if we are
1140 * localhost or the hostname was an ip address to begin with
1142 if (options.check_host_ip && !local && strcmp(host, ip)) {
1143 RSA *ip_key = RSA_new();
1144 ip_key->n = BN_new();
1145 ip_key->e = BN_new();
1146 ip_status = check_host_in_hostfile(options.user_hostfile, ip,
1147 host_key->e, host_key->n,
1148 ip_key->e, ip_key->n);
1150 if (ip_status == HOST_NEW)
1151 ip_status = check_host_in_hostfile(options.system_hostfile, ip,
1152 host_key->e, host_key->n,
1153 ip_key->e, ip_key->n);
1154 if (host_status == HOST_CHANGED &&
1155 (ip_status != HOST_CHANGED ||
1156 (BN_cmp(ip_key->e, file_key->e) || BN_cmp(ip_key->n, file_key->n))))
1161 ip_status = host_status;
1165 switch (host_status) {
1167 /* The host is known and the key matches. */
1168 debug("Host '%.200s' is known and matches the host key.", host);
1169 if (options.check_host_ip) {
1170 if (ip_status == HOST_NEW) {
1171 if (!add_host_to_hostfile(options.user_hostfile, ip,
1172 host_key->e, host_key->n))
1173 log("Failed to add the host key for IP address '%.30s' to the list of known hosts (%.30s).",
1174 ip, options.user_hostfile);
1176 log("Warning: Permanently added host key for IP address '%.30s' to the list of known hosts.",
1178 } else if (ip_status != HOST_OK)
1179 log("Warning: the host key for '%.200s' differs from the key for the IP address '%.30s'",
1184 /* The host is new. */
1185 if (options.strict_host_key_checking == 1) {
1186 /* User has requested strict host key checking. We will not add the host key
1187 automatically. The only alternative left is to abort. */
1188 fatal("No host key is known for %.200s and you have requested strict checking.", host);
1189 } else if (options.strict_host_key_checking == 2) {
1192 char *fp = fingerprint(host_key->e, host_key->n);
1193 snprintf(prompt, sizeof(prompt),
1194 "The authenticity of host '%.200s' can't be established.\n"
1195 "Key fingerprint is %d %s.\n"
1196 "Are you sure you want to continue connecting (yes/no)? ",
1197 host, BN_num_bits(host_key->n), fp);
1198 if (!read_yes_or_no(prompt, -1))
1199 fatal("Aborted by user!\n");
1201 if (options.check_host_ip && ip_status == HOST_NEW && strcmp(host, ip)) {
1202 snprintf(hostline, sizeof(hostline), "%s,%s", host, ip);
1207 /* If not in strict mode, add the key automatically to the local known_hosts file. */
1208 if (!add_host_to_hostfile(options.user_hostfile, hostp,
1209 host_key->e, host_key->n))
1210 log("Failed to add the host to the list of known hosts (%.500s).",
1211 options.user_hostfile);
1213 log("Warning: Permanently added '%.200s' to the list of known hosts.",
1217 if (options.check_host_ip && host_ip_differ) {
1219 if (ip_status == HOST_NEW)
1221 else if (ip_status == HOST_OK)
1222 msg = "is unchanged";
1224 msg = "has a different value";
1225 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1226 error("@ WARNING: POSSIBLE DNS SPOOFING DETECTED! @");
1227 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1228 error("The host key for %s has changed,", host);
1229 error("and the key for the according IP address %s", ip);
1230 error("%s. This could either mean that", msg);
1231 error("DNS SPOOFING is happening or the IP address for the host");
1232 error("and its host key have changed at the same time");
1234 /* The host key has changed. */
1235 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1236 error("@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @");
1237 error("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1238 error("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1239 error("Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1240 error("It is also possible that the host key has just been changed.");
1241 error("Please contact your system administrator.");
1242 error("Add correct host key in %.100s to get rid of this message.",
1243 options.user_hostfile);
1246 * If strict host key checking is in use, the user will have
1247 * to edit the key manually and we can only abort.
1249 if (options.strict_host_key_checking)
1250 fatal("Host key for %.200s has changed and you have requested strict checking.", host);
1253 * If strict host key checking has not been requested, allow
1254 * the connection but without password authentication or
1257 if (options.password_authentication) {
1258 error("Password authentication is disabled to avoid trojan horses.");
1259 options.password_authentication = 0;
1261 if (options.forward_agent) {
1262 error("Agent forwarding is disabled to avoid trojan horses.");
1263 options.forward_agent = 0;
1266 * XXX Should permit the user to change to use the new id.
1267 * This could be done by converting the host key to an
1268 * identifying sentence, tell that the host identifies itself
1269 * by that sentence, and ask the user if he/she whishes to
1270 * accept the authentication.
1274 if (options.check_host_ip)
1282 ssh_kex(char *host, struct sockaddr *hostaddr)
1289 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
1290 unsigned char cookie[8];
1291 unsigned int supported_ciphers;
1292 unsigned int server_flags, client_flags;
1293 int payload_len, clen, sum_len = 0;
1296 debug("Waiting for server public key.");
1298 /* Wait for a public key packet from the server. */
1299 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
1301 /* Get cookie from the packet. */
1302 for (i = 0; i < 8; i++)
1303 cookie[i] = packet_get_char();
1305 /* Get the public key. */
1306 public_key = RSA_new();
1307 bits = packet_get_int();/* bits */
1308 public_key->e = BN_new();
1309 packet_get_bignum(public_key->e, &clen);
1311 public_key->n = BN_new();
1312 packet_get_bignum(public_key->n, &clen);
1315 rbits = BN_num_bits(public_key->n);
1316 if (bits != rbits) {
1317 log("Warning: Server lies about size of server public key: "
1318 "actual size is %d bits vs. announced %d.", rbits, bits);
1319 log("Warning: This may be due to an old implementation of ssh.");
1321 /* Get the host key. */
1322 host_key = RSA_new();
1323 bits = packet_get_int();/* bits */
1324 host_key->e = BN_new();
1325 packet_get_bignum(host_key->e, &clen);
1327 host_key->n = BN_new();
1328 packet_get_bignum(host_key->n, &clen);
1331 rbits = BN_num_bits(host_key->n);
1332 if (bits != rbits) {
1333 log("Warning: Server lies about size of server host key: "
1334 "actual size is %d bits vs. announced %d.", rbits, bits);
1335 log("Warning: This may be due to an old implementation of ssh.");
1338 /* Get protocol flags. */
1339 server_flags = packet_get_int();
1340 packet_set_protocol_flags(server_flags);
1342 supported_ciphers = packet_get_int();
1343 supported_authentications = packet_get_int();
1345 debug("Received server public key (%d bits) and host key (%d bits).",
1346 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
1348 packet_integrity_check(payload_len,
1349 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
1350 SSH_SMSG_PUBLIC_KEY);
1352 check_host_key(host, hostaddr, host_key);
1354 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1356 compute_session_id(session_id, cookie, host_key->n, public_key->n);
1358 /* Generate a session key. */
1362 * Generate an encryption key for the session. The key is a 256 bit
1363 * random number, interpreted as a 32-byte key, with the least
1364 * significant 8 bits being the first byte of the key.
1366 for (i = 0; i < 32; i++) {
1368 rand = arc4random();
1369 session_key[i] = rand & 0xff;
1374 * According to the protocol spec, the first byte of the session key
1375 * is the highest byte of the integer. The session key is xored with
1376 * the first 16 bytes of the session id.
1379 BN_set_word(key, 0);
1380 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1381 BN_lshift(key, key, 8);
1383 BN_add_word(key, session_key[i] ^ session_id[i]);
1385 BN_add_word(key, session_key[i]);
1389 * Encrypt the integer using the public key and host key of the
1390 * server (key with smaller modulus first).
1392 if (BN_cmp(public_key->n, host_key->n) < 0) {
1393 /* Public key has smaller modulus. */
1394 if (BN_num_bits(host_key->n) <
1395 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1396 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1397 "SSH_KEY_BITS_RESERVED %d",
1398 BN_num_bits(host_key->n),
1399 BN_num_bits(public_key->n),
1400 SSH_KEY_BITS_RESERVED);
1402 rsa_public_encrypt(key, key, public_key);
1403 rsa_public_encrypt(key, key, host_key);
1405 /* Host key has smaller modulus (or they are equal). */
1406 if (BN_num_bits(public_key->n) <
1407 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1408 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1409 "SSH_KEY_BITS_RESERVED %d",
1410 BN_num_bits(public_key->n),
1411 BN_num_bits(host_key->n),
1412 SSH_KEY_BITS_RESERVED);
1414 rsa_public_encrypt(key, key, host_key);
1415 rsa_public_encrypt(key, key, public_key);
1418 /* Destroy the public keys since we no longer need them. */
1419 RSA_free(public_key);
1422 if (options.cipher == SSH_CIPHER_NOT_SET) {
1423 if (cipher_mask() & supported_ciphers & (1 << ssh_cipher_default))
1424 options.cipher = ssh_cipher_default;
1426 debug("Cipher %s not supported, using %.100s instead.",
1427 cipher_name(ssh_cipher_default),
1428 cipher_name(SSH_FALLBACK_CIPHER));
1429 options.cipher = SSH_FALLBACK_CIPHER;
1432 /* Check that the selected cipher is supported. */
1433 if (!(supported_ciphers & (1 << options.cipher)))
1434 fatal("Selected cipher type %.100s not supported by server.",
1435 cipher_name(options.cipher));
1437 debug("Encryption type: %.100s", cipher_name(options.cipher));
1439 /* Send the encrypted session key to the server. */
1440 packet_start(SSH_CMSG_SESSION_KEY);
1441 packet_put_char(options.cipher);
1443 /* Send the cookie back to the server. */
1444 for (i = 0; i < 8; i++)
1445 packet_put_char(cookie[i]);
1447 /* Send and destroy the encrypted encryption key integer. */
1448 packet_put_bignum(key);
1451 /* Send protocol flags. */
1452 packet_put_int(client_flags);
1454 /* Send the packet now. */
1456 packet_write_wait();
1458 debug("Sent encrypted session key.");
1460 /* Set the encryption key. */
1461 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1463 /* We will no longer need the session key here. Destroy any extra copies. */
1464 memset(session_key, 0, sizeof(session_key));
1467 * Expect a success message from the server. Note that this message
1468 * will be received in encrypted form.
1470 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1472 debug("Received encrypted confirmation.");
1479 ssh_userauth(int host_key_valid, RSA *own_host_key,
1480 uid_t original_real_uid, char *host)
1485 const char *server_user, *local_user;
1487 /* Get local user name. Use it as server user if no user name was given. */
1488 pw = getpwuid(original_real_uid);
1490 fatal("User id %d not found from user database.", original_real_uid);
1491 local_user = xstrdup(pw->pw_name);
1492 server_user = options.user ? options.user : local_user;
1494 /* Send the name of the user to log in as on the server. */
1495 packet_start(SSH_CMSG_USER);
1496 packet_put_string(server_user, strlen(server_user));
1498 packet_write_wait();
1501 * The server should respond with success if no authentication is
1502 * needed (the user has no password). Otherwise the server responds
1505 type = packet_read(&payload_len);
1507 /* check whether the connection was accepted without authentication. */
1508 if (type == SSH_SMSG_SUCCESS)
1510 if (type != SSH_SMSG_FAILURE)
1511 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER",
1515 /* Try Kerberos tgt passing if the server supports it. */
1516 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1517 options.kerberos_tgt_passing) {
1518 if (options.cipher == SSH_CIPHER_NONE)
1519 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1520 (void) send_kerberos_tgt();
1522 /* Try AFS token passing if the server supports it. */
1523 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1524 options.afs_token_passing && k_hasafs()) {
1525 if (options.cipher == SSH_CIPHER_NONE)
1526 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1532 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1533 options.kerberos_authentication) {
1534 debug("Trying Kerberos authentication.");
1535 if (try_kerberos_authentication()) {
1536 /* The server should respond with success or failure. */
1537 type = packet_read(&payload_len);
1538 if (type == SSH_SMSG_SUCCESS)
1540 if (type != SSH_SMSG_FAILURE)
1541 packet_disconnect("Protocol error: got %d in response to Kerberos auth", type);
1547 * Use rhosts authentication if running in privileged socket and we
1548 * do not wish to remain anonymous.
1550 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1551 options.rhosts_authentication) {
1552 debug("Trying rhosts authentication.");
1553 packet_start(SSH_CMSG_AUTH_RHOSTS);
1554 packet_put_string(local_user, strlen(local_user));
1556 packet_write_wait();
1558 /* The server should respond with success or failure. */
1559 type = packet_read(&payload_len);
1560 if (type == SSH_SMSG_SUCCESS)
1562 if (type != SSH_SMSG_FAILURE)
1563 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1567 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1570 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1571 options.rhosts_rsa_authentication && host_key_valid) {
1572 if (try_rhosts_rsa_authentication(local_user, own_host_key))
1575 /* Try RSA authentication if the server supports it. */
1576 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1577 options.rsa_authentication) {
1579 * Try RSA authentication using the authentication agent. The
1580 * agent is tried first because no passphrase is needed for
1581 * it, whereas identity files may require passphrases.
1583 if (try_agent_authentication())
1586 /* Try RSA authentication for each identity. */
1587 for (i = 0; i < options.num_identity_files; i++)
1588 if (try_rsa_authentication(options.identity_files[i]))
1591 /* Try skey authentication if the server supports it. */
1592 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1593 options.skey_authentication && !options.batch_mode) {
1594 if (try_skey_authentication())
1597 /* Try password authentication if the server supports it. */
1598 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1599 options.password_authentication && !options.batch_mode) {
1602 snprintf(prompt, sizeof(prompt), "%.30s@%.40s's password: ",
1604 if (try_password_authentication(prompt))
1607 /* All authentication methods have failed. Exit with an error message. */
1608 fatal("Permission denied.");
1613 * Starts a dialog with the server, and authenticates the current user on the
1614 * server. This does not need any extra privileges. The basic connection
1615 * to the server must already have been established before this is called.
1616 * If login fails, this function prints an error and never returns.
1617 * This function does not require super-user privileges.
1620 ssh_login(int host_key_valid, RSA *own_host_key, const char *orighost,
1621 struct sockaddr *hostaddr, uid_t original_real_uid)
1625 /* Convert the user-supplied hostname into all lowercase. */
1626 host = xstrdup(orighost);
1627 for (cp = host; *cp; cp++)
1631 /* Exchange protocol version identification strings with the server. */
1632 ssh_exchange_identification();
1634 /* Put the connection into non-blocking mode. */
1635 packet_set_nonblocking();
1637 supported_authentications = 0;
1639 ssh_kex(host, hostaddr);
1640 if (supported_authentications == 0)
1641 fatal("supported_authentications == 0.");
1642 /* authenticate user */
1643 ssh_userauth(host_key_valid, own_host_key, original_real_uid, host);