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