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