9f6a85b1a2229d387c6bc007be25fc7fdd6ae759
[amitay/samba.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;
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     free(realms);
165     return ret;
166 }
167
168 static krb5_error_code
169 find_etypelist(krb5_context context,
170                krb5_auth_context auth_context,
171                EtypeList *etypes)
172 {
173     krb5_error_code ret;
174     krb5_authdata *ad;
175     krb5_authdata adIfRelevant;
176     unsigned i;
177
178     adIfRelevant.len = 0;
179
180     etypes->len = 0;
181     etypes->val = NULL;
182
183     ad = auth_context->authenticator->authorization_data;
184     if (ad == NULL)
185         return 0;
186
187     for (i = 0; i < ad->len; i++) {
188         if (ad->val[i].ad_type == KRB5_AUTHDATA_IF_RELEVANT) {
189             ret = decode_AD_IF_RELEVANT(ad->val[i].ad_data.data,
190                                         ad->val[i].ad_data.length,
191                                         &adIfRelevant,
192                                         NULL);
193             if (ret)
194                 return ret;
195
196             if (adIfRelevant.len == 1 &&
197                 adIfRelevant.val[0].ad_type ==
198                         KRB5_AUTHDATA_GSS_API_ETYPE_NEGOTIATION) {
199                 break;
200             }
201             free_AD_IF_RELEVANT(&adIfRelevant);
202             adIfRelevant.len = 0;
203         }
204     }
205
206     if (adIfRelevant.len == 0)
207         return 0;
208
209     ret = decode_EtypeList(adIfRelevant.val[0].ad_data.data,
210                            adIfRelevant.val[0].ad_data.length,
211                            etypes,
212                            NULL);
213     if (ret)
214         krb5_clear_error_message(context);
215
216     free_AD_IF_RELEVANT(&adIfRelevant);
217
218     return ret;
219 }
220
221 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
222 krb5_decrypt_ticket(krb5_context context,
223                     Ticket *ticket,
224                     krb5_keyblock *key,
225                     EncTicketPart *out,
226                     krb5_flags flags)
227 {
228     EncTicketPart t;
229     krb5_error_code ret;
230     ret = decrypt_tkt_enc_part (context, key, &ticket->enc_part, &t);
231     if (ret)
232         return ret;
233
234     {
235         krb5_timestamp now;
236         time_t start = t.authtime;
237
238         krb5_timeofday (context, &now);
239         if(t.starttime)
240             start = *t.starttime;
241         if(start - now > context->max_skew
242            || (t.flags.invalid
243                && !(flags & KRB5_VERIFY_AP_REQ_IGNORE_INVALID))) {
244             free_EncTicketPart(&t);
245             krb5_clear_error_message (context);
246             return KRB5KRB_AP_ERR_TKT_NYV;
247         }
248         if(now - t.endtime > context->max_skew) {
249             free_EncTicketPart(&t);
250             krb5_clear_error_message (context);
251             return KRB5KRB_AP_ERR_TKT_EXPIRED;
252         }
253         
254         if(!t.flags.transited_policy_checked) {
255             ret = check_transited(context, ticket, &t);
256             if(ret) {
257                 free_EncTicketPart(&t);
258                 return ret;
259             }
260         }
261     }
262
263     if(out)
264         *out = t;
265     else
266         free_EncTicketPart(&t);
267     return 0;
268 }
269
270 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
271 krb5_verify_authenticator_checksum(krb5_context context,
272                                    krb5_auth_context ac,
273                                    void *data,
274                                    size_t len)
275 {
276     krb5_error_code ret;
277     krb5_keyblock *key;
278     krb5_authenticator authenticator;
279     krb5_crypto crypto;
280
281     ret = krb5_auth_con_getauthenticator (context,
282                                       ac,
283                                       &authenticator);
284     if(ret)
285         return ret;
286     if(authenticator->cksum == NULL) {
287         krb5_free_authenticator(context, &authenticator);
288         return -17;
289     }
290     ret = krb5_auth_con_getkey(context, ac, &key);
291     if(ret) {
292         krb5_free_authenticator(context, &authenticator);
293         return ret;
294     }
295     ret = krb5_crypto_init(context, key, 0, &crypto);
296     if(ret)
297         goto out;
298     ret = krb5_verify_checksum (context,
299                                 crypto,
300                                 KRB5_KU_AP_REQ_AUTH_CKSUM,
301                                 data,
302                                 len,
303                                 authenticator->cksum);
304     krb5_crypto_destroy(context, crypto);
305 out:
306     krb5_free_authenticator(context, &authenticator);
307     krb5_free_keyblock(context, key);
308     return ret;
309 }
310
311
312 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
313 krb5_verify_ap_req(krb5_context context,
314                    krb5_auth_context *auth_context,
315                    krb5_ap_req *ap_req,
316                    krb5_const_principal server,
317                    krb5_keyblock *keyblock,
318                    krb5_flags flags,
319                    krb5_flags *ap_req_options,
320                    krb5_ticket **ticket)
321 {
322     return krb5_verify_ap_req2 (context,
323                                 auth_context,
324                                 ap_req,
325                                 server,
326                                 keyblock,
327                                 flags,
328                                 ap_req_options,
329                                 ticket,
330                                 KRB5_KU_AP_REQ_AUTH);
331 }
332
333 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
334 krb5_verify_ap_req2(krb5_context context,
335                     krb5_auth_context *auth_context,
336                     krb5_ap_req *ap_req,
337                     krb5_const_principal server,
338                     krb5_keyblock *keyblock,
339                     krb5_flags flags,
340                     krb5_flags *ap_req_options,
341                     krb5_ticket **ticket,
342                     krb5_key_usage usage)
343 {
344     krb5_ticket *t;
345     krb5_auth_context ac;
346     krb5_error_code ret;
347     EtypeList etypes;
348
349     if (ticket)
350         *ticket = NULL;
351
352     if (auth_context && *auth_context) {
353         ac = *auth_context;
354     } else {
355         ret = krb5_auth_con_init (context, &ac);
356         if (ret)
357             return ret;
358     }
359
360     t = calloc(1, sizeof(*t));
361     if (t == NULL) {
362         ret = ENOMEM;
363         krb5_clear_error_message (context);
364         goto out;
365     }
366
367     if (ap_req->ap_options.use_session_key && ac->keyblock){
368         ret = krb5_decrypt_ticket(context, &ap_req->ticket,
369                                   ac->keyblock,
370                                   &t->ticket,
371                                   flags);
372         krb5_free_keyblock(context, ac->keyblock);
373         ac->keyblock = NULL;
374     }else
375         ret = krb5_decrypt_ticket(context, &ap_req->ticket,
376                                   keyblock,
377                                   &t->ticket,
378                                   flags);
379
380     if(ret)
381         goto out;
382
383     ret = _krb5_principalname2krb5_principal(context,
384                                              &t->server,
385                                              ap_req->ticket.sname,
386                                              ap_req->ticket.realm);
387     if (ret) goto out;
388     ret = _krb5_principalname2krb5_principal(context,
389                                              &t->client,
390                                              t->ticket.cname,
391                                              t->ticket.crealm);
392     if (ret) goto out;
393
394     ret = decrypt_authenticator (context,
395                                  &t->ticket.key,
396                                  &ap_req->authenticator,
397                                  ac->authenticator,
398                                  usage);
399     if (ret)
400         goto out;
401
402     {
403         krb5_principal p1, p2;
404         krb5_boolean res;
405         
406         _krb5_principalname2krb5_principal(context,
407                                            &p1,
408                                            ac->authenticator->cname,
409                                            ac->authenticator->crealm);
410         _krb5_principalname2krb5_principal(context,
411                                            &p2,
412                                            t->ticket.cname,
413                                            t->ticket.crealm);
414         res = krb5_principal_compare (context, p1, p2);
415         krb5_free_principal (context, p1);
416         krb5_free_principal (context, p2);
417         if (!res) {
418             ret = KRB5KRB_AP_ERR_BADMATCH;
419             krb5_clear_error_message (context);
420             goto out;
421         }
422     }
423
424     /* check addresses */
425
426     if (t->ticket.caddr
427         && ac->remote_address
428         && !krb5_address_search (context,
429                                  ac->remote_address,
430                                  t->ticket.caddr)) {
431         ret = KRB5KRB_AP_ERR_BADADDR;
432         krb5_clear_error_message (context);
433         goto out;
434     }
435
436     /* check timestamp in authenticator */
437     {
438         krb5_timestamp now;
439
440         krb5_timeofday (context, &now);
441
442         if (abs(ac->authenticator->ctime - now) > context->max_skew) {
443             ret = KRB5KRB_AP_ERR_SKEW;
444             krb5_clear_error_message (context);
445             goto out;
446         }
447     }
448
449     if (ac->authenticator->seq_number)
450         krb5_auth_con_setremoteseqnumber(context, ac,
451                                          *ac->authenticator->seq_number);
452
453     /* XXX - Xor sequence numbers */
454
455     if (ac->authenticator->subkey) {
456         ret = krb5_auth_con_setremotesubkey(context, ac,
457                                             ac->authenticator->subkey);
458         if (ret)
459             goto out;
460     }
461
462     ret = find_etypelist(context, ac, &etypes);
463     if (ret)
464         goto out;
465
466     ac->keytype = ETYPE_NULL;
467
468     if (etypes.val) {
469         int i;
470
471         for (i = 0; i < etypes.len; i++) {
472             if (krb5_enctype_valid(context, etypes.val[i]) == 0) {
473                 ac->keytype = etypes.val[i];
474                 break;
475             }
476         }
477     }
478
479     /* save key */
480     ret = krb5_copy_keyblock(context, &t->ticket.key, &ac->keyblock);
481     if (ret) goto out;
482
483     if (ap_req_options) {
484         *ap_req_options = 0;
485         if (ac->keytype != ETYPE_NULL)
486             *ap_req_options |= AP_OPTS_USE_SUBKEY;
487         if (ap_req->ap_options.use_session_key)
488             *ap_req_options |= AP_OPTS_USE_SESSION_KEY;
489         if (ap_req->ap_options.mutual_required)
490             *ap_req_options |= AP_OPTS_MUTUAL_REQUIRED;
491     }
492
493     if(ticket)
494         *ticket = t;
495     else
496         krb5_free_ticket (context, t);
497     if (auth_context) {
498         if (*auth_context == NULL)
499             *auth_context = ac;
500     } else
501         krb5_auth_con_free (context, ac);
502     free_EtypeList(&etypes);
503     return 0;
504  out:
505     if (t)
506         krb5_free_ticket (context, t);
507     if (auth_context == NULL || *auth_context == NULL)
508         krb5_auth_con_free (context, ac);
509     return ret;
510 }
511                 
512 /*
513  *
514  */
515
516 struct krb5_rd_req_in_ctx_data {
517     krb5_keytab keytab;
518     krb5_keyblock *keyblock;
519     krb5_boolean check_pac;
520 };
521
522 struct krb5_rd_req_out_ctx_data {
523     krb5_keyblock *keyblock;
524     krb5_flags ap_req_options;
525     krb5_ticket *ticket;
526     krb5_principal server;
527 };
528
529 /**
530  * Allocate a krb5_rd_req_in_ctx as an input parameter to
531  * krb5_rd_req_ctx(). The caller should free the context with
532  * krb5_rd_req_in_ctx_free() when done with the context.
533  *
534  * @param context Keberos 5 context.
535  * @param ctx in ctx to krb5_rd_req_ctx().
536  *
537  * @return Kerberos 5 error code, see krb5_get_error_message().
538  *
539  * @ingroup krb5_auth
540  */
541
542 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
543 krb5_rd_req_in_ctx_alloc(krb5_context context, krb5_rd_req_in_ctx *ctx)
544 {
545     *ctx = calloc(1, sizeof(**ctx));
546     if (*ctx == NULL) {
547         krb5_set_error_message(context, ENOMEM,
548                                N_("malloc: out of memory", ""));
549         return ENOMEM;
550     }
551     (*ctx)->check_pac = (context->flags & KRB5_CTX_F_CHECK_PAC) ? 1 : 0;
552     return 0;
553 }
554
555 /**
556  * Set the keytab that krb5_rd_req_ctx() will use.
557  *
558  * @param context Keberos 5 context.
559  * @param in in ctx to krb5_rd_req_ctx().
560  * @param keytab keytab that krb5_rd_req_ctx() will use, only copy the
561  *        pointer, so the caller must free they keytab after
562  *        krb5_rd_req_in_ctx_free() is called.
563  *
564  * @return Kerberos 5 error code, see krb5_get_error_message().
565  *
566  * @ingroup krb5_auth
567  */
568
569 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
570 krb5_rd_req_in_set_keytab(krb5_context context,
571                           krb5_rd_req_in_ctx in,
572                           krb5_keytab keytab)
573 {
574     in->keytab = keytab;
575     return 0;
576 }
577
578 /**
579  * Set if krb5_rq_red() is going to check the Windows PAC or not
580  *
581  * @param context Keberos 5 context.
582  * @param in krb5_rd_req_in_ctx to check the option on.
583  * @param flag flag to select if to check the pac (TRUE) or not (FALSE).
584  *
585  * @return Kerberos 5 error code, see krb5_get_error_message().
586  *
587  * @ingroup krb5_auth
588  */
589
590 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
591 krb5_rd_req_in_set_pac_check(krb5_context context,
592                              krb5_rd_req_in_ctx in,
593                              krb5_boolean flag)
594 {
595     in->check_pac = flag;
596     return 0;
597 }
598
599
600 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
601 krb5_rd_req_in_set_keyblock(krb5_context context,
602                             krb5_rd_req_in_ctx in,
603                             krb5_keyblock *keyblock)
604 {
605     in->keyblock = keyblock; /* XXX should make copy */
606     return 0;
607 }
608
609 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
610 krb5_rd_req_out_get_ap_req_options(krb5_context context,
611                                    krb5_rd_req_out_ctx out,
612                                    krb5_flags *ap_req_options)
613 {
614     *ap_req_options = out->ap_req_options;
615     return 0;
616 }
617
618 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
619 krb5_rd_req_out_get_ticket(krb5_context context,
620                             krb5_rd_req_out_ctx out,
621                             krb5_ticket **ticket)
622 {
623     return krb5_copy_ticket(context, out->ticket, ticket);
624 }
625
626 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
627 krb5_rd_req_out_get_keyblock(krb5_context context,
628                             krb5_rd_req_out_ctx out,
629                             krb5_keyblock **keyblock)
630 {
631     return krb5_copy_keyblock(context, out->keyblock, keyblock);
632 }
633
634 /**
635  * Get the principal that was used in the request from the
636  * client. Might not match whats in the ticket if krb5_rd_req_ctx()
637  * searched in the keytab for a matching key.
638  *
639  * @param context a Kerberos 5 context.
640  * @param out a krb5_rd_req_out_ctx from krb5_rd_req_ctx().
641  * @param principal return principal, free with krb5_free_principal().
642  *
643  * @ingroup krb5_auth
644  */
645
646 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
647 krb5_rd_req_out_get_server(krb5_context context,
648                             krb5_rd_req_out_ctx out,
649                             krb5_principal *principal)
650 {
651     return krb5_copy_principal(context, out->server, principal);
652 }
653
654 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
655 krb5_rd_req_in_ctx_free(krb5_context context, krb5_rd_req_in_ctx ctx)
656 {
657     free(ctx);
658 }
659
660 /**
661  * Free the krb5_rd_req_out_ctx.
662  *
663  * @param context Keberos 5 context.
664  * @param ctx krb5_rd_req_out_ctx context to free.
665  *
666  * @ingroup krb5_auth
667  */
668
669 KRB5_LIB_FUNCTION void KRB5_LIB_CALL
670 krb5_rd_req_out_ctx_free(krb5_context context, krb5_rd_req_out_ctx ctx)
671 {
672     if (ctx->ticket)
673         krb5_free_ticket(context, ctx->ticket);
674     if (ctx->keyblock)
675         krb5_free_keyblock(context, ctx->keyblock);
676     if (ctx->server)
677         krb5_free_principal(context, ctx->server);
678     free(ctx);
679 }
680
681 /*
682  *
683  */
684
685 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
686 krb5_rd_req(krb5_context context,
687             krb5_auth_context *auth_context,
688             const krb5_data *inbuf,
689             krb5_const_principal server,
690             krb5_keytab keytab,
691             krb5_flags *ap_req_options,
692             krb5_ticket **ticket)
693 {
694     krb5_error_code ret;
695     krb5_rd_req_in_ctx in;
696     krb5_rd_req_out_ctx out;
697
698     ret = krb5_rd_req_in_ctx_alloc(context, &in);
699     if (ret)
700         return ret;
701
702     ret = krb5_rd_req_in_set_keytab(context, in, keytab);
703     if (ret) {
704         krb5_rd_req_in_ctx_free(context, in);
705         return ret;
706     }
707
708     ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
709     krb5_rd_req_in_ctx_free(context, in);
710     if (ret)
711         return ret;
712
713     if (ap_req_options)
714         *ap_req_options = out->ap_req_options;
715     if (ticket) {
716         ret = krb5_copy_ticket(context, out->ticket, ticket);
717         if (ret)
718             goto out;
719     }
720
721 out:
722     krb5_rd_req_out_ctx_free(context, out);
723     return ret;
724 }
725
726 /*
727  *
728  */
729
730 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
731 krb5_rd_req_with_keyblock(krb5_context context,
732                           krb5_auth_context *auth_context,
733                           const krb5_data *inbuf,
734                           krb5_const_principal server,
735                           krb5_keyblock *keyblock,
736                           krb5_flags *ap_req_options,
737                           krb5_ticket **ticket)
738 {
739     krb5_error_code ret;
740     krb5_rd_req_in_ctx in;
741     krb5_rd_req_out_ctx out;
742
743     ret = krb5_rd_req_in_ctx_alloc(context, &in);
744     if (ret)
745         return ret;
746
747     ret = krb5_rd_req_in_set_keyblock(context, in, keyblock);
748     if (ret) {
749         krb5_rd_req_in_ctx_free(context, in);
750         return ret;
751     }
752
753     ret = krb5_rd_req_ctx(context, auth_context, inbuf, server, in, &out);
754     krb5_rd_req_in_ctx_free(context, in);
755     if (ret)
756         return ret;
757
758     if (ap_req_options)
759         *ap_req_options = out->ap_req_options;
760     if (ticket) {
761         ret = krb5_copy_ticket(context, out->ticket, ticket);
762         if (ret)
763             goto out;
764     }
765
766 out:
767     krb5_rd_req_out_ctx_free(context, out);
768     return ret;
769 }
770
771 /*
772  *
773  */
774
775 static krb5_error_code
776 get_key_from_keytab(krb5_context context,
777                     krb5_ap_req *ap_req,
778                     krb5_const_principal server,
779                     krb5_keytab keytab,
780                     krb5_keyblock **out_key)
781 {
782     krb5_keytab_entry entry;
783     krb5_error_code ret;
784     int kvno;
785     krb5_keytab real_keytab;
786
787     if(keytab == NULL)
788         krb5_kt_default(context, &real_keytab);
789     else
790         real_keytab = keytab;
791
792     if (ap_req->ticket.enc_part.kvno)
793         kvno = *ap_req->ticket.enc_part.kvno;
794     else
795         kvno = 0;
796
797     ret = krb5_kt_get_entry (context,
798                              real_keytab,
799                              server,
800                              kvno,
801                              ap_req->ticket.enc_part.etype,
802                              &entry);
803     if(ret)
804         goto out;
805     ret = krb5_copy_keyblock(context, &entry.keyblock, out_key);
806     krb5_kt_free_entry (context, &entry);
807 out:
808     if(keytab == NULL)
809         krb5_kt_close(context, real_keytab);
810
811     return ret;
812 }
813
814 /**
815  * The core server function that verify application authentication
816  * requests from clients.
817  *
818  * @param context Keberos 5 context.
819  * @param auth_context the authentication context, can be NULL, then
820  *        default values for the authentication context will used.
821  * @param inbuf the (AP-REQ) authentication buffer
822  *
823  * @param server the server with authenticate as, if NULL the function
824  *        will try to find any avaiable credentintial in the keytab
825  *        that will verify the reply. The function will prefer the
826  *        server the server client specified in the AP-REQ, but if
827  *        there is no mach, it will try all keytab entries for a
828  *        match. This have serious performance issues for larger keytabs.
829  *
830  * @param inctx control the behavior of the function, if NULL, the
831  *        default behavior is used.
832  * @param outctx the return outctx, free with krb5_rd_req_out_ctx_free().
833  * @return Kerberos 5 error code, see krb5_get_error_message().
834  *
835  * @ingroup krb5_auth
836  */
837
838 KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL
839 krb5_rd_req_ctx(krb5_context context,
840                 krb5_auth_context *auth_context,
841                 const krb5_data *inbuf,
842                 krb5_const_principal server,
843                 krb5_rd_req_in_ctx inctx,
844                 krb5_rd_req_out_ctx *outctx)
845 {
846     krb5_error_code ret;
847     krb5_ap_req ap_req;
848     krb5_rd_req_out_ctx o = NULL;
849     krb5_keytab id = NULL, keytab = NULL;
850     krb5_principal service = NULL;
851
852     *outctx = NULL;
853
854     o = calloc(1, sizeof(*o));
855     if (o == NULL) {
856         krb5_set_error_message(context, ENOMEM,
857                                N_("malloc: out of memory", ""));
858         return ENOMEM;
859     }
860
861     if (*auth_context == NULL) {
862         ret = krb5_auth_con_init(context, auth_context);
863         if (ret)
864             goto out;
865     }
866
867     ret = krb5_decode_ap_req(context, inbuf, &ap_req);
868     if(ret)
869         goto out;
870
871     /* Save that principal that was in the request */
872     ret = _krb5_principalname2krb5_principal(context,
873                                              &o->server,
874                                              ap_req.ticket.sname,
875                                              ap_req.ticket.realm);
876     if (ret)
877         goto out;
878
879     if (ap_req.ap_options.use_session_key &&
880         (*auth_context)->keyblock == NULL) {
881         ret = KRB5KRB_AP_ERR_NOKEY;
882         krb5_set_error_message(context, ret,
883                                N_("krb5_rd_req: user to user auth "
884                                   "without session key given", ""));
885         goto out;
886     }
887
888     if (inctx && inctx->keytab)
889         id = inctx->keytab;
890
891     if((*auth_context)->keyblock){
892         ret = krb5_copy_keyblock(context,
893                                  (*auth_context)->keyblock,
894                                  &o->keyblock);
895         if (ret)
896             goto out;
897     } else if(inctx && inctx->keyblock){
898         ret = krb5_copy_keyblock(context,
899                                  inctx->keyblock,
900                                  &o->keyblock);
901         if (ret)
902             goto out;
903     } else {
904
905         if(id == NULL) {
906             krb5_kt_default(context, &keytab);
907             id = keytab;
908         }
909         if (id == NULL)
910             goto out;
911
912         if (server == NULL) {
913             ret = _krb5_principalname2krb5_principal(context,
914                                                      &service,
915                                                      ap_req.ticket.sname,
916                                                      ap_req.ticket.realm);
917             if (ret)
918                 goto out;
919             server = service;
920         }
921
922         ret = get_key_from_keytab(context,
923                                   &ap_req,
924                                   server,
925                                   id,
926                                   &o->keyblock);
927         if (ret) {
928             /* If caller specified a server, fail. */
929             if (service == NULL)
930                 goto out;
931             /* Otherwise, fall back to iterating over the keytab. This
932              * have serious performace issues for larger keytab.
933              */
934             o->keyblock = NULL;
935         }
936     }
937
938     if (o->keyblock) {
939         /*
940          * We got an exact keymatch, use that.
941          */
942
943         ret = krb5_verify_ap_req2(context,
944                                   auth_context,
945                                   &ap_req,
946                                   server,
947                                   o->keyblock,
948                                   0,
949                                   &o->ap_req_options,
950                                   &o->ticket,
951                                   KRB5_KU_AP_REQ_AUTH);
952         
953         if (ret)
954             goto out;
955
956     } else {
957         /*
958          * Interate over keytab to find a key that can decrypt the request.
959          */
960
961         krb5_keytab_entry entry;
962         krb5_kt_cursor cursor;
963         int done = 0, kvno = 0;
964
965         memset(&cursor, 0, sizeof(cursor));
966
967         if (ap_req.ticket.enc_part.kvno)
968             kvno = *ap_req.ticket.enc_part.kvno;
969
970         ret = krb5_kt_start_seq_get(context, id, &cursor);
971         if (ret)
972             goto out;
973
974         done = 0;
975         while (!done) { 
976             krb5_principal p;
977
978             ret = krb5_kt_next_entry(context, id, &entry, &cursor);
979             if (ret) {
980                 _krb5_kt_principal_not_found(context, ret, id, o->server,
981                                              ap_req.ticket.enc_part.etype,
982                                              kvno);
983                 goto out;
984             }
985
986             if (entry.keyblock.keytype != ap_req.ticket.enc_part.etype ||
987                 (kvno && kvno != entry.vno)) {
988                 krb5_kt_free_entry (context, &entry);
989                 continue;
990             }
991
992             ret = krb5_verify_ap_req2(context,
993                                       auth_context,
994                                       &ap_req,
995                                       server,
996                                       &entry.keyblock,
997                                       0,
998                                       &o->ap_req_options,
999                                       &o->ticket,
1000                                       KRB5_KU_AP_REQ_AUTH);
1001             if (ret) {
1002                 krb5_kt_free_entry (context, &entry);
1003                 continue;
1004             }
1005
1006             /*
1007              * Found a match, save the keyblock for PAC processing,
1008              * and update the service principal in the ticket to match
1009              * whatever is in the keytab.
1010              */
1011             
1012             ret = krb5_copy_keyblock(context, 
1013                                      &entry.keyblock,
1014                                      &o->keyblock);
1015             if (ret) {
1016                 krb5_kt_free_entry (context, &entry);
1017                 goto out;
1018             }       
1019
1020             ret = krb5_copy_principal(context, entry.principal, &p);
1021             if (ret) {
1022                 krb5_kt_free_entry (context, &entry);
1023                 goto out;
1024             }
1025             krb5_free_principal(context, o->ticket->server);
1026             o->ticket->server = p;
1027             
1028             krb5_kt_free_entry (context, &entry);
1029
1030             done = 1;
1031         }
1032         krb5_kt_end_seq_get (context, id, &cursor);
1033     }
1034
1035     /* If there is a PAC, verify its server signature */
1036     if (inctx == NULL || inctx->check_pac) {
1037         krb5_pac pac;
1038         krb5_data data;
1039
1040         ret = krb5_ticket_get_authorization_data_type(context,
1041                                                       o->ticket,
1042                                                       KRB5_AUTHDATA_WIN2K_PAC,
1043                                                       &data);
1044         if (ret == 0) {
1045             ret = krb5_pac_parse(context, data.data, data.length, &pac);
1046             krb5_data_free(&data);
1047             if (ret)
1048                 goto out;
1049         
1050             ret = krb5_pac_verify(context,
1051                                   pac,
1052                                   o->ticket->ticket.authtime,
1053                                   o->ticket->client,
1054                                   o->keyblock,
1055                                   NULL);
1056             krb5_pac_free(context, pac);
1057             if (ret)
1058                 goto out;
1059         } else
1060           ret = 0;
1061     }
1062 out:
1063
1064     if (ret || outctx == NULL) {
1065         krb5_rd_req_out_ctx_free(context, o);
1066     } else
1067         *outctx = o;
1068
1069     free_AP_REQ(&ap_req);
1070
1071     if (service)
1072         krb5_free_principal(context, service);
1073
1074     if (keytab)
1075         krb5_kt_close(context, keytab);
1076
1077     return ret;
1078 }