s4:heimdal: import lorikeet-heimdal-200906080040 (commit 904d0124b46eed7a8ad6e5b73e89...
[amitay/samba.git] / source4 / heimdal / kdc / kerberos5.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 "kdc_locl.h"
35
36 RCSID("$Id$");
37
38 #define MAX_TIME ((time_t)((1U << 31) - 1))
39
40 void
41 _kdc_fix_time(time_t **t)
42 {
43     if(*t == NULL){
44         ALLOC(*t);
45         **t = MAX_TIME;
46     }
47     if(**t == 0) **t = MAX_TIME; /* fix for old clients */
48 }
49
50 static int
51 realloc_method_data(METHOD_DATA *md)
52 {
53     PA_DATA *pa;
54     pa = realloc(md->val, (md->len + 1) * sizeof(*md->val));
55     if(pa == NULL)
56         return ENOMEM;
57     md->val = pa;
58     md->len++;
59     return 0;
60 }
61
62 static void
63 set_salt_padata (METHOD_DATA *md, Salt *salt)
64 {
65     if (salt) {
66         realloc_method_data(md);
67         md->val[md->len - 1].padata_type = salt->type;
68         der_copy_octet_string(&salt->salt,
69                               &md->val[md->len - 1].padata_value);
70     }
71 }
72
73 const PA_DATA*
74 _kdc_find_padata(const KDC_REQ *req, int *start, int type)
75 {
76     if (req->padata == NULL)
77         return NULL;
78
79     while(*start < req->padata->len){
80         (*start)++;
81         if(req->padata->val[*start - 1].padata_type == type)
82             return &req->padata->val[*start - 1];
83     }
84     return NULL;
85 }
86
87 /*
88  * This is a hack to allow predefined weak services, like afs to
89  * still use weak types
90  */
91
92 krb5_boolean
93 _kdc_is_weak_exception(krb5_principal principal, krb5_enctype etype)
94 {
95     if (principal->name.name_string.len > 0 &&
96         strcmp(principal->name.name_string.val[0], "afs") == 0 &&
97         (etype == ETYPE_DES_CBC_CRC
98          || etype == ETYPE_DES_CBC_MD4
99          || etype == ETYPE_DES_CBC_MD5))
100         return TRUE;
101     return FALSE;
102 }
103
104
105 /*
106  * Detect if `key' is the using the the precomputed `default_salt'.
107  */
108
109 static krb5_boolean
110 is_default_salt_p(const krb5_salt *default_salt, const Key *key)
111 {
112     if (key->salt == NULL)
113         return TRUE;
114     if (default_salt->salttype != key->salt->type)
115         return FALSE;
116     if (krb5_data_cmp(&default_salt->saltvalue, &key->salt->salt))
117         return FALSE;
118     return TRUE;
119 }
120
121 /*
122  * return the first appropriate key of `princ' in `ret_key'.  Look for
123  * all the etypes in (`etypes', `len'), stopping as soon as we find
124  * one, but preferring one that has default salt
125  */
126
127 krb5_error_code
128 _kdc_find_etype(krb5_context context, const hdb_entry_ex *princ,
129                 krb5_enctype *etypes, unsigned len,
130                 Key **ret_key, krb5_enctype *ret_etype)
131 {
132     int i;
133     krb5_error_code ret = KRB5KDC_ERR_ETYPE_NOSUPP;
134     krb5_salt def_salt;
135
136     krb5_get_pw_salt (context, princ->entry.principal, &def_salt);
137
138     for(i = 0; ret != 0 && i < len ; i++) {
139         Key *key = NULL;
140
141         if (krb5_enctype_valid(context, etypes[i]) != 0 &&
142             !_kdc_is_weak_exception(princ->entry.principal, etypes[i]))
143             continue;
144
145         while (hdb_next_enctype2key(context, &princ->entry, etypes[i], &key) == 0) {
146             if (key->key.keyvalue.length == 0) {
147                 ret = KRB5KDC_ERR_NULL_KEY;
148                 continue;
149             }
150             *ret_key   = key;
151             *ret_etype = etypes[i];
152             ret = 0;
153             if (is_default_salt_p(&def_salt, key)) {
154                 krb5_free_salt (context, def_salt);
155                 return ret;
156             }
157         }
158     }
159     krb5_free_salt (context, def_salt);
160     return ret;
161 }
162
163 krb5_error_code
164 _kdc_make_anonymous_principalname (PrincipalName *pn)
165 {
166     pn->name_type = KRB5_NT_PRINCIPAL;
167     pn->name_string.len = 1;
168     pn->name_string.val = malloc(sizeof(*pn->name_string.val));
169     if (pn->name_string.val == NULL)
170         return ENOMEM;
171     pn->name_string.val[0] = strdup("anonymous");
172     if (pn->name_string.val[0] == NULL) {
173         free(pn->name_string.val);
174         pn->name_string.val = NULL;
175         return ENOMEM;
176     }
177     return 0;
178 }
179
180 void
181 _kdc_log_timestamp(krb5_context context,
182                    krb5_kdc_configuration *config,
183                    const char *type,
184                    KerberosTime authtime, KerberosTime *starttime,
185                    KerberosTime endtime, KerberosTime *renew_till)
186 {
187     char authtime_str[100], starttime_str[100],
188         endtime_str[100], renewtime_str[100];
189
190     krb5_format_time(context, authtime,
191                      authtime_str, sizeof(authtime_str), TRUE);
192     if (starttime)
193         krb5_format_time(context, *starttime,
194                          starttime_str, sizeof(starttime_str), TRUE);
195     else
196         strlcpy(starttime_str, "unset", sizeof(starttime_str));
197     krb5_format_time(context, endtime,
198                      endtime_str, sizeof(endtime_str), TRUE);
199     if (renew_till)
200         krb5_format_time(context, *renew_till,
201                          renewtime_str, sizeof(renewtime_str), TRUE);
202     else
203         strlcpy(renewtime_str, "unset", sizeof(renewtime_str));
204
205     kdc_log(context, config, 5,
206             "%s authtime: %s starttime: %s endtime: %s renew till: %s",
207             type, authtime_str, starttime_str, endtime_str, renewtime_str);
208 }
209
210 static void
211 log_patypes(krb5_context context,
212             krb5_kdc_configuration *config,
213             METHOD_DATA *padata)
214 {
215     struct rk_strpool *p = NULL;
216     char *str;
217     int i;
218         
219     for (i = 0; i < padata->len; i++) {
220         switch(padata->val[i].padata_type) {
221         case KRB5_PADATA_PK_AS_REQ:
222             p = rk_strpoolprintf(p, "PK-INIT(ietf)");
223             break;
224         case KRB5_PADATA_PK_AS_REQ_WIN:
225             p = rk_strpoolprintf(p, "PK-INIT(win2k)");
226             break;
227         case KRB5_PADATA_PA_PK_OCSP_RESPONSE:
228             p = rk_strpoolprintf(p, "OCSP");
229             break;
230         case KRB5_PADATA_ENC_TIMESTAMP:
231             p = rk_strpoolprintf(p, "encrypted-timestamp");
232             break;
233         default:
234             p = rk_strpoolprintf(p, "%d", padata->val[i].padata_type);
235             break;
236         }
237         if (p && i + 1 < padata->len)
238             p = rk_strpoolprintf(p, ", ");
239         if (p == NULL) {
240             kdc_log(context, config, 0, "out of memory");
241             return;
242         }
243     }
244     if (p == NULL)
245         p = rk_strpoolprintf(p, "none");
246         
247     str = rk_strpoolcollect(p);
248     kdc_log(context, config, 0, "Client sent patypes: %s", str);
249     free(str);
250 }
251
252 /*
253  *
254  */
255
256
257 krb5_error_code
258 _kdc_encode_reply(krb5_context context,
259                   krb5_kdc_configuration *config,
260                   KDC_REP *rep, const EncTicketPart *et, EncKDCRepPart *ek,
261                   krb5_enctype etype,
262                   int skvno, const EncryptionKey *skey,
263                   int ckvno, const EncryptionKey *reply_key,
264                   const char **e_text,
265                   krb5_data *reply)
266 {
267     unsigned char *buf;
268     size_t buf_size;
269     size_t len;
270     krb5_error_code ret;
271     krb5_crypto crypto;
272
273     ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size, et, &len, ret);
274     if(ret) {
275         kdc_log(context, config, 0, "Failed to encode ticket: %s",
276                 krb5_get_err_text(context, ret));
277         return ret;
278     }
279     if(buf_size != len) {
280         free(buf);
281         kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
282         *e_text = "KDC internal error";
283         return KRB5KRB_ERR_GENERIC;
284     }
285
286     ret = krb5_crypto_init(context, skey, etype, &crypto);
287     if (ret) {
288         free(buf);
289         kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
290                 krb5_get_err_text(context, ret));
291         return ret;
292     }
293
294     ret = krb5_encrypt_EncryptedData(context,
295                                      crypto,
296                                      KRB5_KU_TICKET,
297                                      buf,
298                                      len,
299                                      skvno,
300                                      &rep->ticket.enc_part);
301     free(buf);
302     krb5_crypto_destroy(context, crypto);
303     if(ret) {
304         kdc_log(context, config, 0, "Failed to encrypt data: %s",
305                 krb5_get_err_text(context, ret));
306         return ret;
307     }
308
309     if(rep->msg_type == krb_as_rep && !config->encode_as_rep_as_tgs_rep)
310         ASN1_MALLOC_ENCODE(EncASRepPart, buf, buf_size, ek, &len, ret);
311     else
312         ASN1_MALLOC_ENCODE(EncTGSRepPart, buf, buf_size, ek, &len, ret);
313     if(ret) {
314         kdc_log(context, config, 0, "Failed to encode KDC-REP: %s",
315                 krb5_get_err_text(context, ret));
316         return ret;
317     }
318     if(buf_size != len) {
319         free(buf);
320         kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
321         *e_text = "KDC internal error";
322         return KRB5KRB_ERR_GENERIC;
323     }
324     ret = krb5_crypto_init(context, reply_key, 0, &crypto);
325     if (ret) {
326         free(buf);
327         kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
328                 krb5_get_err_text(context, ret));
329         return ret;
330     }
331     if(rep->msg_type == krb_as_rep) {
332         krb5_encrypt_EncryptedData(context,
333                                    crypto,
334                                    KRB5_KU_AS_REP_ENC_PART,
335                                    buf,
336                                    len,
337                                    ckvno,
338                                    &rep->enc_part);
339         free(buf);
340         ASN1_MALLOC_ENCODE(AS_REP, buf, buf_size, rep, &len, ret);
341     } else {
342         krb5_encrypt_EncryptedData(context,
343                                    crypto,
344                                    KRB5_KU_TGS_REP_ENC_PART_SESSION,
345                                    buf,
346                                    len,
347                                    ckvno,
348                                    &rep->enc_part);
349         free(buf);
350         ASN1_MALLOC_ENCODE(TGS_REP, buf, buf_size, rep, &len, ret);
351     }
352     krb5_crypto_destroy(context, crypto);
353     if(ret) {
354         kdc_log(context, config, 0, "Failed to encode KDC-REP: %s",
355                 krb5_get_err_text(context, ret));
356         return ret;
357     }
358     if(buf_size != len) {
359         free(buf);
360         kdc_log(context, config, 0, "Internal error in ASN.1 encoder");
361         *e_text = "KDC internal error";
362         return KRB5KRB_ERR_GENERIC;
363     }
364     reply->data = buf;
365     reply->length = buf_size;
366     return 0;
367 }
368
369 /*
370  * Return 1 if the client have only older enctypes, this is for
371  * determining if the server should send ETYPE_INFO2 or not.
372  */
373
374 static int
375 older_enctype(krb5_enctype enctype)
376 {
377     switch (enctype) {
378     case ETYPE_DES_CBC_CRC:
379     case ETYPE_DES_CBC_MD4:
380     case ETYPE_DES_CBC_MD5:
381     case ETYPE_DES3_CBC_SHA1:
382     case ETYPE_ARCFOUR_HMAC_MD5:
383     case ETYPE_ARCFOUR_HMAC_MD5_56:
384     /*
385      * The following three is "old" windows enctypes and is needed for
386      * windows 2000 hosts.
387      */
388     case ETYPE_ARCFOUR_MD4:
389     case ETYPE_ARCFOUR_HMAC_OLD:
390     case ETYPE_ARCFOUR_HMAC_OLD_EXP:
391         return 1;
392     default:
393         return 0;
394     }
395 }
396
397 /*
398  *
399  */
400
401 static krb5_error_code
402 make_etype_info_entry(krb5_context context, ETYPE_INFO_ENTRY *ent, Key *key)
403 {
404     ent->etype = key->key.keytype;
405     if(key->salt){
406 #if 0
407         ALLOC(ent->salttype);
408
409         if(key->salt->type == hdb_pw_salt)
410             *ent->salttype = 0; /* or 1? or NULL? */
411         else if(key->salt->type == hdb_afs3_salt)
412             *ent->salttype = 2;
413         else {
414             kdc_log(context, config, 0, "unknown salt-type: %d",
415                     key->salt->type);
416             return KRB5KRB_ERR_GENERIC;
417         }
418         /* according to `the specs', we can't send a salt if
419            we have AFS3 salted key, but that requires that you
420            *know* what cell you are using (e.g by assuming
421            that the cell is the same as the realm in lower
422            case) */
423 #elif 0
424         ALLOC(ent->salttype);
425         *ent->salttype = key->salt->type;
426 #else
427         /*
428          * We shouldn't sent salttype since it is incompatible with the
429          * specification and it breaks windows clients.  The afs
430          * salting problem is solved by using KRB5-PADATA-AFS3-SALT
431          * implemented in Heimdal 0.7 and later.
432          */
433         ent->salttype = NULL;
434 #endif
435         krb5_copy_data(context, &key->salt->salt,
436                        &ent->salt);
437     } else {
438         /* we return no salt type at all, as that should indicate
439          * the default salt type and make everybody happy.  some
440          * systems (like w2k) dislike being told the salt type
441          * here. */
442
443         ent->salttype = NULL;
444         ent->salt = NULL;
445     }
446     return 0;
447 }
448
449 static krb5_error_code
450 get_pa_etype_info(krb5_context context,
451                   krb5_kdc_configuration *config,
452                   METHOD_DATA *md, Key *ckey)
453 {
454     krb5_error_code ret = 0;
455     ETYPE_INFO pa;
456     unsigned char *buf;
457     size_t len;
458
459
460     pa.len = 1;
461     pa.val = calloc(1, sizeof(pa.val[0]));
462     if(pa.val == NULL)
463         return ENOMEM;
464
465     ret = make_etype_info_entry(context, &pa.val[0], ckey);
466     if (ret) {
467         free_ETYPE_INFO(&pa);
468         return ret;
469     }
470
471     ASN1_MALLOC_ENCODE(ETYPE_INFO, buf, len, &pa, &len, ret);
472     free_ETYPE_INFO(&pa);
473     if(ret)
474         return ret;
475     ret = realloc_method_data(md);
476     if(ret) {
477         free(buf);
478         return ret;
479     }
480     md->val[md->len - 1].padata_type = KRB5_PADATA_ETYPE_INFO;
481     md->val[md->len - 1].padata_value.length = len;
482     md->val[md->len - 1].padata_value.data = buf;
483     return 0;
484 }
485
486 /*
487  *
488  */
489
490 extern int _krb5_AES_string_to_default_iterator;
491
492 static krb5_error_code
493 make_etype_info2_entry(ETYPE_INFO2_ENTRY *ent, Key *key)
494 {
495     ent->etype = key->key.keytype;
496     if(key->salt) {
497         ALLOC(ent->salt);
498         if (ent->salt == NULL)
499             return ENOMEM;
500         *ent->salt = malloc(key->salt->salt.length + 1);
501         if (*ent->salt == NULL) {
502             free(ent->salt);
503             ent->salt = NULL;
504             return ENOMEM;
505         }
506         memcpy(*ent->salt, key->salt->salt.data, key->salt->salt.length);
507         (*ent->salt)[key->salt->salt.length] = '\0';
508     } else
509         ent->salt = NULL;
510
511     ent->s2kparams = NULL;
512
513     switch (key->key.keytype) {
514     case ETYPE_AES128_CTS_HMAC_SHA1_96:
515     case ETYPE_AES256_CTS_HMAC_SHA1_96:
516         ALLOC(ent->s2kparams);
517         if (ent->s2kparams == NULL)
518             return ENOMEM;
519         ent->s2kparams->length = 4;
520         ent->s2kparams->data = malloc(ent->s2kparams->length);
521         if (ent->s2kparams->data == NULL) {
522             free(ent->s2kparams);
523             ent->s2kparams = NULL;
524             return ENOMEM;
525         }
526         _krb5_put_int(ent->s2kparams->data,
527                       _krb5_AES_string_to_default_iterator,
528                       ent->s2kparams->length);
529         break;
530     case ETYPE_DES_CBC_CRC:
531     case ETYPE_DES_CBC_MD4:
532     case ETYPE_DES_CBC_MD5:
533         /* Check if this was a AFS3 salted key */
534         if(key->salt && key->salt->type == hdb_afs3_salt){
535             ALLOC(ent->s2kparams);
536             if (ent->s2kparams == NULL)
537                 return ENOMEM;
538             ent->s2kparams->length = 1;
539             ent->s2kparams->data = malloc(ent->s2kparams->length);
540             if (ent->s2kparams->data == NULL) {
541                 free(ent->s2kparams);
542                 ent->s2kparams = NULL;
543                 return ENOMEM;
544             }
545             _krb5_put_int(ent->s2kparams->data,
546                           1,
547                           ent->s2kparams->length);
548         }
549         break;
550     default:
551         break;
552     }
553     return 0;
554 }
555
556 /*
557  * Return an ETYPE-INFO2. Enctypes are storted the same way as in the
558  * database (client supported enctypes first, then the unsupported
559  * enctypes).
560  */
561
562 static krb5_error_code
563 get_pa_etype_info2(krb5_context context,
564                    krb5_kdc_configuration *config,
565                    METHOD_DATA *md, Key *ckey)
566 {
567     krb5_error_code ret = 0;
568     ETYPE_INFO2 pa;
569     unsigned char *buf;
570     size_t len;
571
572     pa.len = 1;
573     pa.val = calloc(1, sizeof(pa.val[0]));
574     if(pa.val == NULL)
575         return ENOMEM;
576
577     ret = make_etype_info2_entry(&pa.val[0], ckey);
578     if (ret) {
579         free_ETYPE_INFO2(&pa);
580         return ret;
581     }
582
583     ASN1_MALLOC_ENCODE(ETYPE_INFO2, buf, len, &pa, &len, ret);
584     free_ETYPE_INFO2(&pa);
585     if(ret)
586         return ret;
587     ret = realloc_method_data(md);
588     if(ret) {
589         free(buf);
590         return ret;
591     }
592     md->val[md->len - 1].padata_type = KRB5_PADATA_ETYPE_INFO2;
593     md->val[md->len - 1].padata_value.length = len;
594     md->val[md->len - 1].padata_value.data = buf;
595     return 0;
596 }
597
598 /*
599  *
600  */
601
602 static void
603 log_as_req(krb5_context context,
604            krb5_kdc_configuration *config,
605            krb5_enctype cetype,
606            krb5_enctype setype,
607            const KDC_REQ_BODY *b)
608 {
609     krb5_error_code ret;
610     struct rk_strpool *p;
611     char *str;
612     int i;
613
614     p = rk_strpoolprintf(NULL, "%s", "Client supported enctypes: ");
615
616     for (i = 0; i < b->etype.len; i++) {
617         ret = krb5_enctype_to_string(context, b->etype.val[i], &str);
618         if (ret == 0) {
619             p = rk_strpoolprintf(p, "%s", str);
620             free(str);
621         } else
622             p = rk_strpoolprintf(p, "%d", b->etype.val[i]);
623         if (p && i + 1 < b->etype.len)
624             p = rk_strpoolprintf(p, ", ");
625         if (p == NULL) {
626             kdc_log(context, config, 0, "out of memory");
627             return;
628         }
629     }
630     if (p == NULL)
631         p = rk_strpoolprintf(p, "no encryption types");
632
633     {
634         char *cet;
635         char *set;
636
637         ret = krb5_enctype_to_string(context, cetype, &cet);
638         if(ret == 0) {
639             ret = krb5_enctype_to_string(context, setype, &set);
640             if (ret == 0) {
641                 p = rk_strpoolprintf(p, ", using %s/%s", cet, set);
642                 free(set);
643             }
644             free(cet);
645         }
646         if (ret != 0)
647             p = rk_strpoolprintf(p, ", using enctypes %d/%d",
648                                  cetype, setype);
649     }
650
651     str = rk_strpoolcollect(p);
652     kdc_log(context, config, 0, "%s", str);
653     free(str);
654
655     {
656         char fixedstr[128];
657         unparse_flags(KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(),
658                       fixedstr, sizeof(fixedstr));
659         if(*fixedstr)
660             kdc_log(context, config, 0, "Requested flags: %s", fixedstr);
661     }
662 }
663
664 /*
665  * verify the flags on `client' and `server', returning 0
666  * if they are OK and generating an error messages and returning
667  * and error code otherwise.
668  */
669
670 krb5_error_code
671 _kdc_check_flags(krb5_context context,
672                  krb5_kdc_configuration *config,
673                  hdb_entry_ex *client_ex, const char *client_name,
674                  hdb_entry_ex *server_ex, const char *server_name,
675                  krb5_boolean is_as_req)
676 {
677     if(client_ex != NULL) {
678         hdb_entry *client = &client_ex->entry;
679
680         /* check client */
681         if (client->flags.invalid) {
682             kdc_log(context, config, 0,
683                     "Client (%s) has invalid bit set", client_name);
684             return KRB5KDC_ERR_POLICY;
685         }
686         
687         if(!client->flags.client){
688             kdc_log(context, config, 0,
689                     "Principal may not act as client -- %s", client_name);
690             return KRB5KDC_ERR_POLICY;
691         }
692         
693         if (client->valid_start && *client->valid_start > kdc_time) {
694             char starttime_str[100];
695             krb5_format_time(context, *client->valid_start,
696                              starttime_str, sizeof(starttime_str), TRUE);
697             kdc_log(context, config, 0,
698                     "Client not yet valid until %s -- %s",
699                     starttime_str, client_name);
700             return KRB5KDC_ERR_CLIENT_NOTYET;
701         }
702         
703         if (client->valid_end && *client->valid_end < kdc_time) {
704             char endtime_str[100];
705             krb5_format_time(context, *client->valid_end,
706                              endtime_str, sizeof(endtime_str), TRUE);
707             kdc_log(context, config, 0,
708                     "Client expired at %s -- %s",
709                     endtime_str, client_name);
710             return KRB5KDC_ERR_NAME_EXP;
711         }
712         
713         if (client->pw_end && *client->pw_end < kdc_time
714             && (server_ex == NULL || !server_ex->entry.flags.change_pw)) {
715             char pwend_str[100];
716             krb5_format_time(context, *client->pw_end,
717                              pwend_str, sizeof(pwend_str), TRUE);
718             kdc_log(context, config, 0,
719                     "Client's key has expired at %s -- %s",
720                     pwend_str, client_name);
721             return KRB5KDC_ERR_KEY_EXPIRED;
722         }
723     }
724
725     /* check server */
726
727     if (server_ex != NULL) {
728         hdb_entry *server = &server_ex->entry;
729
730         if (server->flags.invalid) {
731             kdc_log(context, config, 0,
732                     "Server has invalid flag set -- %s", server_name);
733             return KRB5KDC_ERR_POLICY;
734         }
735
736         if(!server->flags.server){
737             kdc_log(context, config, 0,
738                     "Principal may not act as server -- %s", server_name);
739             return KRB5KDC_ERR_POLICY;
740         }
741
742         if(!is_as_req && server->flags.initial) {
743             kdc_log(context, config, 0,
744                     "AS-REQ is required for server -- %s", server_name);
745             return KRB5KDC_ERR_POLICY;
746         }
747
748         if (server->valid_start && *server->valid_start > kdc_time) {
749             char starttime_str[100];
750             krb5_format_time(context, *server->valid_start,
751                              starttime_str, sizeof(starttime_str), TRUE);
752             kdc_log(context, config, 0,
753                     "Server not yet valid until %s -- %s",
754                     starttime_str, server_name);
755             return KRB5KDC_ERR_SERVICE_NOTYET;
756         }
757
758         if (server->valid_end && *server->valid_end < kdc_time) {
759             char endtime_str[100];
760             krb5_format_time(context, *server->valid_end,
761                              endtime_str, sizeof(endtime_str), TRUE);
762             kdc_log(context, config, 0,
763                     "Server expired at %s -- %s",
764                     endtime_str, server_name);
765             return KRB5KDC_ERR_SERVICE_EXP;
766         }
767
768         if (server->pw_end && *server->pw_end < kdc_time) {
769             char pwend_str[100];
770             krb5_format_time(context, *server->pw_end,
771                              pwend_str, sizeof(pwend_str), TRUE);
772             kdc_log(context, config, 0,
773                     "Server's key has expired at -- %s",
774                     pwend_str, server_name);
775             return KRB5KDC_ERR_KEY_EXPIRED;
776         }
777     }
778     return 0;
779 }
780
781 /*
782  * Return TRUE if `from' is part of `addresses' taking into consideration
783  * the configuration variables that tells us how strict we should be about
784  * these checks
785  */
786
787 krb5_boolean
788 _kdc_check_addresses(krb5_context context,
789                      krb5_kdc_configuration *config,
790                      HostAddresses *addresses, const struct sockaddr *from)
791 {
792     krb5_error_code ret;
793     krb5_address addr;
794     krb5_boolean result;
795     krb5_boolean only_netbios = TRUE;
796     int i;
797
798     if(config->check_ticket_addresses == 0)
799         return TRUE;
800
801     if(addresses == NULL)
802         return config->allow_null_ticket_addresses;
803
804     for (i = 0; i < addresses->len; ++i) {
805         if (addresses->val[i].addr_type != KRB5_ADDRESS_NETBIOS) {
806             only_netbios = FALSE;
807         }
808     }
809
810     /* Windows sends it's netbios name, which I can only assume is
811      * used for the 'allowed workstations' check.  This is painful,
812      * but we still want to check IP addresses if they happen to be
813      * present.
814      */
815
816     if(only_netbios)
817         return config->allow_null_ticket_addresses;
818
819     ret = krb5_sockaddr2address (context, from, &addr);
820     if(ret)
821         return FALSE;
822
823     result = krb5_address_search(context, &addr, addresses);
824     krb5_free_address (context, &addr);
825     return result;
826 }
827
828 /*
829  *
830  */
831
832 static krb5_boolean
833 send_pac_p(krb5_context context, KDC_REQ *req)
834 {
835     krb5_error_code ret;
836     PA_PAC_REQUEST pacreq;
837     const PA_DATA *pa;
838     int i = 0;
839
840     pa = _kdc_find_padata(req, &i, KRB5_PADATA_PA_PAC_REQUEST);
841     if (pa == NULL)
842         return TRUE;
843
844     ret = decode_PA_PAC_REQUEST(pa->padata_value.data,
845                                 pa->padata_value.length,
846                                 &pacreq,
847                                 NULL);
848     if (ret)
849         return TRUE;
850     i = pacreq.include_pac;
851     free_PA_PAC_REQUEST(&pacreq);
852     if (i == 0)
853         return FALSE;
854     return TRUE;
855 }
856
857 krb5_boolean
858 _kdc_is_anonymous(krb5_context context, krb5_principal principal)
859 {
860     if (principal->name.name_type != KRB5_NT_WELLKNOWN ||
861         principal->name.name_string.len != 2 ||
862         strcmp(principal->name.name_string.val[0], KRB5_WELLKNOWN_NAME) != 0 ||
863         strcmp(principal->name.name_string.val[1], KRB5_ANON_NAME) != 0)
864         return 0;
865     return 1;
866 }
867
868 /*
869  *
870  */
871
872 krb5_error_code
873 _kdc_as_rep(krb5_context context,
874             krb5_kdc_configuration *config,
875             KDC_REQ *req,
876             const krb5_data *req_buffer,
877             krb5_data *reply,
878             const char *from,
879             struct sockaddr *from_addr,
880             int datagram_reply)
881 {
882     KDC_REQ_BODY *b = &req->req_body;
883     AS_REP rep;
884     KDCOptions f = b->kdc_options;
885     hdb_entry_ex *client = NULL, *server = NULL;
886     krb5_enctype cetype, setype, sessionetype;
887     krb5_data e_data;
888     EncTicketPart et;
889     EncKDCRepPart ek;
890     krb5_principal client_princ = NULL, server_princ = NULL;
891     char *client_name = NULL, *server_name = NULL;
892     krb5_error_code ret = 0;
893     const char *e_text = NULL;
894     krb5_crypto crypto;
895     Key *ckey, *skey;
896     EncryptionKey *reply_key;
897     int flags = 0;
898 #ifdef PKINIT
899     pk_client_params *pkp = NULL;
900 #endif
901
902     memset(&rep, 0, sizeof(rep));
903     krb5_data_zero(&e_data);
904
905     if (f.canonicalize)
906         flags |= HDB_F_CANON;
907
908     if(b->sname == NULL){
909         ret = KRB5KRB_ERR_GENERIC;
910         e_text = "No server in request";
911     } else{
912         ret = _krb5_principalname2krb5_principal (context,
913                                                   &server_princ,
914                                                   *(b->sname),
915                                                   b->realm);
916         if (ret == 0)
917             ret = krb5_unparse_name(context, server_princ, &server_name);
918     }
919     if (ret) {
920         kdc_log(context, config, 0,
921                 "AS-REQ malformed server name from %s", from);
922         goto out;
923     }
924
925     if(b->cname == NULL){
926         ret = KRB5KRB_ERR_GENERIC;
927         e_text = "No client in request";
928     } else {
929
930         if (b->cname->name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
931             if (b->cname->name_string.len != 1) {
932                 kdc_log(context, config, 0,
933                         "AS-REQ malformed canon request from %s, "
934                         "enterprise name with %d name components",
935                         from, b->cname->name_string.len);
936                 ret = KRB5_PARSE_MALFORMED;
937                 goto out;
938             }
939             ret = krb5_parse_name(context, b->cname->name_string.val[0],
940                                   &client_princ);
941             if (ret)
942                 goto out;
943         } else {
944             ret = _krb5_principalname2krb5_principal (context,
945                                                       &client_princ,
946                                                       *(b->cname),
947                                                       b->realm);
948             if (ret)
949                 goto out;
950         }
951
952         ret = krb5_unparse_name(context, client_princ, &client_name);
953     }
954     if (ret) {
955         kdc_log(context, config, 0,
956                 "AS-REQ malformed client name from %s", from);
957         goto out;
958     }
959
960     kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
961             client_name, from, server_name);
962
963     /*
964      *
965      */
966
967     if (_kdc_is_anonymous(context, client_princ)) {
968         if (!b->kdc_options.request_anonymous) {
969             kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
970             ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
971             goto out;
972         }
973     } else if (b->kdc_options.request_anonymous) {
974         kdc_log(context, config, 0, 
975                 "Request for a anonymous ticket with non "
976                 "anonymous client name: %s", client_name);
977         ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
978         goto out;
979     }
980
981     /*
982      *
983      */
984
985     ret = _kdc_db_fetch(context, config, client_princ,
986                         HDB_F_GET_CLIENT | flags, NULL, &client);
987     if(ret){
988         kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name,
989                 krb5_get_err_text(context, ret));
990         ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
991         goto out;
992     }
993
994     ret = _kdc_db_fetch(context, config, server_princ,
995                         HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
996                         NULL, &server);
997     if(ret){
998         kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name,
999                 krb5_get_err_text(context, ret));
1000         ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
1001         goto out;
1002     }
1003
1004     memset(&et, 0, sizeof(et));
1005     memset(&ek, 0, sizeof(ek));
1006
1007     /*
1008      * Find the client key for reply encryption and pa-type salt, Pick
1009      * the client key upfront before the other keys because that is
1010      * going to affect what enctypes we are going to use in
1011      * ETYPE-INFO{,2}.
1012      */
1013
1014     ret = _kdc_find_etype(context, client, b->etype.val, b->etype.len,
1015                           &ckey, &cetype);
1016     if (ret) {
1017         kdc_log(context, config, 0,
1018                 "Client (%s) has no support for etypes", client_name);
1019         goto out;
1020     }
1021
1022     /*
1023      * Pre-auth processing
1024      */
1025
1026     if(req->padata){
1027         int i;
1028         const PA_DATA *pa;
1029         int found_pa = 0;
1030
1031         log_patypes(context, config, req->padata);
1032
1033 #ifdef PKINIT
1034         kdc_log(context, config, 5,
1035                 "Looking for PKINIT pa-data -- %s", client_name);
1036
1037         e_text = "No PKINIT PA found";
1038
1039         i = 0;
1040         pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ);
1041         if (pa == NULL) {
1042             i = 0;
1043             pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN);
1044         }
1045         if (pa) {
1046             char *client_cert = NULL;
1047
1048             ret = _kdc_pk_rd_padata(context, config, req, pa, client, &pkp);
1049             if (ret) {
1050                 ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
1051                 kdc_log(context, config, 5,
1052                         "Failed to decode PKINIT PA-DATA -- %s",
1053                         client_name);
1054                 goto ts_enc;
1055             }
1056             if (ret == 0 && pkp == NULL)
1057                 goto ts_enc;
1058
1059             ret = _kdc_pk_check_client(context,
1060                                        config,
1061                                        client,
1062                                        pkp,
1063                                        &client_cert);
1064             if (ret) {
1065                 e_text = "PKINIT certificate not allowed to "
1066                     "impersonate principal";
1067                 _kdc_pk_free_client_param(context, pkp);
1068                 
1069                 kdc_log(context, config, 0, "%s", e_text);
1070                 pkp = NULL;
1071                 goto out;
1072             }
1073
1074             found_pa = 1;
1075             et.flags.pre_authent = 1;
1076             kdc_log(context, config, 0,
1077                     "PKINIT pre-authentication succeeded -- %s using %s",
1078                     client_name, client_cert);
1079             free(client_cert);
1080             if (pkp)
1081                 goto preauth_done;
1082         }
1083     ts_enc:
1084 #endif
1085         kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s",
1086                 client_name);
1087
1088         i = 0;
1089         e_text = "No ENC-TS found";
1090         while((pa = _kdc_find_padata(req, &i, KRB5_PADATA_ENC_TIMESTAMP))){
1091             krb5_data ts_data;
1092             PA_ENC_TS_ENC p;
1093             size_t len;
1094             EncryptedData enc_data;
1095             Key *pa_key;
1096             char *str;
1097         
1098             found_pa = 1;
1099         
1100             if (b->kdc_options.request_anonymous) {
1101                 ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
1102                 kdc_log(context, config, 0, "ENC-TS doesn't support anon");
1103                 goto out;
1104             }
1105
1106             ret = decode_EncryptedData(pa->padata_value.data,
1107                                        pa->padata_value.length,
1108                                        &enc_data,
1109                                        &len);
1110             if (ret) {
1111                 ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
1112                 kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s",
1113                         client_name);
1114                 goto out;
1115             }
1116         
1117             ret = hdb_enctype2key(context, &client->entry,
1118                                   enc_data.etype, &pa_key);
1119             if(ret){
1120                 char *estr;
1121                 e_text = "No key matches pa-data";
1122                 ret = KRB5KDC_ERR_ETYPE_NOSUPP;
1123                 if(krb5_enctype_to_string(context, enc_data.etype, &estr))
1124                     estr = NULL;
1125                 if(estr == NULL)
1126                     kdc_log(context, config, 5,
1127                             "No client key matching pa-data (%d) -- %s",
1128                             enc_data.etype, client_name);
1129                 else
1130                     kdc_log(context, config, 5,
1131                             "No client key matching pa-data (%s) -- %s",
1132                             estr, client_name);
1133                 free(estr);
1134                 
1135                 free_EncryptedData(&enc_data);
1136                 continue;
1137             }
1138
1139         try_next_key:
1140             ret = krb5_crypto_init(context, &pa_key->key, 0, &crypto);
1141             if (ret) {
1142                 kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
1143                         krb5_get_err_text(context, ret));
1144                 free_EncryptedData(&enc_data);
1145                 continue;
1146             }
1147
1148             ret = krb5_decrypt_EncryptedData (context,
1149                                               crypto,
1150                                               KRB5_KU_PA_ENC_TIMESTAMP,
1151                                               &enc_data,
1152                                               &ts_data);
1153             krb5_crypto_destroy(context, crypto);
1154             /*
1155              * Since the user might have several keys with the same
1156              * enctype but with diffrent salting, we need to try all
1157              * the keys with the same enctype.
1158              */
1159             if(ret){
1160                 krb5_error_code ret2;
1161                 ret2 = krb5_enctype_to_string(context,
1162                                               pa_key->key.keytype, &str);
1163                 if (ret2)
1164                     str = NULL;
1165                 kdc_log(context, config, 5,
1166                         "Failed to decrypt PA-DATA -- %s "
1167                         "(enctype %s) error %s",
1168                         client_name,
1169                         str ? str : "unknown enctype",
1170                         krb5_get_err_text(context, ret));
1171                 free(str);
1172
1173                 if(hdb_next_enctype2key(context, &client->entry,
1174                                         enc_data.etype, &pa_key) == 0)
1175                     goto try_next_key;
1176                 e_text = "Failed to decrypt PA-DATA";
1177
1178                 free_EncryptedData(&enc_data);
1179                 ret = KRB5KDC_ERR_PREAUTH_FAILED;
1180                 continue;
1181             }
1182             free_EncryptedData(&enc_data);
1183             ret = decode_PA_ENC_TS_ENC(ts_data.data,
1184                                        ts_data.length,
1185                                        &p,
1186                                        &len);
1187             krb5_data_free(&ts_data);
1188             if(ret){
1189                 e_text = "Failed to decode PA-ENC-TS-ENC";
1190                 ret = KRB5KDC_ERR_PREAUTH_FAILED;
1191                 kdc_log(context, config,
1192                         5, "Failed to decode PA-ENC-TS_ENC -- %s",
1193                         client_name);
1194                 continue;
1195             }
1196             free_PA_ENC_TS_ENC(&p);
1197             if (abs(kdc_time - p.patimestamp) > context->max_skew) {
1198                 char client_time[100];
1199                 
1200                 krb5_format_time(context, p.patimestamp,
1201                                  client_time, sizeof(client_time), TRUE);
1202
1203                 ret = KRB5KRB_AP_ERR_SKEW;
1204                 kdc_log(context, config, 0,
1205                         "Too large time skew, "
1206                         "client time %s is out by %u > %u seconds -- %s",
1207                         client_time,
1208                         (unsigned)abs(kdc_time - p.patimestamp),
1209                         context->max_skew,
1210                         client_name);
1211 #if 1
1212                 /* This code is from samba, needs testing */
1213                 /*
1214                  * the following is needed to make windows clients
1215                  * to retry using the timestamp in the error message
1216                  *
1217                  * this is maybe a bug in windows to not trying when e_text
1218                  * is present...
1219                  */
1220                 e_text = NULL;
1221 #else
1222                 e_text = "Too large time skew";
1223 #endif
1224                 goto out;
1225             }
1226             et.flags.pre_authent = 1;
1227
1228             ret = krb5_enctype_to_string(context,pa_key->key.keytype, &str);
1229             if (ret)
1230                 str = NULL;
1231
1232             kdc_log(context, config, 2,
1233                     "ENC-TS Pre-authentication succeeded -- %s using %s",
1234                     client_name, str ? str : "unknown enctype");
1235             free(str);
1236             break;
1237         }
1238 #ifdef PKINIT
1239     preauth_done:
1240 #endif
1241         if(found_pa == 0 && config->require_preauth)
1242             goto use_pa;
1243         /* We come here if we found a pa-enc-timestamp, but if there
1244            was some problem with it, other than too large skew */
1245         if(found_pa && et.flags.pre_authent == 0){
1246             kdc_log(context, config, 0, "%s -- %s", e_text, client_name);
1247             e_text = NULL;
1248             goto out;
1249         }
1250     }else if (config->require_preauth
1251               || b->kdc_options.request_anonymous /* hack to force anon */
1252               || client->entry.flags.require_preauth
1253               || server->entry.flags.require_preauth) {
1254         METHOD_DATA method_data;
1255         PA_DATA *pa;
1256         unsigned char *buf;
1257         size_t len;
1258
1259     use_pa:
1260         method_data.len = 0;
1261         method_data.val = NULL;
1262
1263         ret = realloc_method_data(&method_data);
1264         if (ret) {
1265             free_METHOD_DATA(&method_data);
1266             goto out;
1267         }
1268         pa = &method_data.val[method_data.len-1];
1269         pa->padata_type         = KRB5_PADATA_ENC_TIMESTAMP;
1270         pa->padata_value.length = 0;
1271         pa->padata_value.data   = NULL;
1272
1273 #ifdef PKINIT
1274         ret = realloc_method_data(&method_data);
1275         if (ret) {
1276             free_METHOD_DATA(&method_data);
1277             goto out;
1278         }
1279         pa = &method_data.val[method_data.len-1];
1280         pa->padata_type         = KRB5_PADATA_PK_AS_REQ;
1281         pa->padata_value.length = 0;
1282         pa->padata_value.data   = NULL;
1283
1284         ret = realloc_method_data(&method_data);
1285         if (ret) {
1286             free_METHOD_DATA(&method_data);
1287             goto out;
1288         }
1289         pa = &method_data.val[method_data.len-1];
1290         pa->padata_type         = KRB5_PADATA_PK_AS_REQ_WIN;
1291         pa->padata_value.length = 0;
1292         pa->padata_value.data   = NULL;
1293 #endif
1294
1295         /*
1296          * If there is a client key, send ETYPE_INFO{,2}
1297          */
1298         if (ckey) {
1299
1300             /*
1301              * RFC4120 requires:
1302              * - If the client only knows about old enctypes, then send
1303              *   both info replies (we send 'info' first in the list).
1304              * - If the client is 'modern', because it knows about 'new'
1305              *   enctype types, then only send the 'info2' reply.
1306              *
1307              * Before we send the full list of etype-info data, we pick
1308              * the client key we would have used anyway below, just pick
1309              * that instead.
1310              */
1311
1312             if (older_enctype(ckey->key.keytype)) {
1313                 ret = get_pa_etype_info(context, config,
1314                                         &method_data, ckey);
1315                 if (ret) {
1316                     free_METHOD_DATA(&method_data);
1317                     goto out;
1318                 }
1319             }
1320             ret = get_pa_etype_info2(context, config,
1321                                      &method_data, ckey);
1322             if (ret) {
1323                 free_METHOD_DATA(&method_data);
1324                 goto out;
1325             }
1326         }
1327         
1328         ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
1329         free_METHOD_DATA(&method_data);
1330
1331         e_data.data   = buf;
1332         e_data.length = len;
1333         e_text ="Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ",
1334
1335         ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
1336
1337         kdc_log(context, config, 0,
1338                 "No preauth found, returning PREAUTH-REQUIRED -- %s",
1339                 client_name);
1340         goto out;
1341     }
1342
1343     /*
1344      * Verify flags after the user been required to prove its identity
1345      * with in a preauth mech.
1346      */
1347
1348     ret = _kdc_check_flags(context, config,
1349                            client, client_name,
1350                            server, server_name,
1351                            TRUE);
1352     if(ret)
1353         goto out;
1354
1355     ret = _kdc_windc_client_access(context, client, req, &e_data);
1356     if(ret)
1357         goto out;
1358
1359     /*
1360      * Selelct the best encryption type for the KDC with out regard to
1361      * the client since the client never needs to read that data.
1362      */
1363
1364     ret = _kdc_get_preferred_key(context, config,
1365                                  server, server_name,
1366                                  &setype, &skey);
1367     if(ret)
1368         goto out;
1369
1370     /*
1371      * Select a session enctype from the list of the crypto systems
1372      * supported enctype, is supported by the client and is one of the
1373      * enctype of the enctype of the krbtgt.
1374      *
1375      * The later is used as a hint what enctype all KDC are supporting
1376      * to make sure a newer version of KDC wont generate a session
1377      * enctype that and older version of a KDC in the same realm can't
1378      * decrypt.
1379      *
1380      * But if the KDC admin is paranoid and doesn't want to have "no
1381      * the best" enctypes on the krbtgt, lets save the best pick from
1382      * the client list and hope that that will work for any other
1383      * KDCs.
1384      */
1385     {
1386         const krb5_enctype *p;
1387         krb5_enctype clientbest = ETYPE_NULL;
1388         int i, j;
1389
1390         p = krb5_kerberos_enctypes(context);
1391
1392         sessionetype = ETYPE_NULL;
1393
1394         for (i = 0; p[i] != ETYPE_NULL && sessionetype == ETYPE_NULL; i++) {
1395             if (krb5_enctype_valid(context, p[i]) != 0)
1396                 continue;
1397
1398             for (j = 0; j < b->etype.len && sessionetype == ETYPE_NULL; j++) {
1399                 Key *dummy;
1400                 /* check with client */
1401                 if (p[i] != b->etype.val[j])
1402                     continue;
1403                 /* save best of union of { client, crypto system } */
1404                 if (clientbest == ETYPE_NULL)
1405                     clientbest = p[i];
1406                 /* check with krbtgt */
1407                 ret = hdb_enctype2key(context, &server->entry, p[i], &dummy);
1408                 if (ret)
1409                     continue;
1410                 sessionetype = p[i];
1411             }
1412         }
1413         /* if krbtgt had no shared keys with client, pick clients best */
1414         if (clientbest != ETYPE_NULL && sessionetype == ETYPE_NULL) {
1415             sessionetype = clientbest;
1416         } else if (sessionetype == ETYPE_NULL) {
1417             kdc_log(context, config, 0,
1418                     "Client (%s) from %s has no common enctypes with KDC"
1419                     "to use for the session key",
1420                     client_name, from);
1421             goto out;
1422         }
1423     }
1424
1425     log_as_req(context, config, cetype, setype, b);
1426
1427     if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
1428        || (f.request_anonymous && !config->allow_anonymous)) {
1429         ret = KRB5KDC_ERR_BADOPTION;
1430         kdc_log(context, config, 0, "Bad KDC options -- %s", client_name);
1431         goto out;
1432     }
1433
1434     rep.pvno = 5;
1435     rep.msg_type = krb_as_rep;
1436
1437     ret = copy_Realm(&client->entry.principal->realm, &rep.crealm);
1438     if (ret)
1439         goto out;
1440     ret = _krb5_principal2principalname(&rep.cname, client->entry.principal);
1441     if (ret)
1442         goto out;
1443
1444     rep.ticket.tkt_vno = 5;
1445     copy_Realm(&server->entry.principal->realm, &rep.ticket.realm);
1446     _krb5_principal2principalname(&rep.ticket.sname,
1447                                   server->entry.principal);
1448     /* java 1.6 expects the name to be the same type, lets allow that
1449      * uncomplicated name-types. */
1450 #define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)
1451     if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))
1452         rep.ticket.sname.name_type = b->sname->name_type;
1453 #undef CNT
1454
1455     et.flags.initial = 1;
1456     if(client->entry.flags.forwardable && server->entry.flags.forwardable)
1457         et.flags.forwardable = f.forwardable;
1458     else if (f.forwardable) {
1459         ret = KRB5KDC_ERR_POLICY;
1460         kdc_log(context, config, 0,
1461                 "Ticket may not be forwardable -- %s", client_name);
1462         goto out;
1463     }
1464     if(client->entry.flags.proxiable && server->entry.flags.proxiable)
1465         et.flags.proxiable = f.proxiable;
1466     else if (f.proxiable) {
1467         ret = KRB5KDC_ERR_POLICY;
1468         kdc_log(context, config, 0,
1469                 "Ticket may not be proxiable -- %s", client_name);
1470         goto out;
1471     }
1472     if(client->entry.flags.postdate && server->entry.flags.postdate)
1473         et.flags.may_postdate = f.allow_postdate;
1474     else if (f.allow_postdate){
1475         ret = KRB5KDC_ERR_POLICY;
1476         kdc_log(context, config, 0,
1477                 "Ticket may not be postdatable -- %s", client_name);
1478         goto out;
1479     }
1480
1481     /* check for valid set of addresses */
1482     if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
1483         ret = KRB5KRB_AP_ERR_BADADDR;
1484         kdc_log(context, config, 0,
1485                 "Bad address list requested -- %s", client_name);
1486         goto out;
1487     }
1488
1489     ret = copy_PrincipalName(&rep.cname, &et.cname);
1490     if (ret)
1491         goto out;
1492     ret = copy_Realm(&rep.crealm, &et.crealm);
1493     if (ret)
1494         goto out;
1495
1496     {
1497         time_t start;
1498         time_t t;
1499         
1500         start = et.authtime = kdc_time;
1501
1502         if(f.postdated && req->req_body.from){
1503             ALLOC(et.starttime);
1504             start = *et.starttime = *req->req_body.from;
1505             et.flags.invalid = 1;
1506             et.flags.postdated = 1; /* XXX ??? */
1507         }
1508         _kdc_fix_time(&b->till);
1509         t = *b->till;
1510
1511         /* be careful not overflowing */
1512
1513         if(client->entry.max_life)
1514             t = start + min(t - start, *client->entry.max_life);
1515         if(server->entry.max_life)
1516             t = start + min(t - start, *server->entry.max_life);
1517 #if 0
1518         t = min(t, start + realm->max_life);
1519 #endif
1520         et.endtime = t;
1521         if(f.renewable_ok && et.endtime < *b->till){
1522             f.renewable = 1;
1523             if(b->rtime == NULL){
1524                 ALLOC(b->rtime);
1525                 *b->rtime = 0;
1526             }
1527             if(*b->rtime < *b->till)
1528                 *b->rtime = *b->till;
1529         }
1530         if(f.renewable && b->rtime){
1531             t = *b->rtime;
1532             if(t == 0)
1533                 t = MAX_TIME;
1534             if(client->entry.max_renew)
1535                 t = start + min(t - start, *client->entry.max_renew);
1536             if(server->entry.max_renew)
1537                 t = start + min(t - start, *server->entry.max_renew);
1538 #if 0
1539             t = min(t, start + realm->max_renew);
1540 #endif
1541             ALLOC(et.renew_till);
1542             *et.renew_till = t;
1543             et.flags.renewable = 1;
1544         }
1545     }
1546
1547     if (f.request_anonymous)
1548         et.flags.anonymous = 1;
1549
1550     if(b->addresses){
1551         ALLOC(et.caddr);
1552         copy_HostAddresses(b->addresses, et.caddr);
1553     }
1554
1555     et.transited.tr_type = DOMAIN_X500_COMPRESS;
1556     krb5_data_zero(&et.transited.contents);
1557
1558     /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
1559      * as 0 and as 0x80 (meaning indefinite length) apart, and is thus
1560      * incapable of correctly decoding SEQUENCE OF's of zero length.
1561      *
1562      * To fix this, always send at least one no-op last_req
1563      *
1564      * If there's a pw_end or valid_end we will use that,
1565      * otherwise just a dummy lr.
1566      */
1567     ek.last_req.val = malloc(2 * sizeof(*ek.last_req.val));
1568     if (ek.last_req.val == NULL) {
1569         ret = ENOMEM;
1570         goto out;
1571     }
1572     ek.last_req.len = 0;
1573     if (client->entry.pw_end
1574         && (config->kdc_warn_pwexpire == 0
1575             || kdc_time + config->kdc_warn_pwexpire >= *client->entry.pw_end)) {
1576         ek.last_req.val[ek.last_req.len].lr_type  = LR_PW_EXPTIME;
1577         ek.last_req.val[ek.last_req.len].lr_value = *client->entry.pw_end;
1578         ++ek.last_req.len;
1579     }
1580     if (client->entry.valid_end) {
1581         ek.last_req.val[ek.last_req.len].lr_type  = LR_ACCT_EXPTIME;
1582         ek.last_req.val[ek.last_req.len].lr_value = *client->entry.valid_end;
1583         ++ek.last_req.len;
1584     }
1585     if (ek.last_req.len == 0) {
1586         ek.last_req.val[ek.last_req.len].lr_type  = LR_NONE;
1587         ek.last_req.val[ek.last_req.len].lr_value = 0;
1588         ++ek.last_req.len;
1589     }
1590     ek.nonce = b->nonce;
1591     if (client->entry.valid_end || client->entry.pw_end) {
1592         ALLOC(ek.key_expiration);
1593         if (client->entry.valid_end) {
1594             if (client->entry.pw_end)
1595                 *ek.key_expiration = min(*client->entry.valid_end,
1596                                          *client->entry.pw_end);
1597             else
1598                 *ek.key_expiration = *client->entry.valid_end;
1599         } else
1600             *ek.key_expiration = *client->entry.pw_end;
1601     } else
1602         ek.key_expiration = NULL;
1603     ek.flags = et.flags;
1604     ek.authtime = et.authtime;
1605     if (et.starttime) {
1606         ALLOC(ek.starttime);
1607         *ek.starttime = *et.starttime;
1608     }
1609     ek.endtime = et.endtime;
1610     if (et.renew_till) {
1611         ALLOC(ek.renew_till);
1612         *ek.renew_till = *et.renew_till;
1613     }
1614     copy_Realm(&rep.ticket.realm, &ek.srealm);
1615     copy_PrincipalName(&rep.ticket.sname, &ek.sname);
1616     if(et.caddr){
1617         ALLOC(ek.caddr);
1618         copy_HostAddresses(et.caddr, ek.caddr);
1619     }
1620
1621     ALLOC(rep.padata);
1622     rep.padata->len = 0;
1623     rep.padata->val = NULL;
1624
1625 #if PKINIT
1626     if (pkp) {
1627         e_text = "Failed to build PK-INIT reply";
1628         ret = _kdc_pk_mk_pa_reply(context, config, pkp, client,
1629                                   sessionetype, req, req_buffer,
1630                                   &reply_key, &et.key, rep.padata);
1631         if (ret)
1632             goto out;
1633         ret = _kdc_add_inital_verified_cas(context,
1634                                            config,
1635                                            pkp,
1636                                            &et);
1637         if (ret)
1638             goto out;
1639     } else
1640 #endif
1641     if (ckey) {
1642         reply_key = &ckey->key;
1643         ret = krb5_generate_random_keyblock(context, sessionetype, &et.key);
1644         if (ret)
1645             goto out;
1646     } else {
1647         e_text = "Client have no reply key";
1648         ret = KRB5KDC_ERR_CLIENT_NOTYET;
1649         goto out;
1650     }
1651
1652     ret = copy_EncryptionKey(&et.key, &ek.key);
1653     if (ret)
1654         goto out;
1655
1656     if (ckey)
1657         set_salt_padata (rep.padata, ckey->salt);
1658
1659     /* Add signing of alias referral */
1660     if (f.canonicalize) {
1661         PA_ClientCanonicalized canon;
1662         krb5_data data;
1663         PA_DATA pa;
1664         krb5_crypto crypto;
1665         size_t len;
1666
1667         memset(&canon, 0, sizeof(canon));
1668
1669         canon.names.requested_name = *b->cname;
1670         canon.names.mapped_name = client->entry.principal->name;
1671
1672         ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
1673                            &canon.names, &len, ret);
1674         if (ret)
1675             goto out;
1676         if (data.length != len)
1677             krb5_abortx(context, "internal asn.1 error");
1678
1679         /* sign using "returned session key" */
1680         ret = krb5_crypto_init(context, &et.key, 0, &crypto);
1681         if (ret) {
1682             free(data.data);
1683             goto out;
1684         }
1685
1686         ret = krb5_create_checksum(context, crypto,
1687                                    KRB5_KU_CANONICALIZED_NAMES, 0,
1688                                    data.data, data.length,
1689                                    &canon.canon_checksum);
1690         free(data.data);
1691         krb5_crypto_destroy(context, crypto);
1692         if (ret)
1693             goto out;
1694         
1695         ASN1_MALLOC_ENCODE(PA_ClientCanonicalized, data.data, data.length,
1696                            &canon, &len, ret);
1697         free_Checksum(&canon.canon_checksum);
1698         if (ret)
1699             goto out;
1700         if (data.length != len)
1701             krb5_abortx(context, "internal asn.1 error");
1702
1703         pa.padata_type = KRB5_PADATA_CLIENT_CANONICALIZED;
1704         pa.padata_value = data;
1705         ret = add_METHOD_DATA(rep.padata, &pa);
1706         free(data.data);
1707         if (ret)
1708             goto out;
1709     }
1710
1711     if (rep.padata->len == 0) {
1712         free(rep.padata);
1713         rep.padata = NULL;
1714     }
1715
1716     /* Add the PAC */
1717     if (send_pac_p(context, req)) {
1718         krb5_pac p = NULL;
1719         krb5_data data;
1720
1721         ret = _kdc_pac_generate(context, client, &p);
1722         if (ret) {
1723             kdc_log(context, config, 0, "PAC generation failed for -- %s",
1724                     client_name);
1725             goto out;
1726         }
1727         if (p != NULL) {
1728             ret = _krb5_pac_sign(context, p, et.authtime,
1729                                  client->entry.principal,
1730                                  &skey->key, /* Server key */
1731                                  &skey->key, /* FIXME: should be krbtgt key */
1732                                  &data);
1733             krb5_pac_free(context, p);
1734             if (ret) {
1735                 kdc_log(context, config, 0, "PAC signing failed for -- %s",
1736                         client_name);
1737                 goto out;
1738             }
1739
1740             ret = _kdc_tkt_add_if_relevant_ad(context, &et,
1741                                               KRB5_AUTHDATA_WIN2K_PAC,
1742                                               &data);
1743             krb5_data_free(&data);
1744             if (ret)
1745                 goto out;
1746         }
1747     }
1748
1749     _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttime,
1750                        et.endtime, et.renew_till);
1751
1752     /* do this as the last thing since this signs the EncTicketPart */
1753     ret = _kdc_add_KRB5SignedPath(context,
1754                                   config,
1755                                   server,
1756                                   setype,
1757                                   NULL,
1758                                   NULL,
1759                                   &et);
1760     if (ret)
1761         goto out;
1762
1763     ret = _kdc_encode_reply(context, config,
1764                             &rep, &et, &ek, setype, server->entry.kvno,
1765                             &skey->key, client->entry.kvno,
1766                             reply_key, &e_text, reply);
1767     free_EncTicketPart(&et);
1768     free_EncKDCRepPart(&ek);
1769     if (ret)
1770         goto out;
1771
1772     /* */
1773     if (datagram_reply && reply->length > config->max_datagram_reply_length) {
1774         krb5_data_free(reply);
1775         ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
1776         e_text = "Reply packet too large";
1777     }
1778
1779 out:
1780     free_AS_REP(&rep);
1781     if(ret){
1782         krb5_mk_error(context,
1783                       ret,
1784                       e_text,
1785                       (e_data.data ? &e_data : NULL),
1786                       client_princ,
1787                       server_princ,
1788                       NULL,
1789                       NULL,
1790                       reply);
1791         ret = 0;
1792     }
1793 #ifdef PKINIT
1794     if (pkp)
1795         _kdc_pk_free_client_param(context, pkp);
1796 #endif
1797     if (e_data.data)
1798         free(e_data.data);
1799     if (client_princ)
1800         krb5_free_principal(context, client_princ);
1801     free(client_name);
1802     if (server_princ)
1803         krb5_free_principal(context, server_princ);
1804     free(server_name);
1805     if(client)
1806         _kdc_free_ent(context, client);
1807     if(server)
1808         _kdc_free_ent(context, server);
1809     return ret;
1810 }
1811
1812 /*
1813  * Add the AuthorizationData `data´ of `type´ to the last element in
1814  * the sequence of authorization_data in `tkt´ wrapped in an IF_RELEVANT
1815  */
1816
1817 krb5_error_code
1818 _kdc_tkt_add_if_relevant_ad(krb5_context context,
1819                             EncTicketPart *tkt,
1820                             int type,
1821                             const krb5_data *data)
1822 {
1823     krb5_error_code ret;
1824     size_t size;
1825
1826     if (tkt->authorization_data == NULL) {
1827         tkt->authorization_data = calloc(1, sizeof(*tkt->authorization_data));
1828         if (tkt->authorization_data == NULL) {
1829             krb5_set_error_message(context, ENOMEM, "out of memory");
1830             return ENOMEM;
1831         }
1832     }
1833         
1834     /* add the entry to the last element */
1835     {
1836         AuthorizationData ad = { 0, NULL };
1837         AuthorizationDataElement ade;
1838
1839         ade.ad_type = type;
1840         ade.ad_data = *data;
1841
1842         ret = add_AuthorizationData(&ad, &ade);
1843         if (ret) {
1844             krb5_set_error_message(context, ret, "add AuthorizationData failed");
1845             return ret;
1846         }
1847
1848         ade.ad_type = KRB5_AUTHDATA_IF_RELEVANT;
1849
1850         ASN1_MALLOC_ENCODE(AuthorizationData,
1851                            ade.ad_data.data, ade.ad_data.length,
1852                            &ad, &size, ret);
1853         free_AuthorizationData(&ad);
1854         if (ret) {
1855             krb5_set_error_message(context, ret, "ASN.1 encode of "
1856                                    "AuthorizationData failed");
1857             return ret;
1858         }
1859         if (ade.ad_data.length != size)
1860             krb5_abortx(context, "internal asn.1 encoder error");
1861         
1862         ret = add_AuthorizationData(tkt->authorization_data, &ade);
1863         der_free_octet_string(&ade.ad_data);
1864         if (ret) {
1865             krb5_set_error_message(context, ret, "add AuthorizationData failed");
1866             return ret;
1867         }
1868     }
1869
1870     return 0;
1871 }