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