r19831: Big ldb_dn optimization and interfaces enhancement patch
[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 "dsdb/common/flags.h"
39 #include "hdb.h"
40 #include "krb5_locl.h"
41 #include "lib/ldb/include/ldb.h"
42 #include "lib/ldb/include/ldb_errors.h"
43 #include "librpc/gen_ndr/netlogon.h"
44 #include "auth/auth.h"
45 #include "auth/credentials/credentials.h"
46 #include "auth/auth_sam.h"
47 #include "db_wrap.h"
48 #include "dsdb/samdb/samdb.h"
49
50 enum hdb_ldb_ent_type 
51 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
52   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
53
54 static const char * const krb5_attrs[] = {
55         "objectClass",
56         "sAMAccountName",
57
58         "userPrincipalName",
59         "servicePrincipalName",
60
61         "krb5Key",
62
63         "userAccountControl",
64
65         "pwdLastSet",
66         "accountExpires",
67
68         "whenCreated",
69         "whenChanged",
70
71         "msDS-KeyVersionNumber",
72         NULL
73 };
74
75 static const char *realm_ref_attrs[] = {
76         "nCName", 
77         "dnsRoot", 
78         NULL
79 };
80
81 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
82 {
83     const char *tmp;
84     const char *gentime;
85     struct tm tm;
86
87     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
88     if (!gentime)
89         return default_val;
90
91     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
92     if (tmp == NULL) {
93             return default_val;
94     }
95
96     return timegm(&tm);
97 }
98
99 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
100 {
101         HDBFlags flags = int2HDBFlags(0);
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         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
155 */
156         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
157                 flags.invalid = 1;
158         }
159
160 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
161
162 /*
163         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
164                 flags.invalid = 1;
165         }
166 */
167         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
168                 flags.require_hwauth = 1;
169         }
170         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
171                 flags.ok_as_delegate = 1;
172         }       
173         if (!(userAccountControl & UF_NOT_DELEGATED)) {
174                 flags.forwardable = 1;
175                 flags.proxiable = 1;
176         }
177
178         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
179                 flags.require_preauth = 0;
180         } else {
181                 flags.require_preauth = 1;
182
183         }
184         return flags;
185 }
186
187 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
188 {
189     hdb_entry_ex *entry_ex = private->entry_ex;
190     free_hdb_entry(&entry_ex->entry);
191     return 0;
192 }
193
194 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
195 {
196         talloc_free(entry_ex->ctx);
197 }
198
199 /*
200  * Construct an hdb_entry from a directory entry.
201  */
202 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
203                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
204                                          enum hdb_ldb_ent_type ent_type, 
205                                          struct ldb_message *msg,
206                                          struct ldb_message *realm_ref_msg,
207                                          hdb_entry_ex *entry_ex)
208 {
209         unsigned int userAccountControl;
210         int i;
211         krb5_error_code ret = 0;
212         krb5_boolean is_computer = FALSE;
213         const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL);
214         char *realm = strupper_talloc(mem_ctx, dnsdomain);
215         struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db,
216                                                         mem_ctx,
217                                                         realm_ref_msg,
218                                                         "nCName",
219                                                         ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL));
220
221         struct hdb_ldb_private *private;
222         NTTIME acct_expiry;
223         struct ldb_message_element *ldb_keys;
224
225         struct ldb_message_element *objectclasses;
226         struct ldb_val computer_val;
227         computer_val.data = discard_const_p(uint8_t,"computer");
228         computer_val.length = strlen((const char *)computer_val.data);
229         
230         objectclasses = ldb_msg_find_element(msg, "objectClass");
231         
232         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
233                 is_computer = TRUE;
234         }
235
236         memset(entry_ex, 0, sizeof(*entry_ex));
237
238         if (!realm) {
239                 krb5_set_error_string(context, "talloc_strdup: out of memory");
240                 ret = ENOMEM;
241                 goto out;
242         }
243                         
244         private = talloc(mem_ctx, struct hdb_ldb_private);
245         if (!private) {
246                 ret = ENOMEM;
247                 goto out;
248         }
249
250         private->entry_ex = entry_ex;
251
252         talloc_set_destructor(private, hdb_ldb_destrutor);
253
254         entry_ex->ctx = private;
255         entry_ex->free_entry = hdb_ldb_free_entry;
256
257         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
258
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_attr_as_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_attr_as_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                 /* this has to be with malloc() */
285                 strdup_realm = strdup(realm);
286                 if (!strdup_realm) {
287                         ret = ENOMEM;
288                         krb5_clear_error_string(context);
289                         goto out;
290                 }
291                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
292                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
293         }
294
295         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
296
297         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
298
299         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
300                 entry_ex->entry.flags.invalid = 0;
301                 entry_ex->entry.flags.server = 1;
302                 entry_ex->entry.flags.forwardable = 1;
303                 entry_ex->entry.flags.ok_as_delegate = 1;
304         }
305
306         if (lp_parm_bool(-1, "kdc", "require spn for service", True)) {
307                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
308                         entry_ex->entry.flags.server = 0;
309                 }
310         }
311
312         /* use 'whenCreated' */
313         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
314         /* use '???' */
315         entry_ex->entry.created_by.principal = NULL;
316
317         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
318         if (entry_ex->entry.modified_by == NULL) {
319                 krb5_set_error_string(context, "malloc: out of memory");
320                 ret = ENOMEM;
321                 goto out;
322         }
323
324         /* use 'whenChanged' */
325         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
326         /* use '???' */
327         entry_ex->entry.modified_by->principal = NULL;
328
329         entry_ex->entry.valid_start = NULL;
330
331         acct_expiry = samdb_result_nttime(msg, "accountExpires", (NTTIME)-1);
332         if ((acct_expiry == (NTTIME)-1) ||
333             (acct_expiry == 0x7FFFFFFFFFFFFFFFULL)) {
334                 entry_ex->entry.valid_end = NULL;
335         } else {
336                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
337                 if (entry_ex->entry.valid_end == NULL) {
338                         ret = ENOMEM;
339                         goto out;
340                 }
341                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
342         }
343
344         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
345                 NTTIME must_change_time
346                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
347                                                              domain_dn, msg);
348                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
349                         entry_ex->entry.pw_end = NULL;
350                 } else {
351                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
352                         if (entry_ex->entry.pw_end == NULL) {
353                                 ret = ENOMEM;
354                                 goto out;
355                         }
356                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
357                 }
358         } else {
359                 entry_ex->entry.pw_end = NULL;
360         }
361                         
362         entry_ex->entry.max_life = NULL;
363
364         entry_ex->entry.max_renew = NULL;
365
366         entry_ex->entry.generation = NULL;
367
368         /* Get krb5Key from the db */
369
370         ldb_keys = ldb_msg_find_element(msg, "krb5Key");
371
372         if (!ldb_keys) {
373                 /* oh, no password.  Apparently (comment in
374                  * hdb-ldap.c) this violates the ASN.1, but this
375                  * allows an entry with no keys (yet). */
376                 entry_ex->entry.keys.val = NULL;
377                 entry_ex->entry.keys.len = 0;
378         } else {
379                 /* allocate space to decode into */
380                 entry_ex->entry.keys.val = calloc(ldb_keys->num_values, sizeof(Key));
381                 if (entry_ex->entry.keys.val == NULL) {
382                         ret = ENOMEM;
383                         goto out;
384                 }
385
386                 entry_ex->entry.keys.len = 0;
387
388                 /* Decode Kerberos keys into the hdb structure */
389                 for (i=0; i < ldb_keys->num_values; i++) {
390                         size_t decode_len;
391                         Key key;
392                         ret = decode_Key(ldb_keys->values[i].data, ldb_keys->values[i].length, 
393                                          &key, &decode_len);
394                         if (ret) {
395                                 /* Could be bougus data in the entry, or out of memory */
396                                 goto out;
397                         }
398
399                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
400                                 switch (key.key.keytype) {
401                                 case KEYTYPE_DES:
402                                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
403                                         entry_ex->entry.keys.len++;
404                                 default:
405                                         /* We must use DES keys only */
406                                         break;
407                                 }
408                         } else {
409                                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
410                                 entry_ex->entry.keys.len++;
411                         }
412                 }
413         } 
414
415         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
416         if (entry_ex->entry.etypes == NULL) {
417                 krb5_clear_error_string(context);
418                 ret = ENOMEM;
419                 goto out;
420         }
421         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
422         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
423         if (entry_ex->entry.etypes->val == NULL) {
424                 krb5_clear_error_string(context);
425                 ret = ENOMEM;
426                 goto out;
427         }
428         for (i=0; i < entry_ex->entry.etypes->len; i++) {
429                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
430         }
431
432
433         private->msg = talloc_steal(private, msg);
434         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
435         private->samdb = (struct ldb_context *)db->hdb_db;
436         
437         entry_ex->check_client_access = hdb_ldb_check_client_access;
438         entry_ex->authz_data_tgs_req = hdb_ldb_authz_data_tgs_req;
439         entry_ex->authz_data_as_req = hdb_ldb_authz_data_as_req;
440
441 out:
442         if (ret != 0) {
443                 /* This doesn't free ent itself, that is for the eventual caller to do */
444                 hdb_free_entry(context, entry_ex);
445         } else {
446                 talloc_steal(db, entry_ex->ctx);
447         }
448
449         return ret;
450 }
451
452 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
453                                             TALLOC_CTX *mem_ctx,
454                                             krb5_const_principal principal,
455                                             enum hdb_ldb_ent_type ent_type,
456                                             struct ldb_dn *realm_dn,
457                                             struct ldb_message ***pmsg)
458 {
459         krb5_error_code ret;
460         int lret;
461         char *filter = NULL;
462         const char * const *princ_attrs = krb5_attrs;
463
464         char *short_princ;
465         char *short_princ_talloc;
466
467         struct ldb_result *res = NULL;
468
469         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
470
471         if (ret != 0) {
472                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
473                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
474                 return ret;
475         }
476
477         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
478         free(short_princ);
479         if (!short_princ_talloc) {
480                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
481                 return ENOMEM;
482         }
483
484         switch (ent_type) {
485         case HDB_LDB_ENT_TYPE_CLIENT:
486                 /* Can't happen */
487                 return EINVAL;
488         case HDB_LDB_ENT_TYPE_ANY:
489                 /* Can't happen */
490                 return EINVAL;
491         case HDB_LDB_ENT_TYPE_KRBTGT:
492                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
493                                          KRB5_TGS_NAME);
494                 break;
495         case HDB_LDB_ENT_TYPE_SERVER:
496                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
497                                          short_princ_talloc);
498                 break;
499         }
500
501         if (!filter) {
502                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
503                 return ENOMEM;
504         }
505
506         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
507
508         if (lret != LDB_SUCCESS) {
509                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
510                 return HDB_ERR_NOENTRY;
511         } else if (res->count == 0 || res->count > 1) {
512                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
513                 talloc_free(res);
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         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
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         struct ldb_dn *realm_dn;
638
639         if (principal->name.name_string.len != 2
640             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
641                 /* Not a krbtgt */
642                 return HDB_ERR_NOENTRY;
643         }
644
645         /* krbtgt case.  Either us or a trusted realm */
646         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
647                               mem_ctx, principal->name.name_string.val[1], &realm_ref_msg) == 0)) {
648                 /* us */                
649                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
650         } else {
651                 /* we should lookup trusted domains */
652                 return HDB_ERR_NOENTRY;
653         }
654
655         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
656         
657         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
658                                    mem_ctx, 
659                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
660         
661         if (ret != 0) {
662                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
663                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
664                 return ret;
665         }
666
667         ret = LDB_message2entry(context, db, mem_ctx, 
668                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
669                                 msg[0], realm_ref_msg[0], entry_ex);
670         if (ret != 0) {
671                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
672         }
673         return ret;
674 }
675
676 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
677                                         TALLOC_CTX *mem_ctx, 
678                                         krb5_const_principal principal,
679                                         unsigned flags,
680                                         hdb_entry_ex *entry_ex)
681 {
682         krb5_error_code ret;
683         const char *realm;
684         struct ldb_message **msg = NULL;
685         struct ldb_message **realm_ref_msg = NULL;
686         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
687         if (principal->name.name_string.len >= 2) {
688                 /* 'normal server' case */
689                 int ldb_ret;
690                 NTSTATUS nt_status;
691                 struct ldb_dn *user_dn, *domain_dn;
692                 char *principal_string;
693                 
694                 ret = krb5_unparse_name_flags(context, principal, 
695                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
696                                               &principal_string);
697                 if (ret != 0) {
698                         return ret;
699                 }
700                 
701                 /* At this point we may find the host is known to be
702                  * in a different realm, so we should generate a
703                  * referral instead */
704                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
705                                                          mem_ctx, principal_string, 
706                                                          &user_dn, &domain_dn);
707                 free(principal_string);
708                 
709                 if (!NT_STATUS_IS_OK(nt_status)) {
710                         return HDB_ERR_NOENTRY;
711                 }
712                 
713                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
714                                           mem_ctx, user_dn, &msg, krb5_attrs);
715                 
716                 if (ldb_ret != 1) {
717                         return HDB_ERR_NOENTRY;
718                 }
719                 
720                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
721                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
722                                        "ncName=%s", ldb_dn_linearize(mem_ctx, domain_dn));
723                 
724                 if (ldb_ret != 1) {
725                         return HDB_ERR_NOENTRY;
726                 }
727                 
728         } else {
729                 struct ldb_dn *realm_dn;
730                 /* server as client principal case, but we must not lookup userPrincipalNames */
731
732                 realm = krb5_principal_get_realm(context, principal);
733                 
734                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
735                                        mem_ctx, realm, &realm_ref_msg);
736                 if (ret != 0) {
737                         return HDB_ERR_NOENTRY;
738                 }
739                 
740                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
741                 
742                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
743                                            mem_ctx, 
744                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
745                 
746                 if (ret != 0) {
747                         return ret;
748                 }
749         }
750
751         ret = LDB_message2entry(context, db, mem_ctx, 
752                                 principal, HDB_LDB_ENT_TYPE_SERVER,
753                                 msg[0], realm_ref_msg[0], entry_ex);
754         if (ret != 0) {
755                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
756         }
757
758         return ret;
759 }
760                         
761 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
762                                  krb5_const_principal principal,
763                                  unsigned flags,
764                                  hdb_entry_ex *entry_ex)
765 {
766         krb5_error_code ret = HDB_ERR_NOENTRY;
767
768         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
769
770         if (!mem_ctx) {
771                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
772                 return ENOMEM;
773         }
774
775         if (flags & HDB_F_GET_CLIENT) {
776                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
777                 if (ret != HDB_ERR_NOENTRY) goto done;
778         }
779         if (flags & HDB_F_GET_SERVER) {
780                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
781                 if (ret != HDB_ERR_NOENTRY) goto done;
782                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
783                 if (ret != HDB_ERR_NOENTRY) goto done;
784         }
785         if (flags & HDB_F_GET_KRBTGT) {
786                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
787                 if (ret != HDB_ERR_NOENTRY) goto done;
788         }
789
790 done:
791         talloc_free(mem_ctx);
792         return ret;
793 }
794
795 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
796 {
797         return HDB_ERR_DB_INUSE;
798 }
799
800 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
801 {
802         return HDB_ERR_DB_INUSE;
803 }
804
805 struct hdb_ldb_seq {
806         struct ldb_context *ctx;
807         int index;
808         int count;
809         struct ldb_message **msgs;
810         struct ldb_message **realm_ref_msgs;
811 };
812
813 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
814 {
815         krb5_error_code ret;
816         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
817         TALLOC_CTX *mem_ctx;
818         hdb_entry_ex entry_ex;
819         memset(&entry_ex, '\0', sizeof(entry_ex));
820
821         if (!priv) {
822                 return HDB_ERR_NOENTRY;
823         }
824
825         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
826
827         if (!mem_ctx) {
828                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
829                 return ENOMEM;
830         }
831
832         if (priv->index < priv->count) {
833                 ret = LDB_message2entry(context, db, mem_ctx, 
834                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
835                                         priv->msgs[priv->index++], 
836                                         priv->realm_ref_msgs[0], entry);
837         } else {
838                 ret = HDB_ERR_NOENTRY;
839         }
840
841         if (ret != 0) {
842                 talloc_free(priv);
843                 db->hdb_openp = NULL;
844         } else {
845                 talloc_free(mem_ctx);
846         }
847
848         return ret;
849 }
850
851 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
852                                         hdb_entry_ex *entry)
853 {
854         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
855         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
856         char *realm;
857         struct ldb_dn *realm_dn = NULL;
858         struct ldb_result *res = NULL;
859         struct ldb_message **realm_ref_msgs = NULL;
860         krb5_error_code ret;
861         TALLOC_CTX *mem_ctx;
862         int lret;
863
864         if (priv) {
865                 talloc_free(priv);
866                 db->hdb_openp = 0;
867         }
868
869         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
870         if (!priv) {
871                 krb5_set_error_string(context, "talloc: out of memory");
872                 return ENOMEM;
873         }
874
875         priv->ctx = ldb_ctx;
876         priv->index = 0;
877         priv->msgs = NULL;
878         priv->realm_ref_msgs = NULL;
879         priv->count = 0;
880
881         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
882
883         if (!mem_ctx) {
884                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
885                 return ENOMEM;
886         }
887
888         ret = krb5_get_default_realm(context, &realm);
889         if (ret != 0) {
890                 talloc_free(priv);
891                 return ret;
892         }
893                 
894         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
895                                mem_ctx, realm, &realm_ref_msgs);
896
897         free(realm);
898
899         if (ret != 0) {
900                 talloc_free(priv);
901                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
902                 return HDB_ERR_NOENTRY;
903         }
904
905         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
906
907         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
908
909         lret = ldb_search(ldb_ctx, realm_dn,
910                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
911                                  krb5_attrs, &res);
912
913         if (lret != LDB_SUCCESS) {
914                 talloc_free(priv);
915                 return HDB_ERR_NOENTRY;
916         }
917
918         priv->count = res->count;
919         priv->msgs = talloc_steal(priv, res->msgs);
920         talloc_free(res);
921
922         db->hdb_openp = priv;
923
924         ret = LDB_seq(context, db, flags, entry);
925         
926         if (ret != 0) {
927                 talloc_free(priv);
928                 db->hdb_openp = NULL;
929         } else {
930                 talloc_free(mem_ctx);
931         }
932         return ret;
933 }
934
935 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
936                                    hdb_entry_ex *entry)
937 {
938         return LDB_seq(context, db, flags, entry);
939 }
940
941 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
942 {
943         talloc_free(db);
944         return 0;
945 }
946
947 /* This interface is to be called by the KDC, which is expecting Samba
948  * calling conventions.  It is also called by a wrapper
949  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
950  * code */
951
952 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
953                             krb5_context context, struct HDB **db, const char *arg)
954 {
955         NTSTATUS nt_status;
956         struct auth_session_info *session_info;
957         *db = talloc(mem_ctx, HDB);
958         if (!*db) {
959                 krb5_set_error_string(context, "malloc: out of memory");
960                 return NT_STATUS_NO_MEMORY;
961         }
962
963         (*db)->hdb_master_key_set = 0;
964         (*db)->hdb_db = NULL;
965
966         nt_status = auth_system_session_info(*db, &session_info);
967         if (!NT_STATUS_IS_OK(nt_status)) {
968                 return nt_status;
969         }
970         
971         /* The idea here is very simple.  Using Kerberos to
972          * authenticate the KDC to the LDAP server is higly likely to
973          * be circular.
974          *
975          * In future we may set this up to use EXERNAL and SSL
976          * certificates, for now it will almost certainly be NTLMSSP
977         */
978         
979         cli_credentials_set_kerberos_state(session_info->credentials, 
980                                            CRED_DONT_USE_KERBEROS);
981
982         /* Setup the link to LDB */
983         (*db)->hdb_db = samdb_connect(*db, session_info);
984         if ((*db)->hdb_db == NULL) {
985                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
986                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
987         }
988
989         (*db)->hdb_openp = 0;
990         (*db)->hdb_open = LDB_open;
991         (*db)->hdb_close = LDB_close;
992         (*db)->hdb_fetch = LDB_fetch;
993         (*db)->hdb_store = LDB_store;
994         (*db)->hdb_remove = LDB_remove;
995         (*db)->hdb_firstkey = LDB_firstkey;
996         (*db)->hdb_nextkey = LDB_nextkey;
997         (*db)->hdb_lock = LDB_lock;
998         (*db)->hdb_unlock = LDB_unlock;
999         (*db)->hdb_rename = LDB_rename;
1000         /* we don't implement these, as we are not a lockable database */
1001         (*db)->hdb__get = NULL;
1002         (*db)->hdb__put = NULL;
1003         /* kadmin should not be used for deletes - use other tools instead */
1004         (*db)->hdb__del = NULL;
1005         (*db)->hdb_destroy = LDB_destroy;
1006
1007         return NT_STATUS_OK;
1008 }
1009
1010 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1011 {
1012         NTSTATUS nt_status;
1013         /* Disgusting, ugly hack, but it means one less private hook */
1014         nt_status = kdc_hdb_ldb_create(context->mem_ctx, context, db, arg);
1015
1016         if (NT_STATUS_IS_OK(nt_status)) {
1017                 return 0;
1018         }
1019         return EINVAL;
1020 }