2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Code to connect to a remote host, and to perform the client side of the
6 * login (authentication) dialog.
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
16 RCSID("$OpenBSD: sshconnect1.c,v 1.40 2001/09/27 15:31:17 markus Exp $");
18 #include <openssl/bn.h>
19 #include <openssl/evp.h>
44 #include "sshconnect.h"
51 /* Session id for the current session. */
52 u_char session_id[16];
53 u_int supported_authentications = 0;
55 extern Options options;
56 extern char *__progname;
59 * Checks if the user has an authentication agent, and if so, tries to
60 * authenticate using the agent.
63 try_agent_authentication(void)
67 AuthenticationConnection *auth;
74 /* Get connection to the agent. */
75 auth = ssh_get_authentication_connection();
81 /* Loop through identities served by the agent. */
82 for (key = ssh_get_first_identity(auth, &comment, 1);
84 key = ssh_get_next_identity(auth, &comment, 1)) {
86 /* Try this identity. */
87 debug("Trying RSA authentication via agent with '%.100s'", comment);
90 /* Tell the server that we are willing to authenticate using this key. */
91 packet_start(SSH_CMSG_AUTH_RSA);
92 packet_put_bignum(key->rsa->n);
96 /* Wait for server's response. */
97 type = packet_read(&plen);
99 /* The server sends failure if it doesn\'t like our key or
100 does not support RSA authentication. */
101 if (type == SSH_SMSG_FAILURE) {
102 debug("Server refused our key.");
106 /* Otherwise it should have sent a challenge. */
107 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
108 packet_disconnect("Protocol error during RSA authentication: %d",
111 packet_get_bignum(challenge, &clen);
113 packet_integrity_check(plen, clen, type);
115 debug("Received RSA challenge from server.");
117 /* Ask the agent to decrypt the challenge. */
118 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
120 * The agent failed to authenticate this identifier
121 * although it advertised it supports this. Just
122 * return a wrong value.
124 log("Authentication agent failed to decrypt challenge.");
125 memset(response, 0, sizeof(response));
128 debug("Sending response to RSA challenge.");
130 /* Send the decrypted challenge back to the server. */
131 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
132 for (i = 0; i < 16; i++)
133 packet_put_char(response[i]);
137 /* Wait for response from the server. */
138 type = packet_read(&plen);
140 /* The server returns success if it accepted the authentication. */
141 if (type == SSH_SMSG_SUCCESS) {
142 ssh_close_authentication_connection(auth);
143 BN_clear_free(challenge);
144 debug("RSA authentication accepted by server.");
147 /* Otherwise it should return failure. */
148 if (type != SSH_SMSG_FAILURE)
149 packet_disconnect("Protocol error waiting RSA auth response: %d",
152 ssh_close_authentication_connection(auth);
153 BN_clear_free(challenge);
154 debug("RSA authentication using agent refused.");
159 * Computes the proper response to a RSA challenge, and sends the response to
163 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
165 u_char buf[32], response[16];
169 /* Decrypt the challenge using the private key. */
170 /* XXX think about Bleichenbacher, too */
171 if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
173 "respond_to_rsa_challenge: rsa_private_decrypt failed");
175 /* Compute the response. */
176 /* The response is MD5 of decrypted challenge plus session id. */
177 len = BN_num_bytes(challenge);
178 if (len <= 0 || len > sizeof(buf))
180 "respond_to_rsa_challenge: bad challenge length %d", len);
182 memset(buf, 0, sizeof(buf));
183 BN_bn2bin(challenge, buf + sizeof(buf) - len);
185 MD5_Update(&md, buf, 32);
186 MD5_Update(&md, session_id, 16);
187 MD5_Final(response, &md);
189 debug("Sending response to host key RSA challenge.");
191 /* Send the response back to the server. */
192 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
193 for (i = 0; i < 16; i++)
194 packet_put_char(response[i]);
198 memset(buf, 0, sizeof(buf));
199 memset(response, 0, sizeof(response));
200 memset(&md, 0, sizeof(md));
204 * Checks if the user has authentication file, and if so, tries to authenticate
208 try_rsa_authentication(int idx)
211 Key *public, *private;
212 char buf[300], *passphrase, *comment, *authfile;
213 int i, type, quit, plen, clen;
215 public = options.identity_keys[idx];
216 authfile = options.identity_files[idx];
217 comment = xstrdup(authfile);
219 debug("Trying RSA authentication with key '%.100s'", comment);
221 /* Tell the server that we are willing to authenticate using this key. */
222 packet_start(SSH_CMSG_AUTH_RSA);
223 packet_put_bignum(public->rsa->n);
227 /* Wait for server's response. */
228 type = packet_read(&plen);
231 * The server responds with failure if it doesn\'t like our key or
232 * doesn\'t support RSA authentication.
234 if (type == SSH_SMSG_FAILURE) {
235 debug("Server refused our key.");
239 /* Otherwise, the server should respond with a challenge. */
240 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
241 packet_disconnect("Protocol error during RSA authentication: %d", type);
243 /* Get the challenge from the packet. */
244 challenge = BN_new();
245 packet_get_bignum(challenge, &clen);
247 packet_integrity_check(plen, clen, type);
249 debug("Received RSA challenge from server.");
252 * If the key is not stored in external hardware, we have to
253 * load the private key. Try first with empty passphrase; if it
254 * fails, ask for a passphrase.
256 if (public->flags && KEY_FLAG_EXT)
259 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
260 if (private == NULL && !options.batch_mode) {
261 snprintf(buf, sizeof(buf),
262 "Enter passphrase for RSA key '%.100s': ", comment);
263 for (i = 0; i < options.number_of_password_prompts; i++) {
264 passphrase = read_passphrase(buf, 0);
265 if (strcmp(passphrase, "") != 0) {
266 private = key_load_private_type(KEY_RSA1,
267 authfile, passphrase, NULL);
270 debug2("no passphrase given, try next key");
273 memset(passphrase, 0, strlen(passphrase));
275 if (private != NULL || quit)
277 debug2("bad passphrase given, try again...");
280 /* We no longer need the comment. */
283 if (private == NULL) {
284 if (!options.batch_mode)
285 error("Bad passphrase.");
287 /* Send a dummy response packet to avoid protocol error. */
288 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
289 for (i = 0; i < 16; i++)
294 /* Expect the server to reject it... */
295 packet_read_expect(&plen, SSH_SMSG_FAILURE);
296 BN_clear_free(challenge);
300 /* Compute and send a response to the challenge. */
301 respond_to_rsa_challenge(challenge, private->rsa);
303 /* Destroy the private key unless it in external hardware. */
304 if (!(private->flags & KEY_FLAG_EXT))
307 /* We no longer need the challenge. */
308 BN_clear_free(challenge);
310 /* Wait for response from the server. */
311 type = packet_read(&plen);
312 if (type == SSH_SMSG_SUCCESS) {
313 debug("RSA authentication accepted by server.");
316 if (type != SSH_SMSG_FAILURE)
317 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
318 debug("RSA authentication refused.");
323 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
324 * authentication and RSA host authentication.
327 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
333 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
335 /* Tell the server that we are willing to authenticate using this key. */
336 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
337 packet_put_cstring(local_user);
338 packet_put_int(BN_num_bits(host_key->rsa->n));
339 packet_put_bignum(host_key->rsa->e);
340 packet_put_bignum(host_key->rsa->n);
344 /* Wait for server's response. */
345 type = packet_read(&plen);
347 /* The server responds with failure if it doesn't admit our
348 .rhosts authentication or doesn't know our host key. */
349 if (type == SSH_SMSG_FAILURE) {
350 debug("Server refused our rhosts authentication or host key.");
353 /* Otherwise, the server should respond with a challenge. */
354 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
355 packet_disconnect("Protocol error during RSA authentication: %d", type);
357 /* Get the challenge from the packet. */
358 challenge = BN_new();
359 packet_get_bignum(challenge, &clen);
361 packet_integrity_check(plen, clen, type);
363 debug("Received RSA challenge for host key from server.");
365 /* Compute a response to the challenge. */
366 respond_to_rsa_challenge(challenge, host_key->rsa);
368 /* We no longer need the challenge. */
369 BN_clear_free(challenge);
371 /* Wait for response from the server. */
372 type = packet_read(&plen);
373 if (type == SSH_SMSG_SUCCESS) {
374 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
377 if (type != SSH_SMSG_FAILURE)
378 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
379 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
385 try_krb4_authentication(void)
387 KTEXT_ST auth; /* Kerberos data */
394 Key_schedule schedule;
395 u_long checksum, cksum;
397 struct sockaddr_in local, foreign;
400 /* Don't do anything if we don't have any tickets. */
401 if (stat(tkt_string(), &st) < 0)
404 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
407 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
409 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
412 /* This can really be anything. */
413 checksum = (u_long)getpid();
415 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
417 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
420 /* Get session key to decrypt the server's reply with. */
421 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
423 debug("get_cred failed: %s", krb_err_txt[r]);
426 des_key_sched((des_cblock *) cred.session, schedule);
428 /* Send authentication info to server. */
429 packet_start(SSH_CMSG_AUTH_KERBEROS);
430 packet_put_string((char *) auth.dat, auth.length);
434 /* Zero the buffer. */
435 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
437 slen = sizeof(local);
438 memset(&local, 0, sizeof(local));
439 if (getsockname(packet_get_connection_in(),
440 (struct sockaddr *)&local, &slen) < 0)
441 debug("getsockname failed: %s", strerror(errno));
443 slen = sizeof(foreign);
444 memset(&foreign, 0, sizeof(foreign));
445 if (getpeername(packet_get_connection_in(),
446 (struct sockaddr *)&foreign, &slen) < 0) {
447 debug("getpeername failed: %s", strerror(errno));
450 /* Get server reply. */
451 type = packet_read(&plen);
453 case SSH_SMSG_FAILURE:
454 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
455 debug("Kerberos v4 authentication failed.");
459 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
460 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
461 debug("Kerberos v4 authentication accepted.");
463 /* Get server's response. */
464 reply = packet_get_string((u_int *) &auth.length);
465 memcpy(auth.dat, reply, auth.length);
468 packet_integrity_check(plen, 4 + auth.length, type);
471 * If his response isn't properly encrypted with the session
472 * key, and the decrypted checksum fails to match, he's
475 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
476 &foreign, &local, &msg_data);
478 debug("Kerberos v4 krb_rd_priv failed: %s",
480 packet_disconnect("Kerberos v4 challenge failed!");
482 /* Fetch the (incremented) checksum that we supplied in the request. */
483 memcpy((char *)&cksum, (char *)msg_data.app_data,
485 cksum = ntohl(cksum);
487 /* If it matches, we're golden. */
488 if (cksum == checksum + 1) {
489 debug("Kerberos v4 challenge successful.");
492 packet_disconnect("Kerberos v4 challenge failed!");
496 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
505 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
507 krb5_error_code problem;
510 krb5_ccache ccache = NULL;
511 const char *remotehost;
513 int type, payload_len;
514 krb5_ap_rep_enc_part *reply = NULL;
517 memset(&ap, 0, sizeof(ap));
519 problem = krb5_init_context(context);
521 debug("Kerberos v5: krb5_init_context failed");
526 tkfile = krb5_cc_default_name(*context);
527 if (strncmp(tkfile, "FILE:", 5) == 0)
530 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
531 debug("Kerberos v5: could not get default ccache (permission denied).");
536 problem = krb5_cc_default(*context, &ccache);
538 debug("Kerberos v5: krb5_cc_default failed: %s",
539 krb5_get_err_text(*context, problem));
544 remotehost = get_canonical_hostname(1);
546 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
547 "host", remotehost, NULL, ccache, &ap);
549 debug("Kerberos v5: krb5_mk_req failed: %s",
550 krb5_get_err_text(*context, problem));
555 packet_start(SSH_CMSG_AUTH_KERBEROS);
556 packet_put_string((char *) ap.data, ap.length);
563 type = packet_read(&payload_len);
565 case SSH_SMSG_FAILURE:
566 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
567 debug("Kerberos v5 authentication failed.");
571 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
572 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
573 debug("Kerberos v5 authentication accepted.");
575 /* Get server's response. */
576 ap.data = packet_get_string((unsigned int *) &ap.length);
578 packet_integrity_check(payload_len, 4 + ap.length, type);
579 /* XXX je to dobre? */
581 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
589 packet_disconnect("Protocol error on Kerberos v5 response: %d",
598 krb5_cc_close(*context, ccache);
600 krb5_free_ap_rep_enc_part(*context, reply);
608 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
610 int fd, type, payload_len;
611 krb5_error_code problem;
613 krb5_ccache ccache = NULL;
615 krb5_kdc_flags flags;
616 const char *remotehost;
618 memset(&creds, 0, sizeof(creds));
619 memset(&outbuf, 0, sizeof(outbuf));
621 fd = packet_get_connection_in();
623 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
627 problem = krb5_cc_default(context, &ccache);
631 problem = krb5_cc_get_principal(context, ccache, &creds.client);
635 problem = krb5_build_principal(context, &creds.server,
636 strlen(creds.client->realm), creds.client->realm,
637 "krbtgt", creds.client->realm, NULL);
641 creds.times.endtime = 0;
644 flags.b.forwarded = 1;
645 flags.b.forwardable = krb5_config_get_bool(context, NULL,
646 "libdefaults", "forwardable", NULL);
648 remotehost = get_canonical_hostname(1);
650 problem = krb5_get_forwarded_creds(context, auth_context,
651 ccache, flags.i, remotehost, &creds, &outbuf);
655 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
656 packet_put_string((char *)outbuf.data, outbuf.length);
660 type = packet_read(&payload_len);
662 if (type == SSH_SMSG_SUCCESS) {
665 krb5_unparse_name(context, creds.client, &pname);
666 debug("Kerberos v5 TGT forwarded (%s).", pname);
669 debug("Kerberos v5 TGT forwarding failed.");
675 debug("Kerberos v5 TGT forwarding failed: %s",
676 krb5_get_err_text(context, problem));
678 krb5_free_principal(context, creds.client);
680 krb5_free_principal(context, creds.server);
682 krb5_cc_close(context, ccache);
694 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
695 int problem, type, len;
697 /* Don't do anything if we don't have any tickets. */
698 if (stat(tkt_string(), &st) < 0)
701 creds = xmalloc(sizeof(*creds));
703 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
707 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
711 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
715 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
717 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
718 packet_put_cstring(buffer);
722 type = packet_read(&len);
724 if (type == SSH_SMSG_SUCCESS)
725 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
726 creds->pname, creds->pinst[0] ? "." : "",
727 creds->pinst, creds->realm);
729 debug("Kerberos v4 TGT rejected.");
735 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
740 send_afs_tokens(void)
743 struct ViceIoctl parms;
744 struct ClearToken ct;
746 char buf[2048], *p, *server_cell;
749 /* Move over ktc_GetToken, here's something leaner. */
750 for (i = 0; i < 100; i++) { /* just in case */
751 parms.in = (char *) &i;
752 parms.in_size = sizeof(i);
754 parms.out_size = sizeof(buf);
755 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
759 /* Get secret token. */
760 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
761 if (creds.ticket_st.length > MAX_KTXT_LEN)
764 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
765 p += creds.ticket_st.length;
767 /* Get clear token. */
768 memcpy(&len, p, sizeof(len));
769 if (len != sizeof(struct ClearToken))
774 p += sizeof(len); /* primary flag */
777 /* Flesh out our credentials. */
778 strlcpy(creds.service, "afs", sizeof(creds.service));
779 creds.instance[0] = '\0';
780 strlcpy(creds.realm, server_cell, REALM_SZ);
781 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
782 creds.issue_date = ct.BeginTimestamp;
783 creds.lifetime = krb_time_to_life(creds.issue_date,
785 creds.kvno = ct.AuthHandle;
786 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
787 creds.pinst[0] = '\0';
789 /* Encode token, ship it off. */
790 if (creds_to_radix(&creds, (u_char *)buffer,
791 sizeof(buffer)) <= 0)
793 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
794 packet_put_cstring(buffer);
798 /* Roger, Roger. Clearance, Clarence. What's your vector,
800 type = packet_read(&len);
802 if (type == SSH_SMSG_FAILURE)
803 debug("AFS token for cell %s rejected.", server_cell);
804 else if (type != SSH_SMSG_SUCCESS)
805 packet_disconnect("Protocol error on AFS token response: %d", type);
812 * Tries to authenticate with any string-based challenge/response system.
813 * Note that the client code is not tied to s/key or TIS.
816 try_challenge_response_authentication(void)
822 char *challenge, *response;
824 debug("Doing challenge response authentication.");
826 for (i = 0; i < options.number_of_password_prompts; i++) {
827 /* request a challenge */
828 packet_start(SSH_CMSG_AUTH_TIS);
832 type = packet_read(&payload_len);
833 if (type != SSH_SMSG_FAILURE &&
834 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
835 packet_disconnect("Protocol error: got %d in response "
836 "to SSH_CMSG_AUTH_TIS", type);
838 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
839 debug("No challenge.");
842 challenge = packet_get_string(&clen);
843 packet_integrity_check(payload_len, (4 + clen), type);
844 snprintf(prompt, sizeof prompt, "%s%s", challenge,
845 strchr(challenge, '\n') ? "" : "\nResponse: ");
848 error("Permission denied, please try again.");
849 if (options.cipher == SSH_CIPHER_NONE)
850 log("WARNING: Encryption is disabled! "
851 "Reponse will be transmitted in clear text.");
852 response = read_passphrase(prompt, 0);
853 if (strcmp(response, "") == 0) {
857 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
858 ssh_put_password(response);
859 memset(response, 0, strlen(response));
863 type = packet_read(&payload_len);
864 if (type == SSH_SMSG_SUCCESS)
866 if (type != SSH_SMSG_FAILURE)
867 packet_disconnect("Protocol error: got %d in response "
868 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
875 * Tries to authenticate with plain passwd authentication.
878 try_password_authentication(char *prompt)
880 int type, i, payload_len;
883 debug("Doing password authentication.");
884 if (options.cipher == SSH_CIPHER_NONE)
885 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
886 for (i = 0; i < options.number_of_password_prompts; i++) {
888 error("Permission denied, please try again.");
889 password = read_passphrase(prompt, 0);
890 packet_start(SSH_CMSG_AUTH_PASSWORD);
891 ssh_put_password(password);
892 memset(password, 0, strlen(password));
897 type = packet_read(&payload_len);
898 if (type == SSH_SMSG_SUCCESS)
900 if (type != SSH_SMSG_FAILURE)
901 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
911 ssh_kex(char *host, struct sockaddr *hostaddr)
919 int ssh_cipher_default = SSH_CIPHER_3DES;
920 u_char session_key[SSH_SESSION_KEY_LENGTH];
922 u_int supported_ciphers;
923 u_int server_flags, client_flags;
924 int payload_len, clen, sum_len = 0;
927 debug("Waiting for server public key.");
929 /* Wait for a public key packet from the server. */
930 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
932 /* Get cookie from the packet. */
933 for (i = 0; i < 8; i++)
934 cookie[i] = packet_get_char();
936 /* Get the public key. */
937 public_key = RSA_new();
938 bits = packet_get_int();/* bits */
939 public_key->e = BN_new();
940 packet_get_bignum(public_key->e, &clen);
942 public_key->n = BN_new();
943 packet_get_bignum(public_key->n, &clen);
946 rbits = BN_num_bits(public_key->n);
948 log("Warning: Server lies about size of server public key: "
949 "actual size is %d bits vs. announced %d.", rbits, bits);
950 log("Warning: This may be due to an old implementation of ssh.");
952 /* Get the host key. */
953 host_key = RSA_new();
954 bits = packet_get_int();/* bits */
955 host_key->e = BN_new();
956 packet_get_bignum(host_key->e, &clen);
958 host_key->n = BN_new();
959 packet_get_bignum(host_key->n, &clen);
962 rbits = BN_num_bits(host_key->n);
964 log("Warning: Server lies about size of server host key: "
965 "actual size is %d bits vs. announced %d.", rbits, bits);
966 log("Warning: This may be due to an old implementation of ssh.");
969 /* Get protocol flags. */
970 server_flags = packet_get_int();
971 packet_set_protocol_flags(server_flags);
973 supported_ciphers = packet_get_int();
974 supported_authentications = packet_get_int();
976 debug("Received server public key (%d bits) and host key (%d bits).",
977 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
979 packet_integrity_check(payload_len,
980 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
981 SSH_SMSG_PUBLIC_KEY);
984 if (verify_host_key(host, hostaddr, &k) == -1)
985 fatal("host_key verification failed");
987 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
989 compute_session_id(session_id, cookie, host_key->n, public_key->n);
991 /* Generate a session key. */
995 * Generate an encryption key for the session. The key is a 256 bit
996 * random number, interpreted as a 32-byte key, with the least
997 * significant 8 bits being the first byte of the key.
999 for (i = 0; i < 32; i++) {
1001 rand = arc4random();
1002 session_key[i] = rand & 0xff;
1007 * According to the protocol spec, the first byte of the session key
1008 * is the highest byte of the integer. The session key is xored with
1009 * the first 16 bytes of the session id.
1012 BN_set_word(key, 0);
1013 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1014 BN_lshift(key, key, 8);
1016 BN_add_word(key, session_key[i] ^ session_id[i]);
1018 BN_add_word(key, session_key[i]);
1022 * Encrypt the integer using the public key and host key of the
1023 * server (key with smaller modulus first).
1025 if (BN_cmp(public_key->n, host_key->n) < 0) {
1026 /* Public key has smaller modulus. */
1027 if (BN_num_bits(host_key->n) <
1028 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1029 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1030 "SSH_KEY_BITS_RESERVED %d",
1031 BN_num_bits(host_key->n),
1032 BN_num_bits(public_key->n),
1033 SSH_KEY_BITS_RESERVED);
1035 rsa_public_encrypt(key, key, public_key);
1036 rsa_public_encrypt(key, key, host_key);
1038 /* Host key has smaller modulus (or they are equal). */
1039 if (BN_num_bits(public_key->n) <
1040 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1041 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1042 "SSH_KEY_BITS_RESERVED %d",
1043 BN_num_bits(public_key->n),
1044 BN_num_bits(host_key->n),
1045 SSH_KEY_BITS_RESERVED);
1047 rsa_public_encrypt(key, key, host_key);
1048 rsa_public_encrypt(key, key, public_key);
1051 /* Destroy the public keys since we no longer need them. */
1052 RSA_free(public_key);
1055 if (options.cipher == SSH_CIPHER_NOT_SET) {
1056 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1057 options.cipher = ssh_cipher_default;
1058 } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1059 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1060 log("No valid SSH1 cipher, using %.100s instead.",
1061 cipher_name(ssh_cipher_default));
1062 options.cipher = ssh_cipher_default;
1064 /* Check that the selected cipher is supported. */
1065 if (!(supported_ciphers & (1 << options.cipher)))
1066 fatal("Selected cipher type %.100s not supported by server.",
1067 cipher_name(options.cipher));
1069 debug("Encryption type: %.100s", cipher_name(options.cipher));
1071 /* Send the encrypted session key to the server. */
1072 packet_start(SSH_CMSG_SESSION_KEY);
1073 packet_put_char(options.cipher);
1075 /* Send the cookie back to the server. */
1076 for (i = 0; i < 8; i++)
1077 packet_put_char(cookie[i]);
1079 /* Send and destroy the encrypted encryption key integer. */
1080 packet_put_bignum(key);
1083 /* Send protocol flags. */
1084 packet_put_int(client_flags);
1086 /* Send the packet now. */
1088 packet_write_wait();
1090 debug("Sent encrypted session key.");
1092 /* Set the encryption key. */
1093 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1095 /* We will no longer need the session key here. Destroy any extra copies. */
1096 memset(session_key, 0, sizeof(session_key));
1099 * Expect a success message from the server. Note that this message
1100 * will be received in encrypted form.
1102 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1104 debug("Received encrypted confirmation.");
1111 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1112 Key **keys, int nkeys)
1115 krb5_context context = NULL;
1116 krb5_auth_context auth_context = NULL;
1121 if (supported_authentications == 0)
1122 fatal("ssh_userauth1: server supports no auth methods");
1124 /* Send the name of the user to log in as on the server. */
1125 packet_start(SSH_CMSG_USER);
1126 packet_put_cstring(server_user);
1128 packet_write_wait();
1131 * The server should respond with success if no authentication is
1132 * needed (the user has no password). Otherwise the server responds
1135 type = packet_read(&payload_len);
1137 /* check whether the connection was accepted without authentication. */
1138 if (type == SSH_SMSG_SUCCESS)
1140 if (type != SSH_SMSG_FAILURE)
1141 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1144 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1145 options.kerberos_authentication) {
1146 debug("Trying Kerberos v5 authentication.");
1148 if (try_krb5_authentication(&context, &auth_context)) {
1149 type = packet_read(&payload_len);
1150 if (type == SSH_SMSG_SUCCESS)
1152 if (type != SSH_SMSG_FAILURE)
1153 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1159 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1160 options.kerberos_authentication) {
1161 debug("Trying Kerberos v4 authentication.");
1163 if (try_krb4_authentication()) {
1164 type = packet_read(&payload_len);
1165 if (type == SSH_SMSG_SUCCESS)
1167 if (type != SSH_SMSG_FAILURE)
1168 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1174 * Use rhosts authentication if running in privileged socket and we
1175 * do not wish to remain anonymous.
1177 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1178 options.rhosts_authentication) {
1179 debug("Trying rhosts authentication.");
1180 packet_start(SSH_CMSG_AUTH_RHOSTS);
1181 packet_put_cstring(local_user);
1183 packet_write_wait();
1185 /* The server should respond with success or failure. */
1186 type = packet_read(&payload_len);
1187 if (type == SSH_SMSG_SUCCESS)
1189 if (type != SSH_SMSG_FAILURE)
1190 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1194 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1197 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1198 options.rhosts_rsa_authentication) {
1199 for (i = 0; i < nkeys; i++) {
1200 if (keys[i] != NULL && keys[i]->type == KEY_RSA1 &&
1201 try_rhosts_rsa_authentication(local_user, keys[i]))
1205 /* Try RSA authentication if the server supports it. */
1206 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1207 options.rsa_authentication) {
1209 * Try RSA authentication using the authentication agent. The
1210 * agent is tried first because no passphrase is needed for
1211 * it, whereas identity files may require passphrases.
1213 if (try_agent_authentication())
1216 /* Try RSA authentication for each identity. */
1217 for (i = 0; i < options.num_identity_files; i++)
1218 if (options.identity_keys[i] != NULL &&
1219 options.identity_keys[i]->type == KEY_RSA1 &&
1220 try_rsa_authentication(i))
1223 /* Try challenge response authentication if the server supports it. */
1224 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1225 options.challenge_response_authentication && !options.batch_mode) {
1226 if (try_challenge_response_authentication())
1229 /* Try password authentication if the server supports it. */
1230 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1231 options.password_authentication && !options.batch_mode) {
1234 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1236 if (try_password_authentication(prompt))
1239 /* All authentication methods have failed. Exit with an error message. */
1240 fatal("Permission denied.");
1245 /* Try Kerberos v5 TGT passing. */
1246 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1247 options.kerberos_tgt_passing && context && auth_context) {
1248 if (options.cipher == SSH_CIPHER_NONE)
1249 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1250 send_krb5_tgt(context, auth_context);
1253 krb5_auth_con_free(context, auth_context);
1255 krb5_free_context(context);
1259 /* Try Kerberos v4 TGT passing if the server supports it. */
1260 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1261 options.kerberos_tgt_passing) {
1262 if (options.cipher == SSH_CIPHER_NONE)
1263 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1266 /* Try AFS token passing if the server supports it. */
1267 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1268 options.afs_token_passing && k_hasafs()) {
1269 if (options.cipher == SSH_CIPHER_NONE)
1270 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1275 return; /* need statement after label */