95c60e2c78c8e443f9f2f958e3d1b23286581cfc
[kai/samba.git] / source4 / kdc / hdb-ldb.c
1 /*
2  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3  * Copyright (c) 2004, Andrew Bartlett <abartlet@samba.org>.
4  * Copyright (c) 2004, Stefan Metzmacher <metze@samba.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * 3. Neither the name of PADL Software  nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "includes.h"
36 #include "system/time.h"
37 #include "dsdb/common/flags.h"
38 #include "lib/ldb/include/ldb.h"
39 #include "lib/ldb/include/ldb_errors.h"
40 #include "librpc/gen_ndr/netlogon.h"
41 #include "auth/auth.h"
42 #include "auth/credentials/credentials.h"
43 #include "auth/auth_sam.h"
44 #include "util/util_ldb.h"
45 #include "dsdb/samdb/samdb.h"
46 #include "librpc/ndr/libndr.h"
47 #include "librpc/gen_ndr/ndr_drsblobs.h"
48 #include "libcli/auth/libcli_auth.h"
49 #include "param/param.h"
50 #include "events/events.h"
51 #include "kdc/kdc.h"
52 #include "lib/crypto/md4.h"
53
54 enum hdb_ldb_ent_type 
55 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
56   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_TRUST, HDB_LDB_ENT_TYPE_ANY };
57
58 enum trust_direction {
59         INBOUND,
60         OUTBOUND,
61         UNKNOWN
62 };
63
64 static const char *realm_ref_attrs[] = {
65         "nCName", 
66         "dnsRoot", 
67         NULL
68 };
69
70 static const char *trust_attrs[] = {
71         "trustPartner",
72         "trustAuthIncoming",
73         "trustAuthOutgoing",
74         "whenCreated",
75         "msDS-SupportedEncryptionTypes",
76         "trustAttributes",
77         "trustDirection",
78         "trustType",
79         NULL
80 };
81
82 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
83 {
84     const char *tmp;
85     const char *gentime;
86     struct tm tm;
87
88     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
89     if (!gentime)
90         return default_val;
91
92     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
93     if (tmp == NULL) {
94             return default_val;
95     }
96
97     return timegm(&tm);
98 }
99
100 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
101 {
102         HDBFlags flags = int2HDBFlags(0);
103
104         /* we don't allow kadmin deletes */
105         flags.immutable = 1;
106
107         /* mark the principal as invalid to start with */
108         flags.invalid = 1;
109
110         flags.renewable = 1;
111
112         /* All accounts are servers, but this may be disabled again in the caller */
113         flags.server = 1;
114
115         /* Account types - clear the invalid bit if it turns out to be valid */
116         if (userAccountControl & UF_NORMAL_ACCOUNT) {
117                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
118                         flags.client = 1;
119                 }
120                 flags.invalid = 0;
121         }
122         
123         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
124                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
125                         flags.client = 1;
126                 }
127                 flags.invalid = 0;
128         }
129         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
130                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
131                         flags.client = 1;
132                 }
133                 flags.invalid = 0;
134         }
135         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
136                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
137                         flags.client = 1;
138                 }
139                 flags.invalid = 0;
140         }
141
142         /* Not permitted to act as a client if disabled */
143         if (userAccountControl & UF_ACCOUNTDISABLE) {
144                 flags.client = 0;
145         }
146         if (userAccountControl & UF_LOCKOUT) {
147                 flags.invalid = 1;
148         }
149 /*
150         if (userAccountControl & UF_PASSWORD_NOTREQD) {
151                 flags.invalid = 1;
152         }
153 */
154 /*
155         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
156 */
157         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
158                 flags.invalid = 1;
159         }
160
161 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
162
163 /*
164         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
165                 flags.invalid = 1;
166         }
167 */
168         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
169                 flags.require_hwauth = 1;
170         }
171         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
172                 flags.ok_as_delegate = 1;
173         }       
174         if (!(userAccountControl & UF_NOT_DELEGATED)) {
175                 flags.forwardable = 1;
176                 flags.proxiable = 1;
177         }
178
179         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
180                 flags.require_preauth = 0;
181         } else {
182                 flags.require_preauth = 1;
183
184         }
185         return flags;
186 }
187
188 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
189 {
190     hdb_entry_ex *entry_ex = private->entry_ex;
191     free_hdb_entry(&entry_ex->entry);
192     return 0;
193 }
194
195 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
196 {
197         talloc_free(entry_ex->ctx);
198 }
199
200 static krb5_error_code LDB_message2entry_keys(krb5_context context,
201                                               struct smb_iconv_convenience *iconv_convenience,
202                                               TALLOC_CTX *mem_ctx,
203                                               struct ldb_message *msg,
204                                               unsigned int userAccountControl,
205                                               hdb_entry_ex *entry_ex)
206 {
207         krb5_error_code ret = 0;
208         enum ndr_err_code ndr_err;
209         struct samr_Password *hash;
210         const struct ldb_val *sc_val;
211         struct supplementalCredentialsBlob scb;
212         struct supplementalCredentialsPackage *scpk = NULL;
213         bool newer_keys = false;
214         struct package_PrimaryKerberosBlob _pkb;
215         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
216         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
217         uint32_t i;
218         uint32_t allocated_keys = 0;
219
220         entry_ex->entry.keys.val = NULL;
221         entry_ex->entry.keys.len = 0;
222
223         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
224
225         /* Get keys from the db */
226
227         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
228         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
229
230         /* unicodePwd for enctype 0x17 (23) if present */
231         if (hash) {
232                 allocated_keys++;
233         }
234
235         /* supplementalCredentials if present */
236         if (sc_val) {
237                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb,
238                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
239                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
240                         dump_data(0, sc_val->data, sc_val->length);
241                         ret = EINVAL;
242                         goto out;
243                 }
244
245                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
246                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
247                         ret = EINVAL;
248                         goto out;
249                 }
250
251                 for (i=0; i < scb.sub.num_packages; i++) {
252                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
253                                 scpk = &scb.sub.packages[i];
254                                 if (!scpk->data || !scpk->data[0]) {
255                                         scpk = NULL;
256                                         continue;
257                                 }
258                                 newer_keys = true;
259                                 break;
260                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
261                                 scpk = &scb.sub.packages[i];
262                                 if (!scpk->data || !scpk->data[0]) {
263                                         scpk = NULL;
264                                 }
265                                 /*
266                                  * we don't break here in hope to find
267                                  * a Kerberos-Newer-Keys package
268                                  */
269                         }
270                 }
271         }
272         /*
273          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
274          * of supplementalCredentials
275          */
276         if (scpk) {
277                 DATA_BLOB blob;
278
279                 blob = strhex_to_data_blob(scpk->data);
280                 if (!blob.data) {
281                         ret = ENOMEM;
282                         goto out;
283                 }
284                 talloc_steal(mem_ctx, blob.data);
285
286                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
287                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb,
288                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
289                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
290                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
291                         krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
292                         ret = EINVAL;
293                         goto out;
294                 }
295
296                 if (newer_keys && _pkb.version != 4) {
297                         krb5_set_error_string(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
298                         krb5_warnx(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
299                         ret = EINVAL;
300                         goto out;
301                 }
302
303                 if (!newer_keys && _pkb.version != 3) {
304                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
305                         krb5_warnx(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
306                         ret = EINVAL;
307                         goto out;
308                 }
309
310                 if (_pkb.version == 4) {
311                         pkb4 = &_pkb.ctr.ctr4;
312                         allocated_keys += pkb4->num_keys;
313                 } else if (_pkb.version == 3) {
314                         pkb3 = &_pkb.ctr.ctr3;
315                         allocated_keys += pkb3->num_keys;
316                 }
317         }
318
319         if (allocated_keys == 0) {
320                 /* oh, no password.  Apparently (comment in
321                  * hdb-ldap.c) this violates the ASN.1, but this
322                  * allows an entry with no keys (yet). */
323                 return 0;
324         }
325
326         /* allocate space to decode into */
327         entry_ex->entry.keys.len = 0;
328         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
329         if (entry_ex->entry.keys.val == NULL) {
330                 ret = ENOMEM;
331                 goto out;
332         }
333
334         if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
335                 Key key;
336
337                 key.mkvno = 0;
338                 key.salt = NULL; /* No salt for this enc type */
339
340                 ret = krb5_keyblock_init(context,
341                                          ENCTYPE_ARCFOUR_HMAC_MD5,
342                                          hash->hash, sizeof(hash->hash), 
343                                          &key.key);
344                 if (ret) {
345                         goto out;
346                 }
347
348                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
349                 entry_ex->entry.keys.len++;
350         }
351
352         if (pkb4) {
353                 for (i=0; i < pkb4->num_keys; i++) {
354                         bool use = true;
355                         Key key;
356
357                         if (!pkb4->keys[i].value) continue;
358
359                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
360                                 switch (pkb4->keys[i].keytype) {
361                                 case ENCTYPE_DES_CBC_CRC:
362                                 case ENCTYPE_DES_CBC_MD5:
363                                         break;
364                                 default:
365                                         use = false;
366                                         break;
367                                 }
368                         }
369
370                         if (!use) continue;
371
372                         key.mkvno = 0;
373                         key.salt = NULL;
374
375                         if (pkb4->salt.string) {
376                                 DATA_BLOB salt;
377
378                                 salt = data_blob_string_const(pkb4->salt.string);
379
380                                 key.salt = calloc(1, sizeof(*key.salt));
381                                 if (key.salt == NULL) {
382                                         ret = ENOMEM;
383                                         goto out;
384                                 }
385
386                                 key.salt->type = hdb_pw_salt;
387
388                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
389                                 if (ret) {
390                                         free(key.salt);
391                                         key.salt = NULL;
392                                         goto out;
393                                 }
394                         }
395
396                         /* TODO: maybe pass the iteration_count somehow... */
397
398                         ret = krb5_keyblock_init(context,
399                                                  pkb4->keys[i].keytype,
400                                                  pkb4->keys[i].value->data,
401                                                  pkb4->keys[i].value->length,
402                                                  &key.key);
403                         if (ret) {
404                                 if (key.salt) {
405                                         free_Salt(key.salt);
406                                         free(key.salt);
407                                         key.salt = NULL;
408                                 }
409                                 goto out;
410                         }
411
412                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
413                         entry_ex->entry.keys.len++;
414                 }
415         } else if (pkb3) {
416                 for (i=0; i < pkb3->num_keys; i++) {
417                         bool use = true;
418                         Key key;
419
420                         if (!pkb3->keys[i].value) continue;
421
422                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
423                                 switch (pkb3->keys[i].keytype) {
424                                 case ENCTYPE_DES_CBC_CRC:
425                                 case ENCTYPE_DES_CBC_MD5:
426                                         break;
427                                 default:
428                                         use = false;
429                                         break;
430                                 }
431                         }
432
433                         if (!use) continue;
434
435                         key.mkvno = 0;
436                         key.salt = NULL;
437
438                         if (pkb3->salt.string) {
439                                 DATA_BLOB salt;
440
441                                 salt = data_blob_string_const(pkb3->salt.string);
442
443                                 key.salt = calloc(1, sizeof(*key.salt));
444                                 if (key.salt == NULL) {
445                                         ret = ENOMEM;
446                                         goto out;
447                                 }
448
449                                 key.salt->type = hdb_pw_salt;
450
451                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
452                                 if (ret) {
453                                         free(key.salt);
454                                         key.salt = NULL;
455                                         goto out;
456                                 }
457                         }
458
459                         ret = krb5_keyblock_init(context,
460                                                  pkb3->keys[i].keytype,
461                                                  pkb3->keys[i].value->data,
462                                                  pkb3->keys[i].value->length,
463                                                  &key.key);
464                         if (ret) {
465                                 if (key.salt) {
466                                         free_Salt(key.salt);
467                                         free(key.salt);
468                                         key.salt = NULL;
469                                 }
470                                 goto out;
471                         }
472
473                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
474                         entry_ex->entry.keys.len++;
475                 }
476         }
477
478 out:
479         if (ret != 0) {
480                 entry_ex->entry.keys.len = 0;
481         }
482         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
483                 free(entry_ex->entry.keys.val);
484                 entry_ex->entry.keys.val = NULL;
485         }
486         return ret;
487 }
488
489 /*
490  * Construct an hdb_entry from a directory entry.
491  */
492 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
493                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
494                                          enum hdb_ldb_ent_type ent_type, 
495                                          struct ldb_message *msg,
496                                          struct ldb_message *realm_ref_msg,
497                                          hdb_entry_ex *entry_ex)
498 {
499         unsigned int userAccountControl;
500         int i;
501         krb5_error_code ret = 0;
502         krb5_boolean is_computer = FALSE;
503         const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL);
504         char *realm = strupper_talloc(mem_ctx, dnsdomain);
505         struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm");
506         struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db,
507                                                         mem_ctx,
508                                                         realm_ref_msg,
509                                                         "nCName",
510                                                         ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL));
511
512         struct hdb_ldb_private *private;
513         NTTIME acct_expiry;
514
515         struct ldb_message_element *objectclasses;
516         struct ldb_val computer_val;
517         computer_val.data = discard_const_p(uint8_t,"computer");
518         computer_val.length = strlen((const char *)computer_val.data);
519         
520         objectclasses = ldb_msg_find_element(msg, "objectClass");
521         
522         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
523                 is_computer = TRUE;
524         }
525
526         memset(entry_ex, 0, sizeof(*entry_ex));
527
528         if (!realm) {
529                 krb5_set_error_string(context, "talloc_strdup: out of memory");
530                 ret = ENOMEM;
531                 goto out;
532         }
533                         
534         private = talloc(mem_ctx, struct hdb_ldb_private);
535         if (!private) {
536                 ret = ENOMEM;
537                 goto out;
538         }
539
540         private->entry_ex = entry_ex;
541         private->iconv_convenience = lp_iconv_convenience(lp_ctx);
542         private->netbios_name = lp_netbios_name(lp_ctx);
543
544         talloc_set_destructor(private, hdb_ldb_destrutor);
545
546         entry_ex->ctx = private;
547         entry_ex->free_entry = hdb_ldb_free_entry;
548
549         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
550
551         
552         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
553         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
554                 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
555                 if (!samAccountName) {
556                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
557                         ret = ENOENT;
558                         goto out;
559                 }
560                 samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
561                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
562         } else {
563                 char *strdup_realm;
564                 ret = copy_Principal(principal, entry_ex->entry.principal);
565                 if (ret) {
566                         krb5_clear_error_string(context);
567                         goto out;
568                 }
569
570                 /* While we have copied the client principal, tests
571                  * show that Win2k3 returns the 'corrected' realm, not
572                  * the client-specified realm.  This code attempts to
573                  * replace the client principal's realm with the one
574                  * we determine from our records */
575                 
576                 /* this has to be with malloc() */
577                 strdup_realm = strdup(realm);
578                 if (!strdup_realm) {
579                         ret = ENOMEM;
580                         krb5_clear_error_string(context);
581                         goto out;
582                 }
583                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
584                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
585         }
586
587         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
588
589         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
590                 entry_ex->entry.flags.invalid = 0;
591                 entry_ex->entry.flags.server = 1;
592                 entry_ex->entry.flags.forwardable = 1;
593                 entry_ex->entry.flags.ok_as_delegate = 1;
594         }
595
596         if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
597                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
598                         entry_ex->entry.flags.server = 0;
599                 }
600         }
601
602         /* use 'whenCreated' */
603         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
604         /* use '???' */
605         entry_ex->entry.created_by.principal = NULL;
606
607         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
608         if (entry_ex->entry.modified_by == NULL) {
609                 krb5_set_error_string(context, "malloc: out of memory");
610                 ret = ENOMEM;
611                 goto out;
612         }
613
614         /* use 'whenChanged' */
615         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
616         /* use '???' */
617         entry_ex->entry.modified_by->principal = NULL;
618
619         entry_ex->entry.valid_start = NULL;
620
621         acct_expiry = samdb_result_account_expires(msg);
622         if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
623                 entry_ex->entry.valid_end = NULL;
624         } else {
625                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
626                 if (entry_ex->entry.valid_end == NULL) {
627                         ret = ENOMEM;
628                         goto out;
629                 }
630                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
631         }
632
633         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
634                 NTTIME must_change_time
635                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
636                                                              domain_dn, msg);
637                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
638                         entry_ex->entry.pw_end = NULL;
639                 } else {
640                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
641                         if (entry_ex->entry.pw_end == NULL) {
642                                 ret = ENOMEM;
643                                 goto out;
644                         }
645                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
646                 }
647         } else {
648                 entry_ex->entry.pw_end = NULL;
649         }
650                         
651         entry_ex->entry.max_life = NULL;
652
653         entry_ex->entry.max_renew = NULL;
654
655         entry_ex->entry.generation = NULL;
656
657         /* Get keys from the db */
658         ret = LDB_message2entry_keys(context, private->iconv_convenience, private, msg, userAccountControl, entry_ex);
659         if (ret) {
660                 /* Could be bougus data in the entry, or out of memory */
661                 goto out;
662         }
663
664         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
665         if (entry_ex->entry.etypes == NULL) {
666                 krb5_clear_error_string(context);
667                 ret = ENOMEM;
668                 goto out;
669         }
670         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
671         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
672         if (entry_ex->entry.etypes->val == NULL) {
673                 krb5_clear_error_string(context);
674                 ret = ENOMEM;
675                 goto out;
676         }
677         for (i=0; i < entry_ex->entry.etypes->len; i++) {
678                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
679         }
680
681
682         private->msg = talloc_steal(private, msg);
683         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
684         private->samdb = (struct ldb_context *)db->hdb_db;
685         
686 out:
687         if (ret != 0) {
688                 /* This doesn't free ent itself, that is for the eventual caller to do */
689                 hdb_free_entry(context, entry_ex);
690         } else {
691                 talloc_steal(db, entry_ex->ctx);
692         }
693
694         return ret;
695 }
696
697 /*
698  * Construct an hdb_entry from a directory entry.
699  */
700 static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, 
701                                                struct loadparm_context *lp_ctx,
702                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
703                                                enum trust_direction direction,
704                                                struct ldb_message *msg,
705                                                hdb_entry_ex *entry_ex)
706 {
707         
708         const char *dnsdomain;
709         char *realm;
710         char *strdup_realm;
711         DATA_BLOB password_utf16;
712         struct samr_Password password_hash;
713         const struct ldb_val *password_val;
714         struct trustAuthInOutBlob password_blob;
715         struct hdb_ldb_private *private;
716
717         enum ndr_err_code ndr_err;
718         int i, ret, trust_direction_flags;
719
720         private = talloc(mem_ctx, struct hdb_ldb_private);
721         if (!private) {
722                 ret = ENOMEM;
723                 goto out;
724         }
725
726         private->entry_ex = entry_ex;
727         private->iconv_convenience = lp_iconv_convenience(lp_ctx);
728         private->netbios_name = lp_netbios_name(lp_ctx);
729
730         talloc_set_destructor(private, hdb_ldb_destrutor);
731
732         entry_ex->ctx = private;
733         entry_ex->free_entry = hdb_ldb_free_entry;
734
735         /* use 'whenCreated' */
736         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
737         /* use '???' */
738         entry_ex->entry.created_by.principal = NULL;
739
740         entry_ex->entry.valid_start = NULL;
741
742         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
743
744         if (direction == INBOUND) {
745                 realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
746                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
747
748         } else { /* OUTBOUND */
749                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
750                 realm = strupper_talloc(mem_ctx, dnsdomain);
751                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
752         }
753
754         ndr_err = ndr_pull_struct_blob_all(password_val, mem_ctx, private->iconv_convenience, &password_blob,
755                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
756         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
757                 ret = EINVAL;
758                 goto out;
759         }
760
761         for (i=0; i < password_blob.count; i++) {
762                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
763                         password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
764                                                          password_blob.current->array[i].AuthInfo.clear.size);
765                         /* In the future, generate all sorts of
766                          * hashes, but for now we can't safely convert
767                          * the random strings windows uses into
768                          * utf8 */
769
770                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
771                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
772                         break;
773                 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
774                         password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
775                         break;
776                 }
777         }
778         entry_ex->entry.keys.len = 0;
779         entry_ex->entry.keys.val = NULL;
780
781         if (i < password_blob.count) {
782                 Key key;
783                 /* Must have found a cleartext or MD4 password */
784                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
785
786                 key.mkvno = 0;
787                 key.salt = NULL; /* No salt for this enc type */
788
789                 if (entry_ex->entry.keys.val == NULL) {
790                         ret = ENOMEM;
791                         goto out;
792                 }
793                 
794                 ret = krb5_keyblock_init(context,
795                                          ENCTYPE_ARCFOUR_HMAC_MD5,
796                                          password_hash.hash, sizeof(password_hash.hash), 
797                                          &key.key);
798                 
799                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
800                 entry_ex->entry.keys.len++;
801         }
802                 
803         ret = copy_Principal(principal, entry_ex->entry.principal);
804         if (ret) {
805                 krb5_clear_error_string(context);
806                 goto out;
807         }
808         
809         /* While we have copied the client principal, tests
810          * show that Win2k3 returns the 'corrected' realm, not
811          * the client-specified realm.  This code attempts to
812          * replace the client principal's realm with the one
813          * we determine from our records */
814         
815         /* this has to be with malloc() */
816         strdup_realm = strdup(realm);
817         if (!strdup_realm) {
818                 ret = ENOMEM;
819                 krb5_clear_error_string(context);
820                 goto out;
821         }
822         free(*krb5_princ_realm(context, entry_ex->entry.principal));
823         krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
824         
825         entry_ex->entry.flags = int2HDBFlags(0);
826         entry_ex->entry.flags.immutable = 1;
827         entry_ex->entry.flags.invalid = 0;
828         entry_ex->entry.flags.server = 1;
829         entry_ex->entry.flags.require_preauth = 1;
830
831         entry_ex->entry.pw_end = NULL;
832                         
833         entry_ex->entry.max_life = NULL;
834
835         entry_ex->entry.max_renew = NULL;
836
837         entry_ex->entry.generation = NULL;
838
839         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
840         if (entry_ex->entry.etypes == NULL) {
841                 krb5_clear_error_string(context);
842                 ret = ENOMEM;
843                 goto out;
844         }
845         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
846         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
847         if (entry_ex->entry.etypes->val == NULL) {
848                 krb5_clear_error_string(context);
849                 ret = ENOMEM;
850                 goto out;
851         }
852         for (i=0; i < entry_ex->entry.etypes->len; i++) {
853                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
854         }
855
856
857         private->msg = talloc_steal(private, msg);
858         private->realm_ref_msg = NULL;
859         private->samdb = (struct ldb_context *)db->hdb_db;
860         
861 out:
862         if (ret != 0) {
863                 /* This doesn't free ent itself, that is for the eventual caller to do */
864                 hdb_free_entry(context, entry_ex);
865         } else {
866                 talloc_steal(db, entry_ex->ctx);
867         }
868
869         return ret;
870
871 }
872
873 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
874                                             TALLOC_CTX *mem_ctx,
875                                             krb5_const_principal principal,
876                                             enum hdb_ldb_ent_type ent_type,
877                                             struct ldb_dn *realm_dn,
878                                             struct ldb_message ***pmsg)
879 {
880         krb5_error_code ret;
881         int lret;
882         char *filter = NULL;
883         const char * const *princ_attrs = user_attrs;
884
885         char *short_princ;
886         char *short_princ_talloc;
887
888         struct ldb_result *res = NULL;
889
890         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
891
892         if (ret != 0) {
893                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
894                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
895                 return ret;
896         }
897
898         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
899         free(short_princ);
900         if (!short_princ_talloc) {
901                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
902                 return ENOMEM;
903         }
904
905         switch (ent_type) {
906         case HDB_LDB_ENT_TYPE_CLIENT:
907         case HDB_LDB_ENT_TYPE_TRUST:
908         case HDB_LDB_ENT_TYPE_ANY:
909                 /* Can't happen */
910                 return EINVAL;
911         case HDB_LDB_ENT_TYPE_KRBTGT:
912                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
913                                          KRB5_TGS_NAME);
914                 break;
915         case HDB_LDB_ENT_TYPE_SERVER:
916                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
917                                          short_princ_talloc);
918                 break;
919         }
920
921         if (!filter) {
922                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
923                 return ENOMEM;
924         }
925
926         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
927
928         if (lret != LDB_SUCCESS) {
929                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
930                 return HDB_ERR_NOENTRY;
931         } else if (res->count == 0 || res->count > 1) {
932                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
933                 talloc_free(res);
934                 return HDB_ERR_NOENTRY;
935         }
936         talloc_steal(mem_ctx, res->msgs);
937         *pmsg = res->msgs;
938         talloc_free(res);
939         return 0;
940 }
941
942 static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,                                      
943                                         TALLOC_CTX *mem_ctx,
944                                         const char *realm,
945                                         struct ldb_dn *realm_dn,
946                                         struct ldb_message ***pmsg)
947 {
948         int lret;
949         char *filter = NULL;
950         const char * const *attrs = trust_attrs;
951
952         struct ldb_result *res = NULL;
953         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
954
955         if (!filter) {
956                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
957                 return ENOMEM;
958         }
959
960         lret = ldb_search(ldb_ctx, ldb_get_default_basedn(ldb_ctx), LDB_SCOPE_SUBTREE, filter, attrs, &res);
961
962         if (lret != LDB_SUCCESS) {
963                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
964                 return HDB_ERR_NOENTRY;
965         } else if (res->count == 0 || res->count > 1) {
966                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
967                 talloc_free(res);
968                 return HDB_ERR_NOENTRY;
969         }
970         talloc_steal(mem_ctx, res->msgs);
971         *pmsg = res->msgs;
972         talloc_free(res);
973         return 0;
974 }
975
976 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
977                                         TALLOC_CTX *mem_ctx,
978                                         const char *realm,
979                                         struct ldb_message ***pmsg)
980 {
981         int ret;
982         struct ldb_result *cross_ref_res;
983         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
984
985         ret = ldb_search_exp_fmt(ldb_ctx, mem_ctx, &cross_ref_res,
986                         partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs,
987                         "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
988                         realm, realm);
989
990         if (ret != LDB_SUCCESS) {
991                 DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx)));
992                 talloc_free(cross_ref_res);
993                 return HDB_ERR_NOENTRY;
994         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
995                 DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count));
996                 talloc_free(cross_ref_res);
997                 return HDB_ERR_NOENTRY;
998         }
999
1000         if (pmsg) {
1001                 *pmsg = cross_ref_res->msgs;
1002                 talloc_steal(mem_ctx, cross_ref_res->msgs);
1003         }
1004         talloc_free(cross_ref_res);
1005
1006         return 0;
1007 }
1008
1009
1010 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
1011 {
1012         if (db->hdb_master_key_set) {
1013                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
1014                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
1015                 return HDB_ERR_NOENTRY;
1016         }               
1017
1018         return 0;
1019 }
1020
1021 static krb5_error_code LDB_close(krb5_context context, HDB *db)
1022 {
1023         return 0;
1024 }
1025
1026 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
1027 {
1028         return 0;
1029 }
1030
1031 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
1032 {
1033         return 0;
1034 }
1035
1036 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
1037 {
1038         return HDB_ERR_DB_INUSE;
1039 }
1040
1041 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
1042                                         TALLOC_CTX *mem_ctx, 
1043                                         krb5_const_principal principal,
1044                                         unsigned flags,
1045                                         hdb_entry_ex *entry_ex) {
1046         NTSTATUS nt_status;
1047         char *principal_string;
1048         krb5_error_code ret;
1049         struct ldb_message **msg = NULL;
1050         struct ldb_message **realm_ref_msg = NULL;
1051
1052         ret = krb5_unparse_name(context, principal, &principal_string);
1053         
1054         if (ret != 0) {
1055                 return ret;
1056         }
1057         
1058         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
1059                                               mem_ctx, principal_string, 
1060                                               &msg, &realm_ref_msg);
1061         free(principal_string);
1062         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1063                 return HDB_ERR_NOENTRY;
1064         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1065                 return ENOMEM;
1066         } else if (!NT_STATUS_IS_OK(nt_status)) {
1067                 return EINVAL;
1068         }
1069         
1070         ret = LDB_message2entry(context, db, mem_ctx, 
1071                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
1072                                 msg[0], realm_ref_msg[0], entry_ex);
1073         return ret;
1074 }
1075
1076 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
1077                                         TALLOC_CTX *mem_ctx, 
1078                                         krb5_const_principal principal,
1079                                         unsigned flags,
1080                                         hdb_entry_ex *entry_ex)
1081 {
1082         krb5_error_code ret;
1083         struct ldb_message **msg = NULL;
1084         struct ldb_message **realm_ref_msg_1 = NULL;
1085         struct ldb_message **realm_ref_msg_2 = NULL;
1086         struct ldb_dn *realm_dn;
1087         const char *realm;
1088
1089         krb5_principal alloc_principal = NULL;
1090         if (principal->name.name_string.len != 2
1091             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1092                 /* Not a krbtgt */
1093                 return HDB_ERR_NOENTRY;
1094         }
1095
1096         /* krbtgt case.  Either us or a trusted realm */
1097
1098         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
1099                               mem_ctx, principal->realm, &realm_ref_msg_1) == 0)
1100             && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
1101                                  mem_ctx, principal->name.name_string.val[1], &realm_ref_msg_2) == 0)
1102             && (ldb_dn_compare(realm_ref_msg_1[0]->dn, realm_ref_msg_1[0]->dn) == 0)) {
1103                 /* us */                
1104                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1105                  * is in our db, then direct the caller at our primary
1106                  * krbtgt */
1107                 
1108                 const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg_1[0], "dnsRoot", NULL);
1109                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
1110                 if (!realm_fixed) {
1111                         krb5_set_error_string(context, "strupper_talloc: out of memory");
1112                         return ENOMEM;
1113                 }
1114                 
1115                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1116                 if (ret) {
1117                         return ret;
1118                 }
1119  
1120                 free(alloc_principal->name.name_string.val[1]);
1121                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1122                 talloc_free(realm_fixed);
1123                 if (!alloc_principal->name.name_string.val[1]) {
1124                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
1125                         return ENOMEM;
1126                 }
1127                 principal = alloc_principal;
1128                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg_1[0], "nCName", NULL);
1129                 
1130                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1131                                            mem_ctx, 
1132                                            principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
1133                 
1134                 if (ret != 0) {
1135                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1136                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1137                         return ret;
1138                 }
1139                 
1140                 ret = LDB_message2entry(context, db, mem_ctx, 
1141                                         principal, HDB_LDB_ENT_TYPE_KRBTGT, 
1142                                         msg[0], realm_ref_msg_1[0], entry_ex);
1143                 if (ret != 0) {
1144                         krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1145                 }
1146                 return ret;
1147
1148         } else {
1149                 enum trust_direction direction = UNKNOWN;
1150
1151                 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context);
1152                 /* Either an inbound or outbound trust */
1153
1154                 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1155                         /* look for inbound trust */
1156                         direction = INBOUND;
1157                         realm = principal->name.name_string.val[1];
1158                 }
1159
1160                 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1161                         /* look for outbound trust */
1162                         direction = OUTBOUND;
1163                         realm = principal->realm;
1164                 }
1165
1166                 /* Trusted domains are under CN=system */
1167                 
1168                 ret = LDB_lookup_trust(context, (struct ldb_context *)db->hdb_db, 
1169                                        mem_ctx, 
1170                                        realm, realm_dn, &msg);
1171                 
1172                 if (ret != 0) {
1173                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1174                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1175                         return ret;
1176                 }
1177                 
1178                 ret = LDB_trust_message2entry(context, db, lp_ctx, mem_ctx, 
1179                                               principal, direction, 
1180                                               msg[0], entry_ex);
1181                 if (ret != 0) {
1182                         krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1183                 }
1184                 return ret;
1185
1186                 
1187                 /* we should lookup trusted domains */
1188                 return HDB_ERR_NOENTRY;
1189         }
1190
1191 }
1192
1193 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
1194                                         TALLOC_CTX *mem_ctx, 
1195                                         krb5_const_principal principal,
1196                                         unsigned flags,
1197                                         hdb_entry_ex *entry_ex)
1198 {
1199         krb5_error_code ret;
1200         const char *realm;
1201         struct ldb_message **msg = NULL;
1202         struct ldb_message **realm_ref_msg = NULL;
1203         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
1204         if (principal->name.name_string.len >= 2) {
1205                 /* 'normal server' case */
1206                 int ldb_ret;
1207                 NTSTATUS nt_status;
1208                 struct ldb_dn *user_dn, *domain_dn;
1209                 char *principal_string;
1210                 
1211                 ret = krb5_unparse_name_flags(context, principal, 
1212                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
1213                                               &principal_string);
1214                 if (ret != 0) {
1215                         return ret;
1216                 }
1217                 
1218                 /* At this point we may find the host is known to be
1219                  * in a different realm, so we should generate a
1220                  * referral instead */
1221                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
1222                                                          mem_ctx, principal_string, 
1223                                                          &user_dn, &domain_dn);
1224                 free(principal_string);
1225                 
1226                 if (!NT_STATUS_IS_OK(nt_status)) {
1227                         return HDB_ERR_NOENTRY;
1228                 }
1229                 
1230                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
1231                                           mem_ctx, user_dn, &msg, user_attrs);
1232                 
1233                 if (ldb_ret != 1) {
1234                         return HDB_ERR_NOENTRY;
1235                 }
1236                 
1237                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
1238                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
1239                                        "ncName=%s", ldb_dn_get_linearized(domain_dn));
1240                 
1241                 if (ldb_ret != 1) {
1242                         return HDB_ERR_NOENTRY;
1243                 }
1244                 
1245         } else {
1246                 struct ldb_dn *realm_dn;
1247                 /* server as client principal case, but we must not lookup userPrincipalNames */
1248
1249                 realm = krb5_principal_get_realm(context, principal);
1250                 
1251                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1252                                        mem_ctx, realm, &realm_ref_msg);
1253                 if (ret != 0) {
1254                         return HDB_ERR_NOENTRY;
1255                 }
1256                 
1257                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
1258                 
1259                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1260                                            mem_ctx, 
1261                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
1262                 
1263                 if (ret != 0) {
1264                         return ret;
1265                 }
1266         }
1267
1268         ret = LDB_message2entry(context, db, mem_ctx, 
1269                                 principal, HDB_LDB_ENT_TYPE_SERVER,
1270                                 msg[0], realm_ref_msg[0], entry_ex);
1271         if (ret != 0) {
1272                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1273         }
1274
1275         return ret;
1276 }
1277                         
1278 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
1279                                  krb5_const_principal principal,
1280                                  unsigned flags,
1281                                  hdb_entry_ex *entry_ex)
1282 {
1283         krb5_error_code ret = HDB_ERR_NOENTRY;
1284
1285         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
1286
1287         if (!mem_ctx) {
1288                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
1289                 return ENOMEM;
1290         }
1291
1292         if (flags & HDB_F_GET_CLIENT) {
1293                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
1294                 if (ret != HDB_ERR_NOENTRY) goto done;
1295         }
1296         if (flags & HDB_F_GET_SERVER) {
1297                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1298                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1299                 if (ret != HDB_ERR_NOENTRY) goto done;
1300
1301                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1302                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
1303                 if (ret != HDB_ERR_NOENTRY) goto done;
1304         }
1305         if (flags & HDB_F_GET_KRBTGT) {
1306                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1307                 if (ret != HDB_ERR_NOENTRY) goto done;
1308         }
1309
1310 done:
1311         talloc_free(mem_ctx);
1312         return ret;
1313 }
1314
1315 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1316 {
1317         return HDB_ERR_DB_INUSE;
1318 }
1319
1320 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1321 {
1322         return HDB_ERR_DB_INUSE;
1323 }
1324
1325 struct hdb_ldb_seq {
1326         struct ldb_context *ctx;
1327         int index;
1328         int count;
1329         struct ldb_message **msgs;
1330         struct ldb_message **realm_ref_msgs;
1331 };
1332
1333 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1334 {
1335         krb5_error_code ret;
1336         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1337         TALLOC_CTX *mem_ctx;
1338         hdb_entry_ex entry_ex;
1339         memset(&entry_ex, '\0', sizeof(entry_ex));
1340
1341         if (!priv) {
1342                 return HDB_ERR_NOENTRY;
1343         }
1344
1345         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
1346
1347         if (!mem_ctx) {
1348                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
1349                 return ENOMEM;
1350         }
1351
1352         if (priv->index < priv->count) {
1353                 ret = LDB_message2entry(context, db, mem_ctx, 
1354                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
1355                                         priv->msgs[priv->index++], 
1356                                         priv->realm_ref_msgs[0], entry);
1357         } else {
1358                 ret = HDB_ERR_NOENTRY;
1359         }
1360
1361         if (ret != 0) {
1362                 talloc_free(priv);
1363                 db->hdb_dbc = NULL;
1364         } else {
1365                 talloc_free(mem_ctx);
1366         }
1367
1368         return ret;
1369 }
1370
1371 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1372                                         hdb_entry_ex *entry)
1373 {
1374         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1375         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1376         char *realm;
1377         struct ldb_dn *realm_dn = NULL;
1378         struct ldb_result *res = NULL;
1379         struct ldb_message **realm_ref_msgs = NULL;
1380         krb5_error_code ret;
1381         TALLOC_CTX *mem_ctx;
1382         int lret;
1383
1384         if (priv) {
1385                 talloc_free(priv);
1386                 db->hdb_dbc = NULL;
1387         }
1388
1389         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1390         if (!priv) {
1391                 krb5_set_error_string(context, "talloc: out of memory");
1392                 return ENOMEM;
1393         }
1394
1395         priv->ctx = ldb_ctx;
1396         priv->index = 0;
1397         priv->msgs = NULL;
1398         priv->realm_ref_msgs = NULL;
1399         priv->count = 0;
1400
1401         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1402
1403         if (!mem_ctx) {
1404                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1405                 return ENOMEM;
1406         }
1407
1408         ret = krb5_get_default_realm(context, &realm);
1409         if (ret != 0) {
1410                 talloc_free(priv);
1411                 return ret;
1412         }
1413                 
1414         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1415                                mem_ctx, realm, &realm_ref_msgs);
1416
1417         free(realm);
1418
1419         if (ret != 0) {
1420                 talloc_free(priv);
1421                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1422                 return HDB_ERR_NOENTRY;
1423         }
1424
1425         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
1426
1427         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
1428
1429         lret = ldb_search(ldb_ctx, realm_dn,
1430                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
1431                                  user_attrs, &res);
1432
1433         if (lret != LDB_SUCCESS) {
1434                 talloc_free(priv);
1435                 return HDB_ERR_NOENTRY;
1436         }
1437
1438         priv->count = res->count;
1439         priv->msgs = talloc_steal(priv, res->msgs);
1440         talloc_free(res);
1441
1442         db->hdb_dbc = priv;
1443
1444         ret = LDB_seq(context, db, flags, entry);
1445
1446         if (ret != 0) {
1447                 talloc_free(priv);
1448                 db->hdb_dbc = NULL;
1449         } else {
1450                 talloc_free(mem_ctx);
1451         }
1452         return ret;
1453 }
1454
1455 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1456                                    hdb_entry_ex *entry)
1457 {
1458         return LDB_seq(context, db, flags, entry);
1459 }
1460
1461 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1462 {
1463         talloc_free(db);
1464         return 0;
1465 }
1466
1467 /* This interface is to be called by the KDC, which is expecting Samba
1468  * calling conventions.  It is also called by a wrapper
1469  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1470  * code */
1471
1472 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1473                             struct event_context *ev_ctx, 
1474                             struct loadparm_context *lp_ctx,
1475                             krb5_context context, struct HDB **db, const char *arg)
1476 {
1477         NTSTATUS nt_status;
1478         struct auth_session_info *session_info;
1479         *db = talloc(mem_ctx, HDB);
1480         if (!*db) {
1481                 krb5_set_error_string(context, "malloc: out of memory");
1482                 return NT_STATUS_NO_MEMORY;
1483         }
1484
1485         (*db)->hdb_master_key_set = 0;
1486         (*db)->hdb_db = NULL;
1487
1488         nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1489         if (!NT_STATUS_IS_OK(nt_status)) {
1490                 return nt_status;
1491         }
1492         
1493         /* The idea here is very simple.  Using Kerberos to
1494          * authenticate the KDC to the LDAP server is higly likely to
1495          * be circular.
1496          *
1497          * In future we may set this up to use EXERNAL and SSL
1498          * certificates, for now it will almost certainly be NTLMSSP
1499         */
1500         
1501         cli_credentials_set_kerberos_state(session_info->credentials, 
1502                                            CRED_DONT_USE_KERBEROS);
1503
1504         /* Setup the link to LDB */
1505         (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1506         if ((*db)->hdb_db == NULL) {
1507                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1508                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1509         }
1510
1511         (*db)->hdb_dbc = NULL;
1512         (*db)->hdb_open = LDB_open;
1513         (*db)->hdb_close = LDB_close;
1514         (*db)->hdb_fetch = LDB_fetch;
1515         (*db)->hdb_store = LDB_store;
1516         (*db)->hdb_remove = LDB_remove;
1517         (*db)->hdb_firstkey = LDB_firstkey;
1518         (*db)->hdb_nextkey = LDB_nextkey;
1519         (*db)->hdb_lock = LDB_lock;
1520         (*db)->hdb_unlock = LDB_unlock;
1521         (*db)->hdb_rename = LDB_rename;
1522         /* we don't implement these, as we are not a lockable database */
1523         (*db)->hdb__get = NULL;
1524         (*db)->hdb__put = NULL;
1525         /* kadmin should not be used for deletes - use other tools instead */
1526         (*db)->hdb__del = NULL;
1527         (*db)->hdb_destroy = LDB_destroy;
1528
1529         return NT_STATUS_OK;
1530 }
1531
1532 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1533 {
1534         NTSTATUS nt_status;
1535         /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1536         nt_status = kdc_hdb_ldb_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
1537                                        context, db, arg);
1538
1539         if (NT_STATUS_IS_OK(nt_status)) {
1540                 return 0;
1541         }
1542         return EINVAL;
1543 }