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