1 /*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 * Code to connect to a remote host, and to perform the client side of the
6 * login (authentication) dialog.
7 *
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".
13 */
14 /*
15 * Copyright 2009 Sun Microsystems, Inc. All rights reserved.
16 * Use is subject to license terms.
17 */
18
19 #include "includes.h"
20 RCSID("$OpenBSD: sshconnect1.c,v 1.52 2002/08/08 13:50:23 aaron Exp $");
21
22 #include <openssl/bn.h>
23 #include <openssl/md5.h>
24
25 #ifdef KRB4
26 #include <krb.h>
27 #endif
28 #ifdef KRB5
29 #include <krb5.h>
30 #ifndef HEIMDAL
31 #define krb5_get_err_text(context,code) error_message(code)
32 #endif /* !HEIMDAL */
33 #endif
34 #ifdef AFS
35 #include <kafs.h>
36 #include "radix.h"
37 #endif
38
39 #include "ssh.h"
40 #include "ssh1.h"
41 #include "xmalloc.h"
42 #include "rsa.h"
43 #include "buffer.h"
44 #include "packet.h"
45 #include "mpaux.h"
46 #include "uidswap.h"
47 #include "log.h"
48 #include "readconf.h"
49 #include "key.h"
50 #include "authfd.h"
51 #include "sshconnect.h"
52 #include "authfile.h"
53 #include "readpass.h"
54 #include "cipher.h"
55 #include "canohost.h"
56 #include "auth.h"
57
58 /* Session id for the current session. */
59 u_char session_id[16];
60 u_int supported_authentications = 0;
61
62 extern Options options;
63 extern char *__progname;
64
65 /*
66 * Checks if the user has an authentication agent, and if so, tries to
67 * authenticate using the agent.
68 */
69 static int
try_agent_authentication(void)70 try_agent_authentication(void)
71 {
72 int type;
73 char *comment;
74 AuthenticationConnection *auth;
75 u_char response[16];
76 u_int i;
77 Key *key;
78 BIGNUM *challenge;
79
80 /* Get connection to the agent. */
81 auth = ssh_get_authentication_connection();
82 if (!auth)
83 return 0;
84
85 if ((challenge = BN_new()) == NULL)
86 fatal("try_agent_authentication: BN_new failed");
87 /* Loop through identities served by the agent. */
88 for (key = ssh_get_first_identity(auth, &comment, 1);
89 key != NULL;
90 key = ssh_get_next_identity(auth, &comment, 1)) {
91
92 /* Try this identity. */
93 debug("Trying RSA authentication via agent with '%.100s'", comment);
94 xfree(comment);
95
96 /* Tell the server that we are willing to authenticate using this key. */
97 packet_start(SSH_CMSG_AUTH_RSA);
98 packet_put_bignum(key->rsa->n);
99 packet_send();
100 packet_write_wait();
101
102 /* Wait for server's response. */
103 type = packet_read();
104
105 /* The server sends failure if it doesn\'t like our key or
106 does not support RSA authentication. */
107 if (type == SSH_SMSG_FAILURE) {
108 debug("Server refused our key.");
109 key_free(key);
110 continue;
111 }
112 /* Otherwise it should have sent a challenge. */
113 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
114 packet_disconnect("Protocol error during RSA authentication: %d",
115 type);
116
117 packet_get_bignum(challenge);
118 packet_check_eom();
119
120 debug("Received RSA challenge from server.");
121
122 /* Ask the agent to decrypt the challenge. */
123 if (!ssh_decrypt_challenge(auth, key, challenge, session_id, 1, response)) {
124 /*
125 * The agent failed to authenticate this identifier
126 * although it advertised it supports this. Just
127 * return a wrong value.
128 */
129 log("Authentication agent failed to decrypt challenge.");
130 memset(response, 0, sizeof(response));
131 }
132 key_free(key);
133 debug("Sending response to RSA challenge.");
134
135 /* Send the decrypted challenge back to the server. */
136 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
137 for (i = 0; i < 16; i++)
138 packet_put_char(response[i]);
139 packet_send();
140 packet_write_wait();
141
142 /* Wait for response from the server. */
143 type = packet_read();
144
145 /* The server returns success if it accepted the authentication. */
146 if (type == SSH_SMSG_SUCCESS) {
147 ssh_close_authentication_connection(auth);
148 BN_clear_free(challenge);
149 debug("RSA authentication accepted by server.");
150 return 1;
151 }
152 /* Otherwise it should return failure. */
153 if (type != SSH_SMSG_FAILURE)
154 packet_disconnect("Protocol error waiting RSA auth response: %d",
155 type);
156 }
157 ssh_close_authentication_connection(auth);
158 BN_clear_free(challenge);
159 debug("RSA authentication using agent refused.");
160 return 0;
161 }
162
163 /*
164 * Computes the proper response to a RSA challenge, and sends the response to
165 * the server.
166 */
167 static void
respond_to_rsa_challenge(BIGNUM * challenge,RSA * prv)168 respond_to_rsa_challenge(BIGNUM * challenge, RSA * prv)
169 {
170 u_char buf[32], response[16];
171 MD5_CTX md;
172 int i, len;
173
174 /* Decrypt the challenge using the private key. */
175 /* XXX think about Bleichenbacher, too */
176 if (rsa_private_decrypt(challenge, challenge, prv) <= 0)
177 packet_disconnect(
178 "respond_to_rsa_challenge: rsa_private_decrypt failed");
179
180 /* Compute the response. */
181 /* The response is MD5 of decrypted challenge plus session id. */
182 len = BN_num_bytes(challenge);
183 if (len <= 0 || len > sizeof(buf))
184 packet_disconnect(
185 "respond_to_rsa_challenge: bad challenge length %d", len);
186
187 memset(buf, 0, sizeof(buf));
188 BN_bn2bin(challenge, buf + sizeof(buf) - len);
189 MD5_Init(&md);
190 MD5_Update(&md, buf, 32);
191 MD5_Update(&md, session_id, 16);
192 MD5_Final(response, &md);
193
194 debug("Sending response to host key RSA challenge.");
195
196 /* Send the response back to the server. */
197 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
198 for (i = 0; i < 16; i++)
199 packet_put_char(response[i]);
200 packet_send();
201 packet_write_wait();
202
203 memset(buf, 0, sizeof(buf));
204 memset(response, 0, sizeof(response));
205 memset(&md, 0, sizeof(md));
206 }
207
208 /*
209 * Checks if the user has authentication file, and if so, tries to authenticate
210 * the user using it.
211 */
212 static int
try_rsa_authentication(int idx)213 try_rsa_authentication(int idx)
214 {
215 BIGNUM *challenge;
216 Key *public, *private;
217 char buf[300], *passphrase, *comment, *authfile;
218 int i, type, quit;
219
220 public = options.identity_keys[idx];
221 authfile = options.identity_files[idx];
222 comment = xstrdup(authfile);
223
224 debug("Trying RSA authentication with key '%.100s'", comment);
225
226 /* Tell the server that we are willing to authenticate using this key. */
227 packet_start(SSH_CMSG_AUTH_RSA);
228 packet_put_bignum(public->rsa->n);
229 packet_send();
230 packet_write_wait();
231
232 /* Wait for server's response. */
233 type = packet_read();
234
235 /*
236 * The server responds with failure if it doesn\'t like our key or
237 * doesn\'t support RSA authentication.
238 */
239 if (type == SSH_SMSG_FAILURE) {
240 debug("Server refused our key.");
241 xfree(comment);
242 return 0;
243 }
244 /* Otherwise, the server should respond with a challenge. */
245 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
246 packet_disconnect("Protocol error during RSA authentication: %d", type);
247
248 /* Get the challenge from the packet. */
249 if ((challenge = BN_new()) == NULL)
250 fatal("try_rsa_authentication: BN_new failed");
251 packet_get_bignum(challenge);
252 packet_check_eom();
253
254 debug("Received RSA challenge from server.");
255
256 /*
257 * If the key is not stored in external hardware, we have to
258 * load the private key. Try first with empty passphrase; if it
259 * fails, ask for a passphrase.
260 */
261 if (public->flags & KEY_FLAG_EXT)
262 private = public;
263 else
264 private = key_load_private_type(KEY_RSA1, authfile, "", NULL);
265 if (private == NULL && !options.batch_mode) {
266 snprintf(buf, sizeof(buf),
267 gettext("Enter passphrase for RSA key '%.100s': "),
268 comment);
269 for (i = 0; i < options.number_of_password_prompts; i++) {
270 passphrase = read_passphrase(buf, 0);
271 if (strcmp(passphrase, "") != 0) {
272 private = key_load_private_type(KEY_RSA1,
273 authfile, passphrase, NULL);
274 quit = 0;
275 } else {
276 debug2("no passphrase given, try next key");
277 quit = 1;
278 }
279 memset(passphrase, 0, strlen(passphrase));
280 xfree(passphrase);
281 if (private != NULL || quit)
282 break;
283 debug2("bad passphrase given, try again...");
284 }
285 }
286 /* We no longer need the comment. */
287 xfree(comment);
288
289 if (private == NULL) {
290 if (!options.batch_mode)
291 error("Bad passphrase.");
292
293 /* Send a dummy response packet to avoid protocol error. */
294 packet_start(SSH_CMSG_AUTH_RSA_RESPONSE);
295 for (i = 0; i < 16; i++)
296 packet_put_char(0);
297 packet_send();
298 packet_write_wait();
299
300 /* Expect the server to reject it... */
301 packet_read_expect(SSH_SMSG_FAILURE);
302 BN_clear_free(challenge);
303 return 0;
304 }
305
306 /* Compute and send a response to the challenge. */
307 respond_to_rsa_challenge(challenge, private->rsa);
308
309 /* Destroy the private key unless it in external hardware. */
310 if (!(private->flags & KEY_FLAG_EXT))
311 key_free(private);
312
313 /* We no longer need the challenge. */
314 BN_clear_free(challenge);
315
316 /* Wait for response from the server. */
317 type = packet_read();
318 if (type == SSH_SMSG_SUCCESS) {
319 debug("RSA authentication accepted by server.");
320 return 1;
321 }
322 if (type != SSH_SMSG_FAILURE)
323 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
324 debug("RSA authentication refused.");
325 return 0;
326 }
327
328 /*
329 * Tries to authenticate the user using combined rhosts or /etc/hosts.equiv
330 * authentication and RSA host authentication.
331 */
332 static int
try_rhosts_rsa_authentication(const char * local_user,Key * host_key)333 try_rhosts_rsa_authentication(const char *local_user, Key * host_key)
334 {
335 int type;
336 BIGNUM *challenge;
337
338 debug("Trying rhosts or /etc/hosts.equiv with RSA host authentication.");
339
340 /* Tell the server that we are willing to authenticate using this key. */
341 packet_start(SSH_CMSG_AUTH_RHOSTS_RSA);
342 packet_put_cstring(local_user);
343 packet_put_int(BN_num_bits(host_key->rsa->n));
344 packet_put_bignum(host_key->rsa->e);
345 packet_put_bignum(host_key->rsa->n);
346 packet_send();
347 packet_write_wait();
348
349 /* Wait for server's response. */
350 type = packet_read();
351
352 /* The server responds with failure if it doesn't admit our
353 .rhosts authentication or doesn't know our host key. */
354 if (type == SSH_SMSG_FAILURE) {
355 debug("Server refused our rhosts authentication or host key.");
356 return 0;
357 }
358 /* Otherwise, the server should respond with a challenge. */
359 if (type != SSH_SMSG_AUTH_RSA_CHALLENGE)
360 packet_disconnect("Protocol error during RSA authentication: %d", type);
361
362 /* Get the challenge from the packet. */
363 if ((challenge = BN_new()) == NULL)
364 fatal("try_rhosts_rsa_authentication: BN_new failed");
365 packet_get_bignum(challenge);
366 packet_check_eom();
367
368 debug("Received RSA challenge for host key from server.");
369
370 /* Compute a response to the challenge. */
371 respond_to_rsa_challenge(challenge, host_key->rsa);
372
373 /* We no longer need the challenge. */
374 BN_clear_free(challenge);
375
376 /* Wait for response from the server. */
377 type = packet_read();
378 if (type == SSH_SMSG_SUCCESS) {
379 debug("Rhosts or /etc/hosts.equiv with RSA host authentication accepted by server.");
380 return 1;
381 }
382 if (type != SSH_SMSG_FAILURE)
383 packet_disconnect("Protocol error waiting RSA auth response: %d", type);
384 debug("Rhosts or /etc/hosts.equiv with RSA host authentication refused.");
385 return 0;
386 }
387
388 #ifdef KRB4
389 static int
try_krb4_authentication(void)390 try_krb4_authentication(void)
391 {
392 KTEXT_ST auth; /* Kerberos data */
393 char *reply;
394 char inst[INST_SZ];
395 char *realm;
396 CREDENTIALS cred;
397 int r, type;
398 socklen_t slen;
399 Key_schedule schedule;
400 u_long checksum, cksum;
401 MSG_DAT msg_data;
402 struct sockaddr_in local, foreign;
403 struct stat st;
404
405 /* Don't do anything if we don't have any tickets. */
406 if (stat(tkt_string(), &st) < 0)
407 return 0;
408
409 strlcpy(inst, (char *)krb_get_phost(get_canonical_hostname(1)),
410 INST_SZ);
411
412 realm = (char *)krb_realmofhost(get_canonical_hostname(1));
413 if (!realm) {
414 debug("Kerberos v4: no realm for %s", get_canonical_hostname(1));
415 return 0;
416 }
417 /* This can really be anything. */
418 checksum = (u_long)getpid();
419
420 r = krb_mk_req(&auth, KRB4_SERVICE_NAME, inst, realm, checksum);
421 if (r != KSUCCESS) {
422 debug("Kerberos v4 krb_mk_req failed: %s", krb_err_txt[r]);
423 return 0;
424 }
425 /* Get session key to decrypt the server's reply with. */
426 r = krb_get_cred(KRB4_SERVICE_NAME, inst, realm, &cred);
427 if (r != KSUCCESS) {
428 debug("get_cred failed: %s", krb_err_txt[r]);
429 return 0;
430 }
431 des_key_sched((des_cblock *) cred.session, schedule);
432
433 /* Send authentication info to server. */
434 packet_start(SSH_CMSG_AUTH_KERBEROS);
435 packet_put_string((char *) auth.dat, auth.length);
436 packet_send();
437 packet_write_wait();
438
439 /* Zero the buffer. */
440 (void) memset(auth.dat, 0, MAX_KTXT_LEN);
441
442 slen = sizeof(local);
443 memset(&local, 0, sizeof(local));
444 if (getsockname(packet_get_connection_in(),
445 (struct sockaddr *)&local, &slen) < 0)
446 debug("getsockname failed: %s", strerror(errno));
447
448 slen = sizeof(foreign);
449 memset(&foreign, 0, sizeof(foreign));
450 if (getpeername(packet_get_connection_in(),
451 (struct sockaddr *)&foreign, &slen) < 0) {
452 debug("getpeername failed: %s", strerror(errno));
453 fatal_cleanup();
454 }
455 /* Get server reply. */
456 type = packet_read();
457 switch (type) {
458 case SSH_SMSG_FAILURE:
459 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
460 debug("Kerberos v4 authentication failed.");
461 return 0;
462 break;
463
464 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
465 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
466 debug("Kerberos v4 authentication accepted.");
467
468 /* Get server's response. */
469 reply = packet_get_string((u_int *) &auth.length);
470 if (auth.length >= MAX_KTXT_LEN)
471 fatal("Kerberos v4: Malformed response from server");
472 memcpy(auth.dat, reply, auth.length);
473 xfree(reply);
474
475 packet_check_eom();
476
477 /*
478 * If his response isn't properly encrypted with the session
479 * key, and the decrypted checksum fails to match, he's
480 * bogus. Bail out.
481 */
482 r = krb_rd_priv(auth.dat, auth.length, schedule, &cred.session,
483 &foreign, &local, &msg_data);
484 if (r != KSUCCESS) {
485 debug("Kerberos v4 krb_rd_priv failed: %s",
486 krb_err_txt[r]);
487 packet_disconnect("Kerberos v4 challenge failed!");
488 }
489 /* Fetch the (incremented) checksum that we supplied in the request. */
490 memcpy((char *)&cksum, (char *)msg_data.app_data,
491 sizeof(cksum));
492 cksum = ntohl(cksum);
493
494 /* If it matches, we're golden. */
495 if (cksum == checksum + 1) {
496 debug("Kerberos v4 challenge successful.");
497 return 1;
498 } else
499 packet_disconnect("Kerberos v4 challenge failed!");
500 break;
501
502 default:
503 packet_disconnect("Protocol error on Kerberos v4 response: %d", type);
504 }
505 return 0;
506 }
507
508 #endif /* KRB4 */
509
510 #ifdef KRB5
511 static int
try_krb5_authentication(krb5_context * context,krb5_auth_context * auth_context)512 try_krb5_authentication(krb5_context *context, krb5_auth_context *auth_context)
513 {
514 krb5_error_code problem;
515 const char *tkfile;
516 struct stat buf;
517 krb5_ccache ccache = NULL;
518 const char *remotehost;
519 krb5_data ap;
520 int type;
521 krb5_ap_rep_enc_part *reply = NULL;
522 int ret;
523
524 memset(&ap, 0, sizeof(ap));
525
526 problem = krb5_init_context(context);
527 if (problem) {
528 debug("Kerberos v5: krb5_init_context failed");
529 ret = 0;
530 goto out;
531 }
532
533 problem = krb5_auth_con_init(*context, auth_context);
534 if (problem) {
535 debug("Kerberos v5: krb5_auth_con_init failed");
536 ret = 0;
537 goto out;
538 }
539
540 #ifndef HEIMDAL
541 problem = krb5_auth_con_setflags(*context, *auth_context,
542 KRB5_AUTH_CONTEXT_RET_TIME);
543 if (problem) {
544 debug("Keberos v5: krb5_auth_con_setflags failed");
545 ret = 0;
546 goto out;
547 }
548 #endif
549
550 tkfile = krb5_cc_default_name(*context);
551 if (strncmp(tkfile, "FILE:", 5) == 0)
552 tkfile += 5;
553
554 if (stat(tkfile, &buf) == 0 && getuid() != buf.st_uid) {
555 debug("Kerberos v5: could not get default ccache (permission denied).");
556 ret = 0;
557 goto out;
558 }
559
560 problem = krb5_cc_default(*context, &ccache);
561 if (problem) {
562 debug("Kerberos v5: krb5_cc_default failed: %s",
563 krb5_get_err_text(*context, problem));
564 ret = 0;
565 goto out;
566 }
567
568 remotehost = get_canonical_hostname(1);
569
570 problem = krb5_mk_req(*context, auth_context, AP_OPTS_MUTUAL_REQUIRED,
571 "host", remotehost, NULL, ccache, &ap);
572 if (problem) {
573 debug("Kerberos v5: krb5_mk_req failed: %s",
574 krb5_get_err_text(*context, problem));
575 ret = 0;
576 goto out;
577 }
578
579 packet_start(SSH_CMSG_AUTH_KERBEROS);
580 packet_put_string((char *) ap.data, ap.length);
581 packet_send();
582 packet_write_wait();
583
584 xfree(ap.data);
585 ap.length = 0;
586
587 type = packet_read();
588 switch (type) {
589 case SSH_SMSG_FAILURE:
590 /* Should really be SSH_SMSG_AUTH_KERBEROS_FAILURE */
591 debug("Kerberos v5 authentication failed.");
592 ret = 0;
593 break;
594
595 case SSH_SMSG_AUTH_KERBEROS_RESPONSE:
596 /* SSH_SMSG_AUTH_KERBEROS_SUCCESS */
597 debug("Kerberos v5 authentication accepted.");
598
599 /* Get server's response. */
600 ap.data = packet_get_string((unsigned int *) &ap.length);
601 packet_check_eom();
602 /* XXX je to dobre? */
603
604 problem = krb5_rd_rep(*context, *auth_context, &ap, &reply);
605 if (problem) {
606 ret = 0;
607 }
608 ret = 1;
609 break;
610
611 default:
612 packet_disconnect("Protocol error on Kerberos v5 response: %d",
613 type);
614 ret = 0;
615 break;
616
617 }
618
619 out:
620 if (ccache != NULL)
621 krb5_cc_close(*context, ccache);
622 if (reply != NULL)
623 krb5_free_ap_rep_enc_part(*context, reply);
624 if (ap.length > 0)
625 #ifdef HEIMDAL
626 krb5_data_free(&ap);
627 #else
628 krb5_free_data_contents(*context, &ap);
629 #endif
630
631 return (ret);
632 }
633
634 static void
send_krb5_tgt(krb5_context context,krb5_auth_context auth_context)635 send_krb5_tgt(krb5_context context, krb5_auth_context auth_context)
636 {
637 int fd, type;
638 krb5_error_code problem;
639 krb5_data outbuf;
640 krb5_ccache ccache = NULL;
641 krb5_creds creds;
642 #ifdef HEIMDAL
643 krb5_kdc_flags flags;
644 #else
645 int forwardable;
646 #endif
647 const char *remotehost;
648
649 memset(&creds, 0, sizeof(creds));
650 memset(&outbuf, 0, sizeof(outbuf));
651
652 fd = packet_get_connection_in();
653
654 #ifdef HEIMDAL
655 problem = krb5_auth_con_setaddrs_from_fd(context, auth_context, &fd);
656 #else
657 problem = krb5_auth_con_genaddrs(context, auth_context, fd,
658 KRB5_AUTH_CONTEXT_GENERATE_REMOTE_FULL_ADDR |
659 KRB5_AUTH_CONTEXT_GENERATE_LOCAL_FULL_ADDR);
660 #endif
661 if (problem)
662 goto out;
663
664 problem = krb5_cc_default(context, &ccache);
665 if (problem)
666 goto out;
667
668 problem = krb5_cc_get_principal(context, ccache, &creds.client);
669 if (problem)
670 goto out;
671
672 remotehost = get_canonical_hostname(1);
673
674 #ifdef HEIMDAL
675 problem = krb5_build_principal(context, &creds.server,
676 strlen(creds.client->realm), creds.client->realm,
677 "krbtgt", creds.client->realm, NULL);
678 #else
679 problem = krb5_build_principal(context, &creds.server,
680 creds.client->realm.length, creds.client->realm.data,
681 "host", remotehost, NULL);
682 #endif
683 if (problem)
684 goto out;
685
686 creds.times.endtime = 0;
687
688 #ifdef HEIMDAL
689 flags.i = 0;
690 flags.b.forwarded = 1;
691 flags.b.forwardable = krb5_config_get_bool(context, NULL,
692 "libdefaults", "forwardable", NULL);
693 problem = krb5_get_forwarded_creds(context, auth_context,
694 ccache, flags.i, remotehost, &creds, &outbuf);
695 #else
696 forwardable = 1;
697 problem = krb5_fwd_tgt_creds(context, auth_context, remotehost,
698 creds.client, creds.server, ccache, forwardable, &outbuf);
699 #endif
700
701 if (problem)
702 goto out;
703
704 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
705 packet_put_string((char *)outbuf.data, outbuf.length);
706 packet_send();
707 packet_write_wait();
708
709 type = packet_read();
710
711 if (type == SSH_SMSG_SUCCESS) {
712 char *pname;
713
714 krb5_unparse_name(context, creds.client, &pname);
715 debug("Kerberos v5 TGT forwarded (%s).", pname);
716 xfree(pname);
717 } else
718 debug("Kerberos v5 TGT forwarding failed.");
719
720 return;
721
722 out:
723 if (problem)
724 debug("Kerberos v5 TGT forwarding failed: %s",
725 krb5_get_err_text(context, problem));
726 if (creds.client)
727 krb5_free_principal(context, creds.client);
728 if (creds.server)
729 krb5_free_principal(context, creds.server);
730 if (ccache)
731 krb5_cc_close(context, ccache);
732 if (outbuf.data)
733 xfree(outbuf.data);
734 }
735 #endif /* KRB5 */
736
737 #ifdef AFS
738 static void
send_krb4_tgt(void)739 send_krb4_tgt(void)
740 {
741 CREDENTIALS *creds;
742 struct stat st;
743 char buffer[4096], pname[ANAME_SZ], pinst[INST_SZ], prealm[REALM_SZ];
744 int problem, type;
745
746 /* Don't do anything if we don't have any tickets. */
747 if (stat(tkt_string(), &st) < 0)
748 return;
749
750 creds = xmalloc(sizeof(*creds));
751
752 problem = krb_get_tf_fullname(TKT_FILE, pname, pinst, prealm);
753 if (problem)
754 goto out;
755
756 problem = krb_get_cred("krbtgt", prealm, prealm, creds);
757 if (problem)
758 goto out;
759
760 if (time(0) > krb_life_to_time(creds->issue_date, creds->lifetime)) {
761 problem = RD_AP_EXP;
762 goto out;
763 }
764 creds_to_radix(creds, (u_char *)buffer, sizeof(buffer));
765
766 packet_start(SSH_CMSG_HAVE_KERBEROS_TGT);
767 packet_put_cstring(buffer);
768 packet_send();
769 packet_write_wait();
770
771 type = packet_read();
772
773 if (type == SSH_SMSG_SUCCESS)
774 debug("Kerberos v4 TGT forwarded (%s%s%s@%s).",
775 creds->pname, creds->pinst[0] ? "." : "",
776 creds->pinst, creds->realm);
777 else
778 debug("Kerberos v4 TGT rejected.");
779
780 xfree(creds);
781 return;
782
783 out:
784 debug("Kerberos v4 TGT passing failed: %s", krb_err_txt[problem]);
785 xfree(creds);
786 }
787
788 static void
send_afs_tokens(void)789 send_afs_tokens(void)
790 {
791 CREDENTIALS creds;
792 struct ViceIoctl parms;
793 struct ClearToken ct;
794 int i, type, len;
795 char buf[2048], *p, *server_cell;
796 char buffer[8192];
797
798 /* Move over ktc_GetToken, here's something leaner. */
799 for (i = 0; i < 100; i++) { /* just in case */
800 parms.in = (char *) &i;
801 parms.in_size = sizeof(i);
802 parms.out = buf;
803 parms.out_size = sizeof(buf);
804 if (k_pioctl(0, VIOCGETTOK, &parms, 0) != 0)
805 break;
806 p = buf;
807
808 /* Get secret token. */
809 memcpy(&creds.ticket_st.length, p, sizeof(u_int));
810 if (creds.ticket_st.length > MAX_KTXT_LEN)
811 break;
812 p += sizeof(u_int);
813 memcpy(creds.ticket_st.dat, p, creds.ticket_st.length);
814 p += creds.ticket_st.length;
815
816 /* Get clear token. */
817 memcpy(&len, p, sizeof(len));
818 if (len != sizeof(struct ClearToken))
819 break;
820 p += sizeof(len);
821 memcpy(&ct, p, len);
822 p += len;
823 p += sizeof(len); /* primary flag */
824 server_cell = p;
825
826 /* Flesh out our credentials. */
827 strlcpy(creds.service, "afs", sizeof(creds.service));
828 creds.instance[0] = '\0';
829 strlcpy(creds.realm, server_cell, REALM_SZ);
830 memcpy(creds.session, ct.HandShakeKey, DES_KEY_SZ);
831 creds.issue_date = ct.BeginTimestamp;
832 creds.lifetime = krb_time_to_life(creds.issue_date,
833 ct.EndTimestamp);
834 creds.kvno = ct.AuthHandle;
835 snprintf(creds.pname, sizeof(creds.pname), "AFS ID %d", ct.ViceId);
836 creds.pinst[0] = '\0';
837
838 /* Encode token, ship it off. */
839 if (creds_to_radix(&creds, (u_char *)buffer,
840 sizeof(buffer)) <= 0)
841 break;
842 packet_start(SSH_CMSG_HAVE_AFS_TOKEN);
843 packet_put_cstring(buffer);
844 packet_send();
845 packet_write_wait();
846
847 /* Roger, Roger. Clearance, Clarence. What's your vector,
848 Victor? */
849 type = packet_read();
850
851 if (type == SSH_SMSG_FAILURE)
852 debug("AFS token for cell %s rejected.", server_cell);
853 else if (type != SSH_SMSG_SUCCESS)
854 packet_disconnect("Protocol error on AFS token response: %d", type);
855 }
856 }
857
858 #endif /* AFS */
859
860 /*
861 * Tries to authenticate with any string-based challenge/response system.
862 * Note that the client code is not tied to s/key or TIS.
863 */
864 static int
try_challenge_response_authentication(void)865 try_challenge_response_authentication(void)
866 {
867 int type, i;
868 u_int clen;
869 char prompt[1024];
870 char *challenge, *response;
871
872 debug("Doing challenge response authentication.");
873
874 for (i = 0; i < options.number_of_password_prompts; i++) {
875 /* request a challenge */
876 packet_start(SSH_CMSG_AUTH_TIS);
877 packet_send();
878 packet_write_wait();
879
880 type = packet_read();
881 if (type != SSH_SMSG_FAILURE &&
882 type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
883 packet_disconnect("Protocol error: got %d in response "
884 "to SSH_CMSG_AUTH_TIS", type);
885 }
886 if (type != SSH_SMSG_AUTH_TIS_CHALLENGE) {
887 debug("No challenge.");
888 return 0;
889 }
890 challenge = packet_get_string(&clen);
891 packet_check_eom();
892 snprintf(prompt, sizeof prompt, "%s%s", challenge,
893 strchr(challenge, '\n') ? "" : gettext("\nResponse: "));
894 xfree(challenge);
895 if (i != 0)
896 error("Permission denied, please try again.");
897 if (options.cipher == SSH_CIPHER_NONE)
898 log("WARNING: Encryption is disabled! "
899 "Response will be transmitted in clear text.");
900 response = read_passphrase(prompt, 0);
901 if (strcmp(response, "") == 0) {
902 xfree(response);
903 break;
904 }
905 packet_start(SSH_CMSG_AUTH_TIS_RESPONSE);
906 ssh_put_password(response);
907 memset(response, 0, strlen(response));
908 xfree(response);
909 packet_send();
910 packet_write_wait();
911 type = packet_read();
912 if (type == SSH_SMSG_SUCCESS)
913 return 1;
914 if (type != SSH_SMSG_FAILURE)
915 packet_disconnect("Protocol error: got %d in response "
916 "to SSH_CMSG_AUTH_TIS_RESPONSE", type);
917 }
918 /* failure */
919 return 0;
920 }
921
922 /*
923 * Tries to authenticate with plain passwd authentication.
924 */
925 static int
try_password_authentication(char * prompt)926 try_password_authentication(char *prompt)
927 {
928 int type, i;
929 char *password;
930
931 debug("Doing password authentication.");
932 if (options.cipher == SSH_CIPHER_NONE)
933 log("WARNING: Encryption is disabled! Password will be transmitted in clear text.");
934 for (i = 0; i < options.number_of_password_prompts; i++) {
935 if (i != 0)
936 error("Permission denied, please try again.");
937 password = read_passphrase(prompt, 0);
938 packet_start(SSH_CMSG_AUTH_PASSWORD);
939 ssh_put_password(password);
940 memset(password, 0, strlen(password));
941 xfree(password);
942 packet_send();
943 packet_write_wait();
944
945 type = packet_read();
946 if (type == SSH_SMSG_SUCCESS)
947 return 1;
948 if (type != SSH_SMSG_FAILURE)
949 packet_disconnect("Protocol error: got %d in response to passwd auth", type);
950 }
951 /* failure */
952 return 0;
953 }
954
955 /*
956 * SSH1 key exchange
957 */
958 void
ssh_kex(char * host,struct sockaddr * hostaddr)959 ssh_kex(char *host, struct sockaddr *hostaddr)
960 {
961 int i;
962 BIGNUM *key;
963 Key *host_key, *server_key;
964 int bits, rbits;
965 int ssh_cipher_default = SSH_CIPHER_3DES;
966 u_char session_key[SSH_SESSION_KEY_LENGTH];
967 u_char cookie[8];
968 u_int supported_ciphers;
969 u_int server_flags, client_flags;
970 u_int32_t rand = 0;
971
972 debug("Waiting for server public key.");
973
974 /* Wait for a public key packet from the server. */
975 packet_read_expect(SSH_SMSG_PUBLIC_KEY);
976
977 /* Get cookie from the packet. */
978 for (i = 0; i < 8; i++)
979 cookie[i] = packet_get_char();
980
981 /* Get the public key. */
982 server_key = key_new(KEY_RSA1);
983 bits = packet_get_int();
984 packet_get_bignum(server_key->rsa->e);
985 packet_get_bignum(server_key->rsa->n);
986
987 rbits = BN_num_bits(server_key->rsa->n);
988 if (bits != rbits) {
989 log("Warning: Server lies about size of server public key: "
990 "actual size is %d bits vs. announced %d.", rbits, bits);
991 log("Warning: This may be due to an old implementation of ssh.");
992 }
993 /* Get the host key. */
994 host_key = key_new(KEY_RSA1);
995 bits = packet_get_int();
996 packet_get_bignum(host_key->rsa->e);
997 packet_get_bignum(host_key->rsa->n);
998
999 rbits = BN_num_bits(host_key->rsa->n);
1000 if (bits != rbits) {
1001 log("Warning: Server lies about size of server host key: "
1002 "actual size is %d bits vs. announced %d.", rbits, bits);
1003 log("Warning: This may be due to an old implementation of ssh.");
1004 }
1005
1006 /* Get protocol flags. */
1007 server_flags = packet_get_int();
1008 packet_set_protocol_flags(server_flags);
1009
1010 supported_ciphers = packet_get_int();
1011 supported_authentications = packet_get_int();
1012 packet_check_eom();
1013
1014 debug("Received server public key (%d bits) and host key (%d bits).",
1015 BN_num_bits(server_key->rsa->n), BN_num_bits(host_key->rsa->n));
1016
1017 if (verify_host_key(host, hostaddr, host_key) == -1)
1018 fatal("Host key verification failed.");
1019
1020 client_flags = SSH_PROTOFLAG_SCREEN_NUMBER | SSH_PROTOFLAG_HOST_IN_FWD_OPEN;
1021
1022 compute_session_id(session_id, cookie, host_key->rsa->n, server_key->rsa->n);
1023
1024 /* Generate a session key. */
1025 arc4random_stir();
1026
1027 /*
1028 * Generate an encryption key for the session. The key is a 256 bit
1029 * random number, interpreted as a 32-byte key, with the least
1030 * significant 8 bits being the first byte of the key.
1031 */
1032 for (i = 0; i < 32; i++) {
1033 if (i % 4 == 0)
1034 rand = arc4random();
1035 session_key[i] = rand & 0xff;
1036 rand >>= 8;
1037 }
1038
1039 /*
1040 * According to the protocol spec, the first byte of the session key
1041 * is the highest byte of the integer. The session key is xored with
1042 * the first 16 bytes of the session id.
1043 */
1044 if ((key = BN_new()) == NULL)
1045 fatal("respond_to_rsa_challenge: BN_new failed");
1046 BN_set_word(key, 0);
1047 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
1048 BN_lshift(key, key, 8);
1049 if (i < 16)
1050 BN_add_word(key, session_key[i] ^ session_id[i]);
1051 else
1052 BN_add_word(key, session_key[i]);
1053 }
1054
1055 /*
1056 * Encrypt the integer using the public key and host key of the
1057 * server (key with smaller modulus first).
1058 */
1059 if (BN_cmp(server_key->rsa->n, host_key->rsa->n) < 0) {
1060 /* Public key has smaller modulus. */
1061 if (BN_num_bits(host_key->rsa->n) <
1062 BN_num_bits(server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1063 fatal("respond_to_rsa_challenge: host_key %d < server_key %d + "
1064 "SSH_KEY_BITS_RESERVED %d",
1065 BN_num_bits(host_key->rsa->n),
1066 BN_num_bits(server_key->rsa->n),
1067 SSH_KEY_BITS_RESERVED);
1068 }
1069 rsa_public_encrypt(key, key, server_key->rsa);
1070 rsa_public_encrypt(key, key, host_key->rsa);
1071 } else {
1072 /* Host key has smaller modulus (or they are equal). */
1073 if (BN_num_bits(server_key->rsa->n) <
1074 BN_num_bits(host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1075 fatal("respond_to_rsa_challenge: server_key %d < host_key %d + "
1076 "SSH_KEY_BITS_RESERVED %d",
1077 BN_num_bits(server_key->rsa->n),
1078 BN_num_bits(host_key->rsa->n),
1079 SSH_KEY_BITS_RESERVED);
1080 }
1081 rsa_public_encrypt(key, key, host_key->rsa);
1082 rsa_public_encrypt(key, key, server_key->rsa);
1083 }
1084
1085 /* Destroy the public keys since we no longer need them. */
1086 key_free(server_key);
1087 key_free(host_key);
1088
1089 if (options.cipher == SSH_CIPHER_NOT_SET) {
1090 if (cipher_mask_ssh1(1) & supported_ciphers & (1 << ssh_cipher_default))
1091 options.cipher = ssh_cipher_default;
1092 } else if (options.cipher == SSH_CIPHER_ILLEGAL ||
1093 !(cipher_mask_ssh1(1) & (1 << options.cipher))) {
1094 log("No valid SSH1 cipher, using %.100s instead.",
1095 cipher_name(ssh_cipher_default));
1096 options.cipher = ssh_cipher_default;
1097 }
1098 /* Check that the selected cipher is supported. */
1099 if (!(supported_ciphers & (1 << options.cipher)))
1100 fatal("Selected cipher type %.100s not supported by server.",
1101 cipher_name(options.cipher));
1102
1103 debug("Encryption type: %.100s", cipher_name(options.cipher));
1104
1105 /* Send the encrypted session key to the server. */
1106 packet_start(SSH_CMSG_SESSION_KEY);
1107 packet_put_char(options.cipher);
1108
1109 /* Send the cookie back to the server. */
1110 for (i = 0; i < 8; i++)
1111 packet_put_char(cookie[i]);
1112
1113 /* Send and destroy the encrypted encryption key integer. */
1114 packet_put_bignum(key);
1115 BN_clear_free(key);
1116
1117 /* Send protocol flags. */
1118 packet_put_int(client_flags);
1119
1120 /* Send the packet now. */
1121 packet_send();
1122 packet_write_wait();
1123
1124 debug("Sent encrypted session key.");
1125
1126 /* Set the encryption key. */
1127 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, options.cipher);
1128
1129 /* We will no longer need the session key here. Destroy any extra copies. */
1130 memset(session_key, 0, sizeof(session_key));
1131
1132 /*
1133 * Expect a success message from the server. Note that this message
1134 * will be received in encrypted form.
1135 */
1136 packet_read_expect(SSH_SMSG_SUCCESS);
1137
1138 debug("Received encrypted confirmation.");
1139 }
1140
1141 /*
1142 * Authenticate user
1143 */
1144 void
ssh_userauth1(const char * local_user,const char * server_user,char * host,Sensitive * sensitive)1145 ssh_userauth1(const char *local_user, const char *server_user, char *host,
1146 Sensitive *sensitive)
1147 {
1148 #ifdef KRB5
1149 krb5_context context = NULL;
1150 krb5_auth_context auth_context = NULL;
1151 #endif
1152 int i, type;
1153
1154 if (supported_authentications == 0)
1155 fatal("ssh_userauth1: server supports no auth methods");
1156
1157 /* Send the name of the user to log in as on the server. */
1158 packet_start(SSH_CMSG_USER);
1159 packet_put_cstring(server_user);
1160 packet_send();
1161 packet_write_wait();
1162
1163 /*
1164 * The server should respond with success if no authentication is
1165 * needed (the user has no password). Otherwise the server responds
1166 * with failure.
1167 */
1168 type = packet_read();
1169
1170 /* check whether the connection was accepted without authentication. */
1171 if (type == SSH_SMSG_SUCCESS)
1172 goto success;
1173 if (type != SSH_SMSG_FAILURE)
1174 packet_disconnect("Protocol error: got %d in response to SSH_CMSG_USER", type);
1175
1176 #ifdef KRB5
1177 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1178 options.kerberos_authentication) {
1179 debug("Trying Kerberos v5 authentication.");
1180
1181 if (try_krb5_authentication(&context, &auth_context)) {
1182 type = packet_read();
1183 if (type == SSH_SMSG_SUCCESS)
1184 goto success;
1185 if (type != SSH_SMSG_FAILURE)
1186 packet_disconnect("Protocol error: got %d in response to Kerberos v5 auth", type);
1187 }
1188 }
1189 #endif /* KRB5 */
1190
1191 #ifdef KRB4
1192 if ((supported_authentications & (1 << SSH_AUTH_KERBEROS)) &&
1193 options.kerberos_authentication) {
1194 debug("Trying Kerberos v4 authentication.");
1195
1196 if (try_krb4_authentication()) {
1197 type = packet_read();
1198 if (type == SSH_SMSG_SUCCESS)
1199 goto success;
1200 if (type != SSH_SMSG_FAILURE)
1201 packet_disconnect("Protocol error: got %d in response to Kerberos v4 auth", type);
1202 }
1203 }
1204 #endif /* KRB4 */
1205
1206 /*
1207 * Use rhosts authentication if running in privileged socket and we
1208 * do not wish to remain anonymous.
1209 */
1210 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS)) &&
1211 options.rhosts_authentication) {
1212 debug("Trying rhosts authentication.");
1213 packet_start(SSH_CMSG_AUTH_RHOSTS);
1214 packet_put_cstring(local_user);
1215 packet_send();
1216 packet_write_wait();
1217
1218 /* The server should respond with success or failure. */
1219 type = packet_read();
1220 if (type == SSH_SMSG_SUCCESS)
1221 goto success;
1222 if (type != SSH_SMSG_FAILURE)
1223 packet_disconnect("Protocol error: got %d in response to rhosts auth",
1224 type);
1225 }
1226 /*
1227 * Try .rhosts or /etc/hosts.equiv authentication with RSA host
1228 * authentication.
1229 */
1230 if ((supported_authentications & (1 << SSH_AUTH_RHOSTS_RSA)) &&
1231 options.rhosts_rsa_authentication) {
1232 for (i = 0; i < sensitive->nkeys; i++) {
1233 if (sensitive->keys[i] != NULL &&
1234 sensitive->keys[i]->type == KEY_RSA1 &&
1235 try_rhosts_rsa_authentication(local_user,
1236 sensitive->keys[i]))
1237 goto success;
1238 }
1239 }
1240 /* Try RSA authentication if the server supports it. */
1241 if ((supported_authentications & (1 << SSH_AUTH_RSA)) &&
1242 options.rsa_authentication) {
1243 /*
1244 * Try RSA authentication using the authentication agent. The
1245 * agent is tried first because no passphrase is needed for
1246 * it, whereas identity files may require passphrases.
1247 */
1248 if (try_agent_authentication())
1249 goto success;
1250
1251 /* Try RSA authentication for each identity. */
1252 for (i = 0; i < options.num_identity_files; i++)
1253 if (options.identity_keys[i] != NULL &&
1254 options.identity_keys[i]->type == KEY_RSA1 &&
1255 try_rsa_authentication(i))
1256 goto success;
1257 }
1258 /* Try challenge response authentication if the server supports it. */
1259 if ((supported_authentications & (1 << SSH_AUTH_TIS)) &&
1260 options.challenge_response_authentication && !options.batch_mode) {
1261 if (try_challenge_response_authentication())
1262 goto success;
1263 }
1264 /* Try password authentication if the server supports it. */
1265 if ((supported_authentications & (1 << SSH_AUTH_PASSWORD)) &&
1266 options.password_authentication && !options.batch_mode) {
1267 char prompt[80];
1268
1269 snprintf(prompt, sizeof(prompt),
1270 gettext("%.30s@%.128s's password: "),
1271 server_user, host);
1272 if (try_password_authentication(prompt))
1273 goto success;
1274 }
1275 /* All authentication methods have failed. Exit with an error message. */
1276 fatal("Permission denied (all authentication methods have failed).");
1277 /* NOTREACHED */
1278
1279 success:
1280 #ifdef KRB5
1281 /* Try Kerberos v5 TGT passing. */
1282 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1283 options.kerberos_tgt_passing && context && auth_context) {
1284 if (options.cipher == SSH_CIPHER_NONE)
1285 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1286 send_krb5_tgt(context, auth_context);
1287 }
1288 if (auth_context)
1289 krb5_auth_con_free(context, auth_context);
1290 if (context)
1291 krb5_free_context(context);
1292 #endif
1293
1294 #ifdef AFS
1295 /* Try Kerberos v4 TGT passing if the server supports it. */
1296 if ((supported_authentications & (1 << SSH_PASS_KERBEROS_TGT)) &&
1297 options.kerberos_tgt_passing) {
1298 if (options.cipher == SSH_CIPHER_NONE)
1299 log("WARNING: Encryption is disabled! Ticket will be transmitted in the clear!");
1300 send_krb4_tgt();
1301 }
1302 /* Try AFS token passing if the server supports it. */
1303 if ((supported_authentications & (1 << SSH_PASS_AFS_TOKEN)) &&
1304 options.afs_token_passing && k_hasafs()) {
1305 if (options.cipher == SSH_CIPHER_NONE)
1306 log("WARNING: Encryption is disabled! Token will be transmitted in the clear!");
1307 send_afs_tokens();
1308 }
1309 #endif /* AFS */
1310
1311 return; /* need statement after label */
1312 }
1313