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.37 2001/06/26 16:15:24 dugsong 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(const char *authfile)
211 Key *public, *private;
212 char buf[300], *passphrase, *comment;
213 int i, type, quit, plen, clen;
215 /* Try to load identification for the authentication key. */
217 public = key_load_public_type(KEY_RSA1, authfile, &comment);
218 if (public == NULL) {
219 /* Could not load it. Fail. */
222 debug("Trying RSA authentication with key '%.100s'", comment);
224 /* Tell the server that we are willing to authenticate using this key. */
225 packet_start(SSH_CMSG_AUTH_RSA);
226 packet_put_bignum(public->rsa->n);
230 /* We no longer need the public key. */
233 /* Wait for server's response. */
234 type = packet_read(&plen);
237 * The server responds with failure if it doesn\'t like our key or
238 * doesn\'t support RSA authentication.
240 if (type == SSH_SMSG_FAILURE) {
241 debug("Server refused our key.");
245 /* Otherwise, the server should respond with a challenge. */
246 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
247 packet_disconnect("Protocol error during RSA authentication: %d", type);
249 /* Get the challenge from the packet. */
250 challenge = BN_new();
251 packet_get_bignum(challenge, &clen);
253 packet_integrity_check(plen, clen, type);
255 debug("Received RSA challenge from server.");
258 * Load the private key. Try first with empty passphrase; if it
259 * fails, ask for a passphrase.
261 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
262 if (private == NULL && !options.batch_mode) {
263 snprintf(buf, sizeof(buf),
264 "Enter passphrase for RSA key '%.100s': ", comment);
265 for (i = 0; i < options.number_of_password_prompts; i++) {
266 passphrase = read_passphrase(buf, 0);
267 if (strcmp(passphrase, "") != 0) {
268 private = key_load_private_type(KEY_RSA1,
269 authfile, passphrase, NULL);
272 debug2("no passphrase given, try next key");
275 memset(passphrase, 0, strlen(passphrase));
277 if (private != NULL || quit)
279 debug2("bad passphrase given, try again...");
282 /* We no longer need the comment. */
285 if (private == NULL) {
286 if (!options.batch_mode)
287 error("Bad passphrase.");
289 /* Send a dummy response packet to avoid protocol error. */
290 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
291 for (i = 0; i < 16; i++)
296 /* Expect the server to reject it... */
297 packet_read_expect(&plen, SSH_SMSG_FAILURE);
298 BN_clear_free(challenge);
302 /* Compute and send a response to the challenge. */
303 respond_to_rsa_challenge(challenge, private->rsa);
305 /* Destroy the private key. */
308 /* We no longer need the challenge. */
309 BN_clear_free(challenge);
311 /* Wait for response from the server. */
312 type = packet_read(&plen);
313 if (type == SSH_SMSG_SUCCESS) {
314 debug("RSA authentication accepted by server.");
317 if (type != SSH_SMSG_FAILURE)
318 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
319 debug("RSA authentication refused.");
324 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
325 * authentication and RSA host authentication.
328 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
334 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
336 /* Tell the server that we are willing to authenticate using this key. */
337 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
338 packet_put_cstring(local_user);
339 packet_put_int(BN_num_bits(host_key->rsa->n));
340 packet_put_bignum(host_key->rsa->e);
341 packet_put_bignum(host_key->rsa->n);
345 /* Wait for server's response. */
346 type = packet_read(&plen);
348 /* The server responds with failure if it doesn't admit our
349 .rhosts authentication or doesn't know our host key. */
350 if (type == SSH_SMSG_FAILURE) {
351 debug("Server refused our rhosts authentication or host key.");
354 /* Otherwise, the server should respond with a challenge. */
355 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
356 packet_disconnect("Protocol error during RSA authentication: %d", type);
358 /* Get the challenge from the packet. */
359 challenge = BN_new();
360 packet_get_bignum(challenge, &clen);
362 packet_integrity_check(plen, clen, type);
364 debug("Received RSA challenge for host key from server.");
366 /* Compute a response to the challenge. */
367 respond_to_rsa_challenge(challenge, host_key->rsa);
369 /* We no longer need the challenge. */
370 BN_clear_free(challenge);
372 /* Wait for response from the server. */
373 type = packet_read(&plen);
374 if (type == SSH_SMSG_SUCCESS) {
375 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
378 if (type != SSH_SMSG_FAILURE)
379 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
380 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
386 try_krb4_authentication(void)
388 KTEXT_ST auth; /* Kerberos data */
395 Key_schedule schedule;
396 u_long checksum, cksum;
398 struct sockaddr_in local, foreign;
401 /* Don't do anything if we don't have any tickets. */
402 if (stat(tkt_string(), &st) < 0)
405 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
408 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
410 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
413 /* This can really be anything. */
414 checksum = (u_long)getpid();
416 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
418 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
421 /* Get session key to decrypt the server's reply with. */
422 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
424 debug("get_cred failed: %s", krb_err_txt[r]);
427 des_key_sched((des_cblock *) cred.session, schedule);
429 /* Send authentication info to server. */
430 packet_start(SSH_CMSG_AUTH_KERBEROS);
431 packet_put_string((char *) auth.dat, auth.length);
435 /* Zero the buffer. */
436 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
438 slen = sizeof(local);
439 memset(&local, 0, sizeof(local));
440 if (getsockname(packet_get_connection_in(),
441 (struct sockaddr *)&local, &slen) < 0)
442 debug("getsockname failed: %s", strerror(errno));
444 slen = sizeof(foreign);
445 memset(&foreign, 0, sizeof(foreign));
446 if (getpeername(packet_get_connection_in(),
447 (struct sockaddr *)&foreign, &slen) < 0) {
448 debug("getpeername failed: %s", strerror(errno));
451 /* Get server reply. */
452 type = packet_read(&plen);
454 case SSH_SMSG_FAILURE:
455 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
456 debug("Kerberos v4 authentication failed.");
460 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
461 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
462 debug("Kerberos v4 authentication accepted.");
464 /* Get server's response. */
465 reply = packet_get_string((u_int *) &auth.length);
466 memcpy(auth.dat, reply, auth.length);
469 packet_integrity_check(plen, 4 + auth.length, type);
472 * If his response isn't properly encrypted with the session
473 * key, and the decrypted checksum fails to match, he's
476 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
477 &foreign, &local, &msg_data);
479 debug("Kerberos v4 krb_rd_priv failed: %s",
481 packet_disconnect("Kerberos v4 challenge failed!");
483 /* Fetch the (incremented) checksum that we supplied in the request. */
484 memcpy((char *)&cksum, (char *)msg_data.app_data,
486 cksum = ntohl(cksum);
488 /* If it matches, we're golden. */
489 if (cksum == checksum + 1) {
490 debug("Kerberos v4 challenge successful.");
493 packet_disconnect("Kerberos v4 challenge failed!");
497 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
506 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
508 krb5_error_code problem;
511 krb5_ccache ccache = NULL;
512 const char *remotehost;
514 int type, payload_len;
515 krb5_ap_rep_enc_part *reply = NULL;
518 memset(&ap, 0, sizeof(ap));
520 problem = krb5_init_context(context);
522 debug("Kerberos v5: krb5_init_context failed");
527 tkfile = krb5_cc_default_name(*context);
528 if (strncmp(tkfile, "FILE:", 5) == 0)
531 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
532 debug("Kerberos v5: could not get default ccache (permission denied).");
537 problem = krb5_cc_default(*context, &ccache);
539 debug("Kerberos v5: krb5_cc_default failed: %s",
540 krb5_get_err_text(*context, problem));
545 remotehost = get_canonical_hostname(1);
547 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
548 "host", remotehost, NULL, ccache, &ap);
550 debug("Kerberos v5: krb5_mk_req failed: %s",
551 krb5_get_err_text(*context, problem));
556 packet_start(SSH_CMSG_AUTH_KERBEROS);
557 packet_put_string((char *) ap.data, ap.length);
564 type = packet_read(&payload_len);
566 case SSH_SMSG_FAILURE:
567 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
568 debug("Kerberos v5 authentication failed.");
572 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
573 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
574 debug("Kerberos v5 authentication accepted.");
576 /* Get server's response. */
577 ap.data = packet_get_string((unsigned int *) &ap.length);
579 packet_integrity_check(payload_len, 4 + ap.length, type);
580 /* XXX je to dobre? */
582 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
590 packet_disconnect("Protocol error on Kerberos v5 response: %d",
599 krb5_cc_close(*context, ccache);
601 krb5_free_ap_rep_enc_part(*context, reply);
609 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
611 int fd, type, payload_len;
612 krb5_error_code problem;
614 krb5_ccache ccache = NULL;
616 krb5_kdc_flags flags;
617 const char *remotehost;
619 memset(&creds, 0, sizeof(creds));
620 memset(&outbuf, 0, sizeof(outbuf));
622 fd = packet_get_connection_in();
624 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
628 problem = krb5_cc_default(context, &ccache);
632 problem = krb5_cc_get_principal(context, ccache, &creds.client);
636 problem = krb5_build_principal(context, &creds.server,
637 strlen(creds.client->realm), creds.client->realm,
638 "krbtgt", creds.client->realm, NULL);
642 creds.times.endtime = 0;
645 flags.b.forwarded = 1;
646 flags.b.forwardable = krb5_config_get_bool(context, NULL,
647 "libdefaults", "forwardable", NULL);
649 remotehost = get_canonical_hostname(1);
651 problem = krb5_get_forwarded_creds(context, auth_context,
652 ccache, flags.i, remotehost, &creds, &outbuf);
656 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
657 packet_put_string((char *)outbuf.data, outbuf.length);
661 type = packet_read(&payload_len);
663 if (type == SSH_SMSG_SUCCESS) {
666 krb5_unparse_name(context, creds.client, &pname);
667 debug("Kerberos v5 TGT forwarded (%s).", pname);
670 debug("Kerberos v5 TGT forwarding failed.");
676 debug("Kerberos v5 TGT forwarding failed: %s",
677 krb5_get_err_text(context, problem));
679 krb5_free_principal(context, creds.client);
681 krb5_free_principal(context, creds.server);
683 krb5_cc_close(context, ccache);
695 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
696 int problem, type, len;
698 /* Don't do anything if we don't have any tickets. */
699 if (stat(tkt_string(), &st) < 0)
702 creds = xmalloc(sizeof(*creds));
704 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
708 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
712 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
716 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
718 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
719 packet_put_cstring(buffer);
723 type = packet_read(&len);
725 if (type == SSH_SMSG_SUCCESS)
726 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
727 creds->pname, creds->pinst[0] ? "." : "",
728 creds->pinst, creds->realm);
730 debug("Kerberos v4 TGT rejected.");
736 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
741 send_afs_tokens(void)
744 struct ViceIoctl parms;
745 struct ClearToken ct;
747 char buf[2048], *p, *server_cell;
750 /* Move over ktc_GetToken, here's something leaner. */
751 for (i = 0; i < 100; i++) { /* just in case */
752 parms.in = (char *) &i;
753 parms.in_size = sizeof(i);
755 parms.out_size = sizeof(buf);
756 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
760 /* Get secret token. */
761 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
762 if (creds.ticket_st.length > MAX_KTXT_LEN)
765 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
766 p += creds.ticket_st.length;
768 /* Get clear token. */
769 memcpy(&len, p, sizeof(len));
770 if (len != sizeof(struct ClearToken))
775 p += sizeof(len); /* primary flag */
778 /* Flesh out our credentials. */
779 strlcpy(creds.service, "afs", sizeof(creds.service));
780 creds.instance[0] = '\0';
781 strlcpy(creds.realm, server_cell, REALM_SZ);
782 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
783 creds.issue_date = ct.BeginTimestamp;
784 creds.lifetime = krb_time_to_life(creds.issue_date,
786 creds.kvno = ct.AuthHandle;
787 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
788 creds.pinst[0] = '\0';
790 /* Encode token, ship it off. */
791 if (creds_to_radix(&creds, (u_char *)buffer,
792 sizeof(buffer)) <= 0)
794 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
795 packet_put_cstring(buffer);
799 /* Roger, Roger. Clearance, Clarence. What's your vector,
801 type = packet_read(&len);
803 if (type == SSH_SMSG_FAILURE)
804 debug("AFS token for cell %s rejected.", server_cell);
805 else if (type != SSH_SMSG_SUCCESS)
806 packet_disconnect("Protocol error on AFS token response: %d", type);
813 * Tries to authenticate with any string-based challenge/response system.
814 * Note that the client code is not tied to s/key or TIS.
817 try_challenge_response_authentication(void)
823 char *challenge, *response;
825 debug("Doing challenge reponse authentication.");
827 for (i = 0; i < options.number_of_password_prompts; i++) {
828 /* request a challenge */
829 packet_start(SSH_CMSG_AUTH_TIS);
833 type = packet_read(&payload_len);
834 if (type != SSH_SMSG_FAILURE &&
835 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
836 packet_disconnect("Protocol error: got %d in response "
837 "to SSH_CMSG_AUTH_TIS", type);
839 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
840 debug("No challenge.");
843 challenge = packet_get_string(&clen);
844 packet_integrity_check(payload_len, (4 + clen), type);
845 snprintf(prompt, sizeof prompt, "%s%s", challenge,
846 strchr(challenge, '\n') ? "" : "\nResponse: ");
849 error("Permission denied, please try again.");
850 if (options.cipher == SSH_CIPHER_NONE)
851 log("WARNING: Encryption is disabled! "
852 "Reponse will be transmitted in clear text.");
853 response = read_passphrase(prompt, 0);
854 if (strcmp(response, "") == 0) {
858 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
859 ssh_put_password(response);
860 memset(response, 0, strlen(response));
864 type = packet_read(&payload_len);
865 if (type == SSH_SMSG_SUCCESS)
867 if (type != SSH_SMSG_FAILURE)
868 packet_disconnect("Protocol error: got %d in response "
869 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
876 * Tries to authenticate with plain passwd authentication.
879 try_password_authentication(char *prompt)
881 int type, i, payload_len;
884 debug("Doing password authentication.");
885 if (options.cipher == SSH_CIPHER_NONE)
886 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
887 for (i = 0; i < options.number_of_password_prompts; i++) {
889 error("Permission denied, please try again.");
890 password = read_passphrase(prompt, 0);
891 packet_start(SSH_CMSG_AUTH_PASSWORD);
892 ssh_put_password(password);
893 memset(password, 0, strlen(password));
898 type = packet_read(&payload_len);
899 if (type == SSH_SMSG_SUCCESS)
901 if (type != SSH_SMSG_FAILURE)
902 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
912 ssh_kex(char *host, struct sockaddr *hostaddr)
920 int ssh_cipher_default = SSH_CIPHER_3DES;
921 u_char session_key[SSH_SESSION_KEY_LENGTH];
923 u_int supported_ciphers;
924 u_int server_flags, client_flags;
925 int payload_len, clen, sum_len = 0;
928 debug("Waiting for server public key.");
930 /* Wait for a public key packet from the server. */
931 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
933 /* Get cookie from the packet. */
934 for (i = 0; i < 8; i++)
935 cookie[i] = packet_get_char();
937 /* Get the public key. */
938 public_key = RSA_new();
939 bits = packet_get_int();/* bits */
940 public_key->e = BN_new();
941 packet_get_bignum(public_key->e, &clen);
943 public_key->n = BN_new();
944 packet_get_bignum(public_key->n, &clen);
947 rbits = BN_num_bits(public_key->n);
949 log("Warning: Server lies about size of server public key: "
950 "actual size is %d bits vs. announced %d.", rbits, bits);
951 log("Warning: This may be due to an old implementation of ssh.");
953 /* Get the host key. */
954 host_key = RSA_new();
955 bits = packet_get_int();/* bits */
956 host_key->e = BN_new();
957 packet_get_bignum(host_key->e, &clen);
959 host_key->n = BN_new();
960 packet_get_bignum(host_key->n, &clen);
963 rbits = BN_num_bits(host_key->n);
965 log("Warning: Server lies about size of server host key: "
966 "actual size is %d bits vs. announced %d.", rbits, bits);
967 log("Warning: This may be due to an old implementation of ssh.");
970 /* Get protocol flags. */
971 server_flags = packet_get_int();
972 packet_set_protocol_flags(server_flags);
974 supported_ciphers = packet_get_int();
975 supported_authentications = packet_get_int();
977 debug("Received server public key (%d bits) and host key (%d bits).",
978 BN_num_bits(public_key->n), BN_num_bits(host_key->n));
980 packet_integrity_check(payload_len,
981 8 + 4 + sum_len + 0 + 4 + 0 + 0 + 4 + 4 + 4,
982 SSH_SMSG_PUBLIC_KEY);
985 if (verify_host_key(host, hostaddr, &k) == -1)
986 fatal("host_key verification failed");
988 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
990 compute_session_id(session_id, cookie, host_key->n, public_key->n);
992 /* Generate a session key. */
996 * Generate an encryption key for the session. The key is a 256 bit
997 * random number, interpreted as a 32-byte key, with the least
998 * significant 8 bits being the first byte of the key.
1000 for (i = 0; i < 32; i++) {
1002 rand = arc4random();
1003 session_key[i] = rand & 0xff;
1008 * According to the protocol spec, the first byte of the session key
1009 * is the highest byte of the integer. The session key is xored with
1010 * the first 16 bytes of the session id.
1013 BN_set_word(key, 0);
1014 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1015 BN_lshift(key, key, 8);
1017 BN_add_word(key, session_key[i] ^ session_id[i]);
1019 BN_add_word(key, session_key[i]);
1023 * Encrypt the integer using the public key and host key of the
1024 * server (key with smaller modulus first).
1026 if (BN_cmp(public_key->n, host_key->n) < 0) {
1027 /* Public key has smaller modulus. */
1028 if (BN_num_bits(host_key->n) <
1029 BN_num_bits(public_key->n) + SSH_KEY_BITS_RESERVED) {
1030 fatal("respond_to_rsa_challenge: host_key %d < public_key %d + "
1031 "SSH_KEY_BITS_RESERVED %d",
1032 BN_num_bits(host_key->n),
1033 BN_num_bits(public_key->n),
1034 SSH_KEY_BITS_RESERVED);
1036 rsa_public_encrypt(key, key, public_key);
1037 rsa_public_encrypt(key, key, host_key);
1039 /* Host key has smaller modulus (or they are equal). */
1040 if (BN_num_bits(public_key->n) <
1041 BN_num_bits(host_key->n) + SSH_KEY_BITS_RESERVED) {
1042 fatal("respond_to_rsa_challenge: public_key %d < host_key %d + "
1043 "SSH_KEY_BITS_RESERVED %d",
1044 BN_num_bits(public_key->n),
1045 BN_num_bits(host_key->n),
1046 SSH_KEY_BITS_RESERVED);
1048 rsa_public_encrypt(key, key, host_key);
1049 rsa_public_encrypt(key, key, public_key);
1052 /* Destroy the public keys since we no longer need them. */
1053 RSA_free(public_key);
1056 if (options.cipher == SSH_CIPHER_NOT_SET) {
1057 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1058 options.cipher = ssh_cipher_default;
1059 } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1060 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1061 log("No valid SSH1 cipher, using %.100s instead.",
1062 cipher_name(ssh_cipher_default));
1063 options.cipher = ssh_cipher_default;
1065 /* Check that the selected cipher is supported. */
1066 if (!(supported_ciphers & (1 << options.cipher)))
1067 fatal("Selected cipher type %.100s not supported by server.",
1068 cipher_name(options.cipher));
1070 debug("Encryption type: %.100s", cipher_name(options.cipher));
1072 /* Send the encrypted session key to the server. */
1073 packet_start(SSH_CMSG_SESSION_KEY);
1074 packet_put_char(options.cipher);
1076 /* Send the cookie back to the server. */
1077 for (i = 0; i < 8; i++)
1078 packet_put_char(cookie[i]);
1080 /* Send and destroy the encrypted encryption key integer. */
1081 packet_put_bignum(key);
1084 /* Send protocol flags. */
1085 packet_put_int(client_flags);
1087 /* Send the packet now. */
1089 packet_write_wait();
1091 debug("Sent encrypted session key.");
1093 /* Set the encryption key. */
1094 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1096 /* We will no longer need the session key here. Destroy any extra copies. */
1097 memset(session_key, 0, sizeof(session_key));
1100 * Expect a success message from the server. Note that this message
1101 * will be received in encrypted form.
1103 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1105 debug("Received encrypted confirmation.");
1112 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1113 Key **keys, int nkeys)
1116 krb5_context context = NULL;
1117 krb5_auth_context auth_context = NULL;
1122 if (supported_authentications == 0)
1123 fatal("ssh_userauth1: server supports no auth methods");
1125 /* Send the name of the user to log in as on the server. */
1126 packet_start(SSH_CMSG_USER);
1127 packet_put_cstring(server_user);
1129 packet_write_wait();
1132 * The server should respond with success if no authentication is
1133 * needed (the user has no password). Otherwise the server responds
1136 type = packet_read(&payload_len);
1138 /* check whether the connection was accepted without authentication. */
1139 if (type == SSH_SMSG_SUCCESS)
1141 if (type != SSH_SMSG_FAILURE)
1142 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1145 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1146 options.kerberos_authentication) {
1147 debug("Trying Kerberos v5 authentication.");
1149 if (try_krb5_authentication(&context, &auth_context)) {
1150 type = packet_read(&payload_len);
1151 if (type == SSH_SMSG_SUCCESS)
1153 if (type != SSH_SMSG_FAILURE)
1154 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1160 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1161 options.kerberos_authentication) {
1162 debug("Trying Kerberos v4 authentication.");
1164 if (try_krb4_authentication()) {
1165 type = packet_read(&payload_len);
1166 if (type == SSH_SMSG_SUCCESS)
1168 if (type != SSH_SMSG_FAILURE)
1169 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1175 * Use rhosts authentication if running in privileged socket and we
1176 * do not wish to remain anonymous.
1178 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1179 options.rhosts_authentication) {
1180 debug("Trying rhosts authentication.");
1181 packet_start(SSH_CMSG_AUTH_RHOSTS);
1182 packet_put_cstring(local_user);
1184 packet_write_wait();
1186 /* The server should respond with success or failure. */
1187 type = packet_read(&payload_len);
1188 if (type == SSH_SMSG_SUCCESS)
1190 if (type != SSH_SMSG_FAILURE)
1191 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1195 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1198 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1199 options.rhosts_rsa_authentication) {
1200 for (i = 0; i < nkeys; i++) {
1201 if (keys[i] != NULL && keys[i]->type == KEY_RSA1 &&
1202 try_rhosts_rsa_authentication(local_user, keys[i]))
1206 /* Try RSA authentication if the server supports it. */
1207 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1208 options.rsa_authentication) {
1210 * Try RSA authentication using the authentication agent. The
1211 * agent is tried first because no passphrase is needed for
1212 * it, whereas identity files may require passphrases.
1214 if (try_agent_authentication())
1217 /* Try RSA authentication for each identity. */
1218 for (i = 0; i < options.num_identity_files; i++)
1219 if (options.identity_keys[i] != NULL &&
1220 options.identity_keys[i]->type == KEY_RSA1 &&
1221 try_rsa_authentication(options.identity_files[i]))
1224 /* Try challenge response authentication if the server supports it. */
1225 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1226 options.challenge_response_authentication && !options.batch_mode) {
1227 if (try_challenge_response_authentication())
1230 /* Try password authentication if the server supports it. */
1231 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1232 options.password_authentication && !options.batch_mode) {
1235 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1237 if (try_password_authentication(prompt))
1240 /* All authentication methods have failed. Exit with an error message. */
1241 fatal("Permission denied.");
1246 /* Try Kerberos v5 TGT passing. */
1247 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1248 options.kerberos_tgt_passing && context && auth_context) {
1249 if (options.cipher == SSH_CIPHER_NONE)
1250 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1251 send_krb5_tgt(context, auth_context);
1254 krb5_auth_con_free(context, auth_context);
1256 krb5_free_context(context);
1260 /* Try Kerberos v4 TGT passing if the server supports it. */
1261 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1262 options.kerberos_tgt_passing) {
1263 if (options.cipher == SSH_CIPHER_NONE)
1264 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1267 /* Try AFS token passing if the server supports it. */
1268 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1269 options.afs_token_passing && k_hasafs()) {
1270 if (options.cipher == SSH_CIPHER_NONE)
1271 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");