a997eb097c7854afb8e53a31003e82451e55994e
[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
53 enum hdb_ldb_ent_type 
54 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
55   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
56
57 static const char *realm_ref_attrs[] = {
58         "nCName", 
59         "dnsRoot", 
60         NULL
61 };
62
63 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
64 {
65     const char *tmp;
66     const char *gentime;
67     struct tm tm;
68
69     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
70     if (!gentime)
71         return default_val;
72
73     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
74     if (tmp == NULL) {
75             return default_val;
76     }
77
78     return timegm(&tm);
79 }
80
81 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
82 {
83         HDBFlags flags = int2HDBFlags(0);
84
85         /* we don't allow kadmin deletes */
86         flags.immutable = 1;
87
88         /* mark the principal as invalid to start with */
89         flags.invalid = 1;
90
91         flags.renewable = 1;
92
93         /* All accounts are servers, but this may be disabled again in the caller */
94         flags.server = 1;
95
96         /* Account types - clear the invalid bit if it turns out to be valid */
97         if (userAccountControl & UF_NORMAL_ACCOUNT) {
98                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
99                         flags.client = 1;
100                 }
101                 flags.invalid = 0;
102         }
103         
104         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
105                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
106                         flags.client = 1;
107                 }
108                 flags.invalid = 0;
109         }
110         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
111                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
112                         flags.client = 1;
113                 }
114                 flags.invalid = 0;
115         }
116         if (userAccountControl & UF_SERVER_TRUST_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         /* Not permitted to act as a client if disabled */
124         if (userAccountControl & UF_ACCOUNTDISABLE) {
125                 flags.client = 0;
126         }
127         if (userAccountControl & UF_LOCKOUT) {
128                 flags.invalid = 1;
129         }
130 /*
131         if (userAccountControl & UF_PASSWORD_NOTREQD) {
132                 flags.invalid = 1;
133         }
134 */
135 /*
136         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
137 */
138         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
139                 flags.invalid = 1;
140         }
141
142 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
143
144 /*
145         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
146                 flags.invalid = 1;
147         }
148 */
149         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
150                 flags.require_hwauth = 1;
151         }
152         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
153                 flags.ok_as_delegate = 1;
154         }       
155         if (!(userAccountControl & UF_NOT_DELEGATED)) {
156                 flags.forwardable = 1;
157                 flags.proxiable = 1;
158         }
159
160         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
161                 flags.require_preauth = 0;
162         } else {
163                 flags.require_preauth = 1;
164
165         }
166         return flags;
167 }
168
169 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
170 {
171     hdb_entry_ex *entry_ex = private->entry_ex;
172     free_hdb_entry(&entry_ex->entry);
173     return 0;
174 }
175
176 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
177 {
178         talloc_free(entry_ex->ctx);
179 }
180
181 static krb5_error_code LDB_message2entry_keys(krb5_context context,
182                                               struct smb_iconv_convenience *iconv_convenience,
183                                               TALLOC_CTX *mem_ctx,
184                                               struct ldb_message *msg,
185                                               unsigned int userAccountControl,
186                                               hdb_entry_ex *entry_ex)
187 {
188         krb5_error_code ret = 0;
189         enum ndr_err_code ndr_err;
190         struct samr_Password *hash;
191         const struct ldb_val *sc_val;
192         struct supplementalCredentialsBlob scb;
193         struct supplementalCredentialsPackage *scpk = NULL;
194         bool newer_keys = false;
195         struct package_PrimaryKerberosBlob _pkb;
196         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
197         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
198         uint32_t i;
199         uint32_t allocated_keys = 0;
200
201         entry_ex->entry.keys.val = NULL;
202         entry_ex->entry.keys.len = 0;
203
204         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
205
206         /* Get keys from the db */
207
208         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
209         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
210
211         /* unicodePwd for enctype 0x17 (23) if present */
212         if (hash) {
213                 allocated_keys++;
214         }
215
216         /* supplementalCredentials if present */
217         if (sc_val) {
218                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb,
219                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
220                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
221                         dump_data(0, sc_val->data, sc_val->length);
222                         ret = EINVAL;
223                         goto out;
224                 }
225
226                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
227                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
228                         ret = EINVAL;
229                         goto out;
230                 }
231
232                 for (i=0; i < scb.sub.num_packages; i++) {
233                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
234                                 scpk = &scb.sub.packages[i];
235                                 if (!scpk->data || !scpk->data[0]) {
236                                         scpk = NULL;
237                                         continue;
238                                 }
239                                 newer_keys = true;
240                                 break;
241                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
242                                 scpk = &scb.sub.packages[i];
243                                 if (!scpk->data || !scpk->data[0]) {
244                                         scpk = NULL;
245                                 }
246                                 /*
247                                  * we don't break here in hope to find
248                                  * a Kerberos-Newer-Keys package
249                                  */
250                         }
251                 }
252         }
253         /*
254          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
255          * of supplementalCredentials
256          */
257         if (scpk) {
258                 DATA_BLOB blob;
259
260                 blob = strhex_to_data_blob(scpk->data);
261                 if (!blob.data) {
262                         ret = ENOMEM;
263                         goto out;
264                 }
265                 talloc_steal(mem_ctx, blob.data);
266
267                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
268                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb,
269                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
270                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
271                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
272                         krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
273                         ret = EINVAL;
274                         goto out;
275                 }
276
277                 if (newer_keys && _pkb.version != 4) {
278                         krb5_set_error_string(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
279                         krb5_warnx(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
280                         ret = EINVAL;
281                         goto out;
282                 }
283
284                 if (!newer_keys && _pkb.version != 3) {
285                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
286                         krb5_warnx(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
287                         ret = EINVAL;
288                         goto out;
289                 }
290
291                 if (_pkb.version == 4) {
292                         pkb4 = &_pkb.ctr.ctr4;
293                         allocated_keys += pkb4->num_keys;
294                 } else if (_pkb.version == 3) {
295                         pkb3 = &_pkb.ctr.ctr3;
296                         allocated_keys += pkb3->num_keys;
297                 }
298         }
299
300         if (allocated_keys == 0) {
301                 /* oh, no password.  Apparently (comment in
302                  * hdb-ldap.c) this violates the ASN.1, but this
303                  * allows an entry with no keys (yet). */
304                 return 0;
305         }
306
307         /* allocate space to decode into */
308         entry_ex->entry.keys.len = 0;
309         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
310         if (entry_ex->entry.keys.val == NULL) {
311                 ret = ENOMEM;
312                 goto out;
313         }
314
315         if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
316                 Key key;
317
318                 key.mkvno = 0;
319                 key.salt = NULL; /* No salt for this enc type */
320
321                 ret = krb5_keyblock_init(context,
322                                          ENCTYPE_ARCFOUR_HMAC_MD5,
323                                          hash->hash, sizeof(hash->hash), 
324                                          &key.key);
325                 if (ret) {
326                         goto out;
327                 }
328
329                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
330                 entry_ex->entry.keys.len++;
331         }
332
333         if (pkb4) {
334                 for (i=0; i < pkb4->num_keys; i++) {
335                         bool use = true;
336                         Key key;
337
338                         if (!pkb4->keys[i].value) continue;
339
340                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
341                                 switch (pkb4->keys[i].keytype) {
342                                 case ENCTYPE_DES_CBC_CRC:
343                                 case ENCTYPE_DES_CBC_MD5:
344                                         break;
345                                 default:
346                                         use = false;
347                                         break;
348                                 }
349                         }
350
351                         if (!use) continue;
352
353                         key.mkvno = 0;
354                         key.salt = NULL;
355
356                         if (pkb4->salt.string) {
357                                 DATA_BLOB salt;
358
359                                 salt = data_blob_string_const(pkb4->salt.string);
360
361                                 key.salt = calloc(1, sizeof(*key.salt));
362                                 if (key.salt == NULL) {
363                                         ret = ENOMEM;
364                                         goto out;
365                                 }
366
367                                 key.salt->type = hdb_pw_salt;
368
369                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
370                                 if (ret) {
371                                         free(key.salt);
372                                         key.salt = NULL;
373                                         goto out;
374                                 }
375                         }
376
377                         /* TODO: maybe pass the iteration_count somehow... */
378
379                         ret = krb5_keyblock_init(context,
380                                                  pkb4->keys[i].keytype,
381                                                  pkb4->keys[i].value->data,
382                                                  pkb4->keys[i].value->length,
383                                                  &key.key);
384                         if (ret) {
385                                 if (key.salt) {
386                                         free_Salt(key.salt);
387                                         free(key.salt);
388                                         key.salt = NULL;
389                                 }
390                                 goto out;
391                         }
392
393                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
394                         entry_ex->entry.keys.len++;
395                 }
396         } else if (pkb3) {
397                 for (i=0; i < pkb3->num_keys; i++) {
398                         bool use = true;
399                         Key key;
400
401                         if (!pkb3->keys[i].value) continue;
402
403                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
404                                 switch (pkb3->keys[i].keytype) {
405                                 case ENCTYPE_DES_CBC_CRC:
406                                 case ENCTYPE_DES_CBC_MD5:
407                                         break;
408                                 default:
409                                         use = false;
410                                         break;
411                                 }
412                         }
413
414                         if (!use) continue;
415
416                         key.mkvno = 0;
417                         key.salt = NULL;
418
419                         if (pkb3->salt.string) {
420                                 DATA_BLOB salt;
421
422                                 salt = data_blob_string_const(pkb3->salt.string);
423
424                                 key.salt = calloc(1, sizeof(*key.salt));
425                                 if (key.salt == NULL) {
426                                         ret = ENOMEM;
427                                         goto out;
428                                 }
429
430                                 key.salt->type = hdb_pw_salt;
431
432                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
433                                 if (ret) {
434                                         free(key.salt);
435                                         key.salt = NULL;
436                                         goto out;
437                                 }
438                         }
439
440                         ret = krb5_keyblock_init(context,
441                                                  pkb3->keys[i].keytype,
442                                                  pkb3->keys[i].value->data,
443                                                  pkb3->keys[i].value->length,
444                                                  &key.key);
445                         if (ret) {
446                                 if (key.salt) {
447                                         free_Salt(key.salt);
448                                         free(key.salt);
449                                         key.salt = NULL;
450                                 }
451                                 goto out;
452                         }
453
454                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
455                         entry_ex->entry.keys.len++;
456                 }
457         }
458
459 out:
460         if (ret != 0) {
461                 entry_ex->entry.keys.len = 0;
462         }
463         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
464                 free(entry_ex->entry.keys.val);
465                 entry_ex->entry.keys.val = NULL;
466         }
467         return ret;
468 }
469
470 /*
471  * Construct an hdb_entry from a directory entry.
472  */
473 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
474                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
475                                          enum hdb_ldb_ent_type ent_type, 
476                                          struct ldb_message *msg,
477                                          struct ldb_message *realm_ref_msg,
478                                          hdb_entry_ex *entry_ex)
479 {
480         unsigned int userAccountControl;
481         int i;
482         krb5_error_code ret = 0;
483         krb5_boolean is_computer = FALSE;
484         const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL);
485         char *realm = strupper_talloc(mem_ctx, dnsdomain);
486         struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm");
487         struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db,
488                                                         mem_ctx,
489                                                         realm_ref_msg,
490                                                         "nCName",
491                                                         ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL));
492
493         struct hdb_ldb_private *private;
494         NTTIME acct_expiry;
495
496         struct ldb_message_element *objectclasses;
497         struct ldb_val computer_val;
498         computer_val.data = discard_const_p(uint8_t,"computer");
499         computer_val.length = strlen((const char *)computer_val.data);
500         
501         objectclasses = ldb_msg_find_element(msg, "objectClass");
502         
503         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
504                 is_computer = TRUE;
505         }
506
507         memset(entry_ex, 0, sizeof(*entry_ex));
508
509         if (!realm) {
510                 krb5_set_error_string(context, "talloc_strdup: out of memory");
511                 ret = ENOMEM;
512                 goto out;
513         }
514                         
515         private = talloc(mem_ctx, struct hdb_ldb_private);
516         if (!private) {
517                 ret = ENOMEM;
518                 goto out;
519         }
520
521         private->entry_ex = entry_ex;
522         private->iconv_convenience = lp_iconv_convenience(lp_ctx);
523         private->netbios_name = lp_netbios_name(lp_ctx);
524
525         talloc_set_destructor(private, hdb_ldb_destrutor);
526
527         entry_ex->ctx = private;
528         entry_ex->free_entry = hdb_ldb_free_entry;
529
530         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
531
532         
533         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
534         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
535                 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
536                 if (!samAccountName) {
537                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
538                         ret = ENOENT;
539                         goto out;
540                 }
541                 samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
542                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
543         } else {
544                 char *strdup_realm;
545                 ret = copy_Principal(principal, entry_ex->entry.principal);
546                 if (ret) {
547                         krb5_clear_error_string(context);
548                         goto out;
549                 }
550
551                 /* While we have copied the client principal, tests
552                  * show that Win2k3 returns the 'corrected' realm, not
553                  * the client-specified realm.  This code attempts to
554                  * replace the client principal's realm with the one
555                  * we determine from our records */
556                 
557                 /* this has to be with malloc() */
558                 strdup_realm = strdup(realm);
559                 if (!strdup_realm) {
560                         ret = ENOMEM;
561                         krb5_clear_error_string(context);
562                         goto out;
563                 }
564                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
565                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
566         }
567
568         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
569
570         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
571                 entry_ex->entry.flags.invalid = 0;
572                 entry_ex->entry.flags.server = 1;
573                 entry_ex->entry.flags.forwardable = 1;
574                 entry_ex->entry.flags.ok_as_delegate = 1;
575         }
576
577         if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
578                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
579                         entry_ex->entry.flags.server = 0;
580                 }
581         }
582
583         /* use 'whenCreated' */
584         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
585         /* use '???' */
586         entry_ex->entry.created_by.principal = NULL;
587
588         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
589         if (entry_ex->entry.modified_by == NULL) {
590                 krb5_set_error_string(context, "malloc: out of memory");
591                 ret = ENOMEM;
592                 goto out;
593         }
594
595         /* use 'whenChanged' */
596         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
597         /* use '???' */
598         entry_ex->entry.modified_by->principal = NULL;
599
600         entry_ex->entry.valid_start = NULL;
601
602         acct_expiry = samdb_result_account_expires(msg);
603         if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
604                 entry_ex->entry.valid_end = NULL;
605         } else {
606                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
607                 if (entry_ex->entry.valid_end == NULL) {
608                         ret = ENOMEM;
609                         goto out;
610                 }
611                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
612         }
613
614         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
615                 NTTIME must_change_time
616                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
617                                                              domain_dn, msg);
618                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
619                         entry_ex->entry.pw_end = NULL;
620                 } else {
621                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
622                         if (entry_ex->entry.pw_end == NULL) {
623                                 ret = ENOMEM;
624                                 goto out;
625                         }
626                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
627                 }
628         } else {
629                 entry_ex->entry.pw_end = NULL;
630         }
631                         
632         entry_ex->entry.max_life = NULL;
633
634         entry_ex->entry.max_renew = NULL;
635
636         entry_ex->entry.generation = NULL;
637
638         /* Get keys from the db */
639         ret = LDB_message2entry_keys(context, private->iconv_convenience, private, msg, userAccountControl, entry_ex);
640         if (ret) {
641                 /* Could be bougus data in the entry, or out of memory */
642                 goto out;
643         }
644
645         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
646         if (entry_ex->entry.etypes == NULL) {
647                 krb5_clear_error_string(context);
648                 ret = ENOMEM;
649                 goto out;
650         }
651         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
652         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
653         if (entry_ex->entry.etypes->val == NULL) {
654                 krb5_clear_error_string(context);
655                 ret = ENOMEM;
656                 goto out;
657         }
658         for (i=0; i < entry_ex->entry.etypes->len; i++) {
659                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
660         }
661
662
663         private->msg = talloc_steal(private, msg);
664         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
665         private->samdb = (struct ldb_context *)db->hdb_db;
666         
667 out:
668         if (ret != 0) {
669                 /* This doesn't free ent itself, that is for the eventual caller to do */
670                 hdb_free_entry(context, entry_ex);
671         } else {
672                 talloc_steal(db, entry_ex->ctx);
673         }
674
675         return ret;
676 }
677
678 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
679                                             TALLOC_CTX *mem_ctx,
680                                             krb5_const_principal principal,
681                                             enum hdb_ldb_ent_type ent_type,
682                                             struct ldb_dn *realm_dn,
683                                             struct ldb_message ***pmsg)
684 {
685         krb5_error_code ret;
686         int lret;
687         char *filter = NULL;
688         const char * const *princ_attrs = user_attrs;
689
690         char *short_princ;
691         char *short_princ_talloc;
692
693         struct ldb_result *res = NULL;
694
695         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
696
697         if (ret != 0) {
698                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
699                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
700                 return ret;
701         }
702
703         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
704         free(short_princ);
705         if (!short_princ_talloc) {
706                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
707                 return ENOMEM;
708         }
709
710         switch (ent_type) {
711         case HDB_LDB_ENT_TYPE_CLIENT:
712                 /* Can't happen */
713                 return EINVAL;
714         case HDB_LDB_ENT_TYPE_ANY:
715                 /* Can't happen */
716                 return EINVAL;
717         case HDB_LDB_ENT_TYPE_KRBTGT:
718                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
719                                          KRB5_TGS_NAME);
720                 break;
721         case HDB_LDB_ENT_TYPE_SERVER:
722                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
723                                          short_princ_talloc);
724                 break;
725         }
726
727         if (!filter) {
728                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
729                 return ENOMEM;
730         }
731
732         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
733
734         if (lret != LDB_SUCCESS) {
735                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
736                 return HDB_ERR_NOENTRY;
737         } else if (res->count == 0 || res->count > 1) {
738                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
739                 talloc_free(res);
740                 return HDB_ERR_NOENTRY;
741         }
742         talloc_steal(mem_ctx, res->msgs);
743         *pmsg = res->msgs;
744         talloc_free(res);
745         return 0;
746 }
747
748 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
749                                         TALLOC_CTX *mem_ctx,
750                                         const char *realm,
751                                         struct ldb_message ***pmsg)
752 {
753         int ret;
754         struct ldb_result *cross_ref_res;
755         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
756
757         ret = ldb_search_exp_fmt(ldb_ctx, mem_ctx, &cross_ref_res,
758                         partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs,
759                         "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
760                         realm, realm);
761
762         if (ret != LDB_SUCCESS) {
763                 DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx)));
764                 talloc_free(cross_ref_res);
765                 return HDB_ERR_NOENTRY;
766         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
767                 DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count));
768                 talloc_free(cross_ref_res);
769                 return HDB_ERR_NOENTRY;
770         }
771
772         if (pmsg) {
773                 *pmsg = cross_ref_res->msgs;
774                 talloc_steal(mem_ctx, cross_ref_res->msgs);
775         }
776         talloc_free(cross_ref_res);
777
778         return 0;
779 }
780
781
782 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
783 {
784         if (db->hdb_master_key_set) {
785                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
786                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
787                 return HDB_ERR_NOENTRY;
788         }               
789
790         return 0;
791 }
792
793 static krb5_error_code LDB_close(krb5_context context, HDB *db)
794 {
795         return 0;
796 }
797
798 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
799 {
800         return 0;
801 }
802
803 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
804 {
805         return 0;
806 }
807
808 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
809 {
810         return HDB_ERR_DB_INUSE;
811 }
812
813 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
814                                         TALLOC_CTX *mem_ctx, 
815                                         krb5_const_principal principal,
816                                         unsigned flags,
817                                         hdb_entry_ex *entry_ex) {
818         NTSTATUS nt_status;
819         char *principal_string;
820         krb5_error_code ret;
821         struct ldb_message **msg = NULL;
822         struct ldb_message **realm_ref_msg = NULL;
823
824         ret = krb5_unparse_name(context, principal, &principal_string);
825         
826         if (ret != 0) {
827                 return ret;
828         }
829         
830         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
831                                               mem_ctx, principal_string, 
832                                               &msg, &realm_ref_msg);
833         free(principal_string);
834         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
835                 return HDB_ERR_NOENTRY;
836         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
837                 return ENOMEM;
838         } else if (!NT_STATUS_IS_OK(nt_status)) {
839                 return EINVAL;
840         }
841         
842         ret = LDB_message2entry(context, db, mem_ctx, 
843                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
844                                 msg[0], realm_ref_msg[0], entry_ex);
845         return ret;
846 }
847
848 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
849                                         TALLOC_CTX *mem_ctx, 
850                                         krb5_const_principal principal,
851                                         unsigned flags,
852                                         hdb_entry_ex *entry_ex)
853 {
854         krb5_error_code ret;
855         struct ldb_message **msg = NULL;
856         struct ldb_message **realm_ref_msg_1 = NULL;
857         struct ldb_message **realm_ref_msg_2 = NULL;
858         struct ldb_dn *realm_dn;
859
860         krb5_principal alloc_principal = NULL;
861         if (principal->name.name_string.len != 2
862             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
863                 /* Not a krbtgt */
864                 return HDB_ERR_NOENTRY;
865         }
866
867         /* krbtgt case.  Either us or a trusted realm */
868
869         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
870                               mem_ctx, principal->realm, &realm_ref_msg_1) == 0)
871             && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
872                                  mem_ctx, principal->name.name_string.val[1], &realm_ref_msg_2) == 0)
873             && (ldb_dn_cmp(realm_ref_msg_1[0]->dn, realm_ref_msg_1[0]->dn) == 0)) {
874                 /* us */                
875                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
876                  * is in our db, then direct the caller at our primary
877                  * krbtgt */
878                 
879                 const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg_1[0], "dnsRoot", NULL);
880                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
881                 if (!realm_fixed) {
882                         krb5_set_error_string(context, "strupper_talloc: out of memory");
883                         return ENOMEM;
884                 }
885                 
886                 ret = krb5_copy_principal(context, principal, &alloc_principal);
887                 if (ret) {
888                         return ret;
889                 }
890  
891                 free(alloc_principal->name.name_string.val[1]);
892                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
893                 talloc_free(realm_fixed);
894                 if (!alloc_principal->name.name_string.val[1]) {
895                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
896                         return ENOMEM;
897                 }
898                 principal = alloc_principal;
899                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg_1[0], "nCName", NULL);
900         } else {
901                 enum direction {
902                         INBOUND,
903                         OUTBOUND
904                 }
905
906                 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(ldb, "loadparm"), struct loadparm_context *);
907                 /* Either an inbound or outbound trust */
908
909                 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
910                         /* look for inbound trust */
911                 }
912
913                 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
914                         /* look for outbound trust */
915                 }
916
917                 /* Trusted domains are under CN=system */
918                 
919                 /* we should lookup trusted domains */
920                 return HDB_ERR_NOENTRY;
921         }
922
923         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
924         
925         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
926                                    mem_ctx, 
927                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
928         
929         if (ret != 0) {
930                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
931                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
932                 return ret;
933         }
934
935         ret = LDB_message2entry(context, db, mem_ctx, 
936                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
937                                 msg[0], realm_ref_msg[0], entry_ex);
938         if (ret != 0) {
939                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
940         }
941         return ret;
942 }
943
944 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
945                                         TALLOC_CTX *mem_ctx, 
946                                         krb5_const_principal principal,
947                                         unsigned flags,
948                                         hdb_entry_ex *entry_ex)
949 {
950         krb5_error_code ret;
951         const char *realm;
952         struct ldb_message **msg = NULL;
953         struct ldb_message **realm_ref_msg = NULL;
954         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
955         if (principal->name.name_string.len >= 2) {
956                 /* 'normal server' case */
957                 int ldb_ret;
958                 NTSTATUS nt_status;
959                 struct ldb_dn *user_dn, *domain_dn;
960                 char *principal_string;
961                 
962                 ret = krb5_unparse_name_flags(context, principal, 
963                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
964                                               &principal_string);
965                 if (ret != 0) {
966                         return ret;
967                 }
968                 
969                 /* At this point we may find the host is known to be
970                  * in a different realm, so we should generate a
971                  * referral instead */
972                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
973                                                          mem_ctx, principal_string, 
974                                                          &user_dn, &domain_dn);
975                 free(principal_string);
976                 
977                 if (!NT_STATUS_IS_OK(nt_status)) {
978                         return HDB_ERR_NOENTRY;
979                 }
980                 
981                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
982                                           mem_ctx, user_dn, &msg, user_attrs);
983                 
984                 if (ldb_ret != 1) {
985                         return HDB_ERR_NOENTRY;
986                 }
987                 
988                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
989                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
990                                        "ncName=%s", ldb_dn_get_linearized(domain_dn));
991                 
992                 if (ldb_ret != 1) {
993                         return HDB_ERR_NOENTRY;
994                 }
995                 
996         } else {
997                 struct ldb_dn *realm_dn;
998                 /* server as client principal case, but we must not lookup userPrincipalNames */
999
1000                 realm = krb5_principal_get_realm(context, principal);
1001                 
1002                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1003                                        mem_ctx, realm, &realm_ref_msg);
1004                 if (ret != 0) {
1005                         return HDB_ERR_NOENTRY;
1006                 }
1007                 
1008                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
1009                 
1010                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1011                                            mem_ctx, 
1012                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
1013                 
1014                 if (ret != 0) {
1015                         return ret;
1016                 }
1017         }
1018
1019         ret = LDB_message2entry(context, db, mem_ctx, 
1020                                 principal, HDB_LDB_ENT_TYPE_SERVER,
1021                                 msg[0], realm_ref_msg[0], entry_ex);
1022         if (ret != 0) {
1023                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1024         }
1025
1026         return ret;
1027 }
1028                         
1029 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
1030                                  krb5_const_principal principal,
1031                                  unsigned flags,
1032                                  hdb_entry_ex *entry_ex)
1033 {
1034         krb5_error_code ret = HDB_ERR_NOENTRY;
1035
1036         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
1037
1038         if (!mem_ctx) {
1039                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
1040                 return ENOMEM;
1041         }
1042
1043         if (flags & HDB_F_GET_CLIENT) {
1044                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
1045                 if (ret != HDB_ERR_NOENTRY) goto done;
1046         }
1047         if (flags & HDB_F_GET_SERVER) {
1048                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1049                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1050                 if (ret != HDB_ERR_NOENTRY) goto done;
1051
1052                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1053                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
1054                 if (ret != HDB_ERR_NOENTRY) goto done;
1055         }
1056         if (flags & HDB_F_GET_KRBTGT) {
1057                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1058                 if (ret != HDB_ERR_NOENTRY) goto done;
1059         }
1060
1061 done:
1062         talloc_free(mem_ctx);
1063         return ret;
1064 }
1065
1066 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1067 {
1068         return HDB_ERR_DB_INUSE;
1069 }
1070
1071 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1072 {
1073         return HDB_ERR_DB_INUSE;
1074 }
1075
1076 struct hdb_ldb_seq {
1077         struct ldb_context *ctx;
1078         int index;
1079         int count;
1080         struct ldb_message **msgs;
1081         struct ldb_message **realm_ref_msgs;
1082 };
1083
1084 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1085 {
1086         krb5_error_code ret;
1087         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1088         TALLOC_CTX *mem_ctx;
1089         hdb_entry_ex entry_ex;
1090         memset(&entry_ex, '\0', sizeof(entry_ex));
1091
1092         if (!priv) {
1093                 return HDB_ERR_NOENTRY;
1094         }
1095
1096         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
1097
1098         if (!mem_ctx) {
1099                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
1100                 return ENOMEM;
1101         }
1102
1103         if (priv->index < priv->count) {
1104                 ret = LDB_message2entry(context, db, mem_ctx, 
1105                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
1106                                         priv->msgs[priv->index++], 
1107                                         priv->realm_ref_msgs[0], entry);
1108         } else {
1109                 ret = HDB_ERR_NOENTRY;
1110         }
1111
1112         if (ret != 0) {
1113                 talloc_free(priv);
1114                 db->hdb_dbc = NULL;
1115         } else {
1116                 talloc_free(mem_ctx);
1117         }
1118
1119         return ret;
1120 }
1121
1122 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1123                                         hdb_entry_ex *entry)
1124 {
1125         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1126         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1127         char *realm;
1128         struct ldb_dn *realm_dn = NULL;
1129         struct ldb_result *res = NULL;
1130         struct ldb_message **realm_ref_msgs = NULL;
1131         krb5_error_code ret;
1132         TALLOC_CTX *mem_ctx;
1133         int lret;
1134
1135         if (priv) {
1136                 talloc_free(priv);
1137                 db->hdb_dbc = NULL;
1138         }
1139
1140         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1141         if (!priv) {
1142                 krb5_set_error_string(context, "talloc: out of memory");
1143                 return ENOMEM;
1144         }
1145
1146         priv->ctx = ldb_ctx;
1147         priv->index = 0;
1148         priv->msgs = NULL;
1149         priv->realm_ref_msgs = NULL;
1150         priv->count = 0;
1151
1152         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1153
1154         if (!mem_ctx) {
1155                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1156                 return ENOMEM;
1157         }
1158
1159         ret = krb5_get_default_realm(context, &realm);
1160         if (ret != 0) {
1161                 talloc_free(priv);
1162                 return ret;
1163         }
1164                 
1165         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1166                                mem_ctx, realm, &realm_ref_msgs);
1167
1168         free(realm);
1169
1170         if (ret != 0) {
1171                 talloc_free(priv);
1172                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1173                 return HDB_ERR_NOENTRY;
1174         }
1175
1176         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
1177
1178         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
1179
1180         lret = ldb_search(ldb_ctx, realm_dn,
1181                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
1182                                  user_attrs, &res);
1183
1184         if (lret != LDB_SUCCESS) {
1185                 talloc_free(priv);
1186                 return HDB_ERR_NOENTRY;
1187         }
1188
1189         priv->count = res->count;
1190         priv->msgs = talloc_steal(priv, res->msgs);
1191         talloc_free(res);
1192
1193         db->hdb_dbc = priv;
1194
1195         ret = LDB_seq(context, db, flags, entry);
1196
1197         if (ret != 0) {
1198                 talloc_free(priv);
1199                 db->hdb_dbc = NULL;
1200         } else {
1201                 talloc_free(mem_ctx);
1202         }
1203         return ret;
1204 }
1205
1206 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1207                                    hdb_entry_ex *entry)
1208 {
1209         return LDB_seq(context, db, flags, entry);
1210 }
1211
1212 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1213 {
1214         talloc_free(db);
1215         return 0;
1216 }
1217
1218 /* This interface is to be called by the KDC, which is expecting Samba
1219  * calling conventions.  It is also called by a wrapper
1220  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1221  * code */
1222
1223 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1224                             struct event_context *ev_ctx, 
1225                             struct loadparm_context *lp_ctx,
1226                             krb5_context context, struct HDB **db, const char *arg)
1227 {
1228         NTSTATUS nt_status;
1229         struct auth_session_info *session_info;
1230         *db = talloc(mem_ctx, HDB);
1231         if (!*db) {
1232                 krb5_set_error_string(context, "malloc: out of memory");
1233                 return NT_STATUS_NO_MEMORY;
1234         }
1235
1236         (*db)->hdb_master_key_set = 0;
1237         (*db)->hdb_db = NULL;
1238
1239         nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1240         if (!NT_STATUS_IS_OK(nt_status)) {
1241                 return nt_status;
1242         }
1243         
1244         /* The idea here is very simple.  Using Kerberos to
1245          * authenticate the KDC to the LDAP server is higly likely to
1246          * be circular.
1247          *
1248          * In future we may set this up to use EXERNAL and SSL
1249          * certificates, for now it will almost certainly be NTLMSSP
1250         */
1251         
1252         cli_credentials_set_kerberos_state(session_info->credentials, 
1253                                            CRED_DONT_USE_KERBEROS);
1254
1255         /* Setup the link to LDB */
1256         (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1257         if ((*db)->hdb_db == NULL) {
1258                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1259                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1260         }
1261
1262         (*db)->hdb_dbc = NULL;
1263         (*db)->hdb_open = LDB_open;
1264         (*db)->hdb_close = LDB_close;
1265         (*db)->hdb_fetch = LDB_fetch;
1266         (*db)->hdb_store = LDB_store;
1267         (*db)->hdb_remove = LDB_remove;
1268         (*db)->hdb_firstkey = LDB_firstkey;
1269         (*db)->hdb_nextkey = LDB_nextkey;
1270         (*db)->hdb_lock = LDB_lock;
1271         (*db)->hdb_unlock = LDB_unlock;
1272         (*db)->hdb_rename = LDB_rename;
1273         /* we don't implement these, as we are not a lockable database */
1274         (*db)->hdb__get = NULL;
1275         (*db)->hdb__put = NULL;
1276         /* kadmin should not be used for deletes - use other tools instead */
1277         (*db)->hdb__del = NULL;
1278         (*db)->hdb_destroy = LDB_destroy;
1279
1280         return NT_STATUS_OK;
1281 }
1282
1283 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1284 {
1285         NTSTATUS nt_status;
1286         /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1287         nt_status = kdc_hdb_ldb_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
1288                                        context, db, arg);
1289
1290         if (NT_STATUS_IS_OK(nt_status)) {
1291                 return 0;
1292         }
1293         return EINVAL;
1294 }