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