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