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.45 2001/12/28 12:14:27 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();
79 if ((challenge = BN_new()) == NULL)
80 fatal("try_agent_authentication: BN_new failed");
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);
114 debug("Received RSA challenge from server.");
116 /* Ask the agent to decrypt the challenge. */
117 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
119 * The agent failed to authenticate this identifier
120 * although it advertised it supports this. Just
121 * return a wrong value.
123 log("Authentication agent failed to decrypt challenge.");
124 memset(response, 0, sizeof(response));
127 debug("Sending response to RSA challenge.");
129 /* Send the decrypted challenge back to the server. */
130 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
131 for (i = 0; i < 16; i++)
132 packet_put_char(response[i]);
136 /* Wait for response from the server. */
137 type = packet_read(&plen);
139 /* The server returns success if it accepted the authentication. */
140 if (type == SSH_SMSG_SUCCESS) {
141 ssh_close_authentication_connection(auth);
142 BN_clear_free(challenge);
143 debug("RSA authentication accepted by server.");
146 /* Otherwise it should return failure. */
147 if (type != SSH_SMSG_FAILURE)
148 packet_disconnect("Protocol error waiting RSA auth response: %d",
151 ssh_close_authentication_connection(auth);
152 BN_clear_free(challenge);
153 debug("RSA authentication using agent refused.");
158 * Computes the proper response to a RSA challenge, and sends the response to
162 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
164 u_char buf[32], response[16];
168 /* Decrypt the challenge using the private key. */
169 /* XXX think about Bleichenbacher, too */
170 if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
172 "respond_to_rsa_challenge: rsa_private_decrypt failed");
174 /* Compute the response. */
175 /* The response is MD5 of decrypted challenge plus session id. */
176 len = BN_num_bytes(challenge);
177 if (len <= 0 || len > sizeof(buf))
179 "respond_to_rsa_challenge: bad challenge length %d", len);
181 memset(buf, 0, sizeof(buf));
182 BN_bn2bin(challenge, buf + sizeof(buf) - len);
184 MD5_Update(&md, buf, 32);
185 MD5_Update(&md, session_id, 16);
186 MD5_Final(response, &md);
188 debug("Sending response to host key RSA challenge.");
190 /* Send the response back to the server. */
191 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
192 for (i = 0; i < 16; i++)
193 packet_put_char(response[i]);
197 memset(buf, 0, sizeof(buf));
198 memset(response, 0, sizeof(response));
199 memset(&md, 0, sizeof(md));
203 * Checks if the user has authentication file, and if so, tries to authenticate
207 try_rsa_authentication(int idx)
210 Key *public, *private;
211 char buf[300], *passphrase, *comment, *authfile;
212 int i, type, quit, plen, clen;
214 public = options.identity_keys[idx];
215 authfile = options.identity_files[idx];
216 comment = xstrdup(authfile);
218 debug("Trying RSA authentication with key '%.100s'", comment);
220 /* Tell the server that we are willing to authenticate using this key. */
221 packet_start(SSH_CMSG_AUTH_RSA);
222 packet_put_bignum(public->rsa->n);
226 /* Wait for server's response. */
227 type = packet_read(&plen);
230 * The server responds with failure if it doesn\'t like our key or
231 * doesn\'t support RSA authentication.
233 if (type == SSH_SMSG_FAILURE) {
234 debug("Server refused our key.");
238 /* Otherwise, the server should respond with a challenge. */
239 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
240 packet_disconnect("Protocol error during RSA authentication: %d", type);
242 /* Get the challenge from the packet. */
243 if ((challenge = BN_new()) == NULL)
244 fatal("try_rsa_authentication: BN_new failed");
245 packet_get_bignum(challenge, &clen);
248 debug("Received RSA challenge from server.");
251 * If the key is not stored in external hardware, we have to
252 * load the private key. Try first with empty passphrase; if it
253 * fails, ask for a passphrase.
255 if (public->flags && KEY_FLAG_EXT)
258 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
259 if (private == NULL && !options.batch_mode) {
260 snprintf(buf, sizeof(buf),
261 "Enter passphrase for RSA key '%.100s': ", comment);
262 for (i = 0; i < options.number_of_password_prompts; i++) {
263 passphrase = read_passphrase(buf, 0);
264 if (strcmp(passphrase, "") != 0) {
265 private = key_load_private_type(KEY_RSA1,
266 authfile, passphrase, NULL);
269 debug2("no passphrase given, try next key");
272 memset(passphrase, 0, strlen(passphrase));
274 if (private != NULL || quit)
276 debug2("bad passphrase given, try again...");
279 /* We no longer need the comment. */
282 if (private == NULL) {
283 if (!options.batch_mode)
284 error("Bad passphrase.");
286 /* Send a dummy response packet to avoid protocol error. */
287 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
288 for (i = 0; i < 16; i++)
293 /* Expect the server to reject it... */
294 packet_read_expect(&plen, SSH_SMSG_FAILURE);
295 BN_clear_free(challenge);
299 /* Compute and send a response to the challenge. */
300 respond_to_rsa_challenge(challenge, private->rsa);
302 /* Destroy the private key unless it in external hardware. */
303 if (!(private->flags & KEY_FLAG_EXT))
306 /* We no longer need the challenge. */
307 BN_clear_free(challenge);
309 /* Wait for response from the server. */
310 type = packet_read(&plen);
311 if (type == SSH_SMSG_SUCCESS) {
312 debug("RSA authentication accepted by server.");
315 if (type != SSH_SMSG_FAILURE)
316 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
317 debug("RSA authentication refused.");
322 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
323 * authentication and RSA host authentication.
326 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
332 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
334 /* Tell the server that we are willing to authenticate using this key. */
335 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
336 packet_put_cstring(local_user);
337 packet_put_int(BN_num_bits(host_key->rsa->n));
338 packet_put_bignum(host_key->rsa->e);
339 packet_put_bignum(host_key->rsa->n);
343 /* Wait for server's response. */
344 type = packet_read(&plen);
346 /* The server responds with failure if it doesn't admit our
347 .rhosts authentication or doesn't know our host key. */
348 if (type == SSH_SMSG_FAILURE) {
349 debug("Server refused our rhosts authentication or host key.");
352 /* Otherwise, the server should respond with a challenge. */
353 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
354 packet_disconnect("Protocol error during RSA authentication: %d", type);
356 /* Get the challenge from the packet. */
357 if ((challenge = BN_new()) == NULL)
358 fatal("try_rhosts_rsa_authentication: BN_new failed");
359 packet_get_bignum(challenge, &clen);
362 debug("Received RSA challenge for host key from server.");
364 /* Compute a response to the challenge. */
365 respond_to_rsa_challenge(challenge, host_key->rsa);
367 /* We no longer need the challenge. */
368 BN_clear_free(challenge);
370 /* Wait for response from the server. */
371 type = packet_read(&plen);
372 if (type == SSH_SMSG_SUCCESS) {
373 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
376 if (type != SSH_SMSG_FAILURE)
377 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
378 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
384 try_krb4_authentication(void)
386 KTEXT_ST auth; /* Kerberos data */
393 Key_schedule schedule;
394 u_long checksum, cksum;
396 struct sockaddr_in local, foreign;
399 /* Don't do anything if we don't have any tickets. */
400 if (stat(tkt_string(), &st) < 0)
403 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
406 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
408 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
411 /* This can really be anything. */
412 checksum = (u_long)getpid();
414 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
416 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
419 /* Get session key to decrypt the server's reply with. */
420 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
422 debug("get_cred failed: %s", krb_err_txt[r]);
425 des_key_sched((des_cblock *) cred.session, schedule);
427 /* Send authentication info to server. */
428 packet_start(SSH_CMSG_AUTH_KERBEROS);
429 packet_put_string((char *) auth.dat, auth.length);
433 /* Zero the buffer. */
434 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
436 slen = sizeof(local);
437 memset(&local, 0, sizeof(local));
438 if (getsockname(packet_get_connection_in(),
439 (struct sockaddr *)&local, &slen) < 0)
440 debug("getsockname failed: %s", strerror(errno));
442 slen = sizeof(foreign);
443 memset(&foreign, 0, sizeof(foreign));
444 if (getpeername(packet_get_connection_in(),
445 (struct sockaddr *)&foreign, &slen) < 0) {
446 debug("getpeername failed: %s", strerror(errno));
449 /* Get server reply. */
450 type = packet_read(&plen);
452 case SSH_SMSG_FAILURE:
453 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
454 debug("Kerberos v4 authentication failed.");
458 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
459 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
460 debug("Kerberos v4 authentication accepted.");
462 /* Get server's response. */
463 reply = packet_get_string((u_int *) &auth.length);
464 memcpy(auth.dat, reply, auth.length);
470 * If his response isn't properly encrypted with the session
471 * key, and the decrypted checksum fails to match, he's
474 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
475 &foreign, &local, &msg_data);
477 debug("Kerberos v4 krb_rd_priv failed: %s",
479 packet_disconnect("Kerberos v4 challenge failed!");
481 /* Fetch the (incremented) checksum that we supplied in the request. */
482 memcpy((char *)&cksum, (char *)msg_data.app_data,
484 cksum = ntohl(cksum);
486 /* If it matches, we're golden. */
487 if (cksum == checksum + 1) {
488 debug("Kerberos v4 challenge successful.");
491 packet_disconnect("Kerberos v4 challenge failed!");
495 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
504 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
506 krb5_error_code problem;
509 krb5_ccache ccache = NULL;
510 const char *remotehost;
512 int type, payload_len;
513 krb5_ap_rep_enc_part *reply = NULL;
516 memset(&ap, 0, sizeof(ap));
518 problem = krb5_init_context(context);
520 debug("Kerberos v5: krb5_init_context failed");
525 tkfile = krb5_cc_default_name(*context);
526 if (strncmp(tkfile, "FILE:", 5) == 0)
529 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
530 debug("Kerberos v5: could not get default ccache (permission denied).");
535 problem = krb5_cc_default(*context, &ccache);
537 debug("Kerberos v5: krb5_cc_default failed: %s",
538 krb5_get_err_text(*context, problem));
543 remotehost = get_canonical_hostname(1);
545 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
546 "host", remotehost, NULL, ccache, &ap);
548 debug("Kerberos v5: krb5_mk_req failed: %s",
549 krb5_get_err_text(*context, problem));
554 packet_start(SSH_CMSG_AUTH_KERBEROS);
555 packet_put_string((char *) ap.data, ap.length);
562 type = packet_read(&payload_len);
564 case SSH_SMSG_FAILURE:
565 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
566 debug("Kerberos v5 authentication failed.");
570 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
571 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
572 debug("Kerberos v5 authentication accepted.");
574 /* Get server's response. */
575 ap.data = packet_get_string((unsigned int *) &ap.length);
577 /* XXX je to dobre? */
579 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
587 packet_disconnect("Protocol error on Kerberos v5 response: %d",
596 krb5_cc_close(*context, ccache);
598 krb5_free_ap_rep_enc_part(*context, reply);
606 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
608 int fd, type, payload_len;
609 krb5_error_code problem;
611 krb5_ccache ccache = NULL;
613 krb5_kdc_flags flags;
614 const char *remotehost;
616 memset(&creds, 0, sizeof(creds));
617 memset(&outbuf, 0, sizeof(outbuf));
619 fd = packet_get_connection_in();
621 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
625 problem = krb5_cc_default(context, &ccache);
629 problem = krb5_cc_get_principal(context, ccache, &creds.client);
633 problem = krb5_build_principal(context, &creds.server,
634 strlen(creds.client->realm), creds.client->realm,
635 "krbtgt", creds.client->realm, NULL);
639 creds.times.endtime = 0;
642 flags.b.forwarded = 1;
643 flags.b.forwardable = krb5_config_get_bool(context, NULL,
644 "libdefaults", "forwardable", NULL);
646 remotehost = get_canonical_hostname(1);
648 problem = krb5_get_forwarded_creds(context, auth_context,
649 ccache, flags.i, remotehost, &creds, &outbuf);
653 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
654 packet_put_string((char *)outbuf.data, outbuf.length);
658 type = packet_read(&payload_len);
660 if (type == SSH_SMSG_SUCCESS) {
663 krb5_unparse_name(context, creds.client, &pname);
664 debug("Kerberos v5 TGT forwarded (%s).", pname);
667 debug("Kerberos v5 TGT forwarding failed.");
673 debug("Kerberos v5 TGT forwarding failed: %s",
674 krb5_get_err_text(context, problem));
676 krb5_free_principal(context, creds.client);
678 krb5_free_principal(context, creds.server);
680 krb5_cc_close(context, ccache);
692 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
693 int problem, type, len;
695 /* Don't do anything if we don't have any tickets. */
696 if (stat(tkt_string(), &st) < 0)
699 creds = xmalloc(sizeof(*creds));
701 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
705 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
709 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
713 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
715 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
716 packet_put_cstring(buffer);
720 type = packet_read(&len);
722 if (type == SSH_SMSG_SUCCESS)
723 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
724 creds->pname, creds->pinst[0] ? "." : "",
725 creds->pinst, creds->realm);
727 debug("Kerberos v4 TGT rejected.");
733 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
738 send_afs_tokens(void)
741 struct ViceIoctl parms;
742 struct ClearToken ct;
744 char buf[2048], *p, *server_cell;
747 /* Move over ktc_GetToken, here's something leaner. */
748 for (i = 0; i < 100; i++) { /* just in case */
749 parms.in = (char *) &i;
750 parms.in_size = sizeof(i);
752 parms.out_size = sizeof(buf);
753 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
757 /* Get secret token. */
758 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
759 if (creds.ticket_st.length > MAX_KTXT_LEN)
762 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
763 p += creds.ticket_st.length;
765 /* Get clear token. */
766 memcpy(&len, p, sizeof(len));
767 if (len != sizeof(struct ClearToken))
772 p += sizeof(len); /* primary flag */
775 /* Flesh out our credentials. */
776 strlcpy(creds.service, "afs", sizeof(creds.service));
777 creds.instance[0] = '\0';
778 strlcpy(creds.realm, server_cell, REALM_SZ);
779 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
780 creds.issue_date = ct.BeginTimestamp;
781 creds.lifetime = krb_time_to_life(creds.issue_date,
783 creds.kvno = ct.AuthHandle;
784 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
785 creds.pinst[0] = '\0';
787 /* Encode token, ship it off. */
788 if (creds_to_radix(&creds, (u_char *)buffer,
789 sizeof(buffer)) <= 0)
791 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
792 packet_put_cstring(buffer);
796 /* Roger, Roger. Clearance, Clarence. What's your vector,
798 type = packet_read(&len);
800 if (type == SSH_SMSG_FAILURE)
801 debug("AFS token for cell %s rejected.", server_cell);
802 else if (type != SSH_SMSG_SUCCESS)
803 packet_disconnect("Protocol error on AFS token response: %d", type);
810 * Tries to authenticate with any string-based challenge/response system.
811 * Note that the client code is not tied to s/key or TIS.
814 try_challenge_response_authentication(void)
820 char *challenge, *response;
822 debug("Doing challenge response authentication.");
824 for (i = 0; i < options.number_of_password_prompts; i++) {
825 /* request a challenge */
826 packet_start(SSH_CMSG_AUTH_TIS);
830 type = packet_read(&payload_len);
831 if (type != SSH_SMSG_FAILURE &&
832 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
833 packet_disconnect("Protocol error: got %d in response "
834 "to SSH_CMSG_AUTH_TIS", type);
836 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
837 debug("No challenge.");
840 challenge = packet_get_string(&clen);
842 snprintf(prompt, sizeof prompt, "%s%s", challenge,
843 strchr(challenge, '\n') ? "" : "\nResponse: ");
846 error("Permission denied, please try again.");
847 if (options.cipher == SSH_CIPHER_NONE)
848 log("WARNING: Encryption is disabled! "
849 "Reponse will be transmitted in clear text.");
850 response = read_passphrase(prompt, 0);
851 if (strcmp(response, "") == 0) {
855 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
856 ssh_put_password(response);
857 memset(response, 0, strlen(response));
861 type = packet_read(&payload_len);
862 if (type == SSH_SMSG_SUCCESS)
864 if (type != SSH_SMSG_FAILURE)
865 packet_disconnect("Protocol error: got %d in response "
866 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
873 * Tries to authenticate with plain passwd authentication.
876 try_password_authentication(char *prompt)
878 int type, i, payload_len;
881 debug("Doing password authentication.");
882 if (options.cipher == SSH_CIPHER_NONE)
883 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
884 for (i = 0; i < options.number_of_password_prompts; i++) {
886 error("Permission denied, please try again.");
887 password = read_passphrase(prompt, 0);
888 packet_start(SSH_CMSG_AUTH_PASSWORD);
889 ssh_put_password(password);
890 memset(password, 0, strlen(password));
895 type = packet_read(&payload_len);
896 if (type == SSH_SMSG_SUCCESS)
898 if (type != SSH_SMSG_FAILURE)
899 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
909 ssh_kex(char *host, struct sockaddr *hostaddr)
913 Key *host_key, *server_key;
915 int ssh_cipher_default = SSH_CIPHER_3DES;
916 u_char session_key[SSH_SESSION_KEY_LENGTH];
918 u_int supported_ciphers;
919 u_int server_flags, client_flags;
920 int payload_len, clen, sum_len = 0;
923 debug("Waiting for server public key.");
925 /* Wait for a public key packet from the server. */
926 packet_read_expect(&payload_len, SSH_SMSG_PUBLIC_KEY);
928 /* Get cookie from the packet. */
929 for (i = 0; i < 8; i++)
930 cookie[i] = packet_get_char();
932 /* Get the public key. */
933 server_key = key_new(KEY_RSA1);
934 bits = packet_get_int();
935 packet_get_bignum(server_key->rsa->e, &clen);
937 packet_get_bignum(server_key->rsa->n, &clen);
940 rbits = BN_num_bits(server_key->rsa->n);
942 log("Warning: Server lies about size of server public key: "
943 "actual size is %d bits vs. announced %d.", rbits, bits);
944 log("Warning: This may be due to an old implementation of ssh.");
946 /* Get the host key. */
947 host_key = key_new(KEY_RSA1);
948 bits = packet_get_int();
949 packet_get_bignum(host_key->rsa->e, &clen);
951 packet_get_bignum(host_key->rsa->n, &clen);
954 rbits = BN_num_bits(host_key->rsa->n);
956 log("Warning: Server lies about size of server host key: "
957 "actual size is %d bits vs. announced %d.", rbits, bits);
958 log("Warning: This may be due to an old implementation of ssh.");
961 /* Get protocol flags. */
962 server_flags = packet_get_int();
963 packet_set_protocol_flags(server_flags);
965 supported_ciphers = packet_get_int();
966 supported_authentications = packet_get_int();
969 debug("Received server public key (%d bits) and host key (%d bits).",
970 BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
972 if (verify_host_key(host, hostaddr, host_key) == -1)
973 fatal("Host key verification failed.");
975 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
977 compute_session_id(session_id, cookie, host_key->rsa->n, server_key->rsa->n);
979 /* Generate a session key. */
983 * Generate an encryption key for the session. The key is a 256 bit
984 * random number, interpreted as a 32-byte key, with the least
985 * significant 8 bits being the first byte of the key.
987 for (i = 0; i < 32; i++) {
990 session_key[i] = rand & 0xff;
995 * According to the protocol spec, the first byte of the session key
996 * is the highest byte of the integer. The session key is xored with
997 * the first 16 bytes of the session id.
999 if ((key = BN_new()) == NULL)
1000 fatal("respond_to_rsa_challenge: BN_new failed");
1001 BN_set_word(key, 0);
1002 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1003 BN_lshift(key, key, 8);
1005 BN_add_word(key, session_key[i] ^ session_id[i]);
1007 BN_add_word(key, session_key[i]);
1011 * Encrypt the integer using the public key and host key of the
1012 * server (key with smaller modulus first).
1014 if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1015 /* Public key has smaller modulus. */
1016 if (BN_num_bits(host_key->rsa->n) <
1017 BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1018 fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1019 "SSH_KEY_BITS_RESERVED %d",
1020 BN_num_bits(host_key->rsa->n),
1021 BN_num_bits(server_key->rsa->n),
1022 SSH_KEY_BITS_RESERVED);
1024 rsa_public_encrypt(key, key, server_key->rsa);
1025 rsa_public_encrypt(key, key, host_key->rsa);
1027 /* Host key has smaller modulus (or they are equal). */
1028 if (BN_num_bits(server_key->rsa->n) <
1029 BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1030 fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1031 "SSH_KEY_BITS_RESERVED %d",
1032 BN_num_bits(server_key->rsa->n),
1033 BN_num_bits(host_key->rsa->n),
1034 SSH_KEY_BITS_RESERVED);
1036 rsa_public_encrypt(key, key, host_key->rsa);
1037 rsa_public_encrypt(key, key, server_key->rsa);
1040 /* Destroy the public keys since we no longer need them. */
1041 key_free(server_key);
1044 if (options.cipher == SSH_CIPHER_NOT_SET) {
1045 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1046 options.cipher = ssh_cipher_default;
1047 } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1048 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1049 log("No valid SSH1 cipher, using %.100s instead.",
1050 cipher_name(ssh_cipher_default));
1051 options.cipher = ssh_cipher_default;
1053 /* Check that the selected cipher is supported. */
1054 if (!(supported_ciphers & (1 << options.cipher)))
1055 fatal("Selected cipher type %.100s not supported by server.",
1056 cipher_name(options.cipher));
1058 debug("Encryption type: %.100s", cipher_name(options.cipher));
1060 /* Send the encrypted session key to the server. */
1061 packet_start(SSH_CMSG_SESSION_KEY);
1062 packet_put_char(options.cipher);
1064 /* Send the cookie back to the server. */
1065 for (i = 0; i < 8; i++)
1066 packet_put_char(cookie[i]);
1068 /* Send and destroy the encrypted encryption key integer. */
1069 packet_put_bignum(key);
1072 /* Send protocol flags. */
1073 packet_put_int(client_flags);
1075 /* Send the packet now. */
1077 packet_write_wait();
1079 debug("Sent encrypted session key.");
1081 /* Set the encryption key. */
1082 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1084 /* We will no longer need the session key here. Destroy any extra copies. */
1085 memset(session_key, 0, sizeof(session_key));
1088 * Expect a success message from the server. Note that this message
1089 * will be received in encrypted form.
1091 packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
1093 debug("Received encrypted confirmation.");
1100 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1101 Key **keys, int nkeys)
1104 krb5_context context = NULL;
1105 krb5_auth_context auth_context = NULL;
1110 if (supported_authentications == 0)
1111 fatal("ssh_userauth1: server supports no auth methods");
1113 /* Send the name of the user to log in as on the server. */
1114 packet_start(SSH_CMSG_USER);
1115 packet_put_cstring(server_user);
1117 packet_write_wait();
1120 * The server should respond with success if no authentication is
1121 * needed (the user has no password). Otherwise the server responds
1124 type = packet_read(&payload_len);
1126 /* check whether the connection was accepted without authentication. */
1127 if (type == SSH_SMSG_SUCCESS)
1129 if (type != SSH_SMSG_FAILURE)
1130 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1133 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1134 options.kerberos_authentication) {
1135 debug("Trying Kerberos v5 authentication.");
1137 if (try_krb5_authentication(&context, &auth_context)) {
1138 type = packet_read(&payload_len);
1139 if (type == SSH_SMSG_SUCCESS)
1141 if (type != SSH_SMSG_FAILURE)
1142 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1148 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1149 options.kerberos_authentication) {
1150 debug("Trying Kerberos v4 authentication.");
1152 if (try_krb4_authentication()) {
1153 type = packet_read(&payload_len);
1154 if (type == SSH_SMSG_SUCCESS)
1156 if (type != SSH_SMSG_FAILURE)
1157 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1163 * Use rhosts authentication if running in privileged socket and we
1164 * do not wish to remain anonymous.
1166 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1167 options.rhosts_authentication) {
1168 debug("Trying rhosts authentication.");
1169 packet_start(SSH_CMSG_AUTH_RHOSTS);
1170 packet_put_cstring(local_user);
1172 packet_write_wait();
1174 /* The server should respond with success or failure. */
1175 type = packet_read(&payload_len);
1176 if (type == SSH_SMSG_SUCCESS)
1178 if (type != SSH_SMSG_FAILURE)
1179 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1183 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1186 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1187 options.rhosts_rsa_authentication) {
1188 for (i = 0; i < nkeys; i++) {
1189 if (keys[i] != NULL && keys[i]->type == KEY_RSA1 &&
1190 try_rhosts_rsa_authentication(local_user, keys[i]))
1194 /* Try RSA authentication if the server supports it. */
1195 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1196 options.rsa_authentication) {
1198 * Try RSA authentication using the authentication agent. The
1199 * agent is tried first because no passphrase is needed for
1200 * it, whereas identity files may require passphrases.
1202 if (try_agent_authentication())
1205 /* Try RSA authentication for each identity. */
1206 for (i = 0; i < options.num_identity_files; i++)
1207 if (options.identity_keys[i] != NULL &&
1208 options.identity_keys[i]->type == KEY_RSA1 &&
1209 try_rsa_authentication(i))
1212 /* Try challenge response authentication if the server supports it. */
1213 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1214 options.challenge_response_authentication && !options.batch_mode) {
1215 if (try_challenge_response_authentication())
1218 /* Try password authentication if the server supports it. */
1219 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1220 options.password_authentication && !options.batch_mode) {
1223 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1225 if (try_password_authentication(prompt))
1228 /* All authentication methods have failed. Exit with an error message. */
1229 fatal("Permission denied.");
1234 /* Try Kerberos v5 TGT passing. */
1235 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1236 options.kerberos_tgt_passing && context && auth_context) {
1237 if (options.cipher == SSH_CIPHER_NONE)
1238 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1239 send_krb5_tgt(context, auth_context);
1242 krb5_auth_con_free(context, auth_context);
1244 krb5_free_context(context);
1248 /* Try Kerberos v4 TGT passing if the server supports it. */
1249 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1250 options.kerberos_tgt_passing) {
1251 if (options.cipher == SSH_CIPHER_NONE)
1252 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1255 /* Try AFS token passing if the server supports it. */
1256 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1257 options.afs_token_passing && k_hasafs()) {
1258 if (options.cipher == SSH_CIPHER_NONE)
1259 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1264 return; /* need statement after label */