auth: For NTLM and KDC authentication, log the authentication duration
[samba.git] / source4 / heimdal / kdc / kerberos5.c
index 2a2c48c233a657d3138b29b37865e2a05155e6b8..12187dde4299de7c8ce5b7f3bafae39ee557354d 100644 (file)
@@ -1,40 +1,38 @@
 /*
- * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden). 
- * All rights reserved. 
+ * Copyright (c) 1997-2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
  *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met: 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
  *
- * 1. Redistributions of source code must retain the above copyright 
- *    notice, this list of conditions and the following disclaimer. 
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
  *
- * 2. Redistributions in binary form must reproduce the above copyright 
- *    notice, this list of conditions and the following disclaimer in the 
- *    documentation and/or other materials provided with the distribution. 
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
  *
- * 3. Neither the name of the Institute nor the names of its contributors 
- *    may be used to endorse or promote products derived from this software 
- *    without specific prior written permission. 
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
- * SUCH DAMAGE. 
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
 
 #include "kdc_locl.h"
 
-RCSID("$Id: kerberos5.c 23316 2008-06-23 04:32:32Z lha $");
-
 #define MAX_TIME ((time_t)((1U << 31) - 1))
 
 void
@@ -60,13 +58,13 @@ realloc_method_data(METHOD_DATA *md)
 }
 
 static void
-set_salt_padata (METHOD_DATA *md, Salt *salt)
+set_salt_padata(METHOD_DATA *md, Salt *salt)
 {
     if (salt) {
-       realloc_method_data(md);
-       md->val[md->len - 1].padata_type = salt->type;
-       der_copy_octet_string(&salt->salt,
-                             &md->val[md->len - 1].padata_value);
+       realloc_method_data(md);
+       md->val[md->len - 1].padata_type = salt->type;
+       der_copy_octet_string(&salt->salt,
+                             &md->val[md->len - 1].padata_value);
     }
 }
 
@@ -76,14 +74,32 @@ _kdc_find_padata(const KDC_REQ *req, int *start, int type)
     if (req->padata == NULL)
        return NULL;
 
-    while(*start < req->padata->len){
+    while((size_t)*start < req->padata->len){
        (*start)++;
-       if(req->padata->val[*start - 1].padata_type == type)
+       if(req->padata->val[*start - 1].padata_type == (unsigned)type)
            return &req->padata->val[*start - 1];
     }
     return NULL;
 }
 
+/*
+ * This is a hack to allow predefined weak services, like afs to
+ * still use weak types
+ */
+
+krb5_boolean
+_kdc_is_weak_exception(krb5_principal principal, krb5_enctype etype)
+{
+    if (principal->name.name_string.len > 0 &&
+       strcmp(principal->name.name_string.val[0], "afs") == 0 &&
+       (etype == ETYPE_DES_CBC_CRC
+        || etype == ETYPE_DES_CBC_MD4
+        || etype == ETYPE_DES_CBC_MD5))
+       return TRUE;
+    return FALSE;
+}
+
+
 /*
  * Detect if `key' is the using the the precomputed `default_salt'.
  */
@@ -107,36 +123,103 @@ is_default_salt_p(const krb5_salt *default_salt, const Key *key)
  */
 
 krb5_error_code
-_kdc_find_etype(krb5_context context, const hdb_entry_ex *princ,
-               krb5_enctype *etypes, unsigned len, 
-               Key **ret_key, krb5_enctype *ret_etype)
+_kdc_find_etype(krb5_context context, krb5_boolean use_strongest_session_key,
+               krb5_boolean is_preauth, hdb_entry_ex *princ,
+               krb5_enctype *etypes, unsigned len,
+               krb5_enctype *ret_enctype, Key **ret_key)
 {
-    int i;
-    krb5_error_code ret = KRB5KDC_ERR_ETYPE_NOSUPP;
+    krb5_error_code ret;
     krb5_salt def_salt;
+    krb5_enctype enctype = ETYPE_NULL;
+    Key *key;
+    int i;
 
-    krb5_get_pw_salt (context, princ->entry.principal, &def_salt);
+    /* We'll want to avoid keys with v4 salted keys in the pre-auth case... */
+    ret = krb5_get_pw_salt(context, princ->entry.principal, &def_salt);
+    if (ret)
+       return ret;
 
-    for(i = 0; ret != 0 && i < len ; i++) {
-       Key *key = NULL;
+    ret = KRB5KDC_ERR_ETYPE_NOSUPP;
 
-       if (krb5_enctype_valid(context, etypes[i]) != 0)
-           continue;
+    if (use_strongest_session_key) {
+       const krb5_enctype *p;
+       krb5_enctype clientbest = ETYPE_NULL;
+       int j;
+
+       /*
+        * Pick the strongest key that the KDC, target service, and
+        * client all support, using the local cryptosystem enctype
+        * list in strongest-to-weakest order to drive the search.
+        *
+        * This is not what RFC4120 says to do, but it encourages
+        * adoption of stronger enctypes.  This doesn't play well with
+        * clients that have multiple Kerberos client implementations
+        * available with different supported enctype lists.
+        */
 
-       while (hdb_next_enctype2key(context, &princ->entry, etypes[i], &key) == 0) {
-           if (key->key.keyvalue.length == 0) {
-               ret = KRB5KDC_ERR_NULL_KEY;
+       /* drive the search with local supported enctypes list */
+       p = krb5_kerberos_enctypes(context);
+       for (i = 0; p[i] != ETYPE_NULL && enctype == ETYPE_NULL; i++) {
+           if (krb5_enctype_valid(context, p[i]) != 0)
                continue;
+
+           /* check that the client supports it too */
+           for (j = 0; j < len && enctype == ETYPE_NULL; j++) {
+               if (p[i] != etypes[j])
+                   continue;
+               /* save best of union of { client, crypto system } */
+               if (clientbest == ETYPE_NULL)
+                   clientbest = p[i];
+               /* check target princ support */
+               ret = hdb_enctype2key(context, &princ->entry, p[i], &key);
+               if (ret)
+                   continue;
+               if (is_preauth && !is_default_salt_p(&def_salt, key))
+                   continue;
+               enctype = p[i];
            }
-           *ret_key   = key;
-           *ret_etype = etypes[i];
-           ret = 0;
-           if (is_default_salt_p(&def_salt, key)) {
-               krb5_free_salt (context, def_salt);
-               return ret;
+       }
+       if (clientbest != ETYPE_NULL && enctype == ETYPE_NULL)
+           enctype = clientbest;
+       else if (enctype == ETYPE_NULL)
+           ret = KRB5KDC_ERR_ETYPE_NOSUPP;
+       if (ret == 0 && ret_enctype != NULL)
+           *ret_enctype = enctype;
+       if (ret == 0 && ret_key != NULL)
+           *ret_key = key;
+    } else {
+       /*
+        * Pick the first key from the client's enctype list that is
+        * supported by the cryptosystem and by the given principal.
+        *
+        * RFC4120 says we SHOULD pick the first _strong_ key from the
+        * client's list... not the first key...  If the admin disallows
+        * weak enctypes in krb5.conf and selects this key selection
+        * algorithm, then we get exactly what RFC4120 says.
+        */
+       for(key = NULL, i = 0; ret != 0 && i < len; i++, key = NULL) {
+
+           if (krb5_enctype_valid(context, etypes[i]) != 0 &&
+               !_kdc_is_weak_exception(princ->entry.principal, etypes[i]))
+               continue;
+
+           while (hdb_next_enctype2key(context, &princ->entry, etypes[i], &key) == 0) {
+               if (key->key.keyvalue.length == 0) {
+                   ret = KRB5KDC_ERR_NULL_KEY;
+                   continue;
+               }
+               if (ret_key != NULL)
+                   *ret_key = key;
+               if (ret_enctype != NULL)
+                   *ret_enctype = etypes[i];
+               ret = 0;
+               if (is_preauth && is_default_salt_p(&def_salt, key))
+                   goto out;
            }
        }
     }
+
+out:
     krb5_free_salt (context, def_salt);
     return ret;
 }
@@ -159,44 +242,44 @@ _kdc_make_anonymous_principalname (PrincipalName *pn)
 }
 
 void
-_kdc_log_timestamp(krb5_context context, 
+_kdc_log_timestamp(krb5_context context,
                   krb5_kdc_configuration *config,
                   const char *type,
-                  KerberosTime authtime, KerberosTime *starttime, 
+                  KerberosTime authtime, KerberosTime *starttime,
                   KerberosTime endtime, KerberosTime *renew_till)
 {
-    char authtime_str[100], starttime_str[100], 
+    char authtime_str[100], starttime_str[100],
        endtime_str[100], renewtime_str[100];
-    
-    krb5_format_time(context, authtime, 
-                    authtime_str, sizeof(authtime_str), TRUE); 
+
+    krb5_format_time(context, authtime,
+                    authtime_str, sizeof(authtime_str), TRUE);
     if (starttime)
-       krb5_format_time(context, *starttime, 
-                        starttime_str, sizeof(starttime_str), TRUE); 
+       krb5_format_time(context, *starttime,
+                        starttime_str, sizeof(starttime_str), TRUE);
     else
        strlcpy(starttime_str, "unset", sizeof(starttime_str));
-    krb5_format_time(context, endtime, 
-                    endtime_str, sizeof(endtime_str), TRUE); 
+    krb5_format_time(context, endtime,
+                    endtime_str, sizeof(endtime_str), TRUE);
     if (renew_till)
-       krb5_format_time(context, *renew_till, 
-                        renewtime_str, sizeof(renewtime_str), TRUE); 
+       krb5_format_time(context, *renew_till,
+                        renewtime_str, sizeof(renewtime_str), TRUE);
     else
        strlcpy(renewtime_str, "unset", sizeof(renewtime_str));
-    
+
     kdc_log(context, config, 5,
            "%s authtime: %s starttime: %s endtime: %s renew till: %s",
            type, authtime_str, starttime_str, endtime_str, renewtime_str);
 }
 
 static void
-log_patypes(krb5_context context, 
+log_patypes(krb5_context context,
            krb5_kdc_configuration *config,
            METHOD_DATA *padata)
 {
     struct rk_strpool *p = NULL;
     char *str;
-    int i;
-           
+    size_t i;
+
     for (i = 0; i < padata->len; i++) {
        switch(padata->val[i].padata_type) {
        case KRB5_PADATA_PK_AS_REQ:
@@ -224,7 +307,7 @@ log_patypes(krb5_context context,
     }
     if (p == NULL)
        p = rk_strpoolprintf(p, "none");
-       
+
     str = rk_strpoolcollect(p);
     kdc_log(context, config, 0, "Client sent patypes: %s", str);
     free(str);
@@ -238,23 +321,25 @@ log_patypes(krb5_context context,
 krb5_error_code
 _kdc_encode_reply(krb5_context context,
                  krb5_kdc_configuration *config,
-                 KDC_REP *rep, const EncTicketPart *et, EncKDCRepPart *ek, 
-                 krb5_enctype etype, 
+                 KDC_REP *rep, const EncTicketPart *et, EncKDCRepPart *ek,
+                 krb5_enctype etype,
                  int skvno, const EncryptionKey *skey,
-                 int ckvno, const EncryptionKey *ckey,
+                 int ckvno, const EncryptionKey *reply_key,
+                 int rk_is_subkey,
                  const char **e_text,
                  krb5_data *reply)
 {
     unsigned char *buf;
     size_t buf_size;
-    size_t len;
+    size_t len = 0;
     krb5_error_code ret;
     krb5_crypto crypto;
 
     ASN1_MALLOC_ENCODE(EncTicketPart, buf, buf_size, et, &len, ret);
     if(ret) {
-       kdc_log(context, config, 0, "Failed to encode ticket: %s", 
-               krb5_get_err_text(context, ret));
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "Failed to encode ticket: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
     if(buf_size != len) {
@@ -266,13 +351,15 @@ _kdc_encode_reply(krb5_context context,
 
     ret = krb5_crypto_init(context, skey, etype, &crypto);
     if (ret) {
+        const char *msg;
        free(buf);
-       kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-               krb5_get_err_text(context, ret));
+       msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
 
-    ret = krb5_encrypt_EncryptedData(context, 
+    ret = krb5_encrypt_EncryptedData(context,
                                     crypto,
                                     KRB5_KU_TICKET,
                                     buf,
@@ -282,18 +369,20 @@ _kdc_encode_reply(krb5_context context,
     free(buf);
     krb5_crypto_destroy(context, crypto);
     if(ret) {
-       kdc_log(context, config, 0, "Failed to encrypt data: %s",
-               krb5_get_err_text(context, ret));
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "Failed to encrypt data: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
-    
+
     if(rep->msg_type == krb_as_rep && !config->encode_as_rep_as_tgs_rep)
        ASN1_MALLOC_ENCODE(EncASRepPart, buf, buf_size, ek, &len, ret);
     else
        ASN1_MALLOC_ENCODE(EncTGSRepPart, buf, buf_size, ek, &len, ret);
     if(ret) {
-       kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", 
-               krb5_get_err_text(context, ret));
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
     if(buf_size != len) {
@@ -302,11 +391,12 @@ _kdc_encode_reply(krb5_context context,
        *e_text = "KDC internal error";
        return KRB5KRB_ERR_GENERIC;
     }
-    ret = krb5_crypto_init(context, ckey, 0, &crypto);
+    ret = krb5_crypto_init(context, reply_key, 0, &crypto);
     if (ret) {
+       const char *msg = krb5_get_error_message(context, ret);
        free(buf);
-       kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-               krb5_get_err_text(context, ret));
+       kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
     if(rep->msg_type == krb_as_rep) {
@@ -322,7 +412,7 @@ _kdc_encode_reply(krb5_context context,
     } else {
        krb5_encrypt_EncryptedData(context,
                                   crypto,
-                                  KRB5_KU_TGS_REP_ENC_PART_SESSION,
+                                  rk_is_subkey ? KRB5_KU_TGS_REP_ENC_PART_SUB_KEY : KRB5_KU_TGS_REP_ENC_PART_SESSION,
                                   buf,
                                   len,
                                   ckvno,
@@ -332,8 +422,9 @@ _kdc_encode_reply(krb5_context context,
     }
     krb5_crypto_destroy(context, crypto);
     if(ret) {
-       kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", 
-               krb5_get_err_text(context, ret));
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "Failed to encode KDC-REP: %s", msg);
+       krb5_free_error_message(context, msg);
        return ret;
     }
     if(buf_size != len) {
@@ -362,7 +453,7 @@ older_enctype(krb5_enctype enctype)
     case ETYPE_DES3_CBC_SHA1:
     case ETYPE_ARCFOUR_HMAC_MD5:
     case ETYPE_ARCFOUR_HMAC_MD5_56:
-    /* 
+    /*
      * The following three is "old" windows enctypes and is needed for
      * windows 2000 hosts.
      */
@@ -375,18 +466,6 @@ older_enctype(krb5_enctype enctype)
     }
 }
 
-static int
-only_older_enctype_p(const KDC_REQ *req)
-{
-    int i;
-
-    for(i = 0; i < req->req_body.etype.len; i++) {
-       if (!older_enctype(req->req_body.etype.val[i]))
-           return 0;
-    }
-    return 1;
-}
-
 /*
  *
  */
@@ -404,7 +483,7 @@ make_etype_info_entry(krb5_context context, ETYPE_INFO_ENTRY *ent, Key *key)
        else if(key->salt->type == hdb_afs3_salt)
            *ent->salttype = 2;
        else {
-           kdc_log(context, config, 0, "unknown salt-type: %d", 
+           kdc_log(context, config, 0, "unknown salt-type: %d",
                    key->salt->type);
            return KRB5KRB_ERR_GENERIC;
        }
@@ -417,7 +496,7 @@ make_etype_info_entry(krb5_context context, ETYPE_INFO_ENTRY *ent, Key *key)
        ALLOC(ent->salttype);
        *ent->salttype = key->salt->type;
 #else
-       /* 
+       /*
         * We shouldn't sent salttype since it is incompatible with the
         * specification and it breaks windows clients.  The afs
         * salting problem is solved by using KRB5-PADATA-AFS3-SALT
@@ -440,74 +519,25 @@ make_etype_info_entry(krb5_context context, ETYPE_INFO_ENTRY *ent, Key *key)
 }
 
 static krb5_error_code
-get_pa_etype_info(krb5_context context, 
+get_pa_etype_info(krb5_context context,
                  krb5_kdc_configuration *config,
-                 METHOD_DATA *md, hdb_entry *client, 
-                 ENCTYPE *etypes, unsigned int etypes_len)
+                 METHOD_DATA *md, Key *ckey)
 {
     krb5_error_code ret = 0;
-    int i, j;
-    unsigned int n = 0;
     ETYPE_INFO pa;
     unsigned char *buf;
     size_t len;
-    
 
-    pa.len = client->keys.len;
-    if(pa.len > UINT_MAX/sizeof(*pa.val))
-       return ERANGE;
-    pa.val = malloc(pa.len * sizeof(*pa.val));
+
+    pa.len = 1;
+    pa.val = calloc(1, sizeof(pa.val[0]));
     if(pa.val == NULL)
        return ENOMEM;
-    memset(pa.val, 0, pa.len * sizeof(*pa.val));
-
-    for(i = 0; i < client->keys.len; i++) {
-       for (j = 0; j < n; j++)
-           if (pa.val[j].etype == client->keys.val[i].key.keytype)
-               goto skip1;
-       for(j = 0; j < etypes_len; j++) {
-           if(client->keys.val[i].key.keytype == etypes[j]) {
-               if (krb5_enctype_valid(context, etypes[j]) != 0)
-                   continue;
-               if (!older_enctype(etypes[j]))
-                   continue;
-               if (n >= pa.len)
-                   krb5_abortx(context, "internal error: n >= p.len");
-               if((ret = make_etype_info_entry(context, 
-                                               &pa.val[n++], 
-                                               &client->keys.val[i])) != 0) {
-                   free_ETYPE_INFO(&pa);
-                   return ret;
-               }
-               break;
-           }
-       }
-    skip1:;
-    }
-    for(i = 0; i < client->keys.len; i++) {
-       /* already added? */
-       for(j = 0; j < etypes_len; j++) {
-           if(client->keys.val[i].key.keytype == etypes[j])
-               goto skip2;
-       }
-       if (krb5_enctype_valid(context, client->keys.val[i].key.keytype) != 0)
-           continue;
-       if (!older_enctype(etypes[j]))
-           continue;
-       if (n >= pa.len)
-           krb5_abortx(context, "internal error: n >= p.len");
-       if((ret = make_etype_info_entry(context, 
-                                       &pa.val[n++], 
-                                       &client->keys.val[i])) != 0) {
-           free_ETYPE_INFO(&pa);
-           return ret;
-       }
-    skip2:;
-    }
-    
-    if(n < pa.len) {
-       /* stripped out dups, newer enctypes, and not valid enctypes */
-       pa.len = n;
+
+    ret = make_etype_info_entry(context, &pa.val[0], ckey);
+    if (ret) {
+       free_ETYPE_INFO(&pa);
+       return ret;
     }
 
     ASN1_MALLOC_ENCODE(ETYPE_INFO, buf, len, &pa, &len, ret);
@@ -565,8 +595,8 @@ make_etype_info2_entry(ETYPE_INFO2_ENTRY *ent, Key *key)
            ent->s2kparams = NULL;
            return ENOMEM;
        }
-       _krb5_put_int(ent->s2kparams->data, 
-                     _krb5_AES_string_to_default_iterator, 
+       _krb5_put_int(ent->s2kparams->data,
+                     _krb5_AES_string_to_default_iterator,
                      ent->s2kparams->length);
        break;
     case ETYPE_DES_CBC_CRC:
@@ -584,7 +614,7 @@ make_etype_info2_entry(ETYPE_INFO2_ENTRY *ent, Key *key)
                ent->s2kparams = NULL;
                return ENOMEM;
            }
-           _krb5_put_int(ent->s2kparams->data, 
+           _krb5_put_int(ent->s2kparams->data,
                          1,
                          ent->s2kparams->length);
        }
@@ -602,68 +632,24 @@ make_etype_info2_entry(ETYPE_INFO2_ENTRY *ent, Key *key)
  */
 
 static krb5_error_code
-get_pa_etype_info2(krb5_context context, 
+get_pa_etype_info2(krb5_context context,
                   krb5_kdc_configuration *config,
-                  METHOD_DATA *md, hdb_entry *client, 
-                  ENCTYPE *etypes, unsigned int etypes_len)
+                  METHOD_DATA *md, Key *ckey)
 {
     krb5_error_code ret = 0;
-    int i, j;
-    unsigned int n = 0;
     ETYPE_INFO2 pa;
     unsigned char *buf;
     size_t len;
 
-    pa.len = client->keys.len;
-    if(pa.len > UINT_MAX/sizeof(*pa.val))
-       return ERANGE;
-    pa.val = malloc(pa.len * sizeof(*pa.val));
+    pa.len = 1;
+    pa.val = calloc(1, sizeof(pa.val[0]));
     if(pa.val == NULL)
        return ENOMEM;
-    memset(pa.val, 0, pa.len * sizeof(*pa.val));
-
-    for(i = 0; i < client->keys.len; i++) {
-       for (j = 0; j < n; j++)
-           if (pa.val[j].etype == client->keys.val[i].key.keytype)
-               goto skip1;
-       for(j = 0; j < etypes_len; j++) {
-           if(client->keys.val[i].key.keytype == etypes[j]) {
-               if (krb5_enctype_valid(context, etypes[j]) != 0)
-                   continue;
-               if (n >= pa.len)
-                   krb5_abortx(context, "internal error: n >= p.len");
-               if((ret = make_etype_info2_entry(&pa.val[n++], 
-                                                &client->keys.val[i])) != 0) {
-                   free_ETYPE_INFO2(&pa);
-                   return ret;
-               }
-               break;
-           }
-       }
-    skip1:;
-    }
-    /* send enctypes that the client doesn't know about too */
-    for(i = 0; i < client->keys.len; i++) {
-       /* already added? */
-       for(j = 0; j < etypes_len; j++) {
-           if(client->keys.val[i].key.keytype == etypes[j])
-               goto skip2;
-       }
-       if (krb5_enctype_valid(context, client->keys.val[i].key.keytype) != 0)
-           continue;
-       if (n >= pa.len)
-           krb5_abortx(context, "internal error: n >= p.len");
-       if((ret = make_etype_info2_entry(&pa.val[n++],
-                                        &client->keys.val[i])) != 0) {
-           free_ETYPE_INFO2(&pa);
-           return ret;
-       }
-      skip2:;
-    }
-    
-    if(n < pa.len) {
-       /* stripped out dups, and not valid enctypes */
-       pa.len = n;
+
+    ret = make_etype_info2_entry(&pa.val[0], ckey);
+    if (ret) {
+       free_ETYPE_INFO2(&pa);
+       return ret;
     }
 
     ASN1_MALLOC_ENCODE(ETYPE_INFO2, buf, len, &pa, &len, ret);
@@ -693,10 +679,12 @@ log_as_req(krb5_context context,
           const KDC_REQ_BODY *b)
 {
     krb5_error_code ret;
-    struct rk_strpool *p = NULL;
+    struct rk_strpool *p;
     char *str;
-    int i;
-    
+    size_t i;
+
+    p = rk_strpoolprintf(NULL, "%s", "Client supported enctypes: ");
+
     for (i = 0; i < b->etype.len; i++) {
        ret = krb5_enctype_to_string(context, b->etype.val[i], &str);
        if (ret == 0) {
@@ -713,10 +701,6 @@ log_as_req(krb5_context context,
     }
     if (p == NULL)
        p = rk_strpoolprintf(p, "no encryption types");
-    
-    str = rk_strpoolcollect(p);
-    kdc_log(context, config, 0, "Client supported enctypes: %s", str);
-    free(str);
 
     {
        char *cet;
@@ -726,21 +710,26 @@ log_as_req(krb5_context context,
        if(ret == 0) {
            ret = krb5_enctype_to_string(context, setype, &set);
            if (ret == 0) {
-               kdc_log(context, config, 5, "Using %s/%s", cet, set);
+               p = rk_strpoolprintf(p, ", using %s/%s", cet, set);
                free(set);
            }
            free(cet);
        }
        if (ret != 0)
-           kdc_log(context, config, 5, "Using e-types %d/%d", cetype, setype);
+           p = rk_strpoolprintf(p, ", using enctypes %d/%d",
+                                cetype, setype);
     }
-    
+
+    str = rk_strpoolcollect(p);
+    kdc_log(context, config, 0, "%s", str);
+    free(str);
+
     {
        char fixedstr[128];
-       unparse_flags(KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(), 
+       unparse_flags(KDCOptions2int(b->kdc_options), asn1_KDCOptions_units(),
                      fixedstr, sizeof(fixedstr));
        if(*fixedstr)
-           kdc_log(context, config, 2, "Requested flags: %s", fixedstr);
+           kdc_log(context, config, 0, "Requested flags: %s", fixedstr);
     }
 }
 
@@ -751,65 +740,76 @@ log_as_req(krb5_context context,
  */
 
 krb5_error_code
-_kdc_check_flags(krb5_context context, 
-                krb5_kdc_configuration *config,
-                hdb_entry_ex *client_ex, const char *client_name,
-                hdb_entry_ex *server_ex, const char *server_name,
-                krb5_boolean is_as_req)
+kdc_check_flags(krb5_context context,
+               krb5_kdc_configuration *config,
+               hdb_entry_ex *client_ex, const char *client_name,
+               hdb_entry_ex *server_ex, const char *server_name,
+               krb5_boolean is_as_req)
 {
     if(client_ex != NULL) {
        hdb_entry *client = &client_ex->entry;
 
        /* check client */
+       if (client->flags.locked_out) {
+           kdc_log(context, config, 0,
+                   "Client (%s) is locked out", client_name);
+           return KRB5KDC_ERR_CLIENT_REVOKED;
+       }
+
        if (client->flags.invalid) {
-           kdc_log(context, config, 0, 
+           kdc_log(context, config, 0,
                    "Client (%s) has invalid bit set", client_name);
            return KRB5KDC_ERR_POLICY;
        }
-       
-       if(!client->flags.client){
+
+       if (!is_as_req && !client->flags.client){
            kdc_log(context, config, 0,
-                   "Principal may not act as client -- %s", client_name);
+                   "Principal may only act as client in AS-REQ -- %s", client_name);
            return KRB5KDC_ERR_POLICY;
        }
-       
+
        if (client->valid_start && *client->valid_start > kdc_time) {
            char starttime_str[100];
-           krb5_format_time(context, *client->valid_start, 
-                            starttime_str, sizeof(starttime_str), TRUE); 
+           krb5_format_time(context, *client->valid_start,
+                            starttime_str, sizeof(starttime_str), TRUE);
            kdc_log(context, config, 0,
-                   "Client not yet valid until %s -- %s", 
+                   "Client not yet valid until %s -- %s",
                    starttime_str, client_name);
            return KRB5KDC_ERR_CLIENT_NOTYET;
        }
-       
+
        if (client->valid_end && *client->valid_end < kdc_time) {
            char endtime_str[100];
-           krb5_format_time(context, *client->valid_end, 
-                            endtime_str, sizeof(endtime_str), TRUE); 
+           krb5_format_time(context, *client->valid_end,
+                            endtime_str, sizeof(endtime_str), TRUE);
            kdc_log(context, config, 0,
                    "Client expired at %s -- %s",
                    endtime_str, client_name);
            return KRB5KDC_ERR_NAME_EXP;
        }
-       
-       if (client->pw_end && *client->pw_end < kdc_time 
+
+       if (client->pw_end && *client->pw_end < kdc_time
            && (server_ex == NULL || !server_ex->entry.flags.change_pw)) {
            char pwend_str[100];
-           krb5_format_time(context, *client->pw_end, 
-                            pwend_str, sizeof(pwend_str), TRUE); 
+           krb5_format_time(context, *client->pw_end,
+                            pwend_str, sizeof(pwend_str), TRUE);
            kdc_log(context, config, 0,
-                   "Client's key has expired at %s -- %s", 
+                   "Client's key has expired at %s -- %s",
                    pwend_str, client_name);
            return KRB5KDC_ERR_KEY_EXPIRED;
        }
     }
 
     /* check server */
-    
+
     if (server_ex != NULL) {
        hdb_entry *server = &server_ex->entry;
 
+       if (server->flags.locked_out) {
+           kdc_log(context, config, 0,
+                   "Client server locked out -- %s", server_name);
+           return KRB5KDC_ERR_POLICY;
+       }
        if (server->flags.invalid) {
            kdc_log(context, config, 0,
                    "Server has invalid flag set -- %s", server_name);
@@ -830,8 +830,8 @@ _kdc_check_flags(krb5_context context,
 
        if (server->valid_start && *server->valid_start > kdc_time) {
            char starttime_str[100];
-           krb5_format_time(context, *server->valid_start, 
-                            starttime_str, sizeof(starttime_str), TRUE); 
+           krb5_format_time(context, *server->valid_start,
+                            starttime_str, sizeof(starttime_str), TRUE);
            kdc_log(context, config, 0,
                    "Server not yet valid until %s -- %s",
                    starttime_str, server_name);
@@ -840,20 +840,20 @@ _kdc_check_flags(krb5_context context,
 
        if (server->valid_end && *server->valid_end < kdc_time) {
            char endtime_str[100];
-           krb5_format_time(context, *server->valid_end, 
-                            endtime_str, sizeof(endtime_str), TRUE); 
+           krb5_format_time(context, *server->valid_end,
+                            endtime_str, sizeof(endtime_str), TRUE);
            kdc_log(context, config, 0,
-                   "Server expired at %s -- %s", 
+                   "Server expired at %s -- %s",
                    endtime_str, server_name);
            return KRB5KDC_ERR_SERVICE_EXP;
        }
 
        if (server->pw_end && *server->pw_end < kdc_time) {
            char pwend_str[100];
-           krb5_format_time(context, *server->pw_end, 
-                            pwend_str, sizeof(pwend_str), TRUE); 
+           krb5_format_time(context, *server->pw_end,
+                            pwend_str, sizeof(pwend_str), TRUE);
            kdc_log(context, config, 0,
-                   "Server's key has expired at -- %s", 
+                   "Server's key has expired at -- %s",
                    pwend_str, server_name);
            return KRB5KDC_ERR_KEY_EXPIRED;
        }
@@ -868,7 +868,7 @@ _kdc_check_flags(krb5_context context,
  */
 
 krb5_boolean
-_kdc_check_addresses(krb5_context context,        
+_kdc_check_addresses(krb5_context context,
                     krb5_kdc_configuration *config,
                     HostAddresses *addresses, const struct sockaddr *from)
 {
@@ -876,14 +876,14 @@ _kdc_check_addresses(krb5_context context,
     krb5_address addr;
     krb5_boolean result;
     krb5_boolean only_netbios = TRUE;
-    int i;
-    
+    size_t i;
+
     if(config->check_ticket_addresses == 0)
        return TRUE;
 
     if(addresses == NULL)
        return config->allow_null_ticket_addresses;
-    
+
     for (i = 0; i < addresses->len; ++i) {
        if (addresses->val[i].addr_type != KRB5_ADDRESS_NETBIOS) {
            only_netbios = FALSE;
@@ -919,7 +919,7 @@ send_pac_p(krb5_context context, KDC_REQ *req)
     PA_PAC_REQUEST pacreq;
     const PA_DATA *pa;
     int i = 0;
-    
+
     pa = _kdc_find_padata(req, &i, KRB5_PADATA_PA_PAC_REQUEST);
     if (pa == NULL)
        return TRUE;
@@ -937,15 +937,26 @@ send_pac_p(krb5_context context, KDC_REQ *req)
     return TRUE;
 }
 
+krb5_boolean
+_kdc_is_anonymous(krb5_context context, krb5_principal principal)
+{
+    if (principal->name.name_type != KRB5_NT_WELLKNOWN ||
+       principal->name.name_string.len != 2 ||
+       strcmp(principal->name.name_string.val[0], KRB5_WELLKNOWN_NAME) != 0 ||
+       strcmp(principal->name.name_string.val[1], KRB5_ANON_NAME) != 0)
+       return 0;
+    return 1;
+}
+
 /*
  *
  */
 
 krb5_error_code
-_kdc_as_rep(krb5_context context, 
+_kdc_as_rep(krb5_context context,
            krb5_kdc_configuration *config,
-           KDC_REQ *req, 
-           const krb5_data *req_buffer, 
+           KDC_REQ *req,
+           const krb5_data *req_buffer,
            krb5_data *reply,
            const char *from,
            struct sockaddr *from_addr,
@@ -955,7 +966,8 @@ _kdc_as_rep(krb5_context context,
     AS_REP rep;
     KDCOptions f = b->kdc_options;
     hdb_entry_ex *client = NULL, *server = NULL;
-    krb5_enctype cetype, setype, sessionetype;
+    HDB *clientdb = NULL;
+    krb5_enctype setype, sessionetype;
     krb5_data e_data;
     EncTicketPart et;
     EncKDCRepPart ek;
@@ -964,16 +976,22 @@ _kdc_as_rep(krb5_context context,
     krb5_error_code ret = 0;
     const char *e_text = NULL;
     krb5_crypto crypto;
-    Key *ckey, *skey;
-    EncryptionKey *reply_key;
-    int flags = 0;
+    Key *skey = NULL;
+    EncryptionKey *reply_key = NULL, session_key;
+    int flags = HDB_F_FOR_AS_REQ;
 #ifdef PKINIT
     pk_client_params *pkp = NULL;
 #endif
+    const EncryptionKey *pk_reply_key = NULL;
 
     memset(&rep, 0, sizeof(rep));
+    memset(&session_key, 0, sizeof(session_key));
     krb5_data_zero(&e_data);
 
+    ALLOC(rep.padata);
+    rep.padata->len = 0;
+    rep.padata->val = NULL;
+
     if (f.canonicalize)
        flags |= HDB_F_CANON;
 
@@ -989,37 +1007,21 @@ _kdc_as_rep(krb5_context context,
            ret = krb5_unparse_name(context, server_princ, &server_name);
     }
     if (ret) {
-       kdc_log(context, config, 0, 
+       kdc_log(context, config, 0,
                "AS-REQ malformed server name from %s", from);
        goto out;
     }
-    
     if(b->cname == NULL){
        ret = KRB5KRB_ERR_GENERIC;
        e_text = "No client in request";
     } else {
+       ret = _krb5_principalname2krb5_principal (context,
+                                                 &client_princ,
+                                                 *(b->cname),
+                                                 b->realm);
+       if (ret)
+           goto out;
 
-       if (b->cname->name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
-           if (b->cname->name_string.len != 1) {
-               kdc_log(context, config, 0,
-                       "AS-REQ malformed canon request from %s, "
-                       "enterprise name with %d name components", 
-                       from, b->cname->name_string.len);
-               ret = KRB5_PARSE_MALFORMED;
-               goto out;
-           }
-           ret = krb5_parse_name(context, b->cname->name_string.val[0],
-                                 &client_princ);
-           if (ret)
-               goto out;
-       } else {
-           ret = _krb5_principalname2krb5_principal (context,
-                                                     &client_princ,
-                                                     *(b->cname),
-                                                     b->realm);
-           if (ret)
-               goto out;
-       }
        ret = krb5_unparse_name(context, client_princ, &client_name);
     }
     if (ret) {
@@ -1028,42 +1030,124 @@ _kdc_as_rep(krb5_context context,
        goto out;
     }
 
-    kdc_log(context, config, 0, "AS-REQ %s from %s for %s", 
+    kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
            client_name, from, server_name);
 
-    ret = _kdc_db_fetch(context, config, client_princ, 
-                       HDB_F_GET_CLIENT | flags, NULL, &client);
-    if(ret){
-       kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name,
-               krb5_get_err_text(context, ret));
+    /*
+     *
+     */
+
+    if (_kdc_is_anonymous(context, client_princ)) {
+       if (!b->kdc_options.request_anonymous) {
+           kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
+           ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
+           goto out;
+       }
+    } else if (b->kdc_options.request_anonymous) {
+       kdc_log(context, config, 0,
+               "Request for a anonymous ticket with non "
+               "anonymous client name: %s", client_name);
        ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
        goto out;
     }
 
-    ret = _kdc_db_fetch(context, config, server_princ,
-                       HDB_F_GET_SERVER|HDB_F_GET_KRBTGT,
-                       NULL, &server);
-    if(ret){
-       kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name,
-               krb5_get_err_text(context, ret));
-       ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
+    /*
+     *
+     */
+
+    ret = _kdc_db_fetch(context, config, client_princ,
+                       HDB_F_GET_ANY | flags, NULL,
+                       &clientdb, &client);
+    if(ret == HDB_ERR_NOT_FOUND_HERE) {
+       kdc_log(context, config, 5, "client %s does not have secrets at this KDC, need to proxy", client_name);
        goto out;
-    }
+    } else if (ret == HDB_ERR_WRONG_REALM) {
+       char *fixed_client_name = NULL;
 
-    ret = _kdc_windc_client_access(context, client, req, &e_data);
-    if(ret)
+       ret = krb5_unparse_name(context, client->entry.principal,
+                               &fixed_client_name);
+       if (ret) {
+           goto out;
+       }
+
+       kdc_log(context, config, 0, "WRONG_REALM - %s -> %s",
+               client_name, fixed_client_name);
+       free(fixed_client_name);
+
+       ret = krb5_mk_error_ext(context,
+                               KRB5_KDC_ERR_WRONG_REALM,
+                               NULL, /* e_text */
+                               NULL, /* e_data */
+                               server_princ,
+                               NULL, /* client_name */
+                               &client->entry.principal->realm,
+                               NULL, /* client_time */
+                               NULL, /* client_usec */
+                               reply);
        goto out;
+    } else if(ret){
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "UNKNOWN -- %s: %s", client_name, msg);
+       krb5_free_error_message(context, msg);
+       ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
 
-    ret = _kdc_check_flags(context, config, 
-                          client, client_name,
-                          server, server_name,
-                          TRUE);
-    if(ret)
+       if (config->db[0] && config->db[0]->hdb_auth_status)
+               (config->db[0]->hdb_auth_status)(context, config->db[0], NULL,
+                                                from_addr,
+                                                &_kdc_now,
+                                                client_name,
+                                                NULL,
+                                                HDB_AUTH_CLIENT_UNKNOWN);
+       goto out;
+    }
+    ret = _kdc_db_fetch(context, config, server_princ,
+                       HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,
+                       NULL, NULL, &server);
+    if(ret == HDB_ERR_NOT_FOUND_HERE) {
+       kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy", server_name);
+       goto out;
+    } else if(ret){
+       const char *msg = krb5_get_error_message(context, ret);
+       kdc_log(context, config, 0, "UNKNOWN -- %s: %s", server_name, msg);
+       krb5_free_error_message(context, msg);
+       ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
        goto out;
+    }
 
     memset(&et, 0, sizeof(et));
     memset(&ek, 0, sizeof(ek));
 
+    /*
+     * Select a session enctype from the list of the crypto system
+     * supported enctypes that is supported by the client and is one of
+     * the enctype of the enctype of the service (likely krbtgt).
+     *
+     * The latter is used as a hint of what enctypes all KDC support,
+     * to make sure a newer version of KDC won't generate a session
+     * enctype that an older version of a KDC in the same realm can't
+     * decrypt.
+     */
+    ret = _kdc_find_etype(context, config->as_use_strongest_session_key, FALSE,
+                         client, b->etype.val, b->etype.len, &sessionetype,
+                         NULL);
+    if (ret) {
+       kdc_log(context, config, 0,
+               "Client (%s) from %s has no common enctypes with KDC "
+               "to use for the session key",
+               client_name, from);
+       goto out;
+    }
+    /*
+     * But if the KDC admin is paranoid and doesn't want to have "not
+     * the best" enctypes on the krbtgt, lets save the best pick from
+     * the client list and hope that that will work for any other
+     * KDCs.
+     */
+
+    /*
+     * Pre-auth processing
+     */
+
     if(req->padata){
        int i;
        const PA_DATA *pa;
@@ -1072,27 +1156,25 @@ _kdc_as_rep(krb5_context context,
        log_patypes(context, config, req->padata);
 
 #ifdef PKINIT
-       kdc_log(context, config, 5, 
+       kdc_log(context, config, 5,
                "Looking for PKINIT pa-data -- %s", client_name);
 
        e_text = "No PKINIT PA found";
 
        i = 0;
-       if ((pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ)))
-           ;
+       pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ);
        if (pa == NULL) {
            i = 0;
-           if((pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN)))
-               ;
+           pa = _kdc_find_padata(req, &i, KRB5_PADATA_PK_AS_REQ_WIN);
        }
        if (pa) {
            char *client_cert = NULL;
 
-           ret = _kdc_pk_rd_padata(context, config, req, pa, &pkp);
+           ret = _kdc_pk_rd_padata(context, config, req, pa, client, &pkp);
            if (ret) {
                ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
-               kdc_log(context, config, 5, 
-                       "Failed to decode PKINIT PA-DATA -- %s", 
+               kdc_log(context, config, 5,
+                       "Failed to decode PKINIT PA-DATA -- %s",
                        client_name);
                goto ts_enc;
            }
@@ -1101,6 +1183,7 @@ _kdc_as_rep(krb5_context context,
 
            ret = _kdc_pk_check_client(context,
                                       config,
+                                      clientdb,
                                       client,
                                       pkp,
                                       &client_cert);
@@ -1113,18 +1196,34 @@ _kdc_as_rep(krb5_context context,
                pkp = NULL;
                goto out;
            }
+
            found_pa = 1;
            et.flags.pre_authent = 1;
            kdc_log(context, config, 0,
-                   "PKINIT pre-authentication succeeded -- %s using %s", 
+                   "PKINIT pre-authentication succeeded -- %s using %s",
                    client_name, client_cert);
+           if (clientdb->hdb_auth_status)
+                   (clientdb->hdb_auth_status)(context, clientdb, client,
+                                               from_addr,
+                                               &_kdc_now,
+                                               client_name,
+                                               "PKINIT",
+                                               HDB_AUTH_PKINIT_SUCCESS);
            free(client_cert);
            if (pkp)
                goto preauth_done;
        }
     ts_enc:
 #endif
-       kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s", 
+
+       if (client->entry.flags.locked_out) {
+           ret = KRB5KDC_ERR_CLIENT_REVOKED;
+           kdc_log(context, config, 0,
+                   "Client (%s) is locked out", client_name);
+           goto out;
+       }
+
+       kdc_log(context, config, 5, "Looking for ENC-TS pa-data -- %s",
                client_name);
 
        i = 0;
@@ -1136,21 +1235,27 @@ _kdc_as_rep(krb5_context context,
            EncryptedData enc_data;
            Key *pa_key;
            char *str;
-           
+
            found_pa = 1;
-           
+
+           if (b->kdc_options.request_anonymous) {
+               ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
+               kdc_log(context, config, 0, "ENC-TS doesn't support anon");
+               goto out;
+           }
+
            ret = decode_EncryptedData(pa->padata_value.data,
                                       pa->padata_value.length,
                                       &enc_data,
                                       &len);
            if (ret) {
                ret = KRB5KRB_AP_ERR_BAD_INTEGRITY;
-               kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s", 
+               kdc_log(context, config, 5, "Failed to decode PA-DATA -- %s",
                        client_name);
                goto out;
            }
-           
-           ret = hdb_enctype2key(context, &client->entry, 
+
+           ret = hdb_enctype2key(context, &client->entry,
                                  enc_data.etype, &pa_key);
            if(ret){
                char *estr;
@@ -1159,24 +1264,25 @@ _kdc_as_rep(krb5_context context,
                if(krb5_enctype_to_string(context, enc_data.etype, &estr))
                    estr = NULL;
                if(estr == NULL)
-                   kdc_log(context, config, 5, 
-                           "No client key matching pa-data (%d) -- %s", 
+                   kdc_log(context, config, 5,
+                           "No client key matching pa-data (%d) -- %s",
                            enc_data.etype, client_name);
                else
                    kdc_log(context, config, 5,
-                           "No client key matching pa-data (%s) -- %s", 
+                           "No client key matching pa-data (%s) -- %s",
                            estr, client_name);
                free(estr);
-                   
                free_EncryptedData(&enc_data);
+
                continue;
            }
 
        try_next_key:
            ret = krb5_crypto_init(context, &pa_key->key, 0, &crypto);
            if (ret) {
-               kdc_log(context, config, 0, "krb5_crypto_init failed: %s",
-                       krb5_get_err_text(context, ret));
+               const char *msg = krb5_get_error_message(context, ret);
+               kdc_log(context, config, 0, "krb5_crypto_init failed: %s", msg);
+               krb5_free_error_message(context, msg);
                free_EncryptedData(&enc_data);
                continue;
            }
@@ -1187,26 +1293,45 @@ _kdc_as_rep(krb5_context context,
                                              &enc_data,
                                              &ts_data);
            krb5_crypto_destroy(context, crypto);
+           /*
+            * Since the user might have several keys with the same
+            * enctype but with diffrent salting, we need to try all
+            * the keys with the same enctype.
+            */
            if(ret){
                krb5_error_code ret2;
-               ret2 = krb5_enctype_to_string(context, 
+               const char *msg = krb5_get_error_message(context, ret);
+
+               ret2 = krb5_enctype_to_string(context,
                                              pa_key->key.keytype, &str);
                if (ret2)
                    str = NULL;
-               kdc_log(context, config, 5, 
+
+               kdc_log(context, config, 5,
                        "Failed to decrypt PA-DATA -- %s "
                        "(enctype %s) error %s",
-                       client_name,
-                       str ? str : "unknown enctype", 
-                       krb5_get_err_text(context, ret));
-               free(str);
+                       client_name, str ? str : "unknown enctype", msg);
+               krb5_free_error_message(context, msg);
 
-               if(hdb_next_enctype2key(context, &client->entry, 
-                                       enc_data.etype, &pa_key) == 0)
+               if(hdb_next_enctype2key(context, &client->entry,
+                                       enc_data.etype, &pa_key) == 0) {
+                   free(str);
                    goto try_next_key;
+               }
                e_text = "Failed to decrypt PA-DATA";
 
                free_EncryptedData(&enc_data);
+
+               if (clientdb->hdb_auth_status)
+                   (clientdb->hdb_auth_status)(context, clientdb, client,
+                                               from_addr,
+                                               &_kdc_now,
+                                               client_name,
+                                               str ? str : "unknown enctype",
+                                               HDB_AUTH_WRONG_PASSWORD);
+
+               free(str);
+
                ret = KRB5KDC_ERR_PREAUTH_FAILED;
                continue;
            }
@@ -1219,7 +1344,7 @@ _kdc_as_rep(krb5_context context,
            if(ret){
                e_text = "Failed to decode PA-ENC-TS-ENC";
                ret = KRB5KDC_ERR_PREAUTH_FAILED;
-               kdc_log(context, config, 
+               kdc_log(context, config,
                        5, "Failed to decode PA-ENC-TS_ENC -- %s",
                        client_name);
                continue;
@@ -1227,42 +1352,48 @@ _kdc_as_rep(krb5_context context,
            free_PA_ENC_TS_ENC(&p);
            if (abs(kdc_time - p.patimestamp) > context->max_skew) {
                char client_time[100];
-               
-               krb5_format_time(context, p.patimestamp, 
-                                client_time, sizeof(client_time), TRUE); 
+
+               krb5_format_time(context, p.patimestamp,
+                                client_time, sizeof(client_time), TRUE);
 
                ret = KRB5KRB_AP_ERR_SKEW;
                kdc_log(context, config, 0,
                        "Too large time skew, "
-                       "client time %s is out by %u > %u seconds -- %s", 
-                       client_time, 
-                       (unsigned)abs(kdc_time - p.patimestamp), 
+                       "client time %s is out by %u > %u seconds -- %s",
+                       client_time,
+                       (unsigned)abs(kdc_time - p.patimestamp),
                        context->max_skew,
                        client_name);
-#if 1
-               /* This code is from samba, needs testing */
-               /* 
-                * the following is needed to make windows clients
-                * to retry using the timestamp in the error message
-                *
-                * this is maybe a bug in windows to not trying when e_text
-                * is present...
+
+               /*
+                * The following is needed to make windows clients to
+                * retry using the timestamp in the error message, if
+                * there is a e_text, they become unhappy.
                 */
                e_text = NULL;
-#else
-               e_text = "Too large time skew";
-#endif
                goto out;
            }
            et.flags.pre_authent = 1;
 
-           ret = krb5_enctype_to_string(context,pa_key->key.keytype, &str);
+           set_salt_padata(rep.padata, pa_key->salt);
+
+           reply_key = &pa_key->key;
+
+           ret = krb5_enctype_to_string(context, pa_key->key.keytype, &str);
            if (ret)
                str = NULL;
 
            kdc_log(context, config, 2,
-                   "ENC-TS Pre-authentication succeeded -- %s using %s", 
+                   "ENC-TS Pre-authentication succeeded -- %s using %s",
                    client_name, str ? str : "unknown enctype");
+           if (clientdb->hdb_auth_status)
+                   (clientdb->hdb_auth_status)(context, clientdb, client,
+                                               from_addr,
+                                               &_kdc_now,
+                                               client_name,
+                                               str ? str : "unknown enctype",
+                                               HDB_AUTH_CORRECT_PASSWORD);
+
            free(str);
            break;
        }
@@ -1275,64 +1406,21 @@ _kdc_as_rep(krb5_context context,
            was some problem with it, other than too large skew */
        if(found_pa && et.flags.pre_authent == 0){
            kdc_log(context, config, 0, "%s -- %s", e_text, client_name);
+           if (!prepare_enc_data(context, config, &e_data, b, client)) {
+               goto out;
+           }
            e_text = NULL;
            goto out;
        }
     }else if (config->require_preauth
+             || b->kdc_options.request_anonymous /* hack to force anon */
              || client->entry.flags.require_preauth
              || server->entry.flags.require_preauth) {
-       METHOD_DATA method_data;
-       PA_DATA *pa;
-       unsigned char *buf;
-       size_t len;
-
-    use_pa: 
-       method_data.len = 0;
-       method_data.val = NULL;
-
-       ret = realloc_method_data(&method_data);
-       pa = &method_data.val[method_data.len-1];
-       pa->padata_type         = KRB5_PADATA_ENC_TIMESTAMP;
-       pa->padata_value.length = 0;
-       pa->padata_value.data   = NULL;
-
-#ifdef PKINIT
-       ret = realloc_method_data(&method_data);
-       pa = &method_data.val[method_data.len-1];
-       pa->padata_type         = KRB5_PADATA_PK_AS_REQ;
-       pa->padata_value.length = 0;
-       pa->padata_value.data   = NULL;
-
-       ret = realloc_method_data(&method_data);
-       pa = &method_data.val[method_data.len-1];
-       pa->padata_type         = KRB5_PADATA_PK_AS_REQ_WIN;
-       pa->padata_value.length = 0;
-       pa->padata_value.data   = NULL;
-#endif
-
-       /* 
-        * RFC4120 requires: 
-        * - If the client only knows about old enctypes, then send
-        *   both info replies (we send 'info' first in the list).
-        * - If the client is 'modern', because it knows about 'new'
-        *   enctype types, then only send the 'info2' reply.
-        */
-
-       /* XXX check ret */
-       if (only_older_enctype_p(req))
-           ret = get_pa_etype_info(context, config,
-                                   &method_data, &client->entry, 
-                                   b->etype.val, b->etype.len); 
-       /* XXX check ret */
-       ret = get_pa_etype_info2(context, config, &method_data, 
-                                &client->entry, b->etype.val, b->etype.len);
-
-       
-       ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
-       free_METHOD_DATA(&method_data);
+    use_pa:
+       if (!prepare_enc_data(context, config, &e_data, b, client)) {
+               goto out;
+       }
 
-       e_data.data   = buf;
-       e_data.length = len;
        e_text ="Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ",
 
        ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
@@ -1342,103 +1430,60 @@ _kdc_as_rep(krb5_context context,
                client_name);
        goto out;
     }
-    
+
+    e_text = NULL;
+
     /*
-     * Find the client key (for preauth ENC-TS verification and reply
-     * encryption).  Then the best encryption type for the KDC and
-     * last the best session key that shared between the client and
-     * KDC runtime enctypes.
+     * Verify flags after the user been required to prove its identity
+     * with in a preauth mech.
      */
 
-    ret = _kdc_find_etype(context, client, b->etype.val, b->etype.len,
-                         &ckey, &cetype);
-    if (ret) {
-       kdc_log(context, config, 0, 
-               "Client (%s) has no support for etypes", client_name);
+    ret = _kdc_check_access(context, config, client, client_name,
+                           server, server_name,
+                           req, &e_data);
+    if(ret)
        goto out;
-    }
-       
+
+    if (clientdb->hdb_auth_status)
+       (clientdb->hdb_auth_status)(context, clientdb, client,
+                                   from_addr,
+                                   &_kdc_now,
+                                   client_name,
+                                   NULL,
+                                   HDB_AUTHZ_SUCCESS);
+
+    /*
+     * Selelct the best encryption type for the KDC with out regard to
+     * the client since the client never needs to read that data.
+     */
+
     ret = _kdc_get_preferred_key(context, config,
                                 server, server_name,
                                 &setype, &skey);
     if(ret)
        goto out;
 
-    /* 
-     * Select a session enctype from the list of the crypto systems
-     * supported enctype, is supported by the client and is one of the
-     * enctype of the enctype of the krbtgt.
-     *
-     * The later is used as a hint what enctype all KDC are supporting
-     * to make sure a newer version of KDC wont generate a session
-     * enctype that and older version of a KDC in the same realm can't
-     * decrypt.
-     *
-     * But if the KDC admin is paranoid and doesn't want to have "no
-     * the best" enctypes on the krbtgt, lets save the best pick from
-     * the client list and hope that that will work for any other
-     * KDCs.
-     */
-    {
-       const krb5_enctype *p;
-       krb5_enctype clientbest = ETYPE_NULL;
-       int i, j;
-
-       p = krb5_kerberos_enctypes(context);
-
-       sessionetype = ETYPE_NULL;
-
-       for (i = 0; p[i] != ETYPE_NULL && sessionetype == ETYPE_NULL; i++) {
-           if (krb5_enctype_valid(context, p[i]) != 0)
-               continue;
-
-           for (j = 0; j < b->etype.len && sessionetype == ETYPE_NULL; j++) {
-               Key *dummy;
-               /* check with client */
-               if (p[i] != b->etype.val[j])
-                   continue; 
-               /* save best of union of { client, crypto system } */
-               if (clientbest == ETYPE_NULL)
-                   clientbest = p[i];
-               /* check with krbtgt */
-               ret = hdb_enctype2key(context, &server->entry, p[i], &dummy);
-               if (ret) 
-                   continue;
-               sessionetype = p[i];
-           }
-       }
-       /* if krbtgt had no shared keys with client, pick clients best */
-       if (clientbest != ETYPE_NULL && sessionetype == ETYPE_NULL) {
-           sessionetype = clientbest;
-       } else if (sessionetype == ETYPE_NULL) {
-           kdc_log(context, config, 0,
-                   "Client (%s) from %s has no common enctypes with KDC"
-                   "to use for the session key", 
-                   client_name, from); 
-           goto out;
-       }
-    }
-
-    log_as_req(context, config, cetype, setype, b);
-
     if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
        || (f.request_anonymous && !config->allow_anonymous)) {
        ret = KRB5KDC_ERR_BADOPTION;
+       e_text = "Bad KDC options";
        kdc_log(context, config, 0, "Bad KDC options -- %s", client_name);
        goto out;
     }
-    
+
     rep.pvno = 5;
     rep.msg_type = krb_as_rep;
-    copy_Realm(&client->entry.principal->realm, &rep.crealm);
-    if (f.request_anonymous)
-       _kdc_make_anonymous_principalname (&rep.cname);
-    else
-       _krb5_principal2principalname(&rep.cname, 
-                                     client->entry.principal);
+
+    ret = copy_Realm(&client->entry.principal->realm, &rep.crealm);
+    if (ret)
+       goto out;
+    ret = _krb5_principal2principalname(&rep.cname, client->entry.principal);
+    if (ret)
+       goto out;
+
     rep.ticket.tkt_vno = 5;
     copy_Realm(&server->entry.principal->realm, &rep.ticket.realm);
-    _krb5_principal2principalname(&rep.ticket.sname, 
+    _krb5_principal2principalname(&rep.ticket.sname,
                                  server->entry.principal);
     /* java 1.6 expects the name to be the same type, lets allow that
      * uncomplicated name-types. */
@@ -1451,6 +1496,7 @@ _kdc_as_rep(krb5_context context,
     if(client->entry.flags.forwardable && server->entry.flags.forwardable)
        et.flags.forwardable = f.forwardable;
     else if (f.forwardable) {
+       e_text = "Ticket may not be forwardable";
        ret = KRB5KDC_ERR_POLICY;
        kdc_log(context, config, 0,
                "Ticket may not be forwardable -- %s", client_name);
@@ -1459,14 +1505,16 @@ _kdc_as_rep(krb5_context context,
     if(client->entry.flags.proxiable && server->entry.flags.proxiable)
        et.flags.proxiable = f.proxiable;
     else if (f.proxiable) {
+       e_text = "Ticket may not be proxiable";
        ret = KRB5KDC_ERR_POLICY;
-       kdc_log(context, config, 0, 
+       kdc_log(context, config, 0,
                "Ticket may not be proxiable -- %s", client_name);
        goto out;
     }
     if(client->entry.flags.postdate && server->entry.flags.postdate)
        et.flags.may_postdate = f.allow_postdate;
     else if (f.allow_postdate){
+       e_text = "Ticket may not be postdate";
        ret = KRB5KDC_ERR_POLICY;
        kdc_log(context, config, 0,
                "Ticket may not be postdatable -- %s", client_name);
@@ -1475,24 +1523,26 @@ _kdc_as_rep(krb5_context context,
 
     /* check for valid set of addresses */
     if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
+       e_text = "Bad address list in requested";
        ret = KRB5KRB_AP_ERR_BADADDR;
        kdc_log(context, config, 0,
                "Bad address list requested -- %s", client_name);
        goto out;
     }
 
-    ret = krb5_generate_random_keyblock(context, sessionetype, &et.key);
+    ret = copy_PrincipalName(&rep.cname, &et.cname);
     if (ret)
        goto out;
-    copy_PrincipalName(&rep.cname, &et.cname);
-    copy_Realm(&rep.crealm, &et.crealm);
-    
+    ret = copy_Realm(&rep.crealm, &et.crealm);
+    if (ret)
+       goto out;
+
     {
        time_t start;
        time_t t;
-       
+
        start = et.authtime = kdc_time;
-    
+
        if(f.postdated && req->req_body.from){
            ALLOC(et.starttime);
            start = *et.starttime = *req->req_body.from;
@@ -1540,16 +1590,14 @@ _kdc_as_rep(krb5_context context,
 
     if (f.request_anonymous)
        et.flags.anonymous = 1;
-    
+
     if(b->addresses){
        ALLOC(et.caddr);
        copy_HostAddresses(b->addresses, et.caddr);
     }
-    
+
     et.transited.tr_type = DOMAIN_X500_COMPRESS;
-    krb5_data_zero(&et.transited.contents); 
-     
-    copy_EncryptionKey(&et.key, &ek.key);
+    krb5_data_zero(&et.transited.contents);
 
     /* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
      * as 0 and as 0x80 (meaning indefinite length) apart, and is thus
@@ -1588,7 +1636,7 @@ _kdc_as_rep(krb5_context context,
        ALLOC(ek.key_expiration);
        if (client->entry.valid_end) {
            if (client->entry.pw_end)
-               *ek.key_expiration = min(*client->entry.valid_end, 
+               *ek.key_expiration = min(*client->entry.valid_end,
                                         *client->entry.pw_end);
            else
                *ek.key_expiration = *client->entry.valid_end;
@@ -1614,16 +1662,12 @@ _kdc_as_rep(krb5_context context,
        copy_HostAddresses(et.caddr, ek.caddr);
     }
 
-    ALLOC(rep.padata);
-    rep.padata->len = 0;
-    rep.padata->val = NULL;
-
-    reply_key = &ckey->key;
-#if PKINIT
+#ifdef PKINIT
     if (pkp) {
-       ret = _kdc_pk_mk_pa_reply(context, config, pkp, client, 
-                                 req, req_buffer, 
-                                 &reply_key, rep.padata);
+        e_text = "Failed to build PK-INIT reply";
+       ret = _kdc_pk_mk_pa_reply(context, config, pkp, client,
+                                 sessionetype, req, req_buffer,
+                                 &reply_key, &et.key, rep.padata);
        if (ret)
            goto out;
        ret = _kdc_add_inital_verified_cas(context,
@@ -1632,63 +1676,30 @@ _kdc_as_rep(krb5_context context,
                                           &et);
        if (ret)
            goto out;
-    }
-#endif
-
-    set_salt_padata (rep.padata, ckey->salt);
-
-    /* Add signing of alias referral */
-    if (f.canonicalize) {
-       PA_ClientCanonicalized canon;
-       krb5_data data;
-       PA_DATA pa;
-       krb5_crypto crypto;
-       size_t len;
 
-       memset(&canon, 0, sizeof(canon));
-
-       canon.names.requested_name = *b->cname;
-       canon.names.mapped_name = client->entry.principal->name;
-
-       ASN1_MALLOC_ENCODE(PA_ClientCanonicalizedNames, data.data, data.length,
-                          &canon.names, &len, ret);
-       if (ret) 
-           goto out;
-       if (data.length != len)
-           krb5_abortx(context, "internal asn.1 error");
-
-       /* sign using "returned session key" */
-       ret = krb5_crypto_init(context, &et.key, 0, &crypto);
-       if (ret) {
-           free(data.data);
-           goto out;
-       }
-
-       ret = krb5_create_checksum(context, crypto, 
-                                  KRB5_KU_CANONICALIZED_NAMES, 0,
-                                  data.data, data.length,
-                                  &canon.canon_checksum);
-       free(data.data);
-       krb5_crypto_destroy(context, crypto);
+       /*
+        * Send reply key as constant value to pac generate which allows
+        * parts of the buffer to be encrypted (i.e., PAC_CREDENTIAL_DATA).
+        */
+       pk_reply_key = reply_key;
+    } else
+#endif
+    {
+       ret = krb5_generate_random_keyblock(context, sessionetype, &et.key);
        if (ret)
            goto out;
-         
-       ASN1_MALLOC_ENCODE(PA_ClientCanonicalized, data.data, data.length,
-                          &canon, &len, ret);
-       free_Checksum(&canon.canon_checksum);
-       if (ret) 
-           goto out;
-       if (data.length != len)
-           krb5_abortx(context, "internal asn.1 error");
+    }
 
-       pa.padata_type = KRB5_PADATA_CLIENT_CANONICALIZED;
-       pa.padata_value = data;
-       ret = add_METHOD_DATA(rep.padata, &pa);
-       free(data.data);
-       if (ret)
-           goto out;
+    if (reply_key == NULL) {
+       e_text = "Client have no reply key";
+       ret = KRB5KDC_ERR_CLIENT_NOTYET;
+       goto out;
     }
 
+    ret = copy_EncryptionKey(&et.key, &ek.key);
+    if (ret)
+       goto out;
+
     if (rep.padata->len == 0) {
        free(rep.padata);
        rep.padata = NULL;
@@ -1699,21 +1710,21 @@ _kdc_as_rep(krb5_context context,
        krb5_pac p = NULL;
        krb5_data data;
 
-       ret = _kdc_pac_generate(context, client, &p);
+       ret = _kdc_pac_generate(context, client, pk_reply_key, &p);
        if (ret) {
-           kdc_log(context, config, 0, "PAC generation failed for -- %s", 
+           kdc_log(context, config, 0, "PAC generation failed for -- %s",
                    client_name);
            goto out;
        }
        if (p != NULL) {
            ret = _krb5_pac_sign(context, p, et.authtime,
                                 client->entry.principal,
-                                &skey->key, /* Server key */ 
+                                &skey->key, /* Server key */
                                 &skey->key, /* FIXME: should be krbtgt key */
                                 &data);
            krb5_pac_free(context, p);
            if (ret) {
-               kdc_log(context, config, 0, "PAC signing failed for -- %s", 
+               kdc_log(context, config, 0, "PAC signing failed for -- %s",
                        client_name);
                goto out;
            }
@@ -1727,7 +1738,7 @@ _kdc_as_rep(krb5_context context,
        }
     }
 
-    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttime, 
+    _kdc_log_timestamp(context, config, "AS-REQ", et.authtime, et.starttime,
                       et.endtime, et.renew_till);
 
     /* do this as the last thing since this signs the EncTicketPart */
@@ -1735,16 +1746,19 @@ _kdc_as_rep(krb5_context context,
                                  config,
                                  server,
                                  setype,
+                                 client->entry.principal,
                                  NULL,
                                  NULL,
                                  &et);
     if (ret)
        goto out;
 
-    ret = _kdc_encode_reply(context, config, 
-                           &rep, &et, &ek, setype, server->entry.kvno, 
-                           &skey->key, client->entry.kvno, 
-                           reply_key, &e_text, reply);
+    log_as_req(context, config, reply_key->keytype, setype, b);
+
+    ret = _kdc_encode_reply(context, config,
+                           &rep, &et, &ek, setype, server->entry.kvno,
+                           &skey->key, client->entry.kvno,
+                           reply_key, 0, &e_text, reply);
     free_EncTicketPart(&et);
     free_EncKDCRepPart(&ek);
     if (ret)
@@ -1759,7 +1773,7 @@ _kdc_as_rep(krb5_context context,
 
 out:
     free_AS_REP(&rep);
-    if(ret){
+    if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {
        krb5_mk_error(context,
                      ret,
                      e_text,
@@ -1790,9 +1804,103 @@ out:
     return ret;
 }
 
+krb5_boolean
+prepare_enc_data(krb5_context context,
+                krb5_kdc_configuration *config,
+                krb5_data *e_data,
+                KDC_REQ_BODY *b,
+                hdb_entry_ex *client)
+{
+       METHOD_DATA method_data;
+       PA_DATA *pa;
+       unsigned char *buf;
+       size_t len;
+       Key *ckey;
+       krb5_error_code ret;
+
+       method_data.len = 0;
+       method_data.val = NULL;
+
+       ret = realloc_method_data(&method_data);
+       if (ret) {
+           free_METHOD_DATA(&method_data);
+           return FALSE;
+       }
+       pa = &method_data.val[method_data.len-1];
+       pa->padata_type         = KRB5_PADATA_ENC_TIMESTAMP;
+       pa->padata_value.length = 0;
+       pa->padata_value.data   = NULL;
+
+#ifdef PKINIT
+       ret = realloc_method_data(&method_data);
+       if (ret) {
+           free_METHOD_DATA(&method_data);
+           return FALSE;
+       }
+       pa = &method_data.val[method_data.len-1];
+       pa->padata_type         = KRB5_PADATA_PK_AS_REQ;
+       pa->padata_value.length = 0;
+       pa->padata_value.data   = NULL;
+
+       ret = realloc_method_data(&method_data);
+       if (ret) {
+           free_METHOD_DATA(&method_data);
+           return FALSE;
+       }
+       pa = &method_data.val[method_data.len-1];
+       pa->padata_type         = KRB5_PADATA_PK_AS_REQ_WIN;
+       pa->padata_value.length = 0;
+       pa->padata_value.data   = NULL;
+#endif
+
+       /*
+        * If there is a client key, send ETYPE_INFO{,2}
+        */
+       ret = _kdc_find_etype(context,
+                             config->preauth_use_strongest_session_key, TRUE,
+                             client, b->etype.val, b->etype.len, NULL, &ckey);
+       if (ret == 0) {
+
+           /*
+            * RFC4120 requires:
+            * - If the client only knows about old enctypes, then send
+            *   both info replies (we send 'info' first in the list).
+            * - If the client is 'modern', because it knows about 'new'
+            *   enctype types, then only send the 'info2' reply.
+            *
+            * Before we send the full list of etype-info data, we pick
+            * the client key we would have used anyway below, just pick
+            * that instead.
+            */
+
+           if (older_enctype(ckey->key.keytype)) {
+               ret = get_pa_etype_info(context, config,
+                                       &method_data, ckey);
+               if (ret) {
+                   free_METHOD_DATA(&method_data);
+                   return FALSE;
+               }
+           }
+           ret = get_pa_etype_info2(context, config,
+                                    &method_data, ckey);
+           if (ret) {
+               free_METHOD_DATA(&method_data);
+               return FALSE;
+           }
+       }
+
+       ASN1_MALLOC_ENCODE(METHOD_DATA, buf, len, &method_data, &len, ret);
+       free_METHOD_DATA(&method_data);
+
+       e_data->data   = buf;
+       e_data->length = len;
+
+       return TRUE;
+}
+
 /*
- * Add the AuthorizationData `data´ of `type´ to the last element in
- * the sequence of authorization_data in `tkt´ wrapped in an IF_RELEVANT
+ * Add the AuthorizationData `data´ of `type´ to the last element in
+ * the sequence of authorization_data in `tkt´ wrapped in an IF_RELEVANT
  */
 
 krb5_error_code
@@ -1802,7 +1910,7 @@ _kdc_tkt_add_if_relevant_ad(krb5_context context,
                            const krb5_data *data)
 {
     krb5_error_code ret;
-    size_t size;
+    size_t size = 0;
 
     if (tkt->authorization_data == NULL) {
        tkt->authorization_data = calloc(1, sizeof(*tkt->authorization_data));
@@ -1811,7 +1919,7 @@ _kdc_tkt_add_if_relevant_ad(krb5_context context,
            return ENOMEM;
        }
     }
-       
+
     /* add the entry to the last element */
     {
        AuthorizationData ad = { 0, NULL };
@@ -1828,8 +1936,8 @@ _kdc_tkt_add_if_relevant_ad(krb5_context context,
 
        ade.ad_type = KRB5_AUTHDATA_IF_RELEVANT;
 
-       ASN1_MALLOC_ENCODE(AuthorizationData, 
-                          ade.ad_data.data, ade.ad_data.length, 
+       ASN1_MALLOC_ENCODE(AuthorizationData,
+                          ade.ad_data.data, ade.ad_data.length,
                           &ad, &size, ret);
        free_AuthorizationData(&ad);
        if (ret) {
@@ -1839,7 +1947,7 @@ _kdc_tkt_add_if_relevant_ad(krb5_context context,
        }
        if (ade.ad_data.length != size)
            krb5_abortx(context, "internal asn.1 encoder error");
-       
+
        ret = add_AuthorizationData(tkt->authorization_data, &ade);
        der_free_octet_string(&ade.ad_data);
        if (ret) {