80e8cdc74e7d53dbba992bcca267385d14709f1a
[jelmer/samba4-debian.git] / source / 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 "kdc.h"
37 #include "ads.h"
38 #include "hdb.h"
39 #include "lib/ldb/include/ldb.h"
40 #include "system/iconv.h"
41
42 enum hdb_ldb_ent_type 
43 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
44   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
45
46 static const char * const krb5_attrs[] = {
47         "objectClass",
48         "sAMAccountName",
49
50         "userPrincipalName",
51         "servicePrincipalName",
52
53         "unicodePwd",
54         "lmPwdHash",
55         "ntPwdHash",
56
57         "userAccountControl",
58
59         "pwdLastSet",
60         "accountExpires",
61
62         "whenCreated",
63         "whenChanged",
64
65         "msDS-KeyVersionNumber",
66         NULL
67 };
68
69 static const char *realm_ref_attrs[] = {
70         "nCName", 
71         "dnsRoot", 
72         NULL
73 };
74
75 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
76 {
77     const char *tmp;
78     const char *gentime;
79     struct tm tm;
80
81     gentime = ldb_msg_find_string(msg, attr, NULL);
82     if (!gentime)
83         return default_val;
84
85     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
86     if (tmp == NULL) {
87             return default_val;
88     }
89
90     return timegm(&tm);
91 }
92
93 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
94 {
95         HDBFlags flags = int2HDBFlags(0);
96
97         krb5_warnx(context, "uf2HDBFlags: userAccountControl: %08x\n", userAccountControl);
98
99         /* we don't allow kadmin deletes */
100         flags.immutable = 1;
101
102         /* mark the principal as invalid to start with */
103         flags.invalid = 1;
104
105         flags.renewable = 1;
106
107         /* All accounts are servers, but this may be disabled again in the caller */
108         flags.server = 1;
109
110         /* Account types - clear the invalid bit if it turns out to be valid */
111         if (userAccountControl & UF_NORMAL_ACCOUNT) {
112                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
113                         flags.client = 1;
114                 }
115                 flags.invalid = 0;
116         }
117         
118         if (userAccountControl & UF_INTERDOMAIN_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_WORKSTATION_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         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
131                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
132                         flags.client = 1;
133                 }
134                 flags.invalid = 0;
135         }
136
137         /* Not permitted to act as a client if disabled */
138         if (userAccountControl & UF_ACCOUNTDISABLE) {
139                 flags.client = 0;
140         }
141         if (userAccountControl & UF_LOCKOUT) {
142                 flags.invalid = 1;
143         }
144 /*
145         if (userAccountControl & UF_PASSWORD_NOTREQD) {
146                 flags.invalid = 1;
147         }
148 */
149 /*
150         if (userAccountControl & UF_PASSWORD_CANT_CHANGE) {
151                 flags.invalid = 1;
152         }
153 */
154 /*
155         if (userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED) {
156                 flags.invalid = 1;
157         }
158 */
159         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
160                 flags.invalid = 1;
161         }
162
163 /* UF_DONT_EXPIRE_PASSWD handled in LDB_message2entry() */
164
165 /*
166         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
167                 flags.invalid = 1;
168         }
169 */
170         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
171                 flags.require_hwauth = 1;
172         }
173         if (flags.server && (userAccountControl & UF_TRUSTED_FOR_DELEGATION)) {
174                 flags.forwardable = 1;
175                 flags.proxiable = 1;
176         } else if (flags.client && (userAccountControl & UF_NOT_DELEGATED)) {
177                 flags.forwardable = 0;
178                 flags.proxiable = 0;
179         } else {
180                 flags.forwardable = 1;
181                 flags.proxiable = 1;
182         }
183
184 /*
185         if (userAccountControl & UF_SMARTCARD_USE_DES_KEY_ONLY) {
186                 flags.invalid = 1;
187         }
188 */
189         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
190                 flags.require_preauth = 0;
191         } else {
192                 flags.require_preauth = 1;
193
194         }
195
196         krb5_warnx(context, "uf2HDBFlags: HDBFlags: %08x\n", HDBFlags2int(flags));
197
198         return flags;
199 }
200
201 /*
202  * Construct an hdb_entry from a directory entry.
203  */
204 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
205                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
206                                          enum hdb_ldb_ent_type ent_type, 
207                                          struct ldb_message *msg,
208                                          struct ldb_message *realm_ref_msg,
209                                          hdb_entry *ent)
210 {
211         const char *unicodePwd;
212         int userAccountControl;
213         int i;
214         krb5_error_code ret = 0;
215         const char *dnsdomain = ldb_msg_find_string(realm_ref_msg, "dnsRoot", NULL);
216         char *realm = strupper_talloc(mem_ctx, dnsdomain);
217
218
219         memset(ent, 0, sizeof(*ent));
220
221         krb5_warnx(context, "LDB_message2entry:\n");
222
223         if (!realm) {
224                 krb5_set_error_string(context, "talloc_strdup: out of memory");
225                 ret = ENOMEM;
226                 goto out;
227         }
228                         
229         userAccountControl = ldb_msg_find_int(msg, "userAccountControl", 0);
230         
231         ent->principal = malloc(sizeof(*(ent->principal)));
232         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
233                 const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
234                 if (!samAccountName) {
235                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
236                         ret = ENOENT;
237                         goto out;
238                 }
239                 samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
240                 krb5_make_principal(context, &ent->principal, realm, samAccountName, NULL);
241         } else {
242                 char *strdup_realm;
243                 ret = copy_Principal(principal, ent->principal);
244                 if (ret) {
245                         krb5_clear_error_string(context);
246                         goto out;
247                 }
248
249                 /* While we have copied the client principal, tests
250                  * show that Win2k3 returns the 'corrected' realm, not
251                  * the client-specified realm.  This code attempts to
252                  * replace the client principal's realm with the one
253                  * we determine from our records */
254                 
255                 /* don't leak */
256                 free(*krb5_princ_realm(context, ent->principal));
257                 
258                 /* this has to be with malloc() */
259                 strdup_realm = strdup(realm);
260                 if (!strdup_realm) {
261                         ret = ENOMEM;
262                         krb5_clear_error_string(context);
263                         goto out;
264                 }
265                 krb5_princ_set_realm(context, ent->principal, &strdup_realm);
266         }
267
268         ent->kvno = ldb_msg_find_int(msg, "msDS-KeyVersionNumber", 0);
269
270         ent->flags = uf2HDBFlags(context, userAccountControl, ent_type);
271
272         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
273                 ent->flags.invalid = 0;
274                 ent->flags.server = 1;
275         }
276
277         if (lp_parm_bool(-1, "kdc", "require spn for service", True)) {
278                 if (!ldb_msg_find_string(msg, "servicePrincipalName", NULL)) {
279                         ent->flags.server = 0;
280                 }
281         }
282
283         /* use 'whenCreated' */
284         ent->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
285         /* use '???' */
286         ent->created_by.principal = NULL;
287
288         ent->modified_by = (Event *) malloc(sizeof(Event));
289         if (ent->modified_by == NULL) {
290                 krb5_set_error_string(context, "malloc: out of memory");
291                 ret = ENOMEM;
292                 goto out;
293         }
294
295         /* use 'whenChanged' */
296         ent->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
297         /* use '???' */
298         ent->modified_by->principal = NULL;
299
300         ent->valid_start = NULL;
301
302         ent->valid_end = NULL;
303         ent->pw_end = NULL;
304
305         ent->max_life = NULL;
306
307         ent->max_renew = NULL;
308
309         ent->generation = NULL;
310
311         /* create the keys and enctypes */
312         unicodePwd = ldb_msg_find_string(msg, "unicodePwd", NULL);
313         if (unicodePwd) {
314                 /* Many, many thanks to lukeh@padl.com for this
315                  * algorithm, described in his Nov 10 2004 mail to
316                  * samba-technical@samba.org */
317
318                 Principal *salt_principal;
319                 const char *user_principal_name = ldb_msg_find_string(msg, "userPrincipalName", NULL);
320                 struct ldb_message_element *objectclasses;
321                 struct ldb_val computer_val;
322                 computer_val.data = discard_const_p(uint8_t,"computer");
323                 computer_val.length = strlen((const char *)computer_val.data);
324                 
325                 objectclasses = ldb_msg_find_element(msg, "objectClass");
326
327                 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
328                         /* Determine a salting principal */
329                         char *samAccountName = talloc_strdup(mem_ctx, ldb_msg_find_string(msg, "samAccountName", NULL));
330                         char *saltbody;
331                         if (!samAccountName) {
332                                 krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
333                                 ret = ENOENT;
334                                 goto out;
335                         }
336                         if (samAccountName[strlen(samAccountName)-1] == '$') {
337                                 samAccountName[strlen(samAccountName)-1] = '\0';
338                         }
339                         saltbody = talloc_asprintf(mem_ctx, "%s.%s", samAccountName, dnsdomain);
340                         
341                         ret = krb5_make_principal(context, &salt_principal, realm, "host", saltbody, NULL);
342                 } else if (user_principal_name) {
343                         char *p;
344                         user_principal_name = talloc_strdup(mem_ctx, user_principal_name);
345                         if (!user_principal_name) {
346                                 ret = ENOMEM;
347                                 goto out;
348                         } else {
349                                 p = strchr(user_principal_name, '@');
350                                 if (p) {
351                                         p[0] = '\0';
352                                 }
353                                 ret = krb5_make_principal(context, &salt_principal, realm, user_principal_name, NULL);
354                         } 
355                 } else {
356                         const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
357                         ret = krb5_make_principal(context, &salt_principal, realm, samAccountName, NULL);
358                 }
359
360                 if (ret == 0) {
361                         size_t num_keys = ent->keys.len;
362                         /*
363                          * create keys from unicodePwd
364                          */
365                         ret = hdb_generate_key_set_password(context, salt_principal, 
366                                                             unicodePwd, 
367                                                             &ent->keys.val, &num_keys);
368                         ent->keys.len = num_keys;
369                         krb5_free_principal(context, salt_principal);
370                 }
371
372                 if (ret != 0) {
373                         krb5_warnx(context, "could not generate keys from unicodePwd\n");
374                         ent->keys.val = NULL;
375                         ent->keys.len = 0;
376                         goto out;
377                 }
378         } else {
379                 const struct ldb_val *val;
380                 krb5_data keyvalue;
381
382                 val = ldb_msg_find_ldb_val(msg, "ntPwdHash");
383                 if (!val) {
384                         krb5_warnx(context, "neither type of key available for this account\n");
385                         ent->keys.val = NULL;
386                         ent->keys.len = 0;
387                 } else if (val->length < 16) {
388                         ent->keys.val = NULL;
389                         ent->keys.len = 0;
390                         krb5_warnx(context, "ntPwdHash has invalid length: %d\n",
391                                    (int)val->length);
392                 } else {
393                         ret = krb5_data_alloc (&keyvalue, 16);
394                         if (ret) {
395                                 krb5_set_error_string(context, "malloc: out of memory");
396                                 ret = ENOMEM;
397                                 goto out;
398                         }
399
400                         memcpy(keyvalue.data, val->data, 16);
401
402                         ent->keys.val = malloc(sizeof(ent->keys.val[0]));
403                         if (ent->keys.val == NULL) {
404                                 krb5_data_free(&keyvalue);
405                                 krb5_set_error_string(context, "malloc: out of memory");
406                                 ret = ENOMEM;
407                                 goto out;
408                         }
409                         
410                         memset(&ent->keys.val[0], 0, sizeof(Key));
411                         ent->keys.val[0].key.keytype = ETYPE_ARCFOUR_HMAC_MD5;
412                         ent->keys.val[0].key.keyvalue = keyvalue;
413                         
414                         ent->keys.len = 1;
415                 }
416         }               
417
418
419         ent->etypes = malloc(sizeof(*(ent->etypes)));
420         if (ent->etypes == NULL) {
421                 krb5_set_error_string(context, "malloc: out of memory");
422                 ret = ENOMEM;
423                 goto out;
424         }
425         ent->etypes->len = ent->keys.len;
426         ent->etypes->val = calloc(ent->etypes->len, sizeof(int));
427         if (ent->etypes->val == NULL) {
428                 krb5_set_error_string(context, "malloc: out of memory");
429                 ret = ENOMEM;
430                 goto out;
431         }
432         for (i=0; i < ent->etypes->len; i++) {
433                 ent->etypes->val[i] = ent->keys.val[i].key.keytype;
434         }
435
436 out:
437         if (ret != 0) {
438                 /* I don't think this frees ent itself. */
439                 hdb_free_entry(context, ent);
440         }
441
442         return ret;
443 }
444
445 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
446                                             TALLOC_CTX *mem_ctx,
447                                             krb5_const_principal principal,
448                                             enum hdb_ldb_ent_type ent_type,
449                                             const struct ldb_dn *realm_dn,
450                                             struct ldb_message ***pmsg)
451 {
452         krb5_error_code ret;
453         int count;
454         char *filter = NULL;
455         const char * const *princ_attrs = krb5_attrs;
456
457         char *princ_str;
458         char *princ_str_talloc;
459         char *short_princ;
460         char *short_princ_talloc;
461
462         char *realm_dn_str;
463
464         struct ldb_message **msg = NULL;
465
466         ret = krb5_unparse_name(context, principal, &princ_str);
467
468         if (ret != 0) {
469                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
470                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
471                 return ret;
472         }
473
474         ret = krb5_unparse_name_norealm(context, principal, &short_princ);
475
476         if (ret != 0) {
477                 free(princ_str);
478                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
479                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
480                 return ret;
481         }
482
483         princ_str_talloc = talloc_strdup(mem_ctx, princ_str);
484         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
485         free(princ_str);
486         free(short_princ);
487         if (!short_princ || !princ_str_talloc) {
488                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
489                 return ENOMEM;
490         }
491
492         switch (ent_type) {
493         case HDB_LDB_ENT_TYPE_CLIENT:
494                 /* Can't happen */
495                 return EINVAL;
496                 break;
497         case HDB_LDB_ENT_TYPE_KRBTGT:
498                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
499                                          KRB5_TGS_NAME);
500                 break;
501         case HDB_LDB_ENT_TYPE_SERVER:
502                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
503                                          short_princ_talloc);
504                 break;
505         case HDB_LDB_ENT_TYPE_ANY:
506                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(|(samAccountName=%s)(servicePrincipalName=%s))(userPrincipalName=%s)))", 
507                                          short_princ_talloc, short_princ_talloc, princ_str_talloc);
508                 break;
509         }
510
511         if (!filter) {
512                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
513                 return ENOMEM;
514         }
515
516         count = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, 
517                            princ_attrs, &msg);
518
519         realm_dn_str = ldb_dn_linearize(mem_ctx, realm_dn);
520
521         if (count < 1) {
522                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
523                            realm_dn_str, filter, count);
524                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
525                                       realm_dn_str, filter, count);
526                 return HDB_ERR_NOENTRY;
527         } else if (count > 1) {
528                 talloc_free(msg);
529                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
530                            realm_dn_str, filter, count);
531                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
532                                       realm_dn_str, filter, count);
533                 return HDB_ERR_NOENTRY;
534         }
535         *pmsg = talloc_steal(mem_ctx, msg);
536         return 0;
537 }
538
539 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
540                                         TALLOC_CTX *mem_ctx,
541                                         const char *realm,
542                                         struct ldb_message ***pmsg)
543 {
544         int count;
545         char *cross_ref_filter;
546         struct ldb_message **cross_ref_msg;
547
548         cross_ref_filter = talloc_asprintf(mem_ctx, 
549                                            "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
550                                            realm, realm);
551         if (!cross_ref_filter) {
552                 krb5_set_error_string(context, "asprintf: out of memory");
553                 return ENOMEM;
554         }
555
556         count = ldb_search(ldb_ctx, NULL, LDB_SCOPE_SUBTREE, cross_ref_filter, 
557                            realm_ref_attrs, &cross_ref_msg);
558
559         if (count < 1) {
560                 krb5_warnx(context, "ldb_search: filter: '%s' failed: %d", cross_ref_filter, count);
561                 krb5_set_error_string(context, "ldb_search: filter: '%s' failed: %d", cross_ref_filter, count);
562
563                 talloc_free(cross_ref_msg);
564                 return HDB_ERR_NOENTRY;
565         } else if (count > 1) {
566                 krb5_warnx(context, "ldb_search: filter: '%s' more than 1 entry: %d", cross_ref_filter, count);
567                 krb5_set_error_string(context, "ldb_search: filter: '%s' more than 1 entry: %d", cross_ref_filter, count);
568
569                 talloc_free(cross_ref_msg);
570                 return HDB_ERR_NOENTRY;
571         }
572
573         if (pmsg) {
574                 *pmsg = talloc_steal(mem_ctx, cross_ref_msg);
575         } else {
576                 talloc_free(cross_ref_msg);
577         }
578
579         return 0;
580 }
581
582
583 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
584 {
585         if (db->hdb_master_key_set) {
586                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
587                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
588                 return HDB_ERR_NOENTRY;
589         }               
590
591         return 0;
592 }
593
594 static krb5_error_code LDB_close(krb5_context context, HDB *db)
595 {
596         return 0;
597 }
598
599 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
600 {
601         return 0;
602 }
603
604 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
605 {
606         return 0;
607 }
608
609 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
610 {
611         return HDB_ERR_DB_INUSE;
612 }
613
614 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, unsigned flags,
615                                  krb5_const_principal principal,
616                                  enum hdb_ent_type ent_type,
617                                  hdb_entry *entry)
618 {
619         struct ldb_message **msg = NULL;
620         struct ldb_message **realm_ref_msg = NULL;
621         struct ldb_message **realm_fixed_msg = NULL;
622         enum hdb_ldb_ent_type ldb_ent_type;
623         krb5_error_code ret;
624
625         const char *realm;
626         const struct ldb_dn *realm_dn;
627         TALLOC_CTX *mem_ctx = talloc_named(NULL, 0, "LDB_fetch context");
628
629         if (!mem_ctx) {
630                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
631                 return ENOMEM;
632         }
633
634         /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
635          * is in our db, then direct the caller at our primary
636          * krgtgt */
637
638         switch (ent_type) {
639         case HDB_ENT_TYPE_CLIENT:
640         {
641                 NTSTATUS nt_status;
642                 char *principal_string;
643                 ldb_ent_type = HDB_LDB_ENT_TYPE_CLIENT;
644
645                 ret = krb5_unparse_name(context, principal, &principal_string);
646                 
647                 if (ret != 0) {
648                         talloc_free(mem_ctx);
649                         return ret;
650                 }
651
652                 nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
653                                                       mem_ctx, principal_string, 
654                                                       &msg, &realm_ref_msg);
655                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
656                         return HDB_ERR_NOENTRY;
657                 } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
658                         return ENOMEM;
659                 } else if (!NT_STATUS_IS_OK(nt_status)) {
660                         return EINVAL;
661                 }
662
663                 ret = LDB_message2entry(context, db, mem_ctx, 
664                                         principal, ldb_ent_type, 
665                                         msg[0], realm_ref_msg[0], entry);
666                 talloc_free(mem_ctx);
667                 return ret;
668         }
669         case HDB_ENT_TYPE_SERVER:
670                 if (principal->name.name_string.len == 2
671                     && (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) == 0)) {
672                         /* krbtgt case.  Either us or a trusted realm */
673                         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
674                                               mem_ctx, principal->name.name_string.val[1], &realm_fixed_msg) == 0)) {
675                                 /* us */
676                                 const char *dnsdomain = ldb_msg_find_string(realm_fixed_msg[0], "dnsRoot", NULL);
677                                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
678                                 if (!realm_fixed) {
679                                         krb5_set_error_string(context, "strupper_talloc: out of memory");
680                                         talloc_free(mem_ctx);
681                                         return ENOMEM;
682                                 }
683                                 
684                                 free(principal->name.name_string.val[1]);
685                                 principal->name.name_string.val[1] = strdup(realm_fixed);
686                                 talloc_free(realm_fixed);
687                                 if (!principal->name.name_string.val[1]) {
688                                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
689                                         talloc_free(mem_ctx);
690                                         return ENOMEM;
691                                 }
692                                 ldb_ent_type = HDB_LDB_ENT_TYPE_KRBTGT;
693                                 break;
694                         } else {
695                                 /* we should lookup trusted domains */
696                                 return HDB_ERR_NOENTRY;
697                         }
698
699                 } else if (principal->name.name_string.len >= 2) {
700                         /* 'normal server' case */
701                         int ldb_ret;
702                         NTSTATUS nt_status;
703                         struct ldb_dn *user_dn, *domain_dn;
704                         char *principal_string;
705                         ldb_ent_type = HDB_LDB_ENT_TYPE_SERVER;
706                         
707                         ret = krb5_unparse_name_norealm(context, principal, &principal_string);
708                         
709                         if (ret != 0) {
710                                 talloc_free(mem_ctx);
711                                 return ret;
712                         }
713                         
714                         /* At this point we may find the host is known to be
715                          * in a different realm, so we should generate a
716                          * referral instead */
717                         nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
718                                                                  mem_ctx, principal_string, 
719                                                                  &user_dn, &domain_dn);
720                         free(principal_string);
721                         
722                         if (!NT_STATUS_IS_OK(nt_status)) {
723                                 talloc_free(mem_ctx);
724                                 return HDB_ERR_NOENTRY;
725                         }
726                         
727                         ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
728                                                   mem_ctx, user_dn, &msg, krb5_attrs);
729                         
730                         if (ldb_ret != 1) {
731                                 return HDB_ERR_NOENTRY;
732                         }
733                         
734                         ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
735                                                mem_ctx, NULL, &realm_ref_msg, realm_ref_attrs, 
736                                                "ncName=%s", ldb_dn_linearize(mem_ctx, domain_dn));
737                         
738                         if (ldb_ret != 1) {
739                                 return HDB_ERR_NOENTRY;
740                         }
741
742                         ret = LDB_message2entry(context, db, mem_ctx, 
743                                                 principal, ldb_ent_type, 
744                                                 msg[0], realm_ref_msg[0], entry);
745                         talloc_free(mem_ctx);
746                         return ret;
747                         
748                 } else {
749                         ldb_ent_type = HDB_LDB_ENT_TYPE_SERVER;
750                         /* server as client principal case, but we must not lookup userPrincipalNames */
751                         break;
752                 }
753         case HDB_ENT_TYPE_ANY:
754                 ldb_ent_type = HDB_LDB_ENT_TYPE_ANY;
755                 break;
756         default:
757                 krb5_warnx(context, "LDB_fetch: invalid ent_type specified!");
758                 talloc_free(mem_ctx);
759                 return HDB_ERR_NOENTRY;
760         }
761
762
763         realm = krb5_principal_get_realm(context, principal);
764
765         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
766                                mem_ctx, realm, &realm_ref_msg);
767         if (ret != 0) {
768                 krb5_warnx(context, "LDB_fetch: could not find realm");
769                 talloc_free(mem_ctx);
770                 return HDB_ERR_NOENTRY;
771         }
772
773         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
774
775         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
776                                    mem_ctx, 
777                                    principal, ldb_ent_type, realm_dn, &msg);
778
779         if (ret != 0) {
780                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
781                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
782                 talloc_free(mem_ctx);
783                 return ret;
784         } else {
785                 ret = LDB_message2entry(context, db, mem_ctx, 
786                                         principal, ldb_ent_type, 
787                                         msg[0], realm_ref_msg[0], entry);
788                 if (ret != 0) {
789                         krb5_warnx(context, "LDB_fetch: message2entry failed\n");       
790                 }
791         }
792
793         talloc_free(mem_ctx);
794         return ret;
795 }
796
797 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
798 {
799         return HDB_ERR_DB_INUSE;
800 }
801
802 static krb5_error_code LDB_remove(krb5_context context, HDB *db, hdb_entry *entry)
803 {
804         return HDB_ERR_DB_INUSE;
805 }
806
807 struct hdb_ldb_seq {
808         struct ldb_context *ctx;
809         int index;
810         int count;
811         struct ldb_message **msgs;
812         struct ldb_message **realm_ref_msgs;
813 };
814
815 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
816 {
817         krb5_error_code ret;
818         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
819         TALLOC_CTX *mem_ctx;
820         if (!priv) {
821                 return HDB_ERR_NOENTRY;
822         }
823
824         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
825
826         if (!mem_ctx) {
827                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
828                 return ENOMEM;
829         }
830
831         if (priv->index < priv->count) {
832                 ret = LDB_message2entry(context, db, mem_ctx, 
833                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
834                                         priv->msgs[priv->index++], 
835                                         priv->realm_ref_msgs[0], entry);
836         } else {
837                 ret = HDB_ERR_NOENTRY;
838         }
839
840         if (ret != 0) {
841                 talloc_free(priv);
842                 db->hdb_openp = NULL;
843         } else {
844                 talloc_free(mem_ctx);
845         }
846
847         return ret;
848 }
849
850 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
851                                         hdb_entry *entry)
852 {
853         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
854         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
855         char *realm;
856         struct ldb_dn *realm_dn = NULL;
857         struct ldb_message **msgs = NULL;
858         struct ldb_message **realm_ref_msgs = NULL;
859         krb5_error_code ret;
860         TALLOC_CTX *mem_ctx;
861
862         if (priv) {
863                 talloc_free(priv);
864                 db->hdb_openp = 0;
865         }
866
867         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
868         if (!priv) {
869                 krb5_set_error_string(context, "talloc: out of memory");
870                 return ENOMEM;
871         }
872
873         priv->ctx = ldb_ctx;
874         priv->index = 0;
875         priv->msgs = NULL;
876         priv->realm_ref_msgs = NULL;
877         priv->count = 0;
878
879         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
880
881         if (!mem_ctx) {
882                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
883                 return ENOMEM;
884         }
885
886         ret = krb5_get_default_realm(context, &realm);
887         if (ret != 0) {
888                 talloc_free(priv);
889                 return ret;
890         }
891                 
892         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
893                                mem_ctx, realm, &realm_ref_msgs);
894
895         free(realm);
896
897         if (ret != 0) {
898                 talloc_free(priv);
899                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
900                 return HDB_ERR_NOENTRY;
901         }
902
903         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msgs[0], "nCName", NULL);
904
905         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
906
907         krb5_warnx(context, "LDB_firstkey: realm ok\n");
908
909         priv->count = ldb_search(ldb_ctx, realm_dn,
910                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
911                                  krb5_attrs, &msgs);
912
913         priv->msgs = talloc_steal(priv, msgs);
914
915         if (priv->count <= 0) {
916                 talloc_free(priv);
917                 return HDB_ERR_NOENTRY;
918         }
919
920         db->hdb_openp = priv;
921
922         ret = LDB_seq(context, db, flags, entry);
923         
924         if (ret != 0) {
925                 talloc_free(priv);
926                 db->hdb_openp = NULL;
927         } else {
928                 talloc_free(mem_ctx);
929         }
930         return ret;
931 }
932
933 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
934                                         hdb_entry *entry)
935 {
936         return LDB_seq(context, db, flags, entry);
937 }
938
939 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
940 {
941         talloc_free(db);
942         return 0;
943 }
944
945 krb5_error_code hdb_ldb_create(TALLOC_CTX *mem_ctx, 
946                                krb5_context context, struct HDB **db, const char *arg)
947 {
948         *db = talloc(mem_ctx, HDB);
949         if (!*db) {
950                 krb5_set_error_string(context, "malloc: out of memory");
951                 return ENOMEM;
952         }
953
954         (*db)->hdb_master_key_set = 0;
955         (*db)->hdb_db = NULL;
956
957         /* Setup the link to LDB */
958         (*db)->hdb_db = samdb_connect(*db, system_session(db));
959         if ((*db)->hdb_db == NULL) {
960                 krb5_warnx(context, "hdb_ldb_create: samdb_connect failed!");
961                 krb5_set_error_string(context, "samdb_connect failed!");
962                 talloc_free(*db);
963                 return HDB_ERR_NOENTRY;
964         }
965
966         (*db)->hdb_openp = 0;
967         (*db)->hdb_open = LDB_open;
968         (*db)->hdb_close = LDB_close;
969         (*db)->hdb_fetch = LDB_fetch;
970         (*db)->hdb_store = LDB_store;
971         (*db)->hdb_remove = LDB_remove;
972         (*db)->hdb_firstkey = LDB_firstkey;
973         (*db)->hdb_nextkey = LDB_nextkey;
974         (*db)->hdb_lock = LDB_lock;
975         (*db)->hdb_unlock = LDB_unlock;
976         (*db)->hdb_rename = LDB_rename;
977         /* we don't implement these, as we are not a lockable database */
978         (*db)->hdb__get = NULL;
979         (*db)->hdb__put = NULL;
980         /* kadmin should not be used for deletes - use other tools instead */
981         (*db)->hdb__del = NULL;
982         (*db)->hdb_destroy = LDB_destroy;
983
984         return 0;
985 }