s4-kdc/db_glue: bad idea to free parent mem_ctx when sub function got a failure.
[mat/samba.git] / source4 / kdc / db-glue.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Database Glue between Samba and the KDC
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
7    Copyright (C) Simo Sorce <idra@samba.org> 2010
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "libcli/security/security.h"
26 #include "auth/auth.h"
27 #include "auth/auth_sam.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "dsdb/common/util.h"
30 #include "librpc/gen_ndr/ndr_drsblobs.h"
31 #include "param/param.h"
32 #include "../lib/crypto/md4.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include <hdb.h>
36 #include "kdc/samba_kdc.h"
37 #include "kdc/db-glue.h"
38
39 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
40         ((uint16_t)(((uint32_t)kvno) >> 16))
41
42 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
43         ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
44          ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
45
46 enum samba_kdc_ent_type
47 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
48   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
49
50 enum trust_direction {
51         UNKNOWN = 0,
52         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
53         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
54 };
55
56 static const char *trust_attrs[] = {
57         "trustPartner",
58         "trustAuthIncoming",
59         "trustAuthOutgoing",
60         "whenCreated",
61         "msDS-SupportedEncryptionTypes",
62         "trustAttributes",
63         "trustDirection",
64         "trustType",
65         NULL
66 };
67
68
69 static time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t default_val)
70 {
71     const char *tmp;
72     const char *gentime;
73     struct tm tm;
74
75     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
76     if (!gentime)
77         return default_val;
78
79     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
80     if (tmp == NULL) {
81             return default_val;
82     }
83
84     return timegm(&tm);
85 }
86
87 static HDBFlags uf2HDBFlags(krb5_context context, uint32_t userAccountControl, enum samba_kdc_ent_type ent_type)
88 {
89         HDBFlags flags = int2HDBFlags(0);
90
91         /* we don't allow kadmin deletes */
92         flags.immutable = 1;
93
94         /* mark the principal as invalid to start with */
95         flags.invalid = 1;
96
97         flags.renewable = 1;
98
99         /* All accounts are servers, but this may be disabled again in the caller */
100         flags.server = 1;
101
102         /* Account types - clear the invalid bit if it turns out to be valid */
103         if (userAccountControl & UF_NORMAL_ACCOUNT) {
104                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
105                         flags.client = 1;
106                 }
107                 flags.invalid = 0;
108         }
109
110         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
111                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
112                         flags.client = 1;
113                 }
114                 flags.invalid = 0;
115         }
116         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
117                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
118                         flags.client = 1;
119                 }
120                 flags.invalid = 0;
121         }
122         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
123                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
124                         flags.client = 1;
125                 }
126                 flags.invalid = 0;
127         }
128
129         /* Not permitted to act as a client if disabled */
130         if (userAccountControl & UF_ACCOUNTDISABLE) {
131                 flags.client = 0;
132         }
133         if (userAccountControl & UF_LOCKOUT) {
134                 flags.locked_out = 1;
135         }
136 /*
137         if (userAccountControl & UF_PASSWORD_NOTREQD) {
138                 flags.invalid = 1;
139         }
140 */
141 /*
142         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
143 */
144         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
145                 flags.invalid = 1;
146         }
147
148 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
149
150 /*
151         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
152                 flags.invalid = 1;
153         }
154 */
155         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
156                 flags.require_hwauth = 1;
157         }
158         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
159                 flags.ok_as_delegate = 1;
160         }
161         if (userAccountControl & UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
162                 /*
163                  * this is confusing...
164                  *
165                  * UF_TRUSTED_FOR_DELEGATION
166                  * => ok_as_delegate
167                  *
168                  * and
169                  *
170                  * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
171                  * => trusted_for_delegation
172                  */
173                 flags.trusted_for_delegation = 1;
174         }
175         if (!(userAccountControl & UF_NOT_DELEGATED)) {
176                 flags.forwardable = 1;
177                 flags.proxiable = 1;
178         }
179
180         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
181                 flags.require_preauth = 0;
182         } else {
183                 flags.require_preauth = 1;
184
185         }
186         return flags;
187 }
188
189 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
190 {
191     hdb_entry_ex *entry_ex = p->entry_ex;
192     free_hdb_entry(&entry_ex->entry);
193     return 0;
194 }
195
196 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
197 {
198         /* this function is called only from hdb_free_entry().
199          * Make sure we neutralize the destructor or we will
200          * get a double free later when hdb_free_entry() will
201          * try to call free_hdb_entry() */
202         talloc_set_destructor(entry_ex->ctx, NULL);
203
204         /* now proceed to free the talloc part */
205         talloc_free(entry_ex->ctx);
206 }
207
208 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
209                                                     struct samba_kdc_db_context *kdc_db_ctx,
210                                                     TALLOC_CTX *mem_ctx,
211                                                     struct ldb_message *msg,
212                                                     uint32_t rid,
213                                                     bool is_rodc,
214                                                     uint32_t userAccountControl,
215                                                     enum samba_kdc_ent_type ent_type,
216                                                     hdb_entry_ex *entry_ex)
217 {
218         krb5_error_code ret = 0;
219         enum ndr_err_code ndr_err;
220         struct samr_Password *hash;
221         const struct ldb_val *sc_val;
222         struct supplementalCredentialsBlob scb;
223         struct supplementalCredentialsPackage *scpk = NULL;
224         bool newer_keys = false;
225         struct package_PrimaryKerberosBlob _pkb;
226         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
227         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
228         uint16_t i;
229         uint16_t allocated_keys = 0;
230         int rodc_krbtgt_number = 0;
231         int kvno = 0;
232         uint32_t supported_enctypes
233                 = ldb_msg_find_attr_as_uint(msg,
234                                             "msDS-SupportedEncryptionTypes",
235                                             0);
236
237         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
238                 /* KDCs (and KDCs on RODCs) use AES */
239                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
240         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
241                 /* DCs and RODCs comptuer accounts use AES */
242                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
243         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
244                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
245                 /* for AS-REQ the client chooses the enc types it
246                  * supports, and this will vary between computers a
247                  * user logs in from.
248                  *
249                  * likewise for 'any' return as much as is supported,
250                  * to export into a keytab */
251                 supported_enctypes = ENC_ALL_TYPES;
252         }
253
254         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
255         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
256                 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
257         } else {
258                 /* Otherwise, add in the default enc types */
259                 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
260         }
261
262         /* Is this the krbtgt or a RODC krbtgt */
263         if (is_rodc) {
264                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
265
266                 if (rodc_krbtgt_number == -1) {
267                         return EINVAL;
268                 }
269         }
270
271         entry_ex->entry.keys.val = NULL;
272         entry_ex->entry.keys.len = 0;
273
274         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
275         if (is_rodc) {
276                 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
277         }
278         entry_ex->entry.kvno = kvno;
279
280         /* Get keys from the db */
281
282         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
283         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
284
285         /* unicodePwd for enctype 0x17 (23) if present */
286         if (hash) {
287                 allocated_keys++;
288         }
289
290         /* supplementalCredentials if present */
291         if (sc_val) {
292                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
293                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
294                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
295                         dump_data(0, sc_val->data, sc_val->length);
296                         ret = EINVAL;
297                         goto out;
298                 }
299
300                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
301                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
302                         ret = EINVAL;
303                         goto out;
304                 }
305
306                 for (i=0; i < scb.sub.num_packages; i++) {
307                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
308                                 scpk = &scb.sub.packages[i];
309                                 if (!scpk->data || !scpk->data[0]) {
310                                         scpk = NULL;
311                                         continue;
312                                 }
313                                 newer_keys = true;
314                                 break;
315                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
316                                 scpk = &scb.sub.packages[i];
317                                 if (!scpk->data || !scpk->data[0]) {
318                                         scpk = NULL;
319                                 }
320                                 /*
321                                  * we don't break here in hope to find
322                                  * a Kerberos-Newer-Keys package
323                                  */
324                         }
325                 }
326         }
327         /*
328          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
329          * of supplementalCredentials
330          */
331         if (scpk) {
332                 DATA_BLOB blob;
333
334                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
335                 if (!blob.data) {
336                         ret = ENOMEM;
337                         goto out;
338                 }
339
340                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
341                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
342                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
343                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
344                         ret = EINVAL;
345                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
346                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
347                         goto out;
348                 }
349
350                 if (newer_keys && _pkb.version != 4) {
351                         ret = EINVAL;
352                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
353                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
354                         goto out;
355                 }
356
357                 if (!newer_keys && _pkb.version != 3) {
358                         ret = EINVAL;
359                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
360                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
361                         goto out;
362                 }
363
364                 if (_pkb.version == 4) {
365                         pkb4 = &_pkb.ctr.ctr4;
366                         allocated_keys += pkb4->num_keys;
367                 } else if (_pkb.version == 3) {
368                         pkb3 = &_pkb.ctr.ctr3;
369                         allocated_keys += pkb3->num_keys;
370                 }
371         }
372
373         if (allocated_keys == 0) {
374                 if (kdc_db_ctx->rodc) {
375                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
376                         /* TODO:  We need to call a generalised version of auth_sam_trigger_repl_secret from here */
377                         return HDB_ERR_NOT_FOUND_HERE;
378                 }
379
380                 /* oh, no password.  Apparently (comment in
381                  * hdb-ldap.c) this violates the ASN.1, but this
382                  * allows an entry with no keys (yet). */
383                 return 0;
384         }
385
386         /* allocate space to decode into */
387         entry_ex->entry.keys.len = 0;
388         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
389         if (entry_ex->entry.keys.val == NULL) {
390                 ret = ENOMEM;
391                 goto out;
392         }
393
394         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
395                 Key key;
396
397                 key.mkvno = 0;
398                 key.salt = NULL; /* No salt for this enc type */
399
400                 ret = smb_krb5_keyblock_init_contents(context,
401                                                       ENCTYPE_ARCFOUR_HMAC,
402                                                       hash->hash,
403                                                       sizeof(hash->hash),
404                                                       &key.key);
405                 if (ret) {
406                         goto out;
407                 }
408
409                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
410                 entry_ex->entry.keys.len++;
411         }
412
413         if (pkb4) {
414                 for (i=0; i < pkb4->num_keys; i++) {
415                         Key key;
416
417                         if (!pkb4->keys[i].value) continue;
418
419                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
420                                 continue;
421                         }
422
423                         key.mkvno = 0;
424                         key.salt = NULL;
425
426                         if (pkb4->salt.string) {
427                                 DATA_BLOB salt;
428
429                                 salt = data_blob_string_const(pkb4->salt.string);
430
431                                 key.salt = calloc(1, sizeof(*key.salt));
432                                 if (key.salt == NULL) {
433                                         ret = ENOMEM;
434                                         goto out;
435                                 }
436
437                                 key.salt->type = KRB5_PW_SALT;
438
439                                 ret = krb5_copy_data_contents(&key.salt->salt,
440                                                               salt.data,
441                                                               salt.length);
442                                 if (ret) {
443                                         free(key.salt);
444                                         key.salt = NULL;
445                                         goto out;
446                                 }
447                         }
448
449                         /* TODO: maybe pass the iteration_count somehow... */
450
451                         ret = smb_krb5_keyblock_init_contents(context,
452                                                               pkb4->keys[i].keytype,
453                                                               pkb4->keys[i].value->data,
454                                                               pkb4->keys[i].value->length,
455                                                               &key.key);
456                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
457                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
458                                          pkb4->keys[i].keytype));
459                                 ret = 0;
460                                 continue;
461                         }
462                         if (ret) {
463                                 if (key.salt) {
464                                         free_Salt(key.salt);
465                                         free(key.salt);
466                                         key.salt = NULL;
467                                 }
468                                 goto out;
469                         }
470
471                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
472                         entry_ex->entry.keys.len++;
473                 }
474         } else if (pkb3) {
475                 for (i=0; i < pkb3->num_keys; i++) {
476                         Key key;
477
478                         if (!pkb3->keys[i].value) continue;
479
480                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
481                                 continue;
482                         }
483
484                         key.mkvno = 0;
485                         key.salt = NULL;
486
487                         if (pkb3->salt.string) {
488                                 DATA_BLOB salt;
489
490                                 salt = data_blob_string_const(pkb3->salt.string);
491
492                                 key.salt = calloc(1, sizeof(*key.salt));
493                                 if (key.salt == NULL) {
494                                         ret = ENOMEM;
495                                         goto out;
496                                 }
497
498                                 key.salt->type = KRB5_PW_SALT;
499
500                                 ret = krb5_copy_data_contents(&key.salt->salt,
501                                                               salt.data,
502                                                               salt.length);
503                                 if (ret) {
504                                         free(key.salt);
505                                         key.salt = NULL;
506                                         goto out;
507                                 }
508                         }
509
510                         ret = smb_krb5_keyblock_init_contents(context,
511                                                               pkb3->keys[i].keytype,
512                                                               pkb3->keys[i].value->data,
513                                                               pkb3->keys[i].value->length,
514                                                               &key.key);
515                         if (ret) {
516                                 if (key.salt) {
517                                         free_Salt(key.salt);
518                                         free(key.salt);
519                                         key.salt = NULL;
520                                 }
521                                 goto out;
522                         }
523
524                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
525                         entry_ex->entry.keys.len++;
526                 }
527         }
528
529 out:
530         if (ret != 0) {
531                 entry_ex->entry.keys.len = 0;
532         }
533         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
534                 free(entry_ex->entry.keys.val);
535                 entry_ex->entry.keys.val = NULL;
536         }
537         return ret;
538 }
539
540 /*
541  * Construct an hdb_entry from a directory entry.
542  */
543 static krb5_error_code samba_kdc_message2entry(krb5_context context,
544                                                struct samba_kdc_db_context *kdc_db_ctx,
545                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
546                                                enum samba_kdc_ent_type ent_type,
547                                                unsigned flags,
548                                                struct ldb_dn *realm_dn,
549                                                struct ldb_message *msg,
550                                                hdb_entry_ex *entry_ex)
551 {
552         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
553         uint32_t userAccountControl;
554         uint32_t msDS_User_Account_Control_Computed;
555         unsigned int i;
556         krb5_error_code ret = 0;
557         krb5_boolean is_computer = FALSE;
558
559         struct samba_kdc_entry *p;
560         NTTIME acct_expiry;
561         NTSTATUS status;
562
563         uint32_t rid;
564         bool is_rodc = false;
565         struct ldb_message_element *objectclasses;
566         struct ldb_val computer_val;
567         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
568         computer_val.data = discard_const_p(uint8_t,"computer");
569         computer_val.length = strlen((const char *)computer_val.data);
570
571         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
572                 is_rodc = true;
573         }
574
575         if (!samAccountName) {
576                 ret = ENOENT;
577                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
578                 goto out;
579         }
580
581         objectclasses = ldb_msg_find_element(msg, "objectClass");
582
583         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
584                 is_computer = TRUE;
585         }
586
587         memset(entry_ex, 0, sizeof(*entry_ex));
588
589         p = talloc(mem_ctx, struct samba_kdc_entry);
590         if (!p) {
591                 ret = ENOMEM;
592                 goto out;
593         }
594
595         p->kdc_db_ctx = kdc_db_ctx;
596         p->entry_ex = entry_ex;
597         p->realm_dn = talloc_reference(p, realm_dn);
598         if (!p->realm_dn) {
599                 ret = ENOMEM;
600                 goto out;
601         }
602
603         talloc_set_destructor(p, samba_kdc_entry_destructor);
604
605         /* make sure we do not have bogus data in there */
606         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
607
608         entry_ex->ctx = p;
609         entry_ex->free_entry = samba_kdc_free_entry;
610
611         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
612
613         msDS_User_Account_Control_Computed
614                 = ldb_msg_find_attr_as_uint(msg,
615                                             "msDS-User-Account-Control-Computed",
616                                             UF_ACCOUNTDISABLE);
617
618         /*
619          * This brings in the lockout flag, block the account if not
620          * found.  We need the weird UF_ACCOUNTDISABLE check because
621          * we do not want to fail open if the value is not returned,
622          * but 0 is a valid value (all OK)
623          */
624         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
625                 ret = EINVAL;
626                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
627                                 "no msDS-User-Account-Control-Computed present");
628                 goto out;
629         } else {
630                 userAccountControl |= msDS_User_Account_Control_Computed;
631         }
632
633         /* 
634          * If we are set to canonicalize, we get back the fixed UPPER
635          * case realm, and the real username (ie matching LDAP
636          * samAccountName) 
637          *
638          * Otherwise, if we are set to enterprise, we
639          * get back the whole principal as-sent 
640          *
641          * Finally, if we are not set to canonicalize, we get back the
642          * fixed UPPER case realm, but the as-sent username
643          */
644
645         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
646         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
647                 if (flags & (HDB_F_CANON)) {
648                         /*
649                          * When requested to do so, ensure that the
650                          * both realm values in the principal are set
651                          * to the upper case, canonical realm
652                          */
653                         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
654                                                       lpcfg_realm(lp_ctx), "krbtgt",
655                                                       lpcfg_realm(lp_ctx), NULL);
656                         if (ret) {
657                                 krb5_clear_error_message(context);
658                                 goto out;
659                         }
660                         krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
661                 } else {
662                         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
663                         if (ret) {
664                                 krb5_clear_error_message(context);
665                                 goto out;
666                         }
667                         /*
668                          * this appears to be required regardless of
669                          * the canonicalize flag from the client
670                          */
671                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
672                         if (ret) {
673                                 krb5_clear_error_message(context);
674                                 goto out;
675                         }
676                 }
677
678         } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
679                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
680                 if (ret) {
681                         krb5_clear_error_message(context);
682                         goto out;
683                 }
684         } else if (flags & HDB_F_CANON && flags & HDB_F_FOR_AS_REQ) {
685                 /*
686                  * HDB_F_CANON maps from the canonicalize flag in the
687                  * packet, and has a different meaning between AS-REQ
688                  * and TGS-REQ.  We only change the principal in the AS-REQ case
689                  */
690                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
691                 if (ret) {
692                         krb5_clear_error_message(context);
693                         goto out;
694                 }
695         } else {
696                 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
697                 if (ret) {
698                         krb5_clear_error_message(context);
699                         goto out;
700                 }
701
702                 if (smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
703                         /* While we have copied the client principal, tests
704                          * show that Win2k3 returns the 'corrected' realm, not
705                          * the client-specified realm.  This code attempts to
706                          * replace the client principal's realm with the one
707                          * we determine from our records */
708                         
709                         /* this has to be with malloc() */
710                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
711                         if (ret) {
712                                 krb5_clear_error_message(context);
713                                 goto out;
714                         }
715                 }
716         }
717
718         /* First try and figure out the flags based on the userAccountControl */
719         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
720
721         /* Windows 2008 seems to enforce this (very sensible) rule by
722          * default - don't allow offline attacks on a user's password
723          * by asking for a ticket to them as a service (encrypted with
724          * their probably patheticly insecure password) */
725
726         if (entry_ex->entry.flags.server
727             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
728                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
729                         entry_ex->entry.flags.server = 0;
730                 }
731         }
732         /*
733          * To give the correct type of error to the client, we must
734          * not just return the entry without .server set, we must
735          * pretend the principal does not exist.  Otherwise we may
736          * return ERR_POLICY instead of
737          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
738          */
739         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
740                 ret = HDB_ERR_NOENTRY;
741                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
742                 goto out;
743         }
744         if (flags & HDB_F_ADMIN_DATA) {
745                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
746                  * of the Heimdal KDC.  They are stored in a the traditional
747                  * DB for audit purposes, and still form part of the structure
748                  * we must return */
749
750                 /* use 'whenCreated' */
751                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
752                 /* use 'kadmin' for now (needed by mit_samba) */
753
754                 ret = smb_krb5_make_principal(context,
755                                               &entry_ex->entry.created_by.principal,
756                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
757                 if (ret) {
758                         krb5_clear_error_message(context);
759                         goto out;
760                 }
761
762                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
763                 if (entry_ex->entry.modified_by == NULL) {
764                         ret = ENOMEM;
765                         krb5_set_error_message(context, ret, "malloc: out of memory");
766                         goto out;
767                 }
768
769                 /* use 'whenChanged' */
770                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
771                 /* use 'kadmin' for now (needed by mit_samba) */
772                 ret = smb_krb5_make_principal(context,
773                                               &entry_ex->entry.modified_by->principal,
774                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
775                 if (ret) {
776                         krb5_clear_error_message(context);
777                         goto out;
778                 }
779         }
780
781
782         /* The lack of password controls etc applies to krbtgt by
783          * virtue of being that particular RID */
784         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
785
786         if (!NT_STATUS_IS_OK(status)) {
787                 ret = EINVAL;
788                 goto out;
789         }
790
791         if (rid == DOMAIN_RID_KRBTGT) {
792                 char *realm = NULL;
793
794                 entry_ex->entry.valid_end = NULL;
795                 entry_ex->entry.pw_end = NULL;
796
797                 entry_ex->entry.flags.invalid = 0;
798                 entry_ex->entry.flags.server = 1;
799
800                 realm = smb_krb5_principal_get_realm(context, principal);
801                 if (realm == NULL) {
802                         ret = ENOMEM;
803                         goto out;
804                 }
805
806                 /* Don't mark all requests for the krbtgt/realm as
807                  * 'change password', as otherwise we could get into
808                  * trouble, and not enforce the password expirty.
809                  * Instead, only do it when request is for the kpasswd service */
810                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
811                     && krb5_princ_size(context, principal) == 2
812                     && (strcmp(krb5_principal_get_comp_string(context, principal, 0), "kadmin") == 0)
813                     && (strcmp(krb5_principal_get_comp_string(context, principal, 1), "changepw") == 0)
814                     && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
815                         entry_ex->entry.flags.change_pw = 1;
816                 }
817
818                 SAFE_FREE(realm);
819
820                 entry_ex->entry.flags.client = 0;
821                 entry_ex->entry.flags.forwardable = 1;
822                 entry_ex->entry.flags.ok_as_delegate = 1;
823         } else if (is_rodc) {
824                 /* The RODC krbtgt account is like the main krbtgt,
825                  * but it does not have a changepw or kadmin
826                  * service */
827
828                 entry_ex->entry.valid_end = NULL;
829                 entry_ex->entry.pw_end = NULL;
830
831                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
832                 entry_ex->entry.flags.client = 0;
833                 entry_ex->entry.flags.invalid = 0;
834                 entry_ex->entry.flags.server = 1;
835
836                 entry_ex->entry.flags.client = 0;
837                 entry_ex->entry.flags.forwardable = 1;
838                 entry_ex->entry.flags.ok_as_delegate = 0;
839         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
840                 /* The account/password expiry only applies when the account is used as a
841                  * client (ie password login), not when used as a server */
842
843                 /* Make very well sure we don't use this for a client,
844                  * it could bypass the password restrictions */
845                 entry_ex->entry.flags.client = 0;
846
847                 entry_ex->entry.valid_end = NULL;
848                 entry_ex->entry.pw_end = NULL;
849
850         } else {
851                 NTTIME must_change_time
852                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
853                                                              realm_dn, msg);
854                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
855                         entry_ex->entry.pw_end = NULL;
856                 } else {
857                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
858                         if (entry_ex->entry.pw_end == NULL) {
859                                 ret = ENOMEM;
860                                 goto out;
861                         }
862                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
863                 }
864
865                 acct_expiry = samdb_result_account_expires(msg);
866                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
867                         entry_ex->entry.valid_end = NULL;
868                 } else {
869                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
870                         if (entry_ex->entry.valid_end == NULL) {
871                                 ret = ENOMEM;
872                                 goto out;
873                         }
874                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
875                 }
876         }
877
878         entry_ex->entry.valid_start = NULL;
879
880         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
881         if (entry_ex->entry.max_life == NULL) {
882                 ret = ENOMEM;
883                 goto out;
884         }
885
886         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
887                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
888         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
889                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
890         } else {
891                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
892                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
893         }
894
895         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
896         if (entry_ex->entry.max_renew == NULL) {
897                 ret = ENOMEM;
898                 goto out;
899         }
900
901         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
902
903         /* Get keys from the db */
904         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
905                                            rid, is_rodc, userAccountControl,
906                                            ent_type, entry_ex);
907         if (ret) {
908                 /* Could be bougus data in the entry, or out of memory */
909                 goto out;
910         }
911
912         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
913         if (entry_ex->entry.etypes == NULL) {
914                 krb5_clear_error_message(context);
915                 ret = ENOMEM;
916                 goto out;
917         }
918         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
919         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
920         if (entry_ex->entry.etypes->val == NULL) {
921                 krb5_clear_error_message(context);
922                 ret = ENOMEM;
923                 goto out;
924         }
925         for (i=0; i < entry_ex->entry.etypes->len; i++) {
926                 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
927         }
928
929
930         p->msg = talloc_steal(p, msg);
931
932 out:
933         if (ret != 0) {
934                 /* This doesn't free ent itself, that is for the eventual caller to do */
935                 hdb_free_entry(context, entry_ex);
936         } else {
937                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
938         }
939
940         return ret;
941 }
942
943 /*
944  * Construct an hdb_entry from a directory entry.
945  * The kvno is what the remote client asked for
946  */
947 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
948                                                struct samba_kdc_db_context *kdc_db_ctx,
949                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
950                                                enum trust_direction direction,
951                                                struct ldb_dn *realm_dn,
952                                                unsigned flags,
953                                                uint32_t kvno,
954                                                struct ldb_message *msg,
955                                                hdb_entry_ex *entry_ex)
956 {
957         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
958         const char *dnsdomain;
959         const char *realm = lpcfg_realm(lp_ctx);
960         DATA_BLOB password_utf16 = data_blob_null;
961         DATA_BLOB password_utf8 = data_blob_null;
962         struct samr_Password _password_hash;
963         const struct samr_Password *password_hash = NULL;
964         const struct ldb_val *password_val;
965         struct trustAuthInOutBlob password_blob;
966         struct samba_kdc_entry *p;
967         bool use_previous;
968         uint32_t current_kvno;
969         uint32_t num_keys = 0;
970         enum ndr_err_code ndr_err;
971         int ret, trust_direction_flags;
972         unsigned int i;
973         struct AuthenticationInformationArray *auth_array;
974         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
975
976         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
977                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
978                                         "msDS-SupportedEncryptionTypes",
979                                         supported_enctypes);
980         }
981
982         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
983
984         if (direction == INBOUND) {
985                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
986
987         } else { /* OUTBOUND */
988                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
989                 /* replace realm */
990                 realm = strupper_talloc(mem_ctx, dnsdomain);
991                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
992         }
993
994         if (!password_val || !(trust_direction_flags & direction)) {
995                 krb5_clear_error_message(context);
996                 ret = HDB_ERR_NOENTRY;
997                 goto out;
998         }
999
1000         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1001                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1002         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1003                 krb5_clear_error_message(context);
1004                 ret = EINVAL;
1005                 goto out;
1006         }
1007
1008         p = talloc(mem_ctx, struct samba_kdc_entry);
1009         if (!p) {
1010                 ret = ENOMEM;
1011                 goto out;
1012         }
1013
1014         p->kdc_db_ctx = kdc_db_ctx;
1015         p->entry_ex = entry_ex;
1016         p->realm_dn = realm_dn;
1017
1018         talloc_set_destructor(p, samba_kdc_entry_destructor);
1019
1020         /* make sure we do not have bogus data in there */
1021         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
1022
1023         entry_ex->ctx = p;
1024         entry_ex->free_entry = samba_kdc_free_entry;
1025
1026         /* use 'whenCreated' */
1027         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1028         /* use 'kadmin' for now (needed by mit_samba) */
1029         ret = smb_krb5_make_principal(context,
1030                                       &entry_ex->entry.created_by.principal,
1031                                       realm, "kadmin", NULL);
1032         if (ret) {
1033                 krb5_clear_error_message(context);
1034                 goto out;
1035         }
1036
1037         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
1038         if (ret) {
1039                 krb5_clear_error_message(context);
1040                 goto out;
1041         }
1042
1043         /*
1044          * While we have copied the client principal, tests
1045          * show that Win2k3 returns the 'corrected' realm, not
1046          * the client-specified realm.  This code attempts to
1047          * replace the client principal's realm with the one
1048          * we determine from our records
1049          */
1050
1051         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
1052         if (ret) {
1053                 krb5_clear_error_message(context);
1054                 goto out;
1055         }
1056
1057         entry_ex->entry.valid_start = NULL;
1058
1059         /* we need to work out if we are going to use the current or
1060          * the previous password hash.
1061          * We base this on the kvno the client passes in. If the kvno
1062          * passed in is equal to the current kvno in our database then
1063          * we use the current structure. If it is the current kvno-1,
1064          * then we use the previous substrucure.
1065          */
1066
1067         /* first work out the current kvno */
1068         current_kvno = 0;
1069         for (i=0; i < password_blob.count; i++) {
1070                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
1071                         current_kvno = password_blob.current.array[i].AuthInfo.version.version;
1072                 }
1073         }
1074
1075         /* work out whether we will use the previous or current
1076            password */
1077         if (password_blob.previous.count == 0) {
1078                 /* there is no previous password */
1079                 use_previous = false;
1080         } else if (!(flags & HDB_F_KVNO_SPECIFIED) ||
1081             kvno == current_kvno) {
1082                 use_previous = false;
1083         } else if ((kvno+1 == current_kvno) ||
1084                    (kvno == 255 && current_kvno == 0)) {
1085                 use_previous = true;
1086         } else {
1087                 DEBUG(1,(__location__ ": Request for unknown kvno %u - current kvno is %u\n",
1088                          kvno, current_kvno));
1089                 krb5_clear_error_message(context);
1090                 ret = HDB_ERR_NOENTRY;
1091                 goto out;
1092         }
1093
1094         if (use_previous) {
1095                 auth_array = &password_blob.previous;
1096         } else {
1097                 auth_array = &password_blob.current;
1098         }
1099
1100         /* use the kvno the client specified, if available */
1101         if (flags & HDB_F_KVNO_SPECIFIED) {
1102                 entry_ex->entry.kvno = kvno;
1103         } else {
1104                 entry_ex->entry.kvno = current_kvno;
1105         }
1106
1107         for (i=0; i < auth_array->count; i++) {
1108                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1109                         bool ok;
1110
1111                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1112                                                          auth_array->array[i].AuthInfo.clear.size);
1113                         if (password_utf16.length == 0) {
1114                                 break;
1115                         }
1116
1117                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1118                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1119                                 if (password_hash == NULL) {
1120                                         num_keys += 1;
1121                                 }
1122                                 password_hash = &_password_hash;
1123                         }
1124
1125                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1126                                 break;
1127                         }
1128
1129                         ok = convert_string_talloc(mem_ctx,
1130                                                    CH_UTF16MUNGED, CH_UTF8,
1131                                                    password_utf16.data,
1132                                                    password_utf16.length,
1133                                                    (void *)&password_utf8.data,
1134                                                    &password_utf8.length);
1135                         if (!ok) {
1136                                 krb5_clear_error_message(context);
1137                                 ret = ENOMEM;
1138                                 goto out;
1139                         }
1140
1141                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1142                                 num_keys += 1;
1143                         }
1144                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1145                                 num_keys += 1;
1146                         }
1147                         break;
1148                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1149                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1150                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1151                                 num_keys += 1;
1152                         }
1153                 }
1154         }
1155
1156         /* Must have found a cleartext or MD4 password */
1157         if (num_keys == 0) {
1158                 DEBUG(1,(__location__ ": no usable key found\n"));
1159                 krb5_clear_error_message(context);
1160                 ret = HDB_ERR_NOENTRY;
1161                 goto out;
1162         }
1163
1164         entry_ex->entry.keys.val = calloc(num_keys, sizeof(Key));
1165         if (entry_ex->entry.keys.val == NULL) {
1166                 krb5_clear_error_message(context);
1167                 ret = ENOMEM;
1168                 goto out;
1169         }
1170
1171         if (password_utf8.length != 0) {
1172                 Key key = {};
1173                 krb5_const_principal salt_principal = principal;
1174                 krb5_salt salt;
1175                 krb5_data cleartext_data;
1176
1177                 cleartext_data.data = password_utf8.data;
1178                 cleartext_data.length = password_utf8.length;
1179
1180                 ret = krb5_get_pw_salt(context,
1181                                        salt_principal,
1182                                        &salt);
1183                 if (ret != 0) {
1184                         goto out;
1185                 }
1186
1187                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1188                         ret = krb5_string_to_key_data_salt(context,
1189                                                            ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1190                                                            cleartext_data,
1191                                                            salt,
1192                                                            &key.key);
1193                         if (ret != 0) {
1194                                 krb5_free_salt(context, salt);
1195                                 goto out;
1196                         }
1197
1198                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1199                         entry_ex->entry.keys.len++;
1200                 }
1201
1202                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1203                         ret = krb5_string_to_key_data_salt(context,
1204                                                            ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1205                                                            cleartext_data,
1206                                                            salt,
1207                                                            &key.key);
1208                         if (ret != 0) {
1209                                 krb5_free_salt(context, salt);
1210                                 goto out;
1211                         }
1212
1213                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1214                         entry_ex->entry.keys.len++;
1215                 }
1216
1217                 krb5_free_salt(context, salt);
1218         }
1219
1220         if (password_hash != NULL) {
1221                 Key key = {};
1222
1223                 ret = smb_krb5_keyblock_init_contents(context,
1224                                                       ENCTYPE_ARCFOUR_HMAC,
1225                                                       password_hash->hash,
1226                                                       sizeof(password_hash->hash),
1227                                                       &key.key);
1228                 if (ret != 0) {
1229                         goto out;
1230                 }
1231
1232                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1233                 entry_ex->entry.keys.len++;
1234         }
1235
1236         entry_ex->entry.flags = int2HDBFlags(0);
1237         entry_ex->entry.flags.immutable = 1;
1238         entry_ex->entry.flags.invalid = 0;
1239         entry_ex->entry.flags.server = 1;
1240         entry_ex->entry.flags.require_preauth = 1;
1241
1242         entry_ex->entry.pw_end = NULL;
1243
1244         entry_ex->entry.max_life = NULL;
1245
1246         entry_ex->entry.max_renew = NULL;
1247
1248         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
1249         if (entry_ex->entry.etypes == NULL) {
1250                 krb5_clear_error_message(context);
1251                 ret = ENOMEM;
1252                 goto out;
1253         }
1254         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
1255         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
1256         if (entry_ex->entry.etypes->val == NULL) {
1257                 krb5_clear_error_message(context);
1258                 ret = ENOMEM;
1259                 goto out;
1260         }
1261         for (i=0; i < entry_ex->entry.etypes->len; i++) {
1262                 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
1263         }
1264
1265
1266         p->msg = talloc_steal(p, msg);
1267
1268 out:
1269         if (ret != 0) {
1270                 /* This doesn't free ent itself, that is for the eventual caller to do */
1271                 hdb_free_entry(context, entry_ex);
1272         } else {
1273                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1274         }
1275
1276         return ret;
1277
1278 }
1279
1280 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1281                                         TALLOC_CTX *mem_ctx,
1282                                         const char *realm,
1283                                         struct ldb_dn *realm_dn,
1284                                         struct ldb_message **pmsg)
1285 {
1286         NTSTATUS status;
1287         const char * const *attrs = trust_attrs;
1288
1289         status = sam_get_results_trust(ldb_ctx,
1290                                        mem_ctx, realm, realm, attrs,
1291                                        pmsg);
1292         if (NT_STATUS_IS_OK(status)) {
1293                 return 0;
1294         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1295                 return HDB_ERR_NOENTRY;
1296         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1297                 int ret = ENOMEM;
1298                 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1299                 return ret;
1300         } else {
1301                 int ret = EINVAL;
1302                 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1303                 return ret;
1304         }
1305 }
1306
1307 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1308                                                 struct samba_kdc_db_context *kdc_db_ctx,
1309                                                 TALLOC_CTX *mem_ctx,
1310                                                 krb5_const_principal principal,
1311                                                 const char **attrs,
1312                                                 struct ldb_dn **realm_dn,
1313                                                 struct ldb_message **msg) {
1314         NTSTATUS nt_status;
1315         char *principal_string;
1316
1317         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1318                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1319                                                                       principal, 0);
1320                 if (principal_string == NULL) {
1321                         return ENOMEM;
1322                 }
1323                 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1324                                                       mem_ctx, principal_string, attrs,
1325                                                       realm_dn, msg);
1326                 TALLOC_FREE(principal_string);
1327         } else {
1328                 krb5_error_code ret;
1329                 ret = krb5_unparse_name(context, principal, &principal_string);
1330                 if (ret != 0) {
1331                         return ret;
1332                 }
1333                 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1334                                                       mem_ctx, principal_string, attrs,
1335                                                       realm_dn, msg);
1336                 free(principal_string);
1337         }
1338
1339         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1340                 return HDB_ERR_NOENTRY;
1341         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1342                 return ENOMEM;
1343         } else if (!NT_STATUS_IS_OK(nt_status)) {
1344                 return EINVAL;
1345         }
1346
1347         return 0;
1348 }
1349
1350 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1351                                                struct samba_kdc_db_context *kdc_db_ctx,
1352                                                TALLOC_CTX *mem_ctx,
1353                                                krb5_const_principal principal,
1354                                                unsigned flags,
1355                                                hdb_entry_ex *entry_ex) {
1356         struct ldb_dn *realm_dn;
1357         krb5_error_code ret;
1358         struct ldb_message *msg = NULL;
1359
1360         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1361                                       mem_ctx, principal, user_attrs,
1362                                       &realm_dn, &msg);
1363         if (ret != 0) {
1364                 return ret;
1365         }
1366
1367         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1368                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1369                                       flags,
1370                                       realm_dn, msg, entry_ex);
1371         return ret;
1372 }
1373
1374 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1375                                               struct samba_kdc_db_context *kdc_db_ctx,
1376                                               TALLOC_CTX *mem_ctx,
1377                                               krb5_const_principal principal,
1378                                               unsigned flags,
1379                                               uint32_t kvno,
1380                                               hdb_entry_ex *entry_ex)
1381 {
1382         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1383         krb5_error_code ret;
1384         struct ldb_message *msg = NULL;
1385         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1386         char *realm_from_princ, *realm_from_princ_malloc;
1387         krb5_principal alloc_principal = NULL;
1388
1389         realm_from_princ_malloc = smb_krb5_principal_get_realm(context, principal);
1390         if (realm_from_princ_malloc == NULL) {
1391                 /* can't happen */
1392                 return HDB_ERR_NOENTRY;
1393         }
1394         realm_from_princ = talloc_strdup(mem_ctx, realm_from_princ_malloc);
1395         free(realm_from_princ_malloc);
1396         if (realm_from_princ == NULL) {
1397                 return HDB_ERR_NOENTRY;
1398         }
1399
1400         if (krb5_princ_size(context, principal) != 2
1401             || (strcmp(krb5_principal_get_comp_string(context, principal, 0), KRB5_TGS_NAME) != 0)) {
1402                 /* Not a krbtgt */
1403                 return HDB_ERR_NOENTRY;
1404         }
1405
1406         /* krbtgt case.  Either us or a trusted realm */
1407
1408         if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1409             && lpcfg_is_my_domain_or_realm(lp_ctx, krb5_principal_get_comp_string(context, principal, 1))) {
1410                 /* us, or someone quite like us */
1411                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1412                  * is in our db, then direct the caller at our primary
1413                  * krbtgt */
1414
1415                 int lret;
1416                 unsigned int krbtgt_number;
1417                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1418                    trust tickets. We don't yet know what this means, but we do
1419                    seem to need to treat it as unspecified */
1420                 if (flags & HDB_F_KVNO_SPECIFIED) {
1421                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1422                         if (kdc_db_ctx->rodc) {
1423                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1424                                         return HDB_ERR_NOT_FOUND_HERE;
1425                                 }
1426                         }
1427                 } else {
1428                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1429                 }
1430
1431                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1432                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1433                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1434                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1435                                                "(objectClass=user)");
1436                 } else {
1437                         /* We need to look up an RODC krbtgt (perhaps
1438                          * ours, if we are an RODC, perhaps another
1439                          * RODC if we are a read-write DC */
1440                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1441                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1442                                                krbtgt_attrs,
1443                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1444                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1445                 }
1446
1447                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1448                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1449                                    (unsigned)(krbtgt_number));
1450                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1451                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1452                                                (unsigned)(krbtgt_number));
1453                         return HDB_ERR_NOENTRY;
1454                 } else if (lret != LDB_SUCCESS) {
1455                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1456                                    (unsigned)(krbtgt_number));
1457                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1458                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1459                                                (unsigned)(krbtgt_number));
1460                         return HDB_ERR_NOENTRY;
1461                 }
1462
1463                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1464                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1465                                               flags, realm_dn, msg, entry_ex);
1466                 if (alloc_principal) {
1467                         /* This is again copied in the message2entry call */
1468                         krb5_free_principal(context, alloc_principal);
1469                 }
1470                 if (ret != 0) {
1471                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1472                 }
1473                 return ret;
1474
1475         } else {
1476                 enum trust_direction direction = UNKNOWN;
1477                 const char *realm = NULL;
1478
1479                 /* Either an inbound or outbound trust */
1480
1481                 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1482                         /* look for inbound trust */
1483                         direction = INBOUND;
1484                         realm = krb5_principal_get_comp_string(context, principal, 1);
1485                 } else if (strcasecmp(lpcfg_realm(lp_ctx), krb5_principal_get_comp_string(context, principal, 1)) == 0) {
1486                         /* look for outbound trust */
1487                         direction = OUTBOUND;
1488                         realm = realm_from_princ;
1489                 } else {
1490                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1491                                    realm_from_princ,
1492                                    krb5_principal_get_comp_string(context, principal, 1));
1493                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1494                                                realm_from_princ,
1495                                                krb5_principal_get_comp_string(context, principal, 1));
1496                         return HDB_ERR_NOENTRY;
1497                 }
1498
1499                 /* Trusted domains are under CN=system */
1500
1501                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1502                                        mem_ctx,
1503                                        realm, realm_dn, &msg);
1504
1505                 if (ret != 0) {
1506                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1507                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1508                         return ret;
1509                 }
1510
1511                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1512                                                     principal, direction,
1513                                                     realm_dn, flags, kvno, msg, entry_ex);
1514                 if (ret != 0) {
1515                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1516                                    ldb_dn_get_linearized(msg->dn));
1517                         krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1518                                                "trust_message2entry failed for %s",
1519                                                ldb_dn_get_linearized(msg->dn));
1520                 }
1521                 return ret;
1522         }
1523
1524 }
1525
1526 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1527                                                struct samba_kdc_db_context *kdc_db_ctx,
1528                                                TALLOC_CTX *mem_ctx,
1529                                                krb5_const_principal principal,
1530                                                unsigned flags,
1531                                                const char **attrs,
1532                                                struct ldb_dn **realm_dn,
1533                                                struct ldb_message **msg)
1534 {
1535         krb5_error_code ret;
1536         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1537             && krb5_princ_size(context, principal) >= 2) {
1538                 /* 'normal server' case */
1539                 int ldb_ret;
1540                 NTSTATUS nt_status;
1541                 struct ldb_dn *user_dn;
1542                 char *principal_string;
1543
1544                 ret = krb5_unparse_name_flags(context, principal,
1545                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1546                                               &principal_string);
1547                 if (ret != 0) {
1548                         return ret;
1549                 }
1550
1551                 /* At this point we may find the host is known to be
1552                  * in a different realm, so we should generate a
1553                  * referral instead */
1554                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1555                                                          mem_ctx, principal_string,
1556                                                          &user_dn, realm_dn);
1557                 free(principal_string);
1558
1559                 if (!NT_STATUS_IS_OK(nt_status)) {
1560                         return HDB_ERR_NOENTRY;
1561                 }
1562
1563                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1564                                           mem_ctx,
1565                                           msg, user_dn, LDB_SCOPE_BASE,
1566                                           attrs,
1567                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1568                                           "(objectClass=*)");
1569                 if (ldb_ret != LDB_SUCCESS) {
1570                         return HDB_ERR_NOENTRY;
1571                 }
1572                 return 0;
1573         } else if (!(flags & HDB_F_FOR_AS_REQ)
1574                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1575                 /*
1576                  * The behaviour of accepting an
1577                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1578                  * containing a UPN only applies to TGS-REQ packets,
1579                  * not AS-REQ packets.
1580                  */
1581                 return samba_kdc_lookup_client(context, kdc_db_ctx,
1582                                                mem_ctx, principal, attrs,
1583                                                realm_dn, msg);
1584         } else {
1585                 /*
1586                  * This case is for:
1587                  *  - the AS-REQ, where we only accept
1588                  *    samAccountName based lookups for the server, no
1589                  *    matter if the name is an
1590                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
1591                  *  - for the TGS-REQ when we are not given an
1592                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1593                  *    only lookup samAccountName based names.
1594                  */
1595                 int lret;
1596                 char *short_princ;
1597                 krb5_principal enterprise_prinicpal = NULL;
1598
1599                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1600                         /* Need to reparse the enterprise principal to find the real target */
1601                         if (krb5_princ_size(context, principal) != 1) {
1602                                 ret = KRB5_PARSE_MALFORMED;
1603                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
1604                                                        "enterprise principal with wrong (%d) number of components",
1605                                                        krb5_princ_size(context, principal));
1606                                 return ret;
1607                         }
1608                         ret = krb5_parse_name(context,
1609                                               krb5_principal_get_comp_string(context, principal, 0),
1610                                               &enterprise_prinicpal);
1611                         if (ret) {
1612                                 return ret;
1613                         }
1614                         principal = enterprise_prinicpal;
1615                 }
1616
1617                 /* server as client principal case, but we must not lookup userPrincipalNames */
1618                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1619
1620                 /* TODO: Check if it is our realm, otherwise give referral */
1621
1622                 ret = krb5_unparse_name_flags(context, principal,
1623                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
1624                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
1625                                               &short_princ);
1626
1627                 if (ret != 0) {
1628                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1629                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1630                         return ret;
1631                 }
1632
1633                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1634                                        *realm_dn, LDB_SCOPE_SUBTREE,
1635                                        attrs,
1636                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1637                                        "(&(objectClass=user)(samAccountName=%s))",
1638                                        ldb_binary_encode_string(mem_ctx, short_princ));
1639                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1640                         DEBUG(3, ("Failed to find an entry for %s\n", short_princ));
1641                         free(short_princ);
1642                         return HDB_ERR_NOENTRY;
1643                 }
1644                 if (lret != LDB_SUCCESS) {
1645                         DEBUG(3, ("Failed single search for %s - %s\n",
1646                                   short_princ, ldb_errstring(kdc_db_ctx->samdb)));
1647                         free(short_princ);
1648                         return HDB_ERR_NOENTRY;
1649                 }
1650                 free(short_princ);
1651                 return 0;
1652         }
1653         return HDB_ERR_NOENTRY;
1654 }
1655
1656
1657
1658 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1659                                               struct samba_kdc_db_context *kdc_db_ctx,
1660                                               TALLOC_CTX *mem_ctx,
1661                                               krb5_const_principal principal,
1662                                               unsigned flags,
1663                                               hdb_entry_ex *entry_ex)
1664 {
1665         krb5_error_code ret;
1666         struct ldb_dn *realm_dn;
1667         struct ldb_message *msg;
1668
1669         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1670                                       flags, server_attrs, &realm_dn, &msg);
1671         if (ret != 0) {
1672                 return ret;
1673         }
1674
1675         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1676                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1677                                       flags,
1678                                       realm_dn, msg, entry_ex);
1679         if (ret != 0) {
1680                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1681         }
1682
1683         return ret;
1684 }
1685
1686 krb5_error_code samba_kdc_fetch(krb5_context context,
1687                                 struct samba_kdc_db_context *kdc_db_ctx,
1688                                 krb5_const_principal principal,
1689                                 unsigned flags,
1690                                 krb5_kvno kvno,
1691                                 hdb_entry_ex *entry_ex)
1692 {
1693         krb5_error_code ret = HDB_ERR_NOENTRY;
1694         TALLOC_CTX *mem_ctx;
1695
1696         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1697         if (!mem_ctx) {
1698                 ret = ENOMEM;
1699                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1700                 return ret;
1701         }
1702
1703         if (flags & HDB_F_GET_CLIENT) {
1704                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1705                 if (ret != HDB_ERR_NOENTRY) goto done;
1706         }
1707         if (flags & HDB_F_GET_SERVER) {
1708                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1709                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1710                 if (ret != HDB_ERR_NOENTRY) goto done;
1711
1712                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1713                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1714                 if (ret != HDB_ERR_NOENTRY) goto done;
1715         }
1716         if (flags & HDB_F_GET_KRBTGT) {
1717                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1718                 if (ret != HDB_ERR_NOENTRY) goto done;
1719         }
1720
1721 done:
1722         talloc_free(mem_ctx);
1723         return ret;
1724 }
1725
1726 struct samba_kdc_seq {
1727         unsigned int index;
1728         unsigned int count;
1729         struct ldb_message **msgs;
1730         struct ldb_dn *realm_dn;
1731 };
1732
1733 static krb5_error_code samba_kdc_seq(krb5_context context,
1734                                      struct samba_kdc_db_context *kdc_db_ctx,
1735                                      hdb_entry_ex *entry)
1736 {
1737         krb5_error_code ret;
1738         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1739         const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
1740         struct ldb_message *msg = NULL;
1741         const char *sAMAccountName = NULL;
1742         krb5_principal principal = NULL;
1743         TALLOC_CTX *mem_ctx;
1744
1745         if (!priv) {
1746                 return HDB_ERR_NOENTRY;
1747         }
1748
1749         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1750
1751         if (!mem_ctx) {
1752                 ret = ENOMEM;
1753                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1754                 return ret;
1755         }
1756
1757         while (priv->index < priv->count) {
1758                 msg = priv->msgs[priv->index++];
1759
1760                 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
1761                 if (sAMAccountName != NULL) {
1762                         break;
1763                 }
1764         }
1765
1766         if (sAMAccountName == NULL) {
1767                 ret = HDB_ERR_NOENTRY;
1768                 goto out;
1769         }
1770
1771         ret = smb_krb5_make_principal(context, &principal,
1772                                       realm, sAMAccountName, NULL);
1773         if (ret != 0) {
1774                 goto out;
1775         }
1776
1777         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1778                                       principal, SAMBA_KDC_ENT_TYPE_ANY,
1779                                       HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1780                                       priv->realm_dn, msg, entry);
1781
1782 out:
1783         if (principal != NULL) {
1784                 krb5_free_principal(context, principal);
1785         }
1786
1787         if (ret != 0) {
1788                 TALLOC_FREE(priv);
1789                 kdc_db_ctx->seq_ctx = NULL;
1790         } else {
1791                 talloc_free(mem_ctx);
1792         }
1793
1794         return ret;
1795 }
1796
1797 krb5_error_code samba_kdc_firstkey(krb5_context context,
1798                                    struct samba_kdc_db_context *kdc_db_ctx,
1799                                    hdb_entry_ex *entry)
1800 {
1801         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1802         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1803         char *realm;
1804         struct ldb_result *res = NULL;
1805         krb5_error_code ret;
1806         TALLOC_CTX *mem_ctx;
1807         int lret;
1808
1809         if (priv) {
1810                 TALLOC_FREE(priv);
1811                 kdc_db_ctx->seq_ctx = NULL;
1812         }
1813
1814         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1815         if (!priv) {
1816                 ret = ENOMEM;
1817                 krb5_set_error_message(context, ret, "talloc: out of memory");
1818                 return ret;
1819         }
1820
1821         priv->index = 0;
1822         priv->msgs = NULL;
1823         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1824         priv->count = 0;
1825
1826         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1827
1828         if (!mem_ctx) {
1829                 ret = ENOMEM;
1830                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1831                 return ret;
1832         }
1833
1834         ret = krb5_get_default_realm(context, &realm);
1835         if (ret != 0) {
1836                 TALLOC_FREE(priv);
1837                 return ret;
1838         }
1839         krb5_free_default_realm(context, realm);
1840
1841         lret = dsdb_search(ldb_ctx, priv, &res,
1842                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1843                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
1844                            "(objectClass=user)");
1845
1846         if (lret != LDB_SUCCESS) {
1847                 TALLOC_FREE(priv);
1848                 return HDB_ERR_NOENTRY;
1849         }
1850
1851         priv->count = res->count;
1852         priv->msgs = talloc_steal(priv, res->msgs);
1853         talloc_free(res);
1854
1855         kdc_db_ctx->seq_ctx = priv;
1856
1857         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1858
1859         if (ret != 0) {
1860                 TALLOC_FREE(priv);
1861                 kdc_db_ctx->seq_ctx = NULL;
1862         } else {
1863                 talloc_free(mem_ctx);
1864         }
1865         return ret;
1866 }
1867
1868 krb5_error_code samba_kdc_nextkey(krb5_context context,
1869                                   struct samba_kdc_db_context *kdc_db_ctx,
1870                                   hdb_entry_ex *entry)
1871 {
1872         return samba_kdc_seq(context, kdc_db_ctx, entry);
1873 }
1874
1875 /* Check if a given entry may delegate or do s4u2self to this target principal
1876  *
1877  * This is currently a very nasty hack - allowing only delegation to itself.
1878  */
1879 krb5_error_code
1880 samba_kdc_check_s4u2self(krb5_context context,
1881                          struct samba_kdc_db_context *kdc_db_ctx,
1882                          hdb_entry_ex *entry,
1883                          krb5_const_principal target_principal)
1884 {
1885         krb5_error_code ret;
1886         struct ldb_dn *realm_dn;
1887         struct ldb_message *msg;
1888         struct dom_sid *orig_sid;
1889         struct dom_sid *target_sid;
1890         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1891         const char *delegation_check_attrs[] = {
1892                 "objectSid", NULL
1893         };
1894
1895         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
1896
1897         if (!mem_ctx) {
1898                 ret = ENOMEM;
1899                 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
1900                 return ret;
1901         }
1902
1903         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1904                                       HDB_F_GET_CLIENT|HDB_F_GET_SERVER,
1905                                       delegation_check_attrs, &realm_dn, &msg);
1906
1907         if (ret != 0) {
1908                 talloc_free(mem_ctx);
1909                 return ret;
1910         }
1911
1912         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1913         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1914
1915         /* Allow delegation to the same principal, even if by a different
1916          * name.  The easy and safe way to prove this is by SID
1917          * comparison */
1918         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1919                 talloc_free(mem_ctx);
1920                 return KRB5KDC_ERR_BADOPTION;
1921         }
1922
1923         talloc_free(mem_ctx);
1924         return ret;
1925 }
1926
1927 /* Certificates printed by a the Certificate Authority might have a
1928  * slightly different form of the user principal name to that in the
1929  * database.  Allow a mismatch where they both refer to the same
1930  * SID */
1931
1932 krb5_error_code
1933 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1934                                     struct samba_kdc_db_context *kdc_db_ctx,
1935                                      hdb_entry_ex *entry,
1936                                      krb5_const_principal certificate_principal)
1937 {
1938         krb5_error_code ret;
1939         struct ldb_dn *realm_dn;
1940         struct ldb_message *msg;
1941         struct dom_sid *orig_sid;
1942         struct dom_sid *target_sid;
1943         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1944         const char *ms_upn_check_attrs[] = {
1945                 "objectSid", NULL
1946         };
1947
1948         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1949
1950         if (!mem_ctx) {
1951                 ret = ENOMEM;
1952                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1953                 return ret;
1954         }
1955
1956         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1957                                       mem_ctx, certificate_principal,
1958                                       ms_upn_check_attrs, &realm_dn, &msg);
1959
1960         if (ret != 0) {
1961                 talloc_free(mem_ctx);
1962                 return ret;
1963         }
1964
1965         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1966         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1967
1968         /* Consider these to be the same principal, even if by a different
1969          * name.  The easy and safe way to prove this is by SID
1970          * comparison */
1971         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1972                 talloc_free(mem_ctx);
1973                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1974         }
1975
1976         talloc_free(mem_ctx);
1977         return ret;
1978 }
1979
1980 /*
1981  * Check if a given entry may delegate to this target principal
1982  * with S4U2Proxy.
1983  */
1984 krb5_error_code
1985 samba_kdc_check_s4u2proxy(krb5_context context,
1986                           struct samba_kdc_db_context *kdc_db_ctx,
1987                           hdb_entry_ex *entry,
1988                           krb5_const_principal target_principal)
1989 {
1990         krb5_error_code ret;
1991         char *tmp = NULL;
1992         const char *client_dn = NULL;
1993         const char *target_principal_name = NULL;
1994         struct ldb_message_element *el;
1995         struct ldb_val val;
1996         unsigned int i;
1997         bool found = false;
1998         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1999
2000         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2001
2002         if (!mem_ctx) {
2003                 ret = ENOMEM;
2004                 krb5_set_error_message(context, ret,
2005                                        "samba_kdc_check_s4u2proxy:"
2006                                        " talloc_named() failed!");
2007                 return ret;
2008         }
2009
2010         client_dn = ldb_dn_get_linearized(p->msg->dn);
2011         if (!client_dn) {
2012                 if (errno == 0) {
2013                         errno = ENOMEM;
2014                 }
2015                 ret = errno;
2016                 krb5_set_error_message(context, ret,
2017                                        "samba_kdc_check_s4u2proxy:"
2018                                        " ldb_dn_get_linearized() failed!");
2019                 return ret;
2020         }
2021
2022         /*
2023          * The main heimdal code already checked that the target_principal
2024          * belongs to the same realm as the client.
2025          *
2026          * So we just need the principal without the realm,
2027          * as that is what is configured in the "msDS-AllowedToDelegateTo"
2028          * attribute.
2029          */
2030         ret = krb5_unparse_name_flags(context, target_principal,
2031                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2032         if (ret) {
2033                 talloc_free(mem_ctx);
2034                 krb5_set_error_message(context, ret,
2035                                        "samba_kdc_check_s4u2proxy:"
2036                                        " krb5_unparse_name() failed!");
2037                 return ret;
2038         }
2039         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2040                  client_dn, tmp));
2041
2042         target_principal_name = talloc_strdup(mem_ctx, tmp);
2043         SAFE_FREE(tmp);
2044         if (target_principal_name == NULL) {
2045                 ret = ENOMEM;
2046                 krb5_set_error_message(context, ret,
2047                                        "samba_kdc_check_s4u2proxy:"
2048                                        " talloc_strdup() failed!");
2049                 return ret;
2050         }
2051
2052         el = ldb_msg_find_element(p->msg, "msDS-AllowedToDelegateTo");
2053         if (el == NULL) {
2054                 goto bad_option;
2055         }
2056
2057         val = data_blob_string_const(target_principal_name);
2058
2059         for (i=0; i<el->num_values; i++) {
2060                 struct ldb_val *val1 = &val;
2061                 struct ldb_val *val2 = &el->values[i];
2062                 int cmp;
2063
2064                 if (val1->length != val2->length) {
2065                         continue;
2066                 }
2067
2068                 cmp = strncasecmp((const char *)val1->data,
2069                                   (const char *)val2->data,
2070                                   val1->length);
2071                 if (cmp != 0) {
2072                         continue;
2073                 }
2074
2075                 found = true;
2076                 break;
2077         }
2078
2079         if (!found) {
2080                 goto bad_option;
2081         }
2082
2083         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2084                  client_dn, tmp));
2085         talloc_free(mem_ctx);
2086         return 0;
2087
2088 bad_option:
2089         krb5_set_error_message(context, ret,
2090                                "samba_kdc_check_s4u2proxy: client[%s] "
2091                                "not allowed for delegation to target[%s]",
2092                                client_dn,
2093                                target_principal_name);
2094         talloc_free(mem_ctx);
2095         return KRB5KDC_ERR_BADOPTION;
2096 }
2097
2098 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2099                                 struct samba_kdc_db_context **kdc_db_ctx_out)
2100 {
2101         int ldb_ret;
2102         struct ldb_message *msg;
2103         struct auth_session_info *session_info;
2104         struct samba_kdc_db_context *kdc_db_ctx;
2105         /* The idea here is very simple.  Using Kerberos to
2106          * authenticate the KDC to the LDAP server is higly likely to
2107          * be circular.
2108          *
2109          * In future we may set this up to use EXERNAL and SSL
2110          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2111         */
2112
2113         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2114         if (kdc_db_ctx == NULL) {
2115                 return NT_STATUS_NO_MEMORY;
2116         }
2117         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2118         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2119
2120         /* get default kdc policy */
2121         lpcfg_default_kdc_policy(base_ctx->lp_ctx,
2122                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
2123                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
2124                                  &kdc_db_ctx->policy.renewal_lifetime);
2125
2126         session_info = system_session(kdc_db_ctx->lp_ctx);
2127         if (session_info == NULL) {
2128                 return NT_STATUS_INTERNAL_ERROR;
2129         }
2130
2131         /* Setup the link to LDB */
2132         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
2133                                           base_ctx->lp_ctx, session_info, 0);
2134         if (kdc_db_ctx->samdb == NULL) {
2135                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2136                 talloc_free(kdc_db_ctx);
2137                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2138         }
2139
2140         /* Find out our own krbtgt kvno */
2141         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2142         if (ldb_ret != LDB_SUCCESS) {
2143                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2144                           ldb_errstring(kdc_db_ctx->samdb)));
2145                 talloc_free(kdc_db_ctx);
2146                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2147         }
2148         if (kdc_db_ctx->rodc) {
2149                 int my_krbtgt_number;
2150                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2151                 struct ldb_dn *account_dn;
2152                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2153                 if (!server_dn) {
2154                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2155                                   ldb_errstring(kdc_db_ctx->samdb)));
2156                         talloc_free(kdc_db_ctx);
2157                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2158                 }
2159
2160                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2161                                              "serverReference", &account_dn);
2162                 if (ldb_ret != LDB_SUCCESS) {
2163                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2164                                   ldb_errstring(kdc_db_ctx->samdb)));
2165                         talloc_free(kdc_db_ctx);
2166                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2167                 }
2168
2169                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2170                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2171                 talloc_free(account_dn);
2172                 if (ldb_ret != LDB_SUCCESS) {
2173                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2174                                   ldb_errstring(kdc_db_ctx->samdb)));
2175                         talloc_free(kdc_db_ctx);
2176                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2177                 }
2178
2179                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2180                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2181                                           secondary_keytab,
2182                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2183                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2184                 if (ldb_ret != LDB_SUCCESS) {
2185                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2186                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2187                                   ldb_errstring(kdc_db_ctx->samdb),
2188                                   ldb_strerror(ldb_ret)));
2189                         talloc_free(kdc_db_ctx);
2190                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2191                 }
2192                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2193                 if (my_krbtgt_number == -1) {
2194                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2195                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2196                                   my_krbtgt_number));
2197                         talloc_free(kdc_db_ctx);
2198                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2199                 }
2200                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2201
2202         } else {
2203                 kdc_db_ctx->my_krbtgt_number = 0;
2204                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2205                                           &msg,
2206                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
2207                                           LDB_SCOPE_SUBTREE,
2208                                           krbtgt_attrs,
2209                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2210                                           "(&(objectClass=user)(samAccountName=krbtgt))");
2211
2212                 if (ldb_ret != LDB_SUCCESS) {
2213                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2214                         talloc_free(kdc_db_ctx);
2215                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2216                 }
2217                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2218                 kdc_db_ctx->my_krbtgt_number = 0;
2219                 talloc_free(msg);
2220         }
2221         *kdc_db_ctx_out = kdc_db_ctx;
2222         return NT_STATUS_OK;
2223 }