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.52 2002/08/08 13:50:23 aaron Exp $");
17 RCSID("$FreeBSD: src/crypto/openssh/sshconnect1.c,v 1.2.2.9 2003/02/03 17:31:08 des Exp $");
18 RCSID("$DragonFly: src/crypto/openssh/Attic/sshconnect1.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
20 #include <openssl/bn.h>
21 #include <openssl/md5.h>
29 #define krb5_get_err_text(context,code) error_message(code)
49 #include "sshconnect.h"
56 /* Session id for the current session. */
57 u_char session_id[16];
58 u_int supported_authentications = 0;
60 extern Options options;
61 extern char *__progname;
64 * Checks if the user has an authentication agent, and if so, tries to
65 * authenticate using the agent.
68 try_agent_authentication(void)
72 AuthenticationConnection *auth;
78 /* Get connection to the agent. */
79 auth = ssh_get_authentication_connection();
83 if ((challenge = BN_new()) == NULL)
84 fatal("try_agent_authentication: BN_new failed");
85 /* Loop through identities served by the agent. */
86 for (key = ssh_get_first_identity(auth, &comment, 1);
88 key = ssh_get_next_identity(auth, &comment, 1)) {
90 /* Try this identity. */
91 debug("Trying RSA authentication via agent with '%.100s'", comment);
94 /* Tell the server that we are willing to authenticate using this key. */
95 packet_start(SSH_CMSG_AUTH_RSA);
96 packet_put_bignum(key->rsa->n);
100 /* Wait for server's response. */
101 type = packet_read();
103 /* The server sends failure if it doesn\'t like our key or
104 does not support RSA authentication. */
105 if (type == SSH_SMSG_FAILURE) {
106 debug("Server refused our key.");
110 /* Otherwise it should have sent a challenge. */
111 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
112 packet_disconnect("Protocol error during RSA authentication: %d",
115 packet_get_bignum(challenge);
118 debug("Received RSA challenge from server.");
120 /* Ask the agent to decrypt the challenge. */
121 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
123 * The agent failed to authenticate this identifier
124 * although it advertised it supports this. Just
125 * return a wrong value.
127 log("Authentication agent failed to decrypt challenge.");
128 memset(response, 0, sizeof(response));
131 debug("Sending response to RSA challenge.");
133 /* Send the decrypted challenge back to the server. */
134 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
135 for (i = 0; i < 16; i++)
136 packet_put_char(response[i]);
140 /* Wait for response from the server. */
141 type = packet_read();
143 /* The server returns success if it accepted the authentication. */
144 if (type == SSH_SMSG_SUCCESS) {
145 ssh_close_authentication_connection(auth);
146 BN_clear_free(challenge);
147 debug("RSA authentication accepted by server.");
150 /* Otherwise it should return failure. */
151 if (type != SSH_SMSG_FAILURE)
152 packet_disconnect("Protocol error waiting RSA auth response: %d",
155 ssh_close_authentication_connection(auth);
156 BN_clear_free(challenge);
157 debug("RSA authentication using agent refused.");
162 * Computes the proper response to a RSA challenge, and sends the response to
166 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
168 u_char buf[32], response[16];
172 /* Decrypt the challenge using the private key. */
173 /* XXX think about Bleichenbacher, too */
174 if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
176 "respond_to_rsa_challenge: rsa_private_decrypt failed");
178 /* Compute the response. */
179 /* The response is MD5 of decrypted challenge plus session id. */
180 len = BN_num_bytes(challenge);
181 if (len <= 0 || len > sizeof(buf))
183 "respond_to_rsa_challenge: bad challenge length %d", len);
185 memset(buf, 0, sizeof(buf));
186 BN_bn2bin(challenge, buf + sizeof(buf) - len);
188 MD5_Update(&md, buf, 32);
189 MD5_Update(&md, session_id, 16);
190 MD5_Final(response, &md);
192 debug("Sending response to host key RSA challenge.");
194 /* Send the response back to the server. */
195 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
196 for (i = 0; i < 16; i++)
197 packet_put_char(response[i]);
201 memset(buf, 0, sizeof(buf));
202 memset(response, 0, sizeof(response));
203 memset(&md, 0, sizeof(md));
207 * Checks if the user has authentication file, and if so, tries to authenticate
211 try_rsa_authentication(int idx)
214 Key *public, *private;
215 char buf[300], *passphrase, *comment, *authfile;
218 public = options.identity_keys[idx];
219 authfile = options.identity_files[idx];
220 comment = xstrdup(authfile);
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 /* Wait for server's response. */
231 type = packet_read();
234 * The server responds with failure if it doesn\'t like our key or
235 * doesn\'t support RSA authentication.
237 if (type == SSH_SMSG_FAILURE) {
238 debug("Server refused our key.");
242 /* Otherwise, the server should respond with a challenge. */
243 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
244 packet_disconnect("Protocol error during RSA authentication: %d", type);
246 /* Get the challenge from the packet. */
247 if ((challenge = BN_new()) == NULL)
248 fatal("try_rsa_authentication: BN_new failed");
249 packet_get_bignum(challenge);
252 debug("Received RSA challenge from server.");
255 * If the key is not stored in external hardware, we have to
256 * load the private key. Try first with empty passphrase; if it
257 * fails, ask for a passphrase.
259 if (public->flags & KEY_FLAG_EXT)
262 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
263 if (private == NULL && !options.batch_mode) {
264 snprintf(buf, sizeof(buf),
265 "Enter passphrase for RSA key '%.100s': ", comment);
266 for (i = 0; i < options.number_of_password_prompts; i++) {
267 passphrase = read_passphrase(buf, 0);
268 if (strcmp(passphrase, "") != 0) {
269 private = key_load_private_type(KEY_RSA1,
270 authfile, passphrase, NULL);
273 debug2("no passphrase given, try next key");
276 memset(passphrase, 0, strlen(passphrase));
278 if (private != NULL || quit)
280 debug2("bad passphrase given, try again...");
283 /* We no longer need the comment. */
286 if (private == NULL) {
287 if (!options.batch_mode)
288 error("Bad passphrase.");
290 /* Send a dummy response packet to avoid protocol error. */
291 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
292 for (i = 0; i < 16; i++)
297 /* Expect the server to reject it... */
298 packet_read_expect(SSH_SMSG_FAILURE);
299 BN_clear_free(challenge);
303 /* Compute and send a response to the challenge. */
304 respond_to_rsa_challenge(challenge, private->rsa);
306 /* Destroy the private key unless it in external hardware. */
307 if (!(private->flags & KEY_FLAG_EXT))
310 /* We no longer need the challenge. */
311 BN_clear_free(challenge);
313 /* Wait for response from the server. */
314 type = packet_read();
315 if (type == SSH_SMSG_SUCCESS) {
316 debug("RSA authentication accepted by server.");
319 if (type != SSH_SMSG_FAILURE)
320 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
321 debug("RSA authentication refused.");
326 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
327 * authentication and RSA host authentication.
330 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
335 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
337 /* Tell the server that we are willing to authenticate using this key. */
338 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
339 packet_put_cstring(local_user);
340 packet_put_int(BN_num_bits(host_key->rsa->n));
341 packet_put_bignum(host_key->rsa->e);
342 packet_put_bignum(host_key->rsa->n);
346 /* Wait for server's response. */
347 type = packet_read();
349 /* The server responds with failure if it doesn't admit our
350 .rhosts authentication or doesn't know our host key. */
351 if (type == SSH_SMSG_FAILURE) {
352 debug("Server refused our rhosts authentication or host key.");
355 /* Otherwise, the server should respond with a challenge. */
356 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
357 packet_disconnect("Protocol error during RSA authentication: %d", type);
359 /* Get the challenge from the packet. */
360 if ((challenge = BN_new()) == NULL)
361 fatal("try_rhosts_rsa_authentication: BN_new failed");
362 packet_get_bignum(challenge);
365 debug("Received RSA challenge for host key from server.");
367 /* Compute a response to the challenge. */
368 respond_to_rsa_challenge(challenge, host_key->rsa);
370 /* We no longer need the challenge. */
371 BN_clear_free(challenge);
373 /* Wait for response from the server. */
374 type = packet_read();
375 if (type == SSH_SMSG_SUCCESS) {
376 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
379 if (type != SSH_SMSG_FAILURE)
380 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
381 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
387 try_krb4_authentication(void)
389 KTEXT_ST auth; /* Kerberos data */
396 Key_schedule schedule;
397 u_long checksum, cksum;
399 struct sockaddr_in local, foreign;
402 /* Don't do anything if we don't have any tickets. */
403 if (stat(tkt_string(), &st) < 0)
406 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
409 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
411 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
414 /* This can really be anything. */
415 checksum = (u_long)getpid();
417 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
419 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
422 /* Get session key to decrypt the server's reply with. */
423 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
425 debug("get_cred failed: %s", krb_err_txt[r]);
428 des_key_sched((des_cblock *) cred.session, schedule);
430 /* Send authentication info to server. */
431 packet_start(SSH_CMSG_AUTH_KERBEROS);
432 packet_put_string((char *) auth.dat, auth.length);
436 /* Zero the buffer. */
437 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
439 slen = sizeof(local);
440 memset(&local, 0, sizeof(local));
441 if (getsockname(packet_get_connection_in(),
442 (struct sockaddr *)&local, &slen) < 0)
443 debug("getsockname failed: %s", strerror(errno));
445 slen = sizeof(foreign);
446 memset(&foreign, 0, sizeof(foreign));
447 if (getpeername(packet_get_connection_in(),
448 (struct sockaddr *)&foreign, &slen) < 0) {
449 debug("getpeername failed: %s", strerror(errno));
452 /* Get server reply. */
453 type = packet_read();
455 case SSH_SMSG_FAILURE:
456 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
457 debug("Kerberos v4 authentication failed.");
461 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
462 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
463 debug("Kerberos v4 authentication accepted.");
465 /* Get server's response. */
466 reply = packet_get_string((u_int *) &auth.length);
467 if (auth.length >= MAX_KTXT_LEN)
468 fatal("Kerberos v4: Malformed response from server");
469 memcpy(auth.dat, reply, auth.length);
475 * If his response isn't properly encrypted with the session
476 * key, and the decrypted checksum fails to match, he's
479 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
480 &foreign, &local, &msg_data);
482 debug("Kerberos v4 krb_rd_priv failed: %s",
484 packet_disconnect("Kerberos v4 challenge failed!");
486 /* Fetch the (incremented) checksum that we supplied in the request. */
487 memcpy((char *)&cksum, (char *)msg_data.app_data,
489 cksum = ntohl(cksum);
491 /* If it matches, we're golden. */
492 if (cksum == checksum + 1) {
493 debug("Kerberos v4 challenge successful.");
496 packet_disconnect("Kerberos v4 challenge failed!");
500 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
509 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
511 krb5_error_code problem;
514 krb5_ccache ccache = NULL;
515 const char *remotehost;
518 krb5_ap_rep_enc_part *reply = NULL;
521 memset(&ap, 0, sizeof(ap));
523 problem = krb5_init_context(context);
525 debug("Kerberos v5: krb5_init_context failed");
530 problem = krb5_auth_con_init(*context, auth_context);
532 debug("Kerberos v5: krb5_auth_con_init failed");
538 problem = krb5_auth_con_setflags(*context, *auth_context,
539 KRB5_AUTH_CONTEXT_RET_TIME);
541 debug("Keberos v5: krb5_auth_con_setflags failed");
547 tkfile = krb5_cc_default_name(*context);
548 if (strncmp(tkfile, "FILE:", 5) == 0)
551 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
552 debug("Kerberos v5: could not get default ccache (permission denied).");
557 problem = krb5_cc_default(*context, &ccache);
559 debug("Kerberos v5: krb5_cc_default failed: %s",
560 krb5_get_err_text(*context, problem));
565 remotehost = get_canonical_hostname(1);
567 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
568 "host", remotehost, NULL, ccache, &ap);
570 debug("Kerberos v5: krb5_mk_req failed: %s",
571 krb5_get_err_text(*context, problem));
576 packet_start(SSH_CMSG_AUTH_KERBEROS);
577 packet_put_string((char *) ap.data, ap.length);
584 type = packet_read();
586 case SSH_SMSG_FAILURE:
587 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
588 debug("Kerberos v5 authentication failed.");
592 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
593 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
594 debug("Kerberos v5 authentication accepted.");
596 /* Get server's response. */
597 ap.data = packet_get_string((unsigned int *) &ap.length);
599 /* XXX je to dobre? */
601 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
609 packet_disconnect("Protocol error on Kerberos v5 response: %d",
618 krb5_cc_close(*context, ccache);
620 krb5_free_ap_rep_enc_part(*context, reply);
625 krb5_free_data_contents(*context, &ap);
632 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
635 krb5_error_code problem;
637 krb5_ccache ccache = NULL;
640 krb5_kdc_flags flags;
644 const char *remotehost;
646 memset(&creds, 0, sizeof(creds));
647 memset(&outbuf, 0, sizeof(outbuf));
649 fd = packet_get_connection_in();
652 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
654 problem = krb5_auth_con_genaddrs(context, auth_context, fd,
655 KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR |
656 KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR);
661 problem = krb5_cc_default(context, &ccache);
665 problem = krb5_cc_get_principal(context, ccache, &creds.client);
669 remotehost = get_canonical_hostname(1);
672 problem = krb5_build_principal(context, &creds.server,
673 strlen(creds.client->realm), creds.client->realm,
674 "krbtgt", creds.client->realm, NULL);
676 problem = krb5_build_principal(context, &creds.server,
677 creds.client->realm.length, creds.client->realm.data,
678 "host", remotehost, NULL);
683 creds.times.endtime = 0;
687 flags.b.forwarded = 1;
688 flags.b.forwardable = krb5_config_get_bool(context, NULL,
689 "libdefaults", "forwardable", NULL);
690 problem = krb5_get_forwarded_creds(context, auth_context,
691 ccache, flags.i, remotehost, &creds, &outbuf);
694 problem = krb5_fwd_tgt_creds(context, auth_context, remotehost,
695 creds.client, creds.server, ccache, forwardable, &outbuf);
701 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
702 packet_put_string((char *)outbuf.data, outbuf.length);
706 type = packet_read();
708 if (type == SSH_SMSG_SUCCESS) {
711 krb5_unparse_name(context, creds.client, &pname);
712 debug("Kerberos v5 TGT forwarded (%s).", pname);
715 debug("Kerberos v5 TGT forwarding failed.");
721 debug("Kerberos v5 TGT forwarding failed: %s",
722 krb5_get_err_text(context, problem));
724 krb5_free_principal(context, creds.client);
726 krb5_free_principal(context, creds.server);
728 krb5_cc_close(context, ccache);
740 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
743 /* Don't do anything if we don't have any tickets. */
744 if (stat(tkt_string(), &st) < 0)
747 creds = xmalloc(sizeof(*creds));
749 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
753 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
757 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
761 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
763 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
764 packet_put_cstring(buffer);
768 type = packet_read();
770 if (type == SSH_SMSG_SUCCESS)
771 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
772 creds->pname, creds->pinst[0] ? "." : "",
773 creds->pinst, creds->realm);
775 debug("Kerberos v4 TGT rejected.");
781 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
786 send_afs_tokens(void)
789 struct ViceIoctl parms;
790 struct ClearToken ct;
792 char buf[2048], *p, *server_cell;
795 /* Move over ktc_GetToken, here's something leaner. */
796 for (i = 0; i < 100; i++) { /* just in case */
797 parms.in = (char *) &i;
798 parms.in_size = sizeof(i);
800 parms.out_size = sizeof(buf);
801 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
805 /* Get secret token. */
806 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
807 if (creds.ticket_st.length > MAX_KTXT_LEN)
810 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
811 p += creds.ticket_st.length;
813 /* Get clear token. */
814 memcpy(&len, p, sizeof(len));
815 if (len != sizeof(struct ClearToken))
820 p += sizeof(len); /* primary flag */
823 /* Flesh out our credentials. */
824 strlcpy(creds.service, "afs", sizeof(creds.service));
825 creds.instance[0] = '\0';
826 strlcpy(creds.realm, server_cell, REALM_SZ);
827 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
828 creds.issue_date = ct.BeginTimestamp;
829 creds.lifetime = krb_time_to_life(creds.issue_date,
831 creds.kvno = ct.AuthHandle;
832 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
833 creds.pinst[0] = '\0';
835 /* Encode token, ship it off. */
836 if (creds_to_radix(&creds, (u_char *)buffer,
837 sizeof(buffer)) <= 0)
839 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
840 packet_put_cstring(buffer);
844 /* Roger, Roger. Clearance, Clarence. What's your vector,
846 type = packet_read();
848 if (type == SSH_SMSG_FAILURE)
849 debug("AFS token for cell %s rejected.", server_cell);
850 else if (type != SSH_SMSG_SUCCESS)
851 packet_disconnect("Protocol error on AFS token response: %d", type);
858 * Tries to authenticate with any string-based challenge/response system.
859 * Note that the client code is not tied to s/key or TIS.
862 try_challenge_response_authentication(void)
867 char *challenge, *response;
869 debug("Doing challenge response authentication.");
871 for (i = 0; i < options.number_of_password_prompts; i++) {
872 /* request a challenge */
873 packet_start(SSH_CMSG_AUTH_TIS);
877 type = packet_read();
878 if (type != SSH_SMSG_FAILURE &&
879 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
880 packet_disconnect("Protocol error: got %d in response "
881 "to SSH_CMSG_AUTH_TIS", type);
883 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
884 debug("No challenge.");
887 challenge = packet_get_string(&clen);
889 snprintf(prompt, sizeof prompt, "%s%s", challenge,
890 strchr(challenge, '\n') ? "" : "\nResponse: ");
893 error("Permission denied, please try again.");
894 if (options.cipher == SSH_CIPHER_NONE)
895 log("WARNING: Encryption is disabled! "
896 "Response will be transmitted in clear text.");
897 response = read_passphrase(prompt, 0);
898 if (strcmp(response, "") == 0) {
902 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
903 ssh_put_password(response);
904 memset(response, 0, strlen(response));
908 type = packet_read();
909 if (type == SSH_SMSG_SUCCESS)
911 if (type != SSH_SMSG_FAILURE)
912 packet_disconnect("Protocol error: got %d in response "
913 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
920 * Tries to authenticate with plain passwd authentication.
923 try_password_authentication(char *prompt)
928 debug("Doing password authentication.");
929 if (options.cipher == SSH_CIPHER_NONE)
930 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
931 for (i = 0; i < options.number_of_password_prompts; i++) {
933 error("Permission denied, please try again.");
934 password = read_passphrase(prompt, 0);
935 packet_start(SSH_CMSG_AUTH_PASSWORD);
936 ssh_put_password(password);
937 memset(password, 0, strlen(password));
942 type = packet_read();
943 if (type == SSH_SMSG_SUCCESS)
945 if (type != SSH_SMSG_FAILURE)
946 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
956 ssh_kex(char *host, struct sockaddr *hostaddr)
960 Key *host_key, *server_key;
962 int ssh_cipher_default = SSH_CIPHER_3DES;
963 u_char session_key[SSH_SESSION_KEY_LENGTH];
965 u_int supported_ciphers;
966 u_int server_flags, client_flags;
969 debug("Waiting for server public key.");
971 /* Wait for a public key packet from the server. */
972 packet_read_expect(SSH_SMSG_PUBLIC_KEY);
974 /* Get cookie from the packet. */
975 for (i = 0; i < 8; i++)
976 cookie[i] = packet_get_char();
978 /* Get the public key. */
979 server_key = key_new(KEY_RSA1);
980 bits = packet_get_int();
981 packet_get_bignum(server_key->rsa->e);
982 packet_get_bignum(server_key->rsa->n);
984 rbits = BN_num_bits(server_key->rsa->n);
986 log("Warning: Server lies about size of server public key: "
987 "actual size is %d bits vs. announced %d.", rbits, bits);
988 log("Warning: This may be due to an old implementation of ssh.");
990 /* Get the host key. */
991 host_key = key_new(KEY_RSA1);
992 bits = packet_get_int();
993 packet_get_bignum(host_key->rsa->e);
994 packet_get_bignum(host_key->rsa->n);
996 rbits = BN_num_bits(host_key->rsa->n);
998 log("Warning: Server lies about size of server host key: "
999 "actual size is %d bits vs. announced %d.", rbits, bits);
1000 log("Warning: This may be due to an old implementation of ssh.");
1003 /* Get protocol flags. */
1004 server_flags = packet_get_int();
1005 packet_set_protocol_flags(server_flags);
1007 supported_ciphers = packet_get_int();
1008 supported_authentications = packet_get_int();
1011 debug("Received server public key (%d bits) and host key (%d bits).",
1012 BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
1014 if (verify_host_key(host, hostaddr, host_key) == -1)
1015 fatal("Host key verification failed.");
1017 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1019 compute_session_id(session_id, cookie, host_key->rsa->n, server_key->rsa->n);
1021 /* Generate a session key. */
1025 * Generate an encryption key for the session. The key is a 256 bit
1026 * random number, interpreted as a 32-byte key, with the least
1027 * significant 8 bits being the first byte of the key.
1029 for (i = 0; i < 32; i++) {
1031 rand = arc4random();
1032 session_key[i] = rand & 0xff;
1037 * According to the protocol spec, the first byte of the session key
1038 * is the highest byte of the integer. The session key is xored with
1039 * the first 16 bytes of the session id.
1041 if ((key = BN_new()) == NULL)
1042 fatal("respond_to_rsa_challenge: BN_new failed");
1043 BN_set_word(key, 0);
1044 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1045 BN_lshift(key, key, 8);
1047 BN_add_word(key, session_key[i] ^ session_id[i]);
1049 BN_add_word(key, session_key[i]);
1053 * Encrypt the integer using the public key and host key of the
1054 * server (key with smaller modulus first).
1056 if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1057 /* Public key has smaller modulus. */
1058 if (BN_num_bits(host_key->rsa->n) <
1059 BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1060 fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1061 "SSH_KEY_BITS_RESERVED %d",
1062 BN_num_bits(host_key->rsa->n),
1063 BN_num_bits(server_key->rsa->n),
1064 SSH_KEY_BITS_RESERVED);
1066 rsa_public_encrypt(key, key, server_key->rsa);
1067 rsa_public_encrypt(key, key, host_key->rsa);
1069 /* Host key has smaller modulus (or they are equal). */
1070 if (BN_num_bits(server_key->rsa->n) <
1071 BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1072 fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1073 "SSH_KEY_BITS_RESERVED %d",
1074 BN_num_bits(server_key->rsa->n),
1075 BN_num_bits(host_key->rsa->n),
1076 SSH_KEY_BITS_RESERVED);
1078 rsa_public_encrypt(key, key, host_key->rsa);
1079 rsa_public_encrypt(key, key, server_key->rsa);
1082 /* Destroy the public keys since we no longer need them. */
1083 key_free(server_key);
1086 if (options.cipher == SSH_CIPHER_NOT_SET) {
1087 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1088 options.cipher = ssh_cipher_default;
1089 } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1090 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1091 log("No valid SSH1 cipher, using %.100s instead.",
1092 cipher_name(ssh_cipher_default));
1093 options.cipher = ssh_cipher_default;
1095 /* Check that the selected cipher is supported. */
1096 if (!(supported_ciphers & (1 << options.cipher)))
1097 fatal("Selected cipher type %.100s not supported by server.",
1098 cipher_name(options.cipher));
1100 debug("Encryption type: %.100s", cipher_name(options.cipher));
1102 /* Send the encrypted session key to the server. */
1103 packet_start(SSH_CMSG_SESSION_KEY);
1104 packet_put_char(options.cipher);
1106 /* Send the cookie back to the server. */
1107 for (i = 0; i < 8; i++)
1108 packet_put_char(cookie[i]);
1110 /* Send and destroy the encrypted encryption key integer. */
1111 packet_put_bignum(key);
1114 /* Send protocol flags. */
1115 packet_put_int(client_flags);
1117 /* Send the packet now. */
1119 packet_write_wait();
1121 debug("Sent encrypted session key.");
1123 /* Set the encryption key. */
1124 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1126 /* We will no longer need the session key here. Destroy any extra copies. */
1127 memset(session_key, 0, sizeof(session_key));
1130 * Expect a success message from the server. Note that this message
1131 * will be received in encrypted form.
1133 packet_read_expect(SSH_SMSG_SUCCESS);
1135 debug("Received encrypted confirmation.");
1142 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1143 Sensitive *sensitive)
1146 krb5_context context = NULL;
1147 krb5_auth_context auth_context = NULL;
1151 if (supported_authentications == 0)
1152 fatal("ssh_userauth1: server supports no auth methods");
1154 /* Send the name of the user to log in as on the server. */
1155 packet_start(SSH_CMSG_USER);
1156 packet_put_cstring(server_user);
1158 packet_write_wait();
1161 * The server should respond with success if no authentication is
1162 * needed (the user has no password). Otherwise the server responds
1165 type = packet_read();
1167 /* check whether the connection was accepted without authentication. */
1168 if (type == SSH_SMSG_SUCCESS)
1170 if (type != SSH_SMSG_FAILURE)
1171 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1174 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1175 options.kerberos_authentication) {
1176 debug("Trying Kerberos v5 authentication.");
1178 if (try_krb5_authentication(&context, &auth_context)) {
1179 type = packet_read();
1180 if (type == SSH_SMSG_SUCCESS)
1182 if (type != SSH_SMSG_FAILURE)
1183 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1189 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1190 options.kerberos_authentication) {
1191 debug("Trying Kerberos v4 authentication.");
1193 if (try_krb4_authentication()) {
1194 type = packet_read();
1195 if (type == SSH_SMSG_SUCCESS)
1197 if (type != SSH_SMSG_FAILURE)
1198 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1204 * Use rhosts authentication if running in privileged socket and we
1205 * do not wish to remain anonymous.
1207 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1208 options.rhosts_authentication) {
1209 debug("Trying rhosts authentication.");
1210 packet_start(SSH_CMSG_AUTH_RHOSTS);
1211 packet_put_cstring(local_user);
1213 packet_write_wait();
1215 /* The server should respond with success or failure. */
1216 type = packet_read();
1217 if (type == SSH_SMSG_SUCCESS)
1219 if (type != SSH_SMSG_FAILURE)
1220 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1224 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1227 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1228 options.rhosts_rsa_authentication) {
1229 for (i = 0; i < sensitive->nkeys; i++) {
1230 if (sensitive->keys[i] != NULL &&
1231 sensitive->keys[i]->type == KEY_RSA1 &&
1232 try_rhosts_rsa_authentication(local_user,
1233 sensitive->keys[i]))
1237 /* Try RSA authentication if the server supports it. */
1238 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1239 options.rsa_authentication) {
1241 * Try RSA authentication using the authentication agent. The
1242 * agent is tried first because no passphrase is needed for
1243 * it, whereas identity files may require passphrases.
1245 if (try_agent_authentication())
1248 /* Try RSA authentication for each identity. */
1249 for (i = 0; i < options.num_identity_files; i++)
1250 if (options.identity_keys[i] != NULL &&
1251 options.identity_keys[i]->type == KEY_RSA1 &&
1252 try_rsa_authentication(i))
1255 /* Try challenge response authentication if the server supports it. */
1256 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1257 options.challenge_response_authentication && !options.batch_mode) {
1258 if (try_challenge_response_authentication())
1261 /* Try password authentication if the server supports it. */
1262 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1263 options.password_authentication && !options.batch_mode) {
1266 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1268 if (try_password_authentication(prompt))
1271 /* All authentication methods have failed. Exit with an error message. */
1272 fatal("Permission denied.");
1277 /* Try Kerberos v5 TGT passing. */
1278 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1279 options.kerberos_tgt_passing && context && auth_context) {
1280 if (options.cipher == SSH_CIPHER_NONE)
1281 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1282 send_krb5_tgt(context, auth_context);
1285 krb5_auth_con_free(context, auth_context);
1287 krb5_free_context(context);
1291 /* Try Kerberos v4 TGT passing if the server supports it. */
1292 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1293 options.kerberos_tgt_passing) {
1294 if (options.cipher == SSH_CIPHER_NONE)
1295 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1298 /* Try AFS token passing if the server supports it. */
1299 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1300 options.afs_token_passing && k_hasafs()) {
1301 if (options.cipher == SSH_CIPHER_NONE)
1302 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1307 return; /* need statement after label */