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