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