r16237: Use an appropriate basedn for these searches, so they occour into the
[jelmer/samba4-debian.git] / source / kdc / hdb-ldb.c
1 /*
2  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3  * Copyright (c) 2004, Andrew Bartlett <abartlet@samba.org>.
4  * Copyright (c) 2004, Stefan Metzmacher <metze@samba.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * 3. Neither the name of PADL Software  nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "includes.h"
36 #include "system/time.h"
37 #include "kdc.h"
38 #include "ads.h"
39 #include "hdb.h"
40 #include "lib/ldb/include/ldb.h"
41 #include "lib/ldb/include/ldb_errors.h"
42 #include "librpc/gen_ndr/netlogon.h"
43 #include "auth/auth.h"
44 #include "auth/auth_sam.h"
45 #include "db_wrap.h"
46 #include "dsdb/samdb/samdb.h"
47
48 enum hdb_ldb_ent_type 
49 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
50   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
51
52 static const char * const krb5_attrs[] = {
53         "objectClass",
54         "sAMAccountName",
55
56         "userPrincipalName",
57         "servicePrincipalName",
58
59         "krb5Key",
60
61         "userAccountControl",
62
63         "pwdLastSet",
64         "accountExpires",
65
66         "whenCreated",
67         "whenChanged",
68
69         "msDS-KeyVersionNumber",
70         NULL
71 };
72
73 static const char *realm_ref_attrs[] = {
74         "nCName", 
75         "dnsRoot", 
76         NULL
77 };
78
79 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
80 {
81     const char *tmp;
82     const char *gentime;
83     struct tm tm;
84
85     gentime = ldb_msg_find_string(msg, attr, NULL);
86     if (!gentime)
87         return default_val;
88
89     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
90     if (tmp == NULL) {
91             return default_val;
92     }
93
94     return timegm(&tm);
95 }
96
97 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
98 {
99         HDBFlags flags = int2HDBFlags(0);
100
101         krb5_warnx(context, "uf2HDBFlags: userAccountControl: %08x\n", userAccountControl);
102
103         /* we don't allow kadmin deletes */
104         flags.immutable = 1;
105
106         /* mark the principal as invalid to start with */
107         flags.invalid = 1;
108
109         flags.renewable = 1;
110
111         /* All accounts are servers, but this may be disabled again in the caller */
112         flags.server = 1;
113
114         /* Account types - clear the invalid bit if it turns out to be valid */
115         if (userAccountControl & UF_NORMAL_ACCOUNT) {
116                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
117                         flags.client = 1;
118                 }
119                 flags.invalid = 0;
120         }
121         
122         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
123                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
124                         flags.client = 1;
125                 }
126                 flags.invalid = 0;
127         }
128         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
129                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
130                         flags.client = 1;
131                 }
132                 flags.invalid = 0;
133         }
134         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
135                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
136                         flags.client = 1;
137                 }
138                 flags.invalid = 0;
139         }
140
141         /* Not permitted to act as a client if disabled */
142         if (userAccountControl & UF_ACCOUNTDISABLE) {
143                 flags.client = 0;
144         }
145         if (userAccountControl & UF_LOCKOUT) {
146                 flags.invalid = 1;
147         }
148 /*
149         if (userAccountControl & UF_PASSWORD_NOTREQD) {
150                 flags.invalid = 1;
151         }
152 */
153 /*
154         if (userAccountControl & UF_PASSWORD_CANT_CHANGE) {
155                 flags.invalid = 1;
156         }
157 */
158 /*
159         if (userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED) {
160                 flags.invalid = 1;
161         }
162 */
163         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
164                 flags.invalid = 1;
165         }
166
167 /* UF_DONT_EXPIRE_PASSWD handled in LDB_message2entry() */
168
169 /*
170         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
171                 flags.invalid = 1;
172         }
173 */
174         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
175                 flags.require_hwauth = 1;
176         }
177         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
178                 flags.ok_as_delegate = 1;
179         }       
180         if (!(userAccountControl & UF_NOT_DELEGATED)) {
181                 flags.forwardable = 1;
182                 flags.proxiable = 1;
183         }
184
185 /*
186         if (userAccountControl & UF_SMARTCARD_USE_DES_KEY_ONLY) {
187                 flags.invalid = 1;
188         }
189 */
190         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
191                 flags.require_preauth = 0;
192         } else {
193                 flags.require_preauth = 1;
194
195         }
196
197         krb5_warnx(context, "uf2HDBFlags: HDBFlags: %08x\n", HDBFlags2int(flags));
198
199         return flags;
200 }
201
202 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
203 {
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         unsigned int userAccountControl;
225         int i;
226         krb5_error_code ret = 0;
227         krb5_boolean is_computer = FALSE;
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         struct ldb_message_element *ldb_keys;
235
236         struct ldb_message_element *objectclasses;
237         struct ldb_val computer_val;
238         computer_val.data = discard_const_p(uint8_t,"computer");
239         computer_val.length = strlen((const char *)computer_val.data);
240         
241         objectclasses = ldb_msg_find_element(msg, "objectClass");
242         
243         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
244                 is_computer = TRUE;
245         }
246
247         memset(entry_ex, 0, sizeof(*entry_ex));
248
249         krb5_warnx(context, "LDB_message2entry:\n");
250
251         if (!realm) {
252                 krb5_set_error_string(context, "talloc_strdup: out of memory");
253                 ret = ENOMEM;
254                 goto out;
255         }
256                         
257         private = talloc(mem_ctx, struct hdb_ldb_private);
258         if (!private) {
259                 ret = ENOMEM;
260                 goto out;
261         }
262
263         private->entry_ex = entry_ex;
264
265         talloc_set_destructor(private, hdb_ldb_destrutor);
266
267         entry_ex->ctx = private;
268         entry_ex->free_entry = hdb_ldb_free_entry;
269
270         userAccountControl = ldb_msg_find_uint(msg, "userAccountControl", 0);
271
272         
273         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
274         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
275                 const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
276                 if (!samAccountName) {
277                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
278                         ret = ENOENT;
279                         goto out;
280                 }
281                 samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
282                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
283         } else {
284                 char *strdup_realm;
285                 ret = copy_Principal(principal, entry_ex->entry.principal);
286                 if (ret) {
287                         krb5_clear_error_string(context);
288                         goto out;
289                 }
290
291                 /* While we have copied the client principal, tests
292                  * show that Win2k3 returns the 'corrected' realm, not
293                  * the client-specified realm.  This code attempts to
294                  * replace the client principal's realm with the one
295                  * we determine from our records */
296                 
297                 /* this has to be with malloc() */
298                 strdup_realm = strdup(realm);
299                 if (!strdup_realm) {
300                         ret = ENOMEM;
301                         krb5_clear_error_string(context);
302                         goto out;
303                 }
304                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
305                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
306         }
307
308         entry_ex->entry.kvno = ldb_msg_find_int(msg, "msDS-KeyVersionNumber", 0);
309
310         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
311
312         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
313                 entry_ex->entry.flags.invalid = 0;
314                 entry_ex->entry.flags.server = 1;
315                 entry_ex->entry.flags.forwardable = 1;
316                 entry_ex->entry.flags.ok_as_delegate = 1;
317         }
318
319         if (lp_parm_bool(-1, "kdc", "require spn for service", True)) {
320                 if (!is_computer && !ldb_msg_find_string(msg, "servicePrincipalName", NULL)) {
321                         entry_ex->entry.flags.server = 0;
322                 }
323         }
324
325         /* use 'whenCreated' */
326         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
327         /* use '???' */
328         entry_ex->entry.created_by.principal = NULL;
329
330         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
331         if (entry_ex->entry.modified_by == NULL) {
332                 krb5_set_error_string(context, "malloc: out of memory");
333                 ret = ENOMEM;
334                 goto out;
335         }
336
337         /* use 'whenChanged' */
338         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
339         /* use '???' */
340         entry_ex->entry.modified_by->principal = NULL;
341
342         entry_ex->entry.valid_start = NULL;
343
344         acct_expiry = samdb_result_nttime(msg, "accountExpires", (NTTIME)-1);
345         if ((acct_expiry == (NTTIME)-1) ||
346             (acct_expiry == 0x7FFFFFFFFFFFFFFFULL)) {
347                 entry_ex->entry.valid_end = NULL;
348         } else {
349                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
350                 if (entry_ex->entry.valid_end == NULL) {
351                         ret = ENOMEM;
352                         goto out;
353                 }
354                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
355         }
356
357         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
358                 NTTIME must_change_time
359                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
360                                                              domain_dn, msg);
361                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
362                         entry_ex->entry.pw_end = NULL;
363                 } else {
364                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
365                         if (entry_ex->entry.pw_end == NULL) {
366                                 ret = ENOMEM;
367                                 goto out;
368                         }
369                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
370                 }
371         } else {
372                 entry_ex->entry.pw_end = NULL;
373         }
374                         
375         entry_ex->entry.max_life = NULL;
376
377         entry_ex->entry.max_renew = NULL;
378
379         entry_ex->entry.generation = NULL;
380
381         /* Get krb5Key from the db */
382
383         ldb_keys = ldb_msg_find_element(msg, "krb5Key");
384
385         if (!ldb_keys) {
386                 /* oh, no password.  Apparently (comment in
387                  * hdb-ldap.c) this violates the ASN.1, but this
388                  * allows an entry with no keys (yet). */
389                 entry_ex->entry.keys.val = NULL;
390                 entry_ex->entry.keys.len = 0;
391         } else {
392                 /* allocate space to decode into */
393                 entry_ex->entry.keys.val = calloc(ldb_keys->num_values, sizeof(Key));
394                 if (entry_ex->entry.keys.val == NULL) {
395                         ret = ENOMEM;
396                         goto out;
397                 }
398                 entry_ex->entry.keys.len = ldb_keys->num_values;
399
400                 /* Decode Kerberos keys into the hdb structure */
401                 for (i=0; i < entry_ex->entry.keys.len; i++) {
402                         size_t decode_len;
403                         ret = decode_Key(ldb_keys->values[i].data, ldb_keys->values[i].length, 
404                                          &entry_ex->entry.keys.val[i], &decode_len);
405                         if (ret) {
406                                 /* Could be bougus data in the entry, or out of memory */
407                                 goto out;
408                         }
409                 }
410         } 
411
412         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
413         if (entry_ex->entry.etypes == NULL) {
414                 krb5_clear_error_string(context);
415                 ret = ENOMEM;
416                 goto out;
417         }
418         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
419         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
420         if (entry_ex->entry.etypes->val == NULL) {
421                 krb5_clear_error_string(context);
422                 ret = ENOMEM;
423                 goto out;
424         }
425         for (i=0; i < entry_ex->entry.etypes->len; i++) {
426                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
427         }
428
429
430         private->msg = talloc_steal(private, msg);
431         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
432         private->samdb = (struct ldb_context *)db->hdb_db;
433         
434         entry_ex->check_client_access = hdb_ldb_check_client_access;
435         entry_ex->authz_data_tgs_req = hdb_ldb_authz_data_tgs_req;
436         entry_ex->authz_data_as_req = hdb_ldb_authz_data_as_req;
437
438 out:
439         if (ret != 0) {
440                 /* This doesn't free ent itself, that is for the eventual caller to do */
441                 hdb_free_entry(context, entry_ex);
442         } else {
443                 talloc_steal(db, entry_ex->ctx);
444         }
445
446         return ret;
447 }
448
449 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
450                                             TALLOC_CTX *mem_ctx,
451                                             krb5_const_principal principal,
452                                             enum hdb_ldb_ent_type ent_type,
453                                             const struct ldb_dn *realm_dn,
454                                             struct ldb_message ***pmsg)
455 {
456         krb5_error_code ret;
457         int lret;
458         char *filter = NULL;
459         const char * const *princ_attrs = krb5_attrs;
460
461         char *short_princ;
462         char *short_princ_talloc;
463
464         char *realm_dn_str;
465
466         struct ldb_result *res = NULL;
467
468         ret = krb5_unparse_name_norealm(context, principal, &short_princ);
469
470         if (ret != 0) {
471                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
472                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
473                 return ret;
474         }
475
476         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
477         free(short_princ);
478         if (!short_princ_talloc) {
479                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
480                 return ENOMEM;
481         }
482
483         switch (ent_type) {
484         case HDB_LDB_ENT_TYPE_CLIENT:
485                 /* Can't happen */
486                 return EINVAL;
487         case HDB_LDB_ENT_TYPE_ANY:
488                 /* Can't happen */
489                 return EINVAL;
490         case HDB_LDB_ENT_TYPE_KRBTGT:
491                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
492                                          KRB5_TGS_NAME);
493                 break;
494         case HDB_LDB_ENT_TYPE_SERVER:
495                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
496                                          short_princ_talloc);
497                 break;
498         }
499
500         if (!filter) {
501                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
502                 return ENOMEM;
503         }
504
505         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
506
507         realm_dn_str = ldb_dn_linearize(mem_ctx, realm_dn);
508
509         if (lret != LDB_SUCCESS) {
510                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
511                 return HDB_ERR_NOENTRY;
512         } else if (res->count == 0 || res->count > 1) {
513                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
514                 return HDB_ERR_NOENTRY;
515         }
516         talloc_steal(mem_ctx, res->msgs);
517         *pmsg = res->msgs;
518         talloc_free(res);
519         return 0;
520 }
521
522 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
523                                         TALLOC_CTX *mem_ctx,
524                                         const char *realm,
525                                         struct ldb_message ***pmsg)
526 {
527         int ret;
528         char *cross_ref_filter;
529         struct ldb_result *cross_ref_res;
530         const struct ldb_dn *partitions_basedn = ldb_dn_string_compose(mem_ctx, samdb_base_dn(mem_ctx), "CN=Partitions,CN=Configuration");
531
532         cross_ref_filter = talloc_asprintf(mem_ctx, 
533                                            "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
534                                            realm, realm);
535         if (!cross_ref_filter) {
536                 krb5_set_error_string(context, "asprintf: out of memory");
537                 return ENOMEM;
538         }
539
540         ret = ldb_search(ldb_ctx, partitions_basedn, LDB_SCOPE_SUBTREE, cross_ref_filter, realm_ref_attrs, &cross_ref_res);
541
542         if (ret != LDB_SUCCESS) {
543                 DEBUG(3, ("Failed to search for %s: %s\n", cross_ref_filter, ldb_errstring(ldb_ctx)));
544                 talloc_free(cross_ref_res);
545                 return HDB_ERR_NOENTRY;
546         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
547                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", cross_ref_filter, cross_ref_res->count));
548                 talloc_free(cross_ref_res);
549                 return HDB_ERR_NOENTRY;
550         }
551
552         if (pmsg) {
553                 *pmsg = cross_ref_res->msgs;
554                 talloc_steal(mem_ctx, cross_ref_res->msgs);
555         }
556         talloc_free(cross_ref_res);
557
558         return 0;
559 }
560
561
562 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
563 {
564         if (db->hdb_master_key_set) {
565                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
566                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
567                 return HDB_ERR_NOENTRY;
568         }               
569
570         return 0;
571 }
572
573 static krb5_error_code LDB_close(krb5_context context, HDB *db)
574 {
575         return 0;
576 }
577
578 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
579 {
580         return 0;
581 }
582
583 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
584 {
585         return 0;
586 }
587
588 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
589 {
590         return HDB_ERR_DB_INUSE;
591 }
592
593 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
594                                         TALLOC_CTX *mem_ctx, 
595                                         krb5_const_principal principal,
596                                         unsigned flags,
597                                         hdb_entry_ex *entry_ex) {
598         NTSTATUS nt_status;
599         char *principal_string;
600         krb5_error_code ret;
601         struct ldb_message **msg = NULL;
602         struct ldb_message **realm_ref_msg = NULL;
603
604         ret = krb5_unparse_name(context, principal, &principal_string);
605         
606         if (ret != 0) {
607                 return ret;
608         }
609         
610         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
611                                               mem_ctx, principal_string, 
612                                               &msg, &realm_ref_msg);
613         free(principal_string);
614         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
615                 return HDB_ERR_NOENTRY;
616         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
617                 return ENOMEM;
618         } else if (!NT_STATUS_IS_OK(nt_status)) {
619                 return EINVAL;
620         }
621         
622         ret = LDB_message2entry(context, db, mem_ctx, 
623                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
624                                 msg[0], realm_ref_msg[0], entry_ex);
625         return ret;
626 }
627
628 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
629                                         TALLOC_CTX *mem_ctx, 
630                                         krb5_const_principal principal,
631                                         unsigned flags,
632                                         hdb_entry_ex *entry_ex)
633 {
634         krb5_error_code ret;
635         struct ldb_message **msg = NULL;
636         struct ldb_message **realm_ref_msg = NULL;
637         const struct ldb_dn *realm_dn;
638
639         krb5_principal alloc_principal = NULL;
640         if (principal->name.name_string.len != 2
641             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
642                 /* Not a krbtgt */
643                 return HDB_ERR_NOENTRY;
644         }
645
646         /* krbtgt case.  Either us or a trusted realm */
647         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
648                               mem_ctx, principal->name.name_string.val[1], &realm_ref_msg) == 0)) {
649                 /* us */
650                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
651                  * is in our db, then direct the caller at our primary
652                  * krgtgt */
653                 
654                 const char *dnsdomain = ldb_msg_find_string(realm_ref_msg[0], "dnsRoot", NULL);
655                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
656                 if (!realm_fixed) {
657                         krb5_set_error_string(context, "strupper_talloc: out of memory");
658                         return ENOMEM;
659                 }
660                 
661                 ret = krb5_copy_principal(context, principal, &alloc_principal);
662                 if (ret) {
663                         return ret;
664                 }
665
666                 free(alloc_principal->name.name_string.val[1]);
667                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
668                 talloc_free(realm_fixed);
669                 if (!alloc_principal->name.name_string.val[1]) {
670                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
671                         return ENOMEM;
672                 }
673                 principal = alloc_principal;
674                 realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
675                 
676         } else {
677                 /* we should lookup trusted domains */
678                 return HDB_ERR_NOENTRY;
679         }
680
681         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
682         
683         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
684                                    mem_ctx, 
685                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
686         
687         if (ret != 0) {
688                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
689                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
690                 return ret;
691         }
692
693         ret = LDB_message2entry(context, db, mem_ctx, 
694                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
695                                 msg[0], realm_ref_msg[0], entry_ex);
696         if (ret != 0) {
697                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
698         }
699         return ret;
700 }
701
702 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
703                                         TALLOC_CTX *mem_ctx, 
704                                         krb5_const_principal principal,
705                                         unsigned flags,
706                                         hdb_entry_ex *entry_ex)
707 {
708         krb5_error_code ret;
709         const char *realm;
710         struct ldb_message **msg = NULL;
711         struct ldb_message **realm_ref_msg = NULL;
712         const struct ldb_dn *partitions_basedn = ldb_dn_string_compose(mem_ctx, samdb_base_dn(mem_ctx), "CN=Partitions,CN=Configuration");
713         if (principal->name.name_string.len >= 2) {
714                 /* 'normal server' case */
715                 int ldb_ret;
716                 NTSTATUS nt_status;
717                 struct ldb_dn *user_dn, *domain_dn;
718                 char *principal_string;
719                 
720                 ret = krb5_unparse_name_norealm(context, principal, &principal_string);
721                 if (ret != 0) {
722                         return ret;
723                 }
724                 
725                 /* At this point we may find the host is known to be
726                  * in a different realm, so we should generate a
727                  * referral instead */
728                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
729                                                          mem_ctx, principal_string, 
730                                                          &user_dn, &domain_dn);
731                 free(principal_string);
732                 
733                 if (!NT_STATUS_IS_OK(nt_status)) {
734                         return HDB_ERR_NOENTRY;
735                 }
736                 
737                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
738                                           mem_ctx, user_dn, &msg, krb5_attrs);
739                 
740                 if (ldb_ret != 1) {
741                         return HDB_ERR_NOENTRY;
742                 }
743                 
744                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
745                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
746                                        "ncName=%s", ldb_dn_linearize(mem_ctx, domain_dn));
747                 
748                 if (ldb_ret != 1) {
749                         return HDB_ERR_NOENTRY;
750                 }
751                 
752         } else {
753                 const struct ldb_dn *realm_dn;
754                 /* server as client principal case, but we must not lookup userPrincipalNames */
755
756                 realm = krb5_principal_get_realm(context, principal);
757                 
758                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
759                                        mem_ctx, realm, &realm_ref_msg);
760                 if (ret != 0) {
761                         return HDB_ERR_NOENTRY;
762                 }
763                 
764                 realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
765                 
766                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
767                                            mem_ctx, 
768                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
769                 
770                 if (ret != 0) {
771                         return ret;
772                 }
773         }
774
775         ret = LDB_message2entry(context, db, mem_ctx, 
776                                 principal, HDB_LDB_ENT_TYPE_SERVER,
777                                 msg[0], realm_ref_msg[0], entry_ex);
778         if (ret != 0) {
779                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
780         }
781
782         return ret;
783 }
784                         
785 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
786                                  krb5_const_principal principal,
787                                  unsigned flags,
788                                  hdb_entry_ex *entry_ex)
789 {
790         krb5_error_code ret = HDB_ERR_NOENTRY;
791
792         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
793
794         if (!mem_ctx) {
795                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
796                 return ENOMEM;
797         }
798
799         if (flags & HDB_F_GET_CLIENT) {
800                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
801                 if (ret != HDB_ERR_NOENTRY) goto done;
802         }
803         if (flags & HDB_F_GET_SERVER) {
804                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
805                 if (ret != HDB_ERR_NOENTRY) goto done;
806                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
807                 if (ret != HDB_ERR_NOENTRY) goto done;
808         }
809         if (flags & HDB_F_GET_KRBTGT) {
810                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
811                 if (ret != HDB_ERR_NOENTRY) goto done;
812         }
813
814 done:
815         talloc_free(mem_ctx);
816         return ret;
817 }
818
819 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
820 {
821         return HDB_ERR_DB_INUSE;
822 }
823
824 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
825 {
826         return HDB_ERR_DB_INUSE;
827 }
828
829 struct hdb_ldb_seq {
830         struct ldb_context *ctx;
831         int index;
832         int count;
833         struct ldb_message **msgs;
834         struct ldb_message **realm_ref_msgs;
835 };
836
837 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
838 {
839         krb5_error_code ret;
840         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
841         TALLOC_CTX *mem_ctx;
842         hdb_entry_ex entry_ex;
843         memset(&entry_ex, '\0', sizeof(entry_ex));
844
845         if (!priv) {
846                 return HDB_ERR_NOENTRY;
847         }
848
849         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
850
851         if (!mem_ctx) {
852                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
853                 return ENOMEM;
854         }
855
856         if (priv->index < priv->count) {
857                 ret = LDB_message2entry(context, db, mem_ctx, 
858                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
859                                         priv->msgs[priv->index++], 
860                                         priv->realm_ref_msgs[0], entry);
861         } else {
862                 ret = HDB_ERR_NOENTRY;
863         }
864
865         if (ret != 0) {
866                 talloc_free(priv);
867                 db->hdb_openp = NULL;
868         } else {
869                 talloc_free(mem_ctx);
870         }
871
872         return ret;
873 }
874
875 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
876                                         hdb_entry_ex *entry)
877 {
878         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
879         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
880         char *realm;
881         struct ldb_dn *realm_dn = NULL;
882         struct ldb_result *res = NULL;
883         struct ldb_message **realm_ref_msgs = NULL;
884         krb5_error_code ret;
885         TALLOC_CTX *mem_ctx;
886         int lret;
887
888         if (priv) {
889                 talloc_free(priv);
890                 db->hdb_openp = 0;
891         }
892
893         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
894         if (!priv) {
895                 krb5_set_error_string(context, "talloc: out of memory");
896                 return ENOMEM;
897         }
898
899         priv->ctx = ldb_ctx;
900         priv->index = 0;
901         priv->msgs = NULL;
902         priv->realm_ref_msgs = NULL;
903         priv->count = 0;
904
905         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
906
907         if (!mem_ctx) {
908                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
909                 return ENOMEM;
910         }
911
912         ret = krb5_get_default_realm(context, &realm);
913         if (ret != 0) {
914                 talloc_free(priv);
915                 return ret;
916         }
917                 
918         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
919                                mem_ctx, realm, &realm_ref_msgs);
920
921         free(realm);
922
923         if (ret != 0) {
924                 talloc_free(priv);
925                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
926                 return HDB_ERR_NOENTRY;
927         }
928
929         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msgs[0], "nCName", NULL);
930
931         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
932
933         krb5_warnx(context, "LDB_firstkey: realm ok\n");
934
935         lret = ldb_search(ldb_ctx, realm_dn,
936                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
937                                  krb5_attrs, &res);
938
939         if (lret != LDB_SUCCESS) {
940                 talloc_free(priv);
941                 return HDB_ERR_NOENTRY;
942         }
943
944         priv->count = res->count;
945         priv->msgs = talloc_steal(priv, res->msgs);
946         talloc_free(res);
947
948         db->hdb_openp = priv;
949
950         ret = LDB_seq(context, db, flags, entry);
951         
952         if (ret != 0) {
953                 talloc_free(priv);
954                 db->hdb_openp = NULL;
955         } else {
956                 talloc_free(mem_ctx);
957         }
958         return ret;
959 }
960
961 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
962                                    hdb_entry_ex *entry)
963 {
964         return LDB_seq(context, db, flags, entry);
965 }
966
967 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
968 {
969         talloc_free(db);
970         return 0;
971 }
972
973 /* This interface is to be called by the KDC, which is expecting Samba
974  * calling conventions.  It is also called by a wrapper
975  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
976  * code */
977
978 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
979                             krb5_context context, struct HDB **db, const char *arg)
980 {
981         NTSTATUS nt_status;
982         struct auth_session_info *session_info;
983         *db = talloc(mem_ctx, HDB);
984         if (!*db) {
985                 krb5_set_error_string(context, "malloc: out of memory");
986                 return NT_STATUS_NO_MEMORY;
987         }
988
989         (*db)->hdb_master_key_set = 0;
990         (*db)->hdb_db = NULL;
991
992         nt_status = auth_system_session_info(*db, &session_info);
993         if (!NT_STATUS_IS_OK(nt_status)) {
994                 return nt_status;
995         }
996         
997         /* The idea here is very simple.  Using Kerberos to
998          * authenticate the KDC to the LDAP server is higly likely to
999          * be circular.
1000          *
1001          * In future we may set this up to use EXERNAL and SSL
1002          * certificates, for now it will almost certainly be NTLMSSP
1003         */
1004         
1005         cli_credentials_set_kerberos_state(session_info->credentials, 
1006                                            CRED_DONT_USE_KERBEROS);
1007
1008         /* Setup the link to LDB */
1009         (*db)->hdb_db = samdb_connect(*db, session_info);
1010         if ((*db)->hdb_db == NULL) {
1011                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1012                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1013         }
1014
1015         (*db)->hdb_openp = 0;
1016         (*db)->hdb_open = LDB_open;
1017         (*db)->hdb_close = LDB_close;
1018         (*db)->hdb_fetch = LDB_fetch;
1019         (*db)->hdb_store = LDB_store;
1020         (*db)->hdb_remove = LDB_remove;
1021         (*db)->hdb_firstkey = LDB_firstkey;
1022         (*db)->hdb_nextkey = LDB_nextkey;
1023         (*db)->hdb_lock = LDB_lock;
1024         (*db)->hdb_unlock = LDB_unlock;
1025         (*db)->hdb_rename = LDB_rename;
1026         /* we don't implement these, as we are not a lockable database */
1027         (*db)->hdb__get = NULL;
1028         (*db)->hdb__put = NULL;
1029         /* kadmin should not be used for deletes - use other tools instead */
1030         (*db)->hdb__del = NULL;
1031         (*db)->hdb_destroy = LDB_destroy;
1032
1033         return NT_STATUS_OK;
1034 }
1035
1036 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1037 {
1038         NTSTATUS nt_status;
1039         /* Disgusting, ugly hack, but it means one less private hook */
1040         nt_status = kdc_hdb_ldb_create(context->mem_ctx, context, db, arg);
1041
1042         if (NT_STATUS_IS_OK(nt_status)) {
1043                 return 0;
1044         }
1045         return EINVAL;
1046 }