No empty .Rs/.Re
[netbsd-mini2440.git] / crypto / external / bsd / openssh / dist / sshconnect1.c
blobd9f077f84f3c1e63617287bd74f84f867ebc4220
1 /* $NetBSD$ */
2 /* $OpenBSD: sshconnect1.c,v 1.70 2006/11/06 21:25:28 markus Exp $ */
3 /*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * All rights reserved
7 * Code to connect to a remote host, and to perform the client side of the
8 * login (authentication) dialog.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
17 #include "includes.h"
18 __RCSID("$NetBSD: sshconnect1.c,v 1.32 2007/03/10 22:52:10 christos Exp $");
19 #include <sys/types.h>
20 #include <sys/socket.h>
21 #include <sys/stat.h>
23 #include <openssl/bn.h>
24 #include <openssl/md5.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <signal.h>
30 #include <pwd.h>
31 #include <unistd.h>
33 #ifdef KRB4
34 #include <krb.h>
35 #ifdef AFS
36 #include <kafs.h>
37 #include "radix.h"
38 #endif
39 #endif
40 #ifdef KRB5
41 #include <krb5.h>
42 #endif
44 #include "xmalloc.h"
45 #include "ssh.h"
46 #include "ssh1.h"
47 #include "rsa.h"
48 #include "buffer.h"
49 #include "packet.h"
50 #include "key.h"
51 #include "cipher.h"
52 #include "kex.h"
53 #include "uidswap.h"
54 #include "log.h"
55 #include "readconf.h"
56 #include "authfd.h"
57 #include "sshconnect.h"
58 #include "authfile.h"
59 #include "misc.h"
60 #include "canohost.h"
61 #include "hostfile.h"
62 #include "auth.h"
64 /* Session id for the current session. */
65 u_char session_id[16];
66 u_int supported_authentications = 0;
68 extern Options options;
69 extern char *__progname;
72 * Checks if the user has an authentication agent, and if so, tries to
73 * authenticate using the agent.
75 static int
76 try_agent_authentication(void)
78 int type;
79 char *comment;
80 AuthenticationConnection *auth;
81 u_char response[16];
82 u_int i;
83 Key *key;
84 BIGNUM *challenge;
86 /* Get connection to the agent. */
87 auth = ssh_get_authentication_connection();
88 if (!auth)
89 return 0;
91 if ((challenge = BN_new()) == NULL)
92 fatal("try_agent_authentication: BN_new failed");
93 /* Loop through identities served by the agent. */
94 for (key = ssh_get_first_identity(auth, &comment, 1);
95 key != NULL;
96 key = ssh_get_next_identity(auth, &comment, 1)) {
98 /* Try this identity. */
99 debug("Trying RSA authentication via agent with '%.100s'", comment);
100 xfree(comment);
102 /* Tell the server that we are willing to authenticate using this key. */
103 packet_start(SSH_CMSG_AUTH_RSA);
104 packet_put_bignum(key->rsa->n);
105 packet_send();
106 packet_write_wait();
108 /* Wait for server's response. */
109 type = packet_read();
111 /* The server sends failure if it doesn't like our key or
112 does not support RSA authentication. */
113 if (type == SSH_SMSG_FAILURE) {
114 debug("Server refused our key.");
115 key_free(key);
116 continue;
118 /* Otherwise it should have sent a challenge. */
119 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
120 packet_disconnect("Protocol error during RSA authentication: %d",
121 type);
123 packet_get_bignum(challenge);
124 packet_check_eom();
126 debug("Received RSA challenge from server.");
128 /* Ask the agent to decrypt the challenge. */
129 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
131 * The agent failed to authenticate this identifier
132 * although it advertised it supports this. Just
133 * return a wrong value.
135 logit("Authentication agent failed to decrypt challenge.");
136 memset(response, 0, sizeof(response));
138 key_free(key);
139 debug("Sending response to RSA challenge.");
141 /* Send the decrypted challenge back to the server. */
142 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
143 for (i = 0; i < 16; i++)
144 packet_put_char(response[i]);
145 packet_send();
146 packet_write_wait();
148 /* Wait for response from the server. */
149 type = packet_read();
151 /* The server returns success if it accepted the authentication. */
152 if (type == SSH_SMSG_SUCCESS) {
153 ssh_close_authentication_connection(auth);
154 BN_clear_free(challenge);
155 debug("RSA authentication accepted by server.");
156 return 1;
158 /* Otherwise it should return failure. */
159 if (type != SSH_SMSG_FAILURE)
160 packet_disconnect("Protocol error waiting RSA auth response: %d",
161 type);
163 ssh_close_authentication_connection(auth);
164 BN_clear_free(challenge);
165 debug("RSA authentication using agent refused.");
166 return 0;
170 * Computes the proper response to a RSA challenge, and sends the response to
171 * the server.
173 static void
174 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
176 u_char buf[32], response[16];
177 MD5_CTX md;
178 int i, len;
180 /* Decrypt the challenge using the private key. */
181 /* XXX think about Bleichenbacher, too */
182 if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
183 packet_disconnect(
184 "respond_to_rsa_challenge: rsa_private_decrypt failed");
186 /* Compute the response. */
187 /* The response is MD5 of decrypted challenge plus session id. */
188 len = BN_num_bytes(challenge);
189 if (len <= 0 || (u_int)len > sizeof(buf))
190 packet_disconnect(
191 "respond_to_rsa_challenge: bad challenge length %d", len);
193 memset(buf, 0, sizeof(buf));
194 BN_bn2bin(challenge, buf + sizeof(buf) - len);
195 MD5_Init(&md);
196 MD5_Update(&md, buf, 32);
197 MD5_Update(&md, session_id, 16);
198 MD5_Final(response, &md);
200 debug("Sending response to host key RSA challenge.");
202 /* Send the response back to the server. */
203 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
204 for (i = 0; i < 16; i++)
205 packet_put_char(response[i]);
206 packet_send();
207 packet_write_wait();
209 memset(buf, 0, sizeof(buf));
210 memset(response, 0, sizeof(response));
211 memset(&md, 0, sizeof(md));
214 #ifdef KRB4
215 static int
216 try_krb4_authentication(void)
218 KTEXT_ST auth; /* Kerberos data */
219 char *reply;
220 char inst[INST_SZ];
221 char *realm;
222 CREDENTIALS cred;
223 int r, type;
224 socklen_t slen;
225 Key_schedule schedule;
226 u_long checksum, cksum;
227 MSG_DAT msg_data;
228 struct sockaddr_in local, foreign;
229 struct stat st;
231 /* Don't do anything if we don't have any tickets. */
232 if (stat(tkt_string(), &st) < 0)
233 return 0;
235 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
236 INST_SZ);
238 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
239 if (!realm) {
240 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
241 return 0;
243 /* This can really be anything. */
244 checksum = (u_long)getpid();
246 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
247 if (r != KSUCCESS) {
248 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
249 return 0;
251 /* Get session key to decrypt the server's reply with. */
252 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
253 if (r != KSUCCESS) {
254 debug("get_cred failed: %s", krb_err_txt[r]);
255 return 0;
257 des_key_sched((des_cblock *) cred.session, schedule);
259 /* Send authentication info to server. */
260 packet_start(SSH_CMSG_AUTH_KERBEROS);
261 packet_put_string((char *) auth.dat, auth.length);
262 packet_send();
263 packet_write_wait();
265 /* Zero the buffer. */
266 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
268 slen = sizeof(local);
269 memset(&local, 0, sizeof(local));
270 if (getsockname(packet_get_connection_in(),
271 (struct sockaddr *)&local, &slen) < 0)
272 debug("getsockname failed: %s", strerror(errno));
274 slen = sizeof(foreign);
275 memset(&foreign, 0, sizeof(foreign));
276 if (getpeername(packet_get_connection_in(),
277 (struct sockaddr *)&foreign, &slen) < 0) {
278 debug("getpeername failed: %s", strerror(errno));
279 cleanup_exit(255);
281 /* Get server reply. */
282 type = packet_read();
283 switch (type) {
284 case SSH_SMSG_FAILURE:
285 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
286 debug("Kerberos v4 authentication failed.");
287 return 0;
288 break;
290 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
291 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
292 debug("Kerberos v4 authentication accepted.");
294 /* Get server's response. */
295 reply = packet_get_string((u_int *) &auth.length);
296 if (auth.length >= MAX_KTXT_LEN)
297 fatal("Kerberos v4: Malformed response from server");
298 memcpy(auth.dat, reply, auth.length);
299 xfree(reply);
301 packet_check_eom();
304 * If his response isn't properly encrypted with the session
305 * key, and the decrypted checksum fails to match, he's
306 * bogus. Bail out.
308 r = krb_rd_priv(auth.dat, auth.length, (void *)schedule,
309 &cred.session, &foreign, &local, &msg_data);
310 if (r != KSUCCESS) {
311 debug("Kerberos v4 krb_rd_priv failed: %s",
312 krb_err_txt[r]);
313 packet_disconnect("Kerberos v4 challenge failed!");
315 /* Fetch the (incremented) checksum that we supplied in the request. */
316 memcpy((char *)&cksum, (char *)msg_data.app_data,
317 sizeof(cksum));
318 cksum = ntohl(cksum);
320 /* If it matches, we're golden. */
321 if (cksum == checksum + 1) {
322 debug("Kerberos v4 challenge successful.");
323 return 1;
324 } else
325 packet_disconnect("Kerberos v4 challenge failed!");
326 break;
328 default:
329 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
331 return 0;
334 #endif /* KRB4 */
337 * Checks if the user has authentication file, and if so, tries to authenticate
338 * the user using it.
340 static int
341 try_rsa_authentication(int idx)
343 BIGNUM *challenge;
344 Key *public, *private;
345 char buf[300], *passphrase, *comment, *authfile;
346 int i, perm_ok = 1, type, quit;
348 public = options.identity_keys[idx];
349 authfile = options.identity_files[idx];
350 comment = xstrdup(authfile);
352 debug("Trying RSA authentication with key '%.100s'", comment);
354 /* Tell the server that we are willing to authenticate using this key. */
355 packet_start(SSH_CMSG_AUTH_RSA);
356 packet_put_bignum(public->rsa->n);
357 packet_send();
358 packet_write_wait();
360 /* Wait for server's response. */
361 type = packet_read();
364 * The server responds with failure if it doesn't like our key or
365 * doesn't support RSA authentication.
367 if (type == SSH_SMSG_FAILURE) {
368 debug("Server refused our key.");
369 xfree(comment);
370 return 0;
372 /* Otherwise, the server should respond with a challenge. */
373 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
374 packet_disconnect("Protocol error during RSA authentication: %d", type);
376 /* Get the challenge from the packet. */
377 if ((challenge = BN_new()) == NULL)
378 fatal("try_rsa_authentication: BN_new failed");
379 packet_get_bignum(challenge);
380 packet_check_eom();
382 debug("Received RSA challenge from server.");
385 * If the key is not stored in external hardware, we have to
386 * load the private key. Try first with empty passphrase; if it
387 * fails, ask for a passphrase.
389 if (public->flags & KEY_FLAG_EXT)
390 private = public;
391 else
392 private = key_load_private_type(KEY_RSA1, authfile, "", NULL,
393 &perm_ok);
394 if (private == NULL && !options.batch_mode && perm_ok) {
395 snprintf(buf, sizeof(buf),
396 "Enter passphrase for RSA key '%.100s': ", comment);
397 for (i = 0; i < options.number_of_password_prompts; i++) {
398 passphrase = read_passphrase(buf, 0);
399 if (strcmp(passphrase, "") != 0) {
400 private = key_load_private_type(KEY_RSA1,
401 authfile, passphrase, NULL, NULL);
402 quit = 0;
403 } else {
404 debug2("no passphrase given, try next key");
405 quit = 1;
407 memset(passphrase, 0, strlen(passphrase));
408 xfree(passphrase);
409 if (private != NULL || quit)
410 break;
411 debug2("bad passphrase given, try again...");
414 /* We no longer need the comment. */
415 xfree(comment);
417 if (private == NULL) {
418 if (!options.batch_mode && perm_ok)
419 error("Bad passphrase.");
421 /* Send a dummy response packet to avoid protocol error. */
422 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
423 for (i = 0; i < 16; i++)
424 packet_put_char(0);
425 packet_send();
426 packet_write_wait();
428 /* Expect the server to reject it... */
429 packet_read_expect(SSH_SMSG_FAILURE);
430 BN_clear_free(challenge);
431 return 0;
434 /* Compute and send a response to the challenge. */
435 respond_to_rsa_challenge(challenge, private->rsa);
437 /* Destroy the private key unless it in external hardware. */
438 if (!(private->flags & KEY_FLAG_EXT))
439 key_free(private);
441 /* We no longer need the challenge. */
442 BN_clear_free(challenge);
444 /* Wait for response from the server. */
445 type = packet_read();
446 if (type == SSH_SMSG_SUCCESS) {
447 debug("RSA authentication accepted by server.");
448 return 1;
450 if (type != SSH_SMSG_FAILURE)
451 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
452 debug("RSA authentication refused.");
453 return 0;
456 #ifdef KRB5
457 static int
458 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
460 krb5_error_code problem;
461 const char *tkfile;
462 struct stat buf;
463 krb5_ccache ccache = NULL;
464 const char *remotehost;
465 krb5_data ap;
466 int type;
467 krb5_ap_rep_enc_part *reply = NULL;
468 int ret;
470 memset(&ap, 0, sizeof(ap));
472 problem = krb5_init_context(context);
473 if (problem) {
474 debug("Kerberos v5: krb5_init_context failed");
475 ret = 0;
476 goto out;
479 tkfile = krb5_cc_default_name(*context);
480 if (strncmp(tkfile, "FILE:", 5) == 0)
481 tkfile += 5;
483 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
484 debug("Kerberos v5: could not get default ccache (permission denied).");
485 ret = 0;
486 goto out;
489 problem = krb5_cc_default(*context, &ccache);
490 if (problem) {
491 debug("Kerberos v5: krb5_cc_default failed: %s",
492 krb5_get_err_text(*context, problem));
493 ret = 0;
494 goto out;
497 remotehost = get_canonical_hostname(1);
499 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
500 "host", remotehost, NULL, ccache, &ap);
501 if (problem) {
502 debug("Kerberos v5: krb5_mk_req failed: %s",
503 krb5_get_err_text(*context, problem));
504 ret = 0;
505 goto out;
508 packet_start(SSH_CMSG_AUTH_KERBEROS);
509 packet_put_string((char *) ap.data, ap.length);
510 packet_send();
511 packet_write_wait();
513 xfree(ap.data);
514 ap.length = 0;
516 type = packet_read();
517 switch (type) {
518 case SSH_SMSG_FAILURE:
519 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
520 debug("Kerberos v5 authentication failed.");
521 ret = 0;
522 break;
524 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
525 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
526 debug("Kerberos v5 authentication accepted.");
528 /* Get server's response. */
529 ap.data = packet_get_string((unsigned int *) &ap.length);
530 packet_check_eom();
531 /* XXX je to dobre? */
533 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
534 if (problem) {
535 ret = 0;
537 ret = 1;
538 break;
540 default:
541 packet_disconnect("Protocol error on Kerberos v5 response: %d",
542 type);
543 ret = 0;
544 break;
548 out:
549 if (ccache != NULL)
550 krb5_cc_close(*context, ccache);
551 if (reply != NULL)
552 krb5_free_ap_rep_enc_part(*context, reply);
553 if (ap.length > 0)
554 krb5_data_free(&ap);
556 return (ret);
559 static void
560 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
562 int fd, type;
563 krb5_error_code problem;
564 krb5_data outbuf;
565 krb5_ccache ccache = NULL;
566 krb5_creds creds;
567 krb5_kdc_flags flags;
568 const char *remotehost;
570 memset(&creds, 0, sizeof(creds));
571 memset(&outbuf, 0, sizeof(outbuf));
573 fd = packet_get_connection_in();
575 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
576 if (problem)
577 goto out;
579 problem = krb5_cc_default(context, &ccache);
580 if (problem)
581 goto out;
583 problem = krb5_cc_get_principal(context, ccache, &creds.client);
584 if (problem)
585 goto out;
587 problem = krb5_build_principal(context, &creds.server,
588 strlen(creds.client->realm), creds.client->realm,
589 "krbtgt", creds.client->realm, NULL);
590 if (problem)
591 goto out;
593 creds.times.endtime = 0;
595 flags.i = 0;
596 flags.b.forwarded = 1;
597 flags.b.forwardable = krb5_config_get_bool(context, NULL,
598 "libdefaults", "forwardable", NULL);
600 remotehost = get_canonical_hostname(1);
602 problem = krb5_get_forwarded_creds(context, auth_context,
603 ccache, flags.i, remotehost, &creds, &outbuf);
604 if (problem)
605 goto out;
607 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
608 packet_put_string((char *)outbuf.data, outbuf.length);
609 packet_send();
610 packet_write_wait();
612 type = packet_read();
614 if (type == SSH_SMSG_SUCCESS) {
615 char *pname;
617 krb5_unparse_name(context, creds.client, &pname);
618 debug("Kerberos v5 TGT forwarded (%s).", pname);
619 xfree(pname);
620 } else
621 debug("Kerberos v5 TGT forwarding failed.");
623 return;
625 out:
626 if (problem)
627 debug("Kerberos v5 TGT forwarding failed: %s",
628 krb5_get_err_text(context, problem));
629 if (creds.client)
630 krb5_free_principal(context, creds.client);
631 if (creds.server)
632 krb5_free_principal(context, creds.server);
633 if (ccache)
634 krb5_cc_close(context, ccache);
635 if (outbuf.data)
636 xfree(outbuf.data);
638 #endif /* KRB5 */
640 #ifdef KRB4
641 #ifdef AFS
642 static void
643 send_krb4_tgt(void)
645 CREDENTIALS *creds;
646 struct stat st;
647 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
648 int problem, type;
650 /* Don't do anything if we don't have any tickets. */
651 if (stat(tkt_string(), &st) < 0)
652 return;
654 creds = xmalloc(sizeof(*creds));
656 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
657 if (problem)
658 goto out;
660 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
661 if (problem)
662 goto out;
664 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
665 problem = RD_AP_EXP;
666 goto out;
668 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
670 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
671 packet_put_cstring(buffer);
672 packet_send();
673 packet_write_wait();
675 type = packet_read();
677 if (type == SSH_SMSG_SUCCESS)
678 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
679 creds->pname, creds->pinst[0] ? "." : "",
680 creds->pinst, creds->realm);
681 else
682 debug("Kerberos v4 TGT rejected.");
684 xfree(creds);
685 return;
687 out:
688 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
689 xfree(creds);
692 static void
693 send_afs_tokens(void)
695 CREDENTIALS creds;
696 struct ViceIoctl parms;
697 struct ClearToken ct;
698 int i, type, len;
699 char buf[2048], *p, *server_cell;
700 char buffer[8192];
702 /* Move over ktc_GetToken, here's something leaner. */
703 for (i = 0; i < 100; i++) { /* just in case */
704 parms.in = (char *) &i;
705 parms.in_size = sizeof(i);
706 parms.out = buf;
707 parms.out_size = sizeof(buf);
708 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
709 break;
710 p = buf;
712 /* Get secret token. */
713 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
714 if (creds.ticket_st.length > MAX_KTXT_LEN)
715 break;
716 p += sizeof(u_int);
717 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
718 p += creds.ticket_st.length;
720 /* Get clear token. */
721 memcpy(&len, p, sizeof(len));
722 if (len != sizeof(struct ClearToken))
723 break;
724 p += sizeof(len);
725 memcpy(&ct, p, len);
726 p += len;
727 p += sizeof(len); /* primary flag */
728 server_cell = p;
730 /* Flesh out our credentials. */
731 strlcpy(creds.service, "afs", sizeof(creds.service));
732 creds.instance[0] = '\0';
733 strlcpy(creds.realm, server_cell, REALM_SZ);
734 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
735 creds.issue_date = ct.BeginTimestamp;
736 creds.lifetime = krb_time_to_life(creds.issue_date,
737 ct.EndTimestamp);
738 creds.kvno = ct.AuthHandle;
739 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
740 creds.pinst[0] = '\0';
742 /* Encode token, ship it off. */
743 if (creds_to_radix(&creds, (u_char *)buffer,
744 sizeof(buffer)) <= 0)
745 break;
746 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
747 packet_put_cstring(buffer);
748 packet_send();
749 packet_write_wait();
751 /* Roger, Roger. Clearance, Clarence. What's your vector,
752 Victor? */
753 type = packet_read();
755 if (type == SSH_SMSG_FAILURE)
756 debug("AFS token for cell %s rejected.", server_cell);
757 else if (type != SSH_SMSG_SUCCESS)
758 packet_disconnect("Protocol error on AFS token response: %d", type);
762 #endif /* AFS */
763 #endif /* KRB4 */
766 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
767 * authentication and RSA host authentication.
769 static int
770 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
772 int type;
773 BIGNUM *challenge;
775 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
777 /* Tell the server that we are willing to authenticate using this key. */
778 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
779 packet_put_cstring(local_user);
780 packet_put_int(BN_num_bits(host_key->rsa->n));
781 packet_put_bignum(host_key->rsa->e);
782 packet_put_bignum(host_key->rsa->n);
783 packet_send();
784 packet_write_wait();
786 /* Wait for server's response. */
787 type = packet_read();
789 /* The server responds with failure if it doesn't admit our
790 .rhosts authentication or doesn't know our host key. */
791 if (type == SSH_SMSG_FAILURE) {
792 debug("Server refused our rhosts authentication or host key.");
793 return 0;
795 /* Otherwise, the server should respond with a challenge. */
796 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
797 packet_disconnect("Protocol error during RSA authentication: %d", type);
799 /* Get the challenge from the packet. */
800 if ((challenge = BN_new()) == NULL)
801 fatal("try_rhosts_rsa_authentication: BN_new failed");
802 packet_get_bignum(challenge);
803 packet_check_eom();
805 debug("Received RSA challenge for host key from server.");
807 /* Compute a response to the challenge. */
808 respond_to_rsa_challenge(challenge, host_key->rsa);
810 /* We no longer need the challenge. */
811 BN_clear_free(challenge);
813 /* Wait for response from the server. */
814 type = packet_read();
815 if (type == SSH_SMSG_SUCCESS) {
816 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
817 return 1;
819 if (type != SSH_SMSG_FAILURE)
820 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
821 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
822 return 0;
826 * Tries to authenticate with any string-based challenge/response system.
827 * Note that the client code is not tied to s/key or TIS.
829 static int
830 try_challenge_response_authentication(void)
832 int type, i;
833 u_int clen;
834 char prompt[1024];
835 char *challenge, *response;
837 debug("Doing challenge response authentication.");
839 for (i = 0; i < options.number_of_password_prompts; i++) {
840 /* request a challenge */
841 packet_start(SSH_CMSG_AUTH_TIS);
842 packet_send();
843 packet_write_wait();
845 type = packet_read();
846 if (type != SSH_SMSG_FAILURE &&
847 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
848 packet_disconnect("Protocol error: got %d in response "
849 "to SSH_CMSG_AUTH_TIS", type);
851 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
852 debug("No challenge.");
853 return 0;
855 challenge = packet_get_string(&clen);
856 packet_check_eom();
857 snprintf(prompt, sizeof prompt, "%s%s", challenge,
858 strchr(challenge, '\n') ? "" : "\nResponse: ");
859 xfree(challenge);
860 if (i != 0)
861 error("Permission denied, please try again.");
862 if (options.cipher == SSH_CIPHER_NONE)
863 logit("WARNING: Encryption is disabled! "
864 "Response will be transmitted in clear text.");
865 response = read_passphrase(prompt, 0);
866 if (strcmp(response, "") == 0) {
867 xfree(response);
868 break;
870 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
871 ssh_put_password(response);
872 memset(response, 0, strlen(response));
873 xfree(response);
874 packet_send();
875 packet_write_wait();
876 type = packet_read();
877 if (type == SSH_SMSG_SUCCESS)
878 return 1;
879 if (type != SSH_SMSG_FAILURE)
880 packet_disconnect("Protocol error: got %d in response "
881 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
883 /* failure */
884 return 0;
888 * Tries to authenticate with plain passwd authentication.
890 static int
891 try_password_authentication(char *prompt)
893 int type, i;
894 char *password;
896 debug("Doing password authentication.");
897 if (options.cipher == SSH_CIPHER_NONE)
898 logit("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
899 for (i = 0; i < options.number_of_password_prompts; i++) {
900 if (i != 0)
901 error("Permission denied, please try again.");
902 password = read_passphrase(prompt, 0);
903 packet_start(SSH_CMSG_AUTH_PASSWORD);
904 ssh_put_password(password);
905 memset(password, 0, strlen(password));
906 xfree(password);
907 packet_send();
908 packet_write_wait();
910 type = packet_read();
911 if (type == SSH_SMSG_SUCCESS)
912 return 1;
913 if (type != SSH_SMSG_FAILURE)
914 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
916 /* failure */
917 return 0;
921 * SSH1 key exchange
923 void
924 ssh_kex(char *host, struct sockaddr *hostaddr)
926 int i;
927 BIGNUM *key;
928 Key *host_key, *server_key;
929 int bits, rbits;
930 int ssh_cipher_default = SSH_CIPHER_3DES;
931 u_char session_key[SSH_SESSION_KEY_LENGTH];
932 u_char cookie[8];
933 u_int supported_ciphers;
934 u_int server_flags, client_flags;
935 u_int32_t rnd = 0;
937 debug("Waiting for server public key.");
939 /* Wait for a public key packet from the server. */
940 packet_read_expect(SSH_SMSG_PUBLIC_KEY);
942 /* Get cookie from the packet. */
943 for (i = 0; i < 8; i++)
944 cookie[i] = packet_get_char();
946 /* Get the public key. */
947 server_key = key_new(KEY_RSA1);
948 bits = packet_get_int();
949 packet_get_bignum(server_key->rsa->e);
950 packet_get_bignum(server_key->rsa->n);
952 rbits = BN_num_bits(server_key->rsa->n);
953 if (bits != rbits) {
954 logit("Warning: Server lies about size of server public key: "
955 "actual size is %d bits vs. announced %d.", rbits, bits);
956 logit("Warning: This may be due to an old implementation of ssh.");
958 /* Get the host key. */
959 host_key = key_new(KEY_RSA1);
960 bits = packet_get_int();
961 packet_get_bignum(host_key->rsa->e);
962 packet_get_bignum(host_key->rsa->n);
964 rbits = BN_num_bits(host_key->rsa->n);
965 if (bits != rbits) {
966 logit("Warning: Server lies about size of server host key: "
967 "actual size is %d bits vs. announced %d.", rbits, bits);
968 logit("Warning: This may be due to an old implementation of ssh.");
971 /* Get protocol flags. */
972 server_flags = packet_get_int();
973 packet_set_protocol_flags(server_flags);
975 supported_ciphers = packet_get_int();
976 supported_authentications = packet_get_int();
977 packet_check_eom();
979 debug("Received server public key (%d bits) and host key (%d bits).",
980 BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
982 if (verify_host_key(host, hostaddr, host_key) == -1)
983 fatal("Host key verification failed.");
985 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
987 derive_ssh1_session_id(host_key->rsa->n, server_key->rsa->n, cookie, session_id);
989 /* Generate a session key. */
990 arc4random_stir();
993 * Generate an encryption key for the session. The key is a 256 bit
994 * random number, interpreted as a 32-byte key, with the least
995 * significant 8 bits being the first byte of the key.
997 for (i = 0; i < 32; i++) {
998 if (i % 4 == 0)
999 rnd = arc4random();
1000 session_key[i] = rnd & 0xff;
1001 rnd >>= 8;
1005 * According to the protocol spec, the first byte of the session key
1006 * is the highest byte of the integer. The session key is xored with
1007 * the first 16 bytes of the session id.
1009 if ((key = BN_new()) == NULL)
1010 fatal("ssh_kex: BN_new failed");
1011 if (BN_set_word(key, 0) == 0)
1012 fatal("ssh_kex: BN_set_word failed");
1013 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1014 if (BN_lshift(key, key, 8) == 0)
1015 fatal("ssh_kex: BN_lshift failed");
1016 if (i < 16) {
1017 if (BN_add_word(key, session_key[i] ^ session_id[i])
1018 == 0)
1019 fatal("ssh_kex: BN_add_word failed");
1020 } else {
1021 if (BN_add_word(key, session_key[i]) == 0)
1022 fatal("ssh_kex: BN_add_word failed");
1027 * Encrypt the integer using the public key and host key of the
1028 * server (key with smaller modulus first).
1030 if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1031 /* Public key has smaller modulus. */
1032 if (BN_num_bits(host_key->rsa->n) <
1033 BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1034 fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1035 "SSH_KEY_BITS_RESERVED %d",
1036 BN_num_bits(host_key->rsa->n),
1037 BN_num_bits(server_key->rsa->n),
1038 SSH_KEY_BITS_RESERVED);
1040 rsa_public_encrypt(key, key, server_key->rsa);
1041 rsa_public_encrypt(key, key, host_key->rsa);
1042 } else {
1043 /* Host key has smaller modulus (or they are equal). */
1044 if (BN_num_bits(server_key->rsa->n) <
1045 BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1046 fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1047 "SSH_KEY_BITS_RESERVED %d",
1048 BN_num_bits(server_key->rsa->n),
1049 BN_num_bits(host_key->rsa->n),
1050 SSH_KEY_BITS_RESERVED);
1052 rsa_public_encrypt(key, key, host_key->rsa);
1053 rsa_public_encrypt(key, key, server_key->rsa);
1056 /* Destroy the public keys since we no longer need them. */
1057 key_free(server_key);
1058 key_free(host_key);
1060 if (options.cipher == SSH_CIPHER_NOT_SET) {
1061 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1062 options.cipher = ssh_cipher_default;
1063 } else if (options.cipher == SSH_CIPHER_INVALID ||
1064 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1065 logit("No valid SSH1 cipher, using %.100s instead.",
1066 cipher_name(ssh_cipher_default));
1067 options.cipher = ssh_cipher_default;
1069 /* Check that the selected cipher is supported. */
1070 if (!(supported_ciphers & (1 << options.cipher)))
1071 fatal("Selected cipher type %.100s not supported by server.",
1072 cipher_name(options.cipher));
1074 debug("Encryption type: %.100s", cipher_name(options.cipher));
1076 /* Send the encrypted session key to the server. */
1077 packet_start(SSH_CMSG_SESSION_KEY);
1078 packet_put_char(options.cipher);
1080 /* Send the cookie back to the server. */
1081 for (i = 0; i < 8; i++)
1082 packet_put_char(cookie[i]);
1084 /* Send and destroy the encrypted encryption key integer. */
1085 packet_put_bignum(key);
1086 BN_clear_free(key);
1088 /* Send protocol flags. */
1089 packet_put_int(client_flags);
1091 /* Send the packet now. */
1092 packet_send();
1093 packet_write_wait();
1095 debug("Sent encrypted session key.");
1097 /* Set the encryption key. */
1098 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1100 /* We will no longer need the session key here. Destroy any extra copies. */
1101 memset(session_key, 0, sizeof(session_key));
1104 * Expect a success message from the server. Note that this message
1105 * will be received in encrypted form.
1107 packet_read_expect(SSH_SMSG_SUCCESS);
1109 debug("Received encrypted confirmation.");
1113 * Authenticate user
1115 void
1116 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1117 Sensitive *sensitive)
1119 #ifdef KRB5
1120 krb5_context context = NULL;
1121 krb5_auth_context auth_context = NULL;
1122 #endif
1123 int i, type;
1125 if (supported_authentications == 0)
1126 fatal("ssh_userauth1: server supports no auth methods");
1128 /* Send the name of the user to log in as on the server. */
1129 packet_start(SSH_CMSG_USER);
1130 packet_put_cstring(server_user);
1131 packet_send();
1132 packet_write_wait();
1135 * The server should respond with success if no authentication is
1136 * needed (the user has no password). Otherwise the server responds
1137 * with failure.
1139 type = packet_read();
1141 /* check whether the connection was accepted without authentication. */
1142 if (type == SSH_SMSG_SUCCESS)
1143 goto success;
1144 if (type != SSH_SMSG_FAILURE)
1145 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1147 #ifdef KRB5
1148 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1149 options.kerberos_authentication) {
1150 debug("Trying Kerberos v5 authentication.");
1152 if (try_krb5_authentication(&context, &auth_context)) {
1153 type = packet_read();
1154 if (type == SSH_SMSG_SUCCESS)
1155 goto success;
1156 if (type != SSH_SMSG_FAILURE)
1157 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1160 #endif /* KRB5 */
1162 #ifdef KRB4
1163 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1164 options.kerberos_authentication) {
1165 debug("Trying Kerberos v4 authentication.");
1167 if (try_krb4_authentication()) {
1168 type = packet_read();
1169 if (type == SSH_SMSG_SUCCESS)
1170 goto success;
1171 if (type != SSH_SMSG_FAILURE)
1172 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1175 #endif /* KRB4 */
1178 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1179 * authentication.
1181 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1182 options.rhosts_rsa_authentication) {
1183 for (i = 0; i < sensitive->nkeys; i++) {
1184 if (sensitive->keys[i] != NULL &&
1185 sensitive->keys[i]->type == KEY_RSA1 &&
1186 try_rhosts_rsa_authentication(local_user,
1187 sensitive->keys[i]))
1188 goto success;
1191 /* Try RSA authentication if the server supports it. */
1192 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1193 options.rsa_authentication) {
1195 * Try RSA authentication using the authentication agent. The
1196 * agent is tried first because no passphrase is needed for
1197 * it, whereas identity files may require passphrases.
1199 if (try_agent_authentication())
1200 goto success;
1202 /* Try RSA authentication for each identity. */
1203 for (i = 0; i < options.num_identity_files; i++)
1204 if (options.identity_keys[i] != NULL &&
1205 options.identity_keys[i]->type == KEY_RSA1 &&
1206 try_rsa_authentication(i))
1207 goto success;
1209 /* Try challenge response authentication if the server supports it. */
1210 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1211 options.challenge_response_authentication && !options.batch_mode) {
1212 if (try_challenge_response_authentication())
1213 goto success;
1215 /* Try password authentication if the server supports it. */
1216 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1217 options.password_authentication && !options.batch_mode) {
1218 char prompt[80];
1220 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ",
1221 server_user, host);
1222 if (try_password_authentication(prompt))
1223 goto success;
1225 /* All authentication methods have failed. Exit with an error message. */
1226 fatal("Permission denied.");
1227 /* NOTREACHED */
1229 success:
1230 #ifdef KRB5
1231 /* Try Kerberos v5 TGT passing. */
1232 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1233 options.kerberos_tgt_passing && context && auth_context) {
1234 if (options.cipher == SSH_CIPHER_NONE)
1235 logit("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1236 send_krb5_tgt(context, auth_context);
1238 if (auth_context)
1239 krb5_auth_con_free(context, auth_context);
1240 if (context)
1241 krb5_free_context(context);
1242 #endif
1244 #ifdef KRB4
1245 #ifdef AFS
1246 /* Try Kerberos v4 TGT passing if the server supports it. */
1247 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1248 options.kerberos_tgt_passing) {
1249 if (options.cipher == SSH_CIPHER_NONE)
1250 logit("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1251 send_krb4_tgt();
1253 /* Try AFS token passing if the server supports it. */
1254 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1255 options.afs_token_passing && k_hasafs()) {
1256 if (options.cipher == SSH_CIPHER_NONE)
1257 logit("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1258 send_afs_tokens();
1260 #endif /* AFS */
1261 #endif /* KRB4 */
1263 return; /* need statement after label */