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