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