Revert "more debug"
[metze/samba/wip.git] / source4 / heimdal / lib / krb5 / rd_req.c
1
2 /*
3  * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
4  * (Royal Institute of Technology, Stockholm, Sweden).
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * 3. Neither the name of the Institute nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "krb5_locl.h"
36
37 static krb5_error_code
38 decrypt_tkt_enc_part (krb5_context context,
39                       krb5_keyblock *key,
40                       EncryptedData *enc_part,
41                       EncTicketPart *decr_part)
42 {
43     krb5_error_code ret;
44     krb5_data plain;
45     size_t len;
46     krb5_crypto crypto;
47
48     ret = krb5_crypto_init(context, key, 0, &crypto);
49     if (ret)
50         return ret;
51     ret = krb5_decrypt_EncryptedData (context,
52                                       crypto,
53                                       KRB5_KU_TICKET,
54                                       enc_part,
55                                       &plain);
56     krb5_crypto_destroy(context, crypto);
57     if (ret)
58         return ret;
59
60     ret = decode_EncTicketPart(plain.data, plain.length, decr_part, &len);
61     if (ret)
62         krb5_set_error_message(context, ret,
63                                N_("Failed to decode encrypted "
64                                   "ticket part", ""));
65     krb5_data_free (&plain);
66     return ret;
67 }
68
69 static krb5_error_code
70 decrypt_authenticator (krb5_context context,
71                        EncryptionKey *key,
72                        EncryptedData *enc_part,
73                        Authenticator *authenticator,
74                        krb5_key_usage usage)
75 {
76     krb5_error_code ret;
77     krb5_data plain;
78     size_t len;
79     krb5_crypto crypto;
80
81     ret = krb5_crypto_init(context, key, 0, &crypto);
82     if (ret)
83         return ret;
84     ret = krb5_decrypt_EncryptedData (context,
85                                       crypto,
86                                       usage /* KRB5_KU_AP_REQ_AUTH */,
87                                       enc_part,
88                                       &plain);
89     /* for backwards compatibility, also try the old usage */
90     if (ret && usage == KRB5_KU_TGS_REQ_AUTH)
91         ret = krb5_decrypt_EncryptedData (context,
92                                           crypto,
93                                           KRB5_KU_AP_REQ_AUTH,
94                                           enc_part,
95                                           &plain);
96     krb5_crypto_destroy(context, crypto);
97     if (ret)
98         return ret;
99
100     ret = decode_Authenticator(plain.data, plain.length,
101                                authenticator, &len);
102     krb5_data_free (&plain);
103     return ret;
104 }
105
106 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
107 krb5_decode_ap_req(krb5_context context,
108                    const krb5_data *inbuf,
109                    krb5_ap_req *ap_req)
110 {
111     krb5_error_code ret;
112     size_t len;
113     ret = decode_AP_REQ(inbuf->data, inbuf->length, ap_req, &len);
114     if (ret)
115         return ret;
116     if (ap_req->pvno != 5){
117         free_AP_REQ(ap_req);
118         krb5_clear_error_message (context);
119         return KRB5KRB_AP_ERR_BADVERSION;
120     }
121     if (ap_req->msg_type != krb_ap_req){
122         free_AP_REQ(ap_req);
123         krb5_clear_error_message (context);
124         return KRB5KRB_AP_ERR_MSG_TYPE;
125     }
126     if (ap_req->ticket.tkt_vno != 5){
127         free_AP_REQ(ap_req);
128         krb5_clear_error_message (context);
129         return KRB5KRB_AP_ERR_BADVERSION;
130     }
131     return 0;
132 }
133
134 static krb5_error_code
135 check_transited(krb5_context context, Ticket *ticket, EncTicketPart *enc)
136 {
137     char **realms;
138     unsigned int num_realms, n;
139     krb5_error_code ret;
140
141     /*
142      * Windows 2000 and 2003 uses this inside their TGT so it's normaly
143      * not seen by others, however, samba4 joined with a Windows AD as
144      * a Domain Controller gets exposed to this.
145      */
146     if(enc->transited.tr_type == 0 && enc->transited.contents.length == 0)
147         return 0;
148
149     if(enc->transited.tr_type != DOMAIN_X500_COMPRESS)
150         return KRB5KDC_ERR_TRTYPE_NOSUPP;
151
152     if(enc->transited.contents.length == 0)
153         return 0;
154
155     ret = krb5_domain_x500_decode(context, enc->transited.contents,
156                                   &realms, &num_realms,
157                                   enc->crealm,
158                                   ticket->realm);
159     if(ret)
160         return ret;
161     ret = krb5_check_transited(context, enc->crealm,
162                                ticket->realm,
163                                realms, num_realms, NULL);
164     for (n = 0; n < num_realms; n++)
165         free(realms[n]);
166     free(realms);
167     return ret;
168 }
169
170 static krb5_error_code
171 find_etypelist(krb5_context context,
172                krb5_auth_context auth_context,
173                EtypeList *etypes)
174 {
175     krb5_error_code ret;
176     krb5_authdata *ad;
177     krb5_authdata adIfRelevant;
178     unsigned i;
179
180     memset(&adIfRelevant, 0, sizeof(adIfRelevant));
181
182     etypes->len = 0;
183     etypes->val = NULL;
184
185     ad = auth_context->authenticator->authorization_data;
186     if (ad == NULL)
187         return 0;
188
189     for (i = 0; i < ad->len; i++) {
190         if (ad->val[i].ad_type == KRB5_AUTHDATA_IF_RELEVANT) {
191             ret = decode_AD_IF_RELEVANT(ad->val[i].ad_data.data,
192                                         ad->val[i].ad_data.length,
193                                         &adIfRelevant,
194                                         NULL);
195             if (ret)
196                 return ret;
197
198             if (adIfRelevant.len == 1 &&
199                 adIfRelevant.val[0].ad_type ==
200                         KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION) {
201                 break;
202             }
203             free_AD_IF_RELEVANT(&adIfRelevant);
204             adIfRelevant.len = 0;
205         }
206     }
207
208     if (adIfRelevant.len == 0)
209         return 0;
210
211     ret = decode_EtypeList(adIfRelevant.val[0].ad_data.data,
212                            adIfRelevant.val[0].ad_data.length,
213                            etypes,
214                            NULL);
215     if (ret)
216         krb5_clear_error_message(context);
217
218     free_AD_IF_RELEVANT(&adIfRelevant);
219
220     return ret;
221 }
222
223 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
224 krb5_decrypt_ticket(krb5_context context,
225                     Ticket *ticket,
226                     krb5_keyblock *key,
227                     EncTicketPart *out,
228                     krb5_flags flags)
229 {
230     EncTicketPart t;
231     krb5_error_code ret;
232     ret = decrypt_tkt_enc_part (context, key, &ticket->enc_part, &t);
233     if (ret)
234         return ret;
235
236     {
237         krb5_timestamp now;
238         time_t start = t.authtime;
239
240         krb5_timeofday (context, &now);
241         if(t.starttime)
242             start = *t.starttime;
243         if(start - now > context->max_skew
244            || (t.flags.invalid
245                && !(flags & KRB5_VERIFY_AP_REQ_IGNORE_INVALID))) {
246             free_EncTicketPart(&t);
247             krb5_clear_error_message (context);
248             return KRB5KRB_AP_ERR_TKT_NYV;
249         }
250         if(now - t.endtime > context->max_skew) {
251             free_EncTicketPart(&t);
252             krb5_clear_error_message (context);
253             return KRB5KRB_AP_ERR_TKT_EXPIRED;
254         }
255
256         if(!t.flags.transited_policy_checked
257            && !(flags & KRB5_VERIFY_AP_REQ_NO_TRANSITED_CHECK)) {
258             ret = check_transited(context, ticket, &t);
259             if(ret) {
260                 free_EncTicketPart(&t);
261                 return ret;
262             }
263         }
264     }
265
266     if(out)
267         *out = t;
268     else
269         free_EncTicketPart(&t);
270     return 0;
271 }
272
273 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
274 krb5_verify_authenticator_checksum(krb5_context context,
275                                    krb5_auth_context ac,
276                                    void *data,
277                                    size_t len)
278 {
279     krb5_error_code ret;
280     krb5_keyblock *key;
281     krb5_authenticator authenticator;
282     krb5_crypto crypto;
283
284     ret = krb5_auth_con_getauthenticator (context,
285                                       ac,
286                                       &authenticator);
287     if(ret)
288         return ret;
289     if(authenticator->cksum == NULL) {
290         krb5_free_authenticator(context, &authenticator);
291         return -17;
292     }
293     ret = krb5_auth_con_getkey(context, ac, &key);
294     if(ret) {
295         krb5_free_authenticator(context, &authenticator);
296         return ret;
297     }
298     ret = krb5_crypto_init(context, key, 0, &crypto);
299     if(ret)
300         goto out;
301     ret = krb5_verify_checksum (context,
302                                 crypto,
303                                 KRB5_KU_AP_REQ_AUTH_CKSUM,
304                                 data,
305                                 len,
306                                 authenticator->cksum);
307     krb5_crypto_destroy(context, crypto);
308 out:
309     krb5_free_authenticator(context, &authenticator);
310     krb5_free_keyblock(context, key);
311     return ret;
312 }
313
314
315 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
316 krb5_verify_ap_req(krb5_context context,
317                    krb5_auth_context *auth_context,
318                    krb5_ap_req *ap_req,
319                    krb5_const_principal server,
320                    krb5_keyblock *keyblock,
321                    krb5_flags flags,
322                    krb5_flags *ap_req_options,
323                    krb5_ticket **ticket)
324 {
325     return krb5_verify_ap_req2 (context,
326                                 auth_context,
327                                 ap_req,
328                                 server,
329                                 keyblock,
330                                 flags,
331                                 ap_req_options,
332                                 ticket,
333                                 KRB5_KU_AP_REQ_AUTH);
334 }
335
336 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
337 krb5_verify_ap_req2(krb5_context context,
338                     krb5_auth_context *auth_context,
339                     krb5_ap_req *ap_req,
340                     krb5_const_principal server,
341                     krb5_keyblock *keyblock,
342                     krb5_flags flags,
343                     krb5_flags *ap_req_options,
344                     krb5_ticket **ticket,
345                     krb5_key_usage usage)
346 {
347     krb5_ticket *t;
348     krb5_auth_context ac;
349     krb5_error_code ret;
350     EtypeList etypes;
351
352     if (ticket)
353         *ticket = NULL;
354
355     if (auth_context && *auth_context) {
356         ac = *auth_context;
357     } else {
358         ret = krb5_auth_con_init (context, &ac);
359         if (ret)
360             return ret;
361     }
362
363     t = calloc(1, sizeof(*t));
364     if (t == NULL) {
365         ret = ENOMEM;
366         krb5_clear_error_message (context);
367         goto out;
368     }
369
370     if (ap_req->ap_options.use_session_key && ac->keyblock){
371         ret = krb5_decrypt_ticket(context, &ap_req->ticket,
372                                   ac->keyblock,
373                                   &t->ticket,
374                                   flags);
375         krb5_free_keyblock(context, ac->keyblock);
376         ac->keyblock = NULL;
377     }else
378         ret = krb5_decrypt_ticket(context, &ap_req->ticket,
379                                   keyblock,
380                                   &t->ticket,
381                                   flags);
382
383     if(ret)
384         goto out;
385
386     ret = _krb5_principalname2krb5_principal(context,
387                                              &t->server,
388                                              ap_req->ticket.sname,
389                                              ap_req->ticket.realm);
390     if (ret) goto out;
391     ret = _krb5_principalname2krb5_principal(context,
392                                              &t->client,
393                                              t->ticket.cname,
394                                              t->ticket.crealm);
395     if (ret) goto out;
396
397     ret = decrypt_authenticator (context,
398                                  &t->ticket.key,
399                                  &ap_req->authenticator,
400                                  ac->authenticator,
401                                  usage);
402     if (ret)
403         goto out;
404
405     {
406         krb5_principal p1, p2;
407         krb5_boolean res;
408
409         _krb5_principalname2krb5_principal(context,
410                                            &p1,
411                                            ac->authenticator->cname,
412                                            ac->authenticator->crealm);
413         _krb5_principalname2krb5_principal(context,
414                                            &p2,
415                                            t->ticket.cname,
416                                            t->ticket.crealm);
417         res = krb5_principal_compare (context, p1, p2);
418         krb5_free_principal (context, p1);
419         krb5_free_principal (context, p2);
420         if (!res) {
421             ret = KRB5KRB_AP_ERR_BADMATCH;
422             krb5_clear_error_message (context);
423             goto out;
424         }
425     }
426
427     /* check addresses */
428
429     if (t->ticket.caddr
430         && ac->remote_address
431         && !krb5_address_search (context,
432                                  ac->remote_address,
433                                  t->ticket.caddr)) {
434         ret = KRB5KRB_AP_ERR_BADADDR;
435         krb5_clear_error_message (context);
436         goto out;
437     }
438
439     /* check timestamp in authenticator */
440     {
441         krb5_timestamp now;
442
443         krb5_timeofday (context, &now);
444
445         if (abs(ac->authenticator->ctime - now) > context->max_skew) {
446             ret = KRB5KRB_AP_ERR_SKEW;
447             krb5_clear_error_message (context);
448             goto out;
449         }
450     }
451
452     if (ac->authenticator->seq_number)
453         krb5_auth_con_setremoteseqnumber(context, ac,
454                                          *ac->authenticator->seq_number);
455
456     /* XXX - Xor sequence numbers */
457
458     if (ac->authenticator->subkey) {
459         ret = krb5_auth_con_setremotesubkey(context, ac,
460                                             ac->authenticator->subkey);
461         if (ret)
462             goto out;
463     }
464
465     ret = find_etypelist(context, ac, &etypes);
466     if (ret)
467         goto out;
468
469     ac->keytype = ETYPE_NULL;
470
471     if (etypes.val) {
472         size_t i;
473
474         for (i = 0; i < etypes.len; i++) {
475             if (krb5_enctype_valid(context, etypes.val[i]) == 0) {
476                 ac->keytype = etypes.val[i];
477                 break;
478             }
479         }
480     }
481
482     /* save key */
483     ret = krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock);
484     if (ret) goto out;
485
486     if (ap_req_options) {
487         *ap_req_options = 0;
488         if (ac->keytype != ETYPE_NULL)
489             *ap_req_options |= AP_OPTS_USE_SUBKEY;
490         if (ap_req->ap_options.use_session_key)
491             *ap_req_options |= AP_OPTS_USE_SESSION_KEY;
492         if (ap_req->ap_options.mutual_required)
493             *ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
494     }
495
496     if(ticket)
497         *ticket = t;
498     else
499         krb5_free_ticket (context, t);
500     if (auth_context) {
501         if (*auth_context == NULL)
502             *auth_context = ac;
503     } else
504         krb5_auth_con_free (context, ac);
505     free_EtypeList(&etypes);
506     return 0;
507  out:
508     if (t)
509         krb5_free_ticket (context, t);
510     if (auth_context == NULL || *auth_context == NULL)
511         krb5_auth_con_free (context, ac);
512     return ret;
513 }
514
515 /*
516  *
517  */
518
519 struct krb5_rd_req_in_ctx_data {
520     krb5_keytab keytab;
521     krb5_boolean iterate_keytab;
522     krb5_keyblock *keyblock;
523     krb5_boolean check_pac;
524     krb5_flags verify_ap_req_flags;
525 };
526
527 struct krb5_rd_req_out_ctx_data {
528     krb5_keyblock *keyblock;
529     krb5_flags ap_req_options;
530     krb5_ticket *ticket;
531     krb5_principal server;
532 };
533
534 /**
535  * Allocate a krb5_rd_req_in_ctx as an input parameter to
536  * krb5_rd_req_ctx(). The caller should free the context with
537  * krb5_rd_req_in_ctx_free() when done with the context.
538  *
539  * @param context Keberos 5 context.
540  * @param ctx in ctx to krb5_rd_req_ctx().
541  *
542  * @return Kerberos 5 error code, see krb5_get_error_message().
543  *
544  * @ingroup krb5_auth
545  */
546
547 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
548 krb5_rd_req_in_ctx_alloc(krb5_context context, krb5_rd_req_in_ctx *ctx)
549 {
550     *ctx = calloc(1, sizeof(**ctx));
551     if (*ctx == NULL) {
552         krb5_set_error_message(context, ENOMEM,
553                                N_("malloc: out of memory", ""));
554         return ENOMEM;
555     }
556     (*ctx)->check_pac = (context->flags & KRB5_CTX_F_CHECK_PAC) ? 1 : 0;
557     return 0;
558 }
559
560 /**
561  * Set the keytab that krb5_rd_req_ctx() will use.
562  *
563  * @param context Keberos 5 context.
564  * @param in in ctx to krb5_rd_req_ctx().
565  * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the
566  *        pointer, so the caller must free they keytab after
567  *        krb5_rd_req_in_ctx_free() is called.
568  *
569  * @return Kerberos 5 error code, see krb5_get_error_message().
570  *
571  * @ingroup krb5_auth
572  */
573
574 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
575 krb5_rd_req_in_set_keytab(krb5_context context,
576                           krb5_rd_req_in_ctx in,
577                           krb5_keytab keytab)
578 {
579     in->keytab = keytab;
580     return 0;
581 }
582
583 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
584 krb5_rd_req_in_set_verify_ap_req_flags(krb5_context context,
585                              krb5_rd_req_in_ctx in,
586                              krb5_flags flags)
587 {
588     in->verify_ap_req_flags = flags;
589     return 0;
590 }
591
592 /**
593  * Set if krb5_rq_red() is going to iterate the keytab to find a key
594  *
595  * @param context Keberos 5 context.
596  * @param in krb5_rd_req_in_ctx to check the option on.
597  * @param flag flag to select if the keytab should be iterated (TRUE) or not (FALSE).
598  *
599  * @return Kerberos 5 error code, see krb5_get_error_message().
600  *
601  * @ingroup krb5_auth
602  */
603
604 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
605 krb5_rd_req_in_set_iterate_keytab(krb5_context context,
606                                   krb5_rd_req_in_ctx in,
607                                   krb5_boolean flag)
608 {
609     in->iterate_keytab = flag;
610     return 0;
611 }
612
613 /**
614  * Set if krb5_rq_red() is going to check the Windows PAC or not
615  *
616  * @param context Keberos 5 context.
617  * @param in krb5_rd_req_in_ctx to check the option on.
618  * @param flag flag to select if to check the pac (TRUE) or not (FALSE).
619  *
620  * @return Kerberos 5 error code, see krb5_get_error_message().
621  *
622  * @ingroup krb5_auth
623  */
624
625 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
626 krb5_rd_req_in_set_pac_check(krb5_context context,
627                              krb5_rd_req_in_ctx in,
628                              krb5_boolean flag)
629 {
630     in->check_pac = flag;
631     return 0;
632 }
633
634
635 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
636 krb5_rd_req_in_set_keyblock(krb5_context context,
637                             krb5_rd_req_in_ctx in,
638                             krb5_keyblock *keyblock)
639 {
640     in->keyblock = keyblock; /* XXX should make copy */
641     return 0;
642 }
643
644 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
645 krb5_rd_req_out_get_ap_req_options(krb5_context context,
646                                    krb5_rd_req_out_ctx out,
647                                    krb5_flags *ap_req_options)
648 {
649     *ap_req_options = out->ap_req_options;
650     return 0;
651 }
652
653 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
654 krb5_rd_req_out_get_ticket(krb5_context context,
655                             krb5_rd_req_out_ctx out,
656                             krb5_ticket **ticket)
657 {
658     return krb5_copy_ticket(context, out->ticket, ticket);
659 }
660
661 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
662 krb5_rd_req_out_get_keyblock(krb5_context context,
663                             krb5_rd_req_out_ctx out,
664                             krb5_keyblock **keyblock)
665 {
666     return krb5_copy_keyblock(context, out->keyblock, keyblock);
667 }
668
669 /**
670  * Get the principal that was used in the request from the
671  * client. Might not match whats in the ticket if krb5_rd_req_ctx()
672  * searched in the keytab for a matching key.
673  *
674  * @param context a Kerberos 5 context.
675  * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx().
676  * @param principal return principal, free with krb5_free_principal().
677  *
678  * @ingroup krb5_auth
679  */
680
681 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
682 krb5_rd_req_out_get_server(krb5_context context,
683                             krb5_rd_req_out_ctx out,
684                             krb5_principal *principal)
685 {
686     return krb5_copy_principal(context, out->server, principal);
687 }
688
689 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
690 krb5_rd_req_in_ctx_free(krb5_context context, krb5_rd_req_in_ctx ctx)
691 {
692     free(ctx);
693 }
694
695 /**
696  * Free the krb5_rd_req_out_ctx.
697  *
698  * @param context Keberos 5 context.
699  * @param ctx krb5_rd_req_out_ctx context to free.
700  *
701  * @ingroup krb5_auth
702  */
703
704 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
705 krb5_rd_req_out_ctx_free(krb5_context context, krb5_rd_req_out_ctx ctx)
706 {
707     if (ctx->ticket)
708         krb5_free_ticket(context, ctx->ticket);
709     if (ctx->keyblock)
710         krb5_free_keyblock(context, ctx->keyblock);
711     if (ctx->server)
712         krb5_free_principal(context, ctx->server);
713     free(ctx);
714 }
715
716 /*
717  *
718  */
719
720 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
721 krb5_rd_req(krb5_context context,
722             krb5_auth_context *auth_context,
723             const krb5_data *inbuf,
724             krb5_const_principal server,
725             krb5_keytab keytab,
726             krb5_flags *ap_req_options,
727             krb5_ticket **ticket)
728 {
729     krb5_error_code ret;
730     krb5_rd_req_in_ctx in;
731     krb5_rd_req_out_ctx out;
732
733     ret = krb5_rd_req_in_ctx_alloc(context, &in);
734     if (ret)
735         return ret;
736
737     ret = krb5_rd_req_in_set_keytab(context, in, keytab);
738     if (ret) {
739         krb5_rd_req_in_ctx_free(context, in);
740         return ret;
741     }
742
743     ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
744     krb5_rd_req_in_ctx_free(context, in);
745     if (ret)
746         return ret;
747
748     if (ap_req_options)
749         *ap_req_options = out->ap_req_options;
750     if (ticket) {
751         ret = krb5_copy_ticket(context, out->ticket, ticket);
752         if (ret)
753             goto out;
754     }
755
756 out:
757     krb5_rd_req_out_ctx_free(context, out);
758     return ret;
759 }
760
761 /*
762  *
763  */
764
765 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
766 krb5_rd_req_with_keyblock(krb5_context context,
767                           krb5_auth_context *auth_context,
768                           const krb5_data *inbuf,
769                           krb5_const_principal server,
770                           krb5_keyblock *keyblock,
771                           krb5_flags *ap_req_options,
772                           krb5_ticket **ticket)
773 {
774     krb5_error_code ret;
775     krb5_rd_req_in_ctx in;
776     krb5_rd_req_out_ctx out;
777
778     ret = krb5_rd_req_in_ctx_alloc(context, &in);
779     if (ret)
780         return ret;
781
782     ret = krb5_rd_req_in_set_keyblock(context, in, keyblock);
783     if (ret) {
784         krb5_rd_req_in_ctx_free(context, in);
785         return ret;
786     }
787
788     ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
789     krb5_rd_req_in_ctx_free(context, in);
790     if (ret)
791         return ret;
792
793     if (ap_req_options)
794         *ap_req_options = out->ap_req_options;
795     if (ticket) {
796         ret = krb5_copy_ticket(context, out->ticket, ticket);
797         if (ret)
798             goto out;
799     }
800
801 out:
802     krb5_rd_req_out_ctx_free(context, out);
803     return ret;
804 }
805
806 /*
807  *
808  */
809
810 static krb5_error_code
811 get_key_from_keytab(krb5_context context,
812                     krb5_ap_req *ap_req,
813                     krb5_const_principal server,
814                     krb5_keytab keytab,
815                     krb5_keyblock **out_key)
816 {
817     krb5_keytab_entry entry;
818     krb5_error_code ret;
819     int kvno;
820     krb5_keytab real_keytab;
821
822     if(keytab == NULL)
823         krb5_kt_default(context, &real_keytab);
824     else
825         real_keytab = keytab;
826
827     if (ap_req->ticket.enc_part.kvno)
828         kvno = *ap_req->ticket.enc_part.kvno;
829     else
830         kvno = 0;
831
832     ret = krb5_kt_get_entry (context,
833                              real_keytab,
834                              server,
835                              kvno,
836                              ap_req->ticket.enc_part.etype,
837                              &entry);
838     if(ret)
839         goto out;
840     ret = krb5_copy_keyblock(context, &entry.keyblock, out_key);
841     krb5_kt_free_entry (context, &entry);
842 out:
843     if(keytab == NULL)
844         krb5_kt_close(context, real_keytab);
845
846     return ret;
847 }
848
849 /**
850  * The core server function that verify application authentication
851  * requests from clients.
852  *
853  * @param context Keberos 5 context.
854  * @param auth_context the authentication context, can be NULL, then
855  *        default values for the authentication context will used.
856  * @param inbuf the (AP-REQ) authentication buffer
857  *
858  * @param server the server with authenticate as, if NULL the function
859  *        will try to find any available credential in the keytab
860  *        that will verify the reply. The function will prefer the
861  *        server the server client specified in the AP-REQ, but if
862  *        there is no mach, it will try all keytab entries for a
863  *        match. This have serious performance issues for larger keytabs.
864  *
865  * @param inctx control the behavior of the function, if NULL, the
866  *        default behavior is used.
867  * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free().
868  * @return Kerberos 5 error code, see krb5_get_error_message().
869  *
870  * @ingroup krb5_auth
871  */
872
873 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
874 krb5_rd_req_ctx(krb5_context context,
875                 krb5_auth_context *auth_context,
876                 const krb5_data *inbuf,
877                 krb5_const_principal server,
878                 krb5_rd_req_in_ctx inctx,
879                 krb5_rd_req_out_ctx *outctx)
880 {
881     krb5_error_code ret;
882     krb5_ap_req ap_req;
883     krb5_rd_req_out_ctx o = NULL;
884     krb5_keytab id = NULL, keytab = NULL;
885     krb5_principal service = NULL;
886     krb5_flags verify_ap_req_flags = 0;
887
888     *outctx = NULL;
889
890     o = calloc(1, sizeof(*o));
891     if (o == NULL) {
892         krb5_set_error_message(context, ENOMEM,
893                                N_("malloc: out of memory", ""));
894         return ENOMEM;
895     }
896
897     if (*auth_context == NULL) {
898         ret = krb5_auth_con_init(context, auth_context);
899         if (ret)
900             goto out;
901     }
902
903     ret = krb5_decode_ap_req(context, inbuf, &ap_req);
904     if(ret)
905         goto out;
906
907     /* Save that principal that was in the request */
908     ret = _krb5_principalname2krb5_principal(context,
909                                              &o->server,
910                                              ap_req.ticket.sname,
911                                              ap_req.ticket.realm);
912     if (ret)
913         goto out;
914
915     if (ap_req.ap_options.use_session_key &&
916         (*auth_context)->keyblock == NULL) {
917         ret = KRB5KRB_AP_ERR_NOKEY;
918         krb5_set_error_message(context, ret,
919                                N_("krb5_rd_req: user to user auth "
920                                   "without session key given", ""));
921         goto out;
922     }
923
924     if (inctx && inctx->keytab)
925         id = inctx->keytab;
926
927     if (inctx)
928         verify_ap_req_flags = inctx->verify_ap_req_flags;
929
930     if((*auth_context)->keyblock){
931         ret = krb5_copy_keyblock(context,
932                                  (*auth_context)->keyblock,
933                                  &o->keyblock);
934         if (ret)
935             goto out;
936     } else if(inctx && inctx->keyblock){
937         ret = krb5_copy_keyblock(context,
938                                  inctx->keyblock,
939                                  &o->keyblock);
940         if (ret)
941             goto out;
942     } else if (id && inctx && inctx->iterate_keytab) {
943             /*
944              * Force iterating over the keytab.
945              */
946             o->keyblock = NULL;
947     } else {
948
949         if(id == NULL) {
950             krb5_kt_default(context, &keytab);
951             id = keytab;
952         }
953         if (id == NULL)
954             goto out;
955
956         if (server == NULL) {
957             ret = _krb5_principalname2krb5_principal(context,
958                                                      &service,
959                                                      ap_req.ticket.sname,
960                                                      ap_req.ticket.realm);
961             if (ret)
962                 goto out;
963             server = service;
964         }
965
966         ret = get_key_from_keytab(context,
967                                   &ap_req,
968                                   server,
969                                   id,
970                                   &o->keyblock);
971         if (ret) {
972             /* If caller specified a server, fail. */
973             if (service == NULL && (context->flags & KRB5_CTX_F_RD_REQ_IGNORE) == 0)
974                 goto out;
975             /* Otherwise, fall back to iterating over the keytab. This
976              * have serious performace issues for larger keytab.
977              */
978             o->keyblock = NULL;
979         }
980     }
981
982     if (o->keyblock) {
983         /*
984          * We got an exact keymatch, use that.
985          */
986
987         ret = krb5_verify_ap_req2(context,
988                                   auth_context,
989                                   &ap_req,
990                                   server,
991                                   o->keyblock,
992                                   verify_ap_req_flags,
993                                   &o->ap_req_options,
994                                   &o->ticket,
995                                   KRB5_KU_AP_REQ_AUTH);
996
997         if (ret)
998             goto out;
999
1000     } else {
1001         /*
1002          * Interate over keytab to find a key that can decrypt the request.
1003          */
1004
1005         krb5_keytab_entry entry;
1006         krb5_kt_cursor cursor;
1007         int done = 0, kvno = 0;
1008
1009         memset(&cursor, 0, sizeof(cursor));
1010
1011         if (ap_req.ticket.enc_part.kvno)
1012             kvno = *ap_req.ticket.enc_part.kvno;
1013
1014         ret = krb5_kt_start_seq_get(context, id, &cursor);
1015         if (ret)
1016             goto out;
1017
1018         done = 0;
1019         while (!done) {
1020             krb5_principal p;
1021
1022             ret = krb5_kt_next_entry(context, id, &entry, &cursor);
1023             if (ret) {
1024                 _krb5_kt_principal_not_found(context, ret, id, o->server,
1025                                              ap_req.ticket.enc_part.etype,
1026                                              kvno);
1027                 goto out;
1028             }
1029
1030             if (entry.keyblock.keytype != ap_req.ticket.enc_part.etype) {
1031                 krb5_kt_free_entry (context, &entry);
1032                 continue;
1033             }
1034
1035             ret = krb5_verify_ap_req2(context,
1036                                       auth_context,
1037                                       &ap_req,
1038                                       server,
1039                                       &entry.keyblock,
1040                                       verify_ap_req_flags,
1041                                       &o->ap_req_options,
1042                                       &o->ticket,
1043                                       KRB5_KU_AP_REQ_AUTH);
1044             if (ret == KRB5KRB_AP_ERR_BAD_INTEGRITY) {
1045                 /* failed to decrypt, try the next key */
1046                 krb5_kt_free_entry (context, &entry);
1047                 continue;
1048             }
1049             if (ret) {
1050                 krb5_kt_free_entry (context, &entry);
1051                 goto out;
1052             }
1053
1054             /*
1055              * Found a match, save the keyblock for PAC processing,
1056              * and update the service principal in the ticket to match
1057              * whatever is in the keytab.
1058              */
1059
1060             ret = krb5_copy_keyblock(context,
1061                                      &entry.keyblock,
1062                                      &o->keyblock);
1063             if (ret) {
1064                 krb5_kt_free_entry (context, &entry);
1065                 goto out;
1066             }
1067
1068             ret = krb5_copy_principal(context, entry.principal, &p);
1069             if (ret) {
1070                 krb5_kt_free_entry (context, &entry);
1071                 goto out;
1072             }
1073             krb5_free_principal(context, o->ticket->server);
1074             o->ticket->server = p;
1075
1076             krb5_kt_free_entry (context, &entry);
1077
1078             done = 1;
1079         }
1080         krb5_kt_end_seq_get (context, id, &cursor);
1081     }
1082
1083     /* If there is a PAC, verify its server signature */
1084     if (inctx == NULL || inctx->check_pac) {
1085         krb5_pac pac;
1086         krb5_data data;
1087
1088         ret = krb5_ticket_get_authorization_data_type(context,
1089                                                       o->ticket,
1090                                                       KRB5_AUTHDATA_WIN2K_PAC,
1091                                                       &data);
1092         if (ret == 0) {
1093             ret = krb5_pac_parse(context, data.data, data.length, &pac);
1094             krb5_data_free(&data);
1095             if (ret)
1096                 goto out;
1097
1098             ret = krb5_pac_verify(context,
1099                                   pac,
1100                                   o->ticket->ticket.authtime,
1101                                   o->ticket->client,
1102                                   o->keyblock,
1103                                   NULL);
1104             krb5_pac_free(context, pac);
1105             if (ret)
1106                 goto out;
1107         } else
1108           ret = 0;
1109     }
1110 out:
1111
1112     if (ret || outctx == NULL) {
1113         krb5_rd_req_out_ctx_free(context, o);
1114     } else
1115         *outctx = o;
1116
1117     free_AP_REQ(&ap_req);
1118
1119     if (service)
1120         krb5_free_principal(context, service);
1121
1122     if (keytab)
1123         krb5_kt_close(context, keytab);
1124
1125     return ret;
1126 }