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