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