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