r11322: Start moving towards using the cracknames code in the KDC.
[jelmer/samba4-debian.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 const char *cross_ref_attrs[] = {
83         "nCName", 
84         NULL
85 };
86
87 const char *realm_attrs[] = {
88         "dnsDomain", 
89         "maxPwdAge",
90         NULL
91 };
92
93 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
94 {
95     const char *tmp;
96     const char *gentime;
97     struct tm tm;
98
99     gentime = ldb_msg_find_string(msg, attr, NULL);
100     if (!gentime)
101         return default_val;
102
103     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
104     if (tmp == NULL) {
105             return default_val;
106     }
107
108     return timegm(&tm);
109 }
110
111 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
112 {
113         HDBFlags flags = int2HDBFlags(0);
114
115         krb5_warnx(context, "uf2HDBFlags: userAccountControl: %08x\n", userAccountControl);
116
117         /* we don't allow kadmin deletes */
118         flags.immutable = 1;
119
120         /* mark the principal as invalid to start with */
121         flags.invalid = 1;
122
123         flags.renewable = 1;
124
125         /* Account types - clear the invalid bit if it turns out to be valid */
126         if (userAccountControl & UF_NORMAL_ACCOUNT) {
127                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
128                         flags.client = 1;
129                 }
130                 if (ent_type == HDB_LDB_ENT_TYPE_SERVER || ent_type == HDB_LDB_ENT_TYPE_ANY) {
131                         flags.server = 1;
132                 }
133                 flags.invalid = 0;
134         }
135         
136         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
137                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
138                         flags.client = 1;
139                 }
140                 flags.invalid = 0;
141         }
142         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
143                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
144                         flags.client = 1;
145                 }
146                 if (ent_type == HDB_LDB_ENT_TYPE_SERVER || ent_type == HDB_LDB_ENT_TYPE_ANY) {
147                         flags.server = 1;
148                 }
149                 flags.invalid = 0;
150         }
151         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
152                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
153                         flags.client = 1;
154                 }
155                 if (ent_type == HDB_LDB_ENT_TYPE_SERVER || ent_type == HDB_LDB_ENT_TYPE_ANY) {
156                         flags.server = 1;
157                 }
158                 flags.invalid = 0;
159         }
160
161         /* Not permitted to act as a client if disabled */
162         if (userAccountControl & UF_ACCOUNTDISABLE) {
163                 flags.client = 0;
164         }
165         if (userAccountControl & UF_LOCKOUT) {
166                 flags.invalid = 1;
167         }
168 /*
169         if (userAccountControl & UF_PASSWORD_NOTREQD) {
170                 flags.invalid = 1;
171         }
172 */
173 /*
174         if (userAccountControl & UF_PASSWORD_CANT_CHANGE) {
175                 flags.invalid = 1;
176         }
177 */
178 /*
179         if (userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED) {
180                 flags.invalid = 1;
181         }
182 */
183         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
184                 flags.invalid = 1;
185         }
186
187 /* UF_DONT_EXPIRE_PASSWD handled in LDB_message2entry() */
188
189 /*
190         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
191                 flags.invalid = 1;
192         }
193 */
194         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
195                 flags.require_hwauth = 1;
196         }
197         if (flags.server && (userAccountControl & UF_TRUSTED_FOR_DELEGATION)) {
198                 flags.forwardable = 1;
199                 flags.proxiable = 1;
200         } else if (flags.client && (userAccountControl & UF_NOT_DELEGATED)) {
201                 flags.forwardable = 0;
202                 flags.proxiable = 0;
203         } else {
204                 flags.forwardable = 1;
205                 flags.proxiable = 1;
206         }
207
208 /*
209         if (userAccountControl & UF_SMARTCARD_USE_DES_KEY_ONLY) {
210                 flags.invalid = 1;
211         }
212 */
213         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
214                 flags.require_preauth = 0;
215         } else {
216                 flags.require_preauth = 1;
217
218         }
219
220         krb5_warnx(context, "uf2HDBFlags: HDBFlags: %08x\n", HDBFlags2int(flags));
221
222         return flags;
223 }
224
225 /*
226  * Construct an hdb_entry from a directory entry.
227  */
228 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
229                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
230                                          enum hdb_ldb_ent_type ent_type, struct ldb_message *realm_msg,
231                                          struct ldb_message *msg,
232                                          hdb_entry *ent)
233 {
234         const char *unicodePwd;
235         int userAccountControl;
236         int i;
237         krb5_error_code ret = 0;
238         const char *dnsdomain = ldb_msg_find_string(realm_msg, "dnsDomain", NULL);
239         char *realm = strupper_talloc(mem_ctx, dnsdomain);
240
241         if (!realm) {
242                 krb5_set_error_string(context, "talloc_strdup: out of memory");
243                 ret = ENOMEM;
244                 goto out;
245         }
246                         
247         krb5_warnx(context, "LDB_message2entry:\n");
248
249         memset(ent, 0, sizeof(*ent));
250
251         userAccountControl = ldb_msg_find_int(msg, "userAccountControl", 0);
252         
253         ent->principal = malloc(sizeof(*(ent->principal)));
254         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
255                 const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
256                 if (!samAccountName) {
257                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
258                         ret = ENOENT;
259                         goto out;
260                 }
261                 samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
262                 krb5_make_principal(context, &ent->principal, realm, samAccountName, NULL);
263         } else {
264                 char *strdup_realm;
265                 ret = copy_Principal(principal, ent->principal);
266                 if (ret) {
267                         krb5_clear_error_string(context);
268                         goto out;
269                 }
270
271                 /* While we have copied the client principal, tests
272                  * show that Win2k3 returns the 'corrected' realm, not
273                  * the client-specified realm.  This code attempts to
274                  * replace the client principal's realm with the one
275                  * we determine from our records */
276                 
277                 /* don't leak */
278                 free(*krb5_princ_realm(context, ent->principal));
279                 
280                 /* this has to be with malloc() */
281                 strdup_realm = strdup(realm);
282                 if (!strdup_realm) {
283                         ret = ENOMEM;
284                         krb5_clear_error_string(context);
285                         goto out;
286                 }
287                 krb5_princ_set_realm(context, ent->principal, &strdup_realm);
288         }
289
290         ent->kvno = ldb_msg_find_int(msg, "msDS-KeyVersionNumber", 0);
291
292         ent->flags = uf2HDBFlags(context, userAccountControl, ent_type);
293
294         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
295                 ent->flags.invalid = 0;
296                 ent->flags.server = 1;
297         }
298
299         /* use 'whenCreated' */
300         ent->created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
301         /* use '???' */
302         ent->created_by.principal = NULL;
303
304         ent->modified_by = (Event *) malloc(sizeof(Event));
305         if (ent->modified_by == NULL) {
306                 krb5_set_error_string(context, "malloc: out of memory");
307                 ret = ENOMEM;
308                 goto out;
309         }
310
311         /* use 'whenChanged' */
312         ent->modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
313         /* use '???' */
314         ent->modified_by->principal = NULL;
315
316         ent->valid_start = NULL;
317
318         ent->valid_end = NULL;
319         ent->pw_end = NULL;
320
321         ent->max_life = NULL;
322
323         ent->max_renew = NULL;
324
325         ent->generation = NULL;
326
327         /* create the keys and enctypes */
328         unicodePwd = ldb_msg_find_string(msg, "unicodePwd", NULL);
329         if (unicodePwd) {
330                 /* Many, many thanks to lukeh@padl.com for this
331                  * algorithm, described in his Nov 10 2004 mail to
332                  * samba-technical@samba.org */
333
334                 Principal *salt_principal;
335                 const char *user_principal_name = ldb_msg_find_string(msg, "userPrincipalName", NULL);
336                 struct ldb_message_element *objectclasses;
337                 struct ldb_val computer_val;
338                 computer_val.data = discard_const_p(uint8_t,"computer");
339                 computer_val.length = strlen((const char *)computer_val.data);
340                 
341                 objectclasses = ldb_msg_find_element(msg, "objectClass");
342
343                 if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
344                         /* Determine a salting principal */
345                         char *samAccountName = talloc_strdup(mem_ctx, ldb_msg_find_string(msg, "samAccountName", NULL));
346                         char *saltbody;
347                         if (!samAccountName) {
348                                 krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
349                                 ret = ENOENT;
350                                 goto out;
351                         }
352                         if (samAccountName[strlen(samAccountName)-1] == '$') {
353                                 samAccountName[strlen(samAccountName)-1] = '\0';
354                         }
355                         saltbody = talloc_asprintf(mem_ctx, "%s.%s", samAccountName, dnsdomain);
356                         
357                         ret = krb5_make_principal(context, &salt_principal, realm, "host", saltbody, NULL);
358                 } else if (user_principal_name) {
359                         char *p;
360                         user_principal_name = talloc_strdup(mem_ctx, user_principal_name);
361                         if (!user_principal_name) {
362                                 ret = ENOMEM;
363                                 goto out;
364                         } else {
365                                 p = strchr(user_principal_name, '@');
366                                 if (p) {
367                                         p[0] = '\0';
368                                 }
369                                 ret = krb5_make_principal(context, &salt_principal, realm, user_principal_name, NULL);
370                         } 
371                 } else {
372                         const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
373                         ret = krb5_make_principal(context, &salt_principal, realm, samAccountName, NULL);
374                 }
375
376                 if (ret == 0) {
377                         size_t num_keys = ent->keys.len;
378                         /*
379                          * create keys from unicodePwd
380                          */
381                         ret = hdb_generate_key_set_password(context, salt_principal, 
382                                                             unicodePwd, 
383                                                             &ent->keys.val, &num_keys);
384                         ent->keys.len = num_keys;
385                         krb5_free_principal(context, salt_principal);
386                 }
387
388                 if (ret != 0) {
389                         krb5_warnx(context, "could not generate keys from unicodePwd\n");
390                         ent->keys.val = NULL;
391                         ent->keys.len = 0;
392                         goto out;
393                 }
394         } else {
395                 const struct ldb_val *val;
396                 krb5_data keyvalue;
397
398                 val = ldb_msg_find_ldb_val(msg, "ntPwdHash");
399                 if (!val) {
400                         krb5_warnx(context, "neither type of key available for this account\n");
401                         ent->keys.val = NULL;
402                         ent->keys.len = 0;
403                 } else if (val->length < 16) {
404                         ent->keys.val = NULL;
405                         ent->keys.len = 0;
406                         krb5_warnx(context, "ntPwdHash has invalid length: %d\n",
407                                    (int)val->length);
408                 } else {
409                         ret = krb5_data_alloc (&keyvalue, 16);
410                         if (ret) {
411                                 krb5_set_error_string(context, "malloc: out of memory");
412                                 ret = ENOMEM;
413                                 goto out;
414                         }
415
416                         memcpy(keyvalue.data, val->data, 16);
417
418                         ent->keys.val = malloc(sizeof(ent->keys.val[0]));
419                         if (ent->keys.val == NULL) {
420                                 krb5_data_free(&keyvalue);
421                                 krb5_set_error_string(context, "malloc: out of memory");
422                                 ret = ENOMEM;
423                                 goto out;
424                         }
425                         
426                         memset(&ent->keys.val[0], 0, sizeof(Key));
427                         ent->keys.val[0].key.keytype = ETYPE_ARCFOUR_HMAC_MD5;
428                         ent->keys.val[0].key.keyvalue = keyvalue;
429                         
430                         ent->keys.len = 1;
431                 }
432         }               
433
434
435         ent->etypes = malloc(sizeof(*(ent->etypes)));
436         if (ent->etypes == NULL) {
437                 krb5_set_error_string(context, "malloc: out of memory");
438                 ret = ENOMEM;
439                 goto out;
440         }
441         ent->etypes->len = ent->keys.len;
442         ent->etypes->val = calloc(ent->etypes->len, sizeof(int));
443         if (ent->etypes->val == NULL) {
444                 krb5_set_error_string(context, "malloc: out of memory");
445                 ret = ENOMEM;
446                 goto out;
447         }
448         for (i=0; i < ent->etypes->len; i++) {
449                 ent->etypes->val[i] = ent->keys.val[i].key.keytype;
450         }
451
452 out:
453         if (ret != 0) {
454                 /* I don't think this frees ent itself. */
455                 hdb_free_entry(context, ent);
456         }
457
458         return ret;
459 }
460
461 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
462                                             TALLOC_CTX *mem_ctx,
463                                             krb5_const_principal principal,
464                                             enum hdb_ldb_ent_type ent_type,
465                                             const struct ldb_dn *realm_dn,
466                                             struct ldb_message ***pmsg)
467 {
468         krb5_error_code ret;
469         int count;
470         char *filter = NULL;
471         const char * const *princ_attrs = krb5_attrs;
472
473         char *princ_str;
474         char *princ_str_talloc;
475         char *short_princ;
476         char *short_princ_talloc;
477
478         char *realm_dn_str;
479
480         struct ldb_message **msg = NULL;
481
482         /* Structure assignment, so we don't mess with the source parameter */
483         struct Principal princ = *principal;
484
485         /* Allow host/dns.name/realm@REALM, just convert into host/dns.name@REALM */
486         if (princ.name.name_string.len == 3
487             && strcasecmp_m(princ.name.name_string.val[2], princ.realm) == 0) { 
488                 princ.name.name_string.len = 2;
489         }
490
491         ret = krb5_unparse_name(context, &princ, &princ_str);
492
493         if (ret != 0) {
494                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
495                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
496                 return ret;
497         }
498
499         ret = krb5_unparse_name_norealm(context, &princ, &short_princ);
500
501         if (ret != 0) {
502                 free(princ_str);
503                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
504                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
505                 return ret;
506         }
507
508         princ_str_talloc = talloc_strdup(mem_ctx, princ_str);
509         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
510         free(princ_str);
511         free(short_princ);
512         if (!short_princ || !princ_str_talloc) {
513                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
514                 return ENOMEM;
515         }
516
517         switch (ent_type) {
518         case HDB_LDB_ENT_TYPE_KRBTGT:
519                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
520                                          KRB5_TGS_NAME);
521                 break;
522         case HDB_LDB_ENT_TYPE_CLIENT:
523                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(samAccountName=%s)(userPrincipalName=%s)))", 
524                                          short_princ_talloc, princ_str_talloc);
525                 break;
526         case HDB_LDB_ENT_TYPE_SERVER:
527                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(samAccountName=%s)(servicePrincipalName=%s)))", 
528                                          short_princ_talloc, short_princ_talloc);
529                 break;
530         case HDB_LDB_ENT_TYPE_ANY:
531                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(|(samAccountName=%s)(servicePrincipalName=%s))(userPrincipalName=%s)))", 
532                                          short_princ_talloc, short_princ_talloc, princ_str_talloc);
533                 break;
534         }
535
536         if (!filter) {
537                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
538                 return ENOMEM;
539         }
540
541         count = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, 
542                            princ_attrs, &msg);
543
544         realm_dn_str = ldb_dn_linearize(mem_ctx, realm_dn);
545
546         if (count < 1) {
547                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
548                            realm_dn_str, filter, count);
549                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
550                                       realm_dn_str, filter, count);
551                 return HDB_ERR_NOENTRY;
552         } else if (count > 1) {
553                 talloc_free(msg);
554                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
555                            realm_dn_str, filter, count);
556                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
557                                       realm_dn_str, filter, count);
558                 return HDB_ERR_NOENTRY;
559         }
560         *pmsg = talloc_steal(mem_ctx, msg);
561         return 0;
562 }
563
564 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
565                                         TALLOC_CTX *mem_ctx,
566                                         const char *realm,
567                                         struct ldb_message ***pmsg)
568 {
569         int count;
570         struct ldb_dn *realm_dn;
571         const char *realm_dn_str;
572         char *cross_ref_filter;
573         struct ldb_message **cross_ref_msg;
574         struct ldb_message **msg;
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                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
756          * is in our db, then direct the caller at our primary
757          * krgtgt */
758         
759         switch (ent_type) {
760         case HDB_ENT_TYPE_SERVER:
761                 if (principal->name.name_string.len == 2
762                     && (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) == 0)
763                     && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
764                                          mem_ctx, principal->name.name_string.val[1], &realm_fixed_msg) == 0)) {
765                         const char *dnsdomain = ldb_msg_find_string(realm_fixed_msg[0], "dnsDomain", NULL);
766                         char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
767                         if (!realm_fixed) {
768                                 krb5_set_error_string(context, "strupper_talloc: out of memory");
769                                 talloc_free(mem_ctx);
770                                 return ENOMEM;
771                         }
772
773                         free(principal->name.name_string.val[1]);
774                         principal->name.name_string.val[1] = strdup(realm_fixed);
775                         talloc_free(realm_fixed);
776                         if (!principal->name.name_string.val[1]) {
777                                 krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
778                                 talloc_free(mem_ctx);
779                                 return ENOMEM;
780                         }
781                         ldb_ent_type = HDB_LDB_ENT_TYPE_KRBTGT;
782                         break;
783                 } else {
784                         ldb_ent_type = HDB_LDB_ENT_TYPE_SERVER;
785                         break;
786                 }
787         case HDB_ENT_TYPE_CLIENT:
788         {
789                 int ldb_ret;
790                 NTSTATUS nt_status;
791                 struct ldb_dn *user_dn, *domain_dn;
792                 char *principal_string;
793                 ldb_ent_type = HDB_LDB_ENT_TYPE_CLIENT;
794
795                 ret = krb5_unparse_name(context, principal, &principal_string);
796                 
797                 if (ret != 0) {
798                         talloc_free(mem_ctx);
799                         return ret;
800                 }
801
802                 nt_status = crack_user_principal_name((struct ldb_context *)db->hdb_db,
803                                                       mem_ctx, principal_string, 
804                                                       &user_dn, &domain_dn);
805                 free(principal_string);
806
807                 if (!NT_STATUS_IS_OK(nt_status)) {
808                         talloc_free(mem_ctx);
809                         return HDB_ERR_NOENTRY;
810                 }
811
812                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
813                                           mem_ctx, user_dn, &msg, krb5_attrs);
814
815                 if (ldb_ret != 1) {
816                         return HDB_ERR_NOENTRY;
817                 }
818
819                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
820                                           mem_ctx, domain_dn, &realm_msg, realm_attrs);
821
822                 if (ldb_ret != 1) {
823                         return HDB_ERR_NOENTRY;
824                 }
825
826                 ret = LDB_message2entry(context, db, mem_ctx, 
827                                         principal, ldb_ent_type, 
828                                         realm_msg[0], msg[0], entry);
829                 talloc_free(mem_ctx);
830                 return ret;
831         }
832         case HDB_ENT_TYPE_ANY:
833                 ldb_ent_type = HDB_LDB_ENT_TYPE_ANY;
834                 break;
835         default:
836                 krb5_warnx(context, "LDB_fetch: invalid ent_type specified!");
837                 talloc_free(mem_ctx);
838                 return HDB_ERR_NOENTRY;
839         }
840
841
842         realm = krb5_principal_get_realm(context, principal);
843
844         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
845                                mem_ctx, realm, &realm_msg);
846         if (ret != 0) {
847                 krb5_warnx(context, "LDB_fetch: could not find realm");
848                 talloc_free(mem_ctx);
849                 return HDB_ERR_NOENTRY;
850         }
851
852         realm_dn = realm_msg[0]->dn;
853
854         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
855                                    mem_ctx, 
856                                    principal, ldb_ent_type, realm_dn, &msg);
857
858         if (ret != 0) {
859                 char *alias_from = principal->name.name_string.val[0];
860                 char *alias_to;
861                 Principal alias_principal;
862                 
863                 /* Try again with a servicePrincipal alias */
864                 if (ent_type != HDB_LDB_ENT_TYPE_SERVER && ent_type != HDB_LDB_ENT_TYPE_ANY) {
865                         talloc_free(mem_ctx);
866                         return ret;
867                 }
868                 if (principal->name.name_string.len < 2) {
869                         krb5_warnx(context, "LDB_fetch: could not find principal in DB, alias not applicable");
870                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB, alias not applicable");
871                         talloc_free(mem_ctx);
872                         return ret;
873                 }
874
875                 /* Look for the list of aliases */
876                 ret = LDB_lookup_spn_alias(context, 
877                                            (struct ldb_context *)db->hdb_db, mem_ctx, 
878                                            realm_dn, alias_from, 
879                                            &alias_to);
880                 if (ret != 0) {
881                         talloc_free(mem_ctx);
882                         return ret;
883                 }
884
885                 ret = copy_Principal(principal, &alias_principal);
886                 if (ret != 0) {
887                         krb5_warnx(context, "LDB_fetch: could not copy principal");
888                         krb5_set_error_string(context, "LDB_fetch: could not copy principal");
889                         talloc_free(mem_ctx);
890                         return ret;
891                 }
892
893                 /* ooh, very nasty playing around in the Principal... */
894                 free(alias_principal.name.name_string.val[0]);
895                 alias_principal.name.name_string.val[0] = strdup(alias_to);
896                 if (!alias_principal.name.name_string.val[0]) {
897                         krb5_warnx(context, "LDB_fetch: strdup() failed");
898                         krb5_set_error_string(context, "LDB_fetch: strdup() failed");
899                         ret = ENOMEM;
900                         talloc_free(mem_ctx);
901                         free_Principal(&alias_principal);
902                         return ret;
903                 }
904
905                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
906                                            mem_ctx, 
907                                            &alias_principal, ent_type, realm_dn, &msg);
908                 free_Principal(&alias_principal);
909
910                 if (ret != 0) {
911                         krb5_warnx(context, "LDB_fetch: could not find alias principal in DB");
912                         krb5_set_error_string(context, "LDB_fetch: could not find alias principal in DB");
913                         talloc_free(mem_ctx);
914                         return ret;
915                 }
916
917         }
918         if (ret == 0) {
919                 ret = LDB_message2entry(context, db, mem_ctx, 
920                                         principal, ldb_ent_type, 
921                                         realm_msg[0], msg[0], entry);
922                 if (ret != 0) {
923                         krb5_warnx(context, "LDB_fetch: message2entry failed\n");       
924                 }
925         }
926
927         talloc_free(mem_ctx);
928         return ret;
929 }
930
931 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
932 {
933         return HDB_ERR_DB_INUSE;
934 }
935
936 static krb5_error_code LDB_remove(krb5_context context, HDB *db, hdb_entry *entry)
937 {
938         return HDB_ERR_DB_INUSE;
939 }
940
941 struct hdb_ldb_seq {
942         struct ldb_context *ctx;
943         int index;
944         int count;
945         struct ldb_message **msgs;
946         struct ldb_message **realm_msgs;
947 };
948
949 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
950 {
951         krb5_error_code ret;
952         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
953         TALLOC_CTX *mem_ctx;
954         if (!priv) {
955                 return HDB_ERR_NOENTRY;
956         }
957
958         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
959
960         if (!mem_ctx) {
961                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
962                 return ENOMEM;
963         }
964
965         if (priv->index < priv->count) {
966                 ret = LDB_message2entry(context, db, mem_ctx, 
967                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
968                                         priv->realm_msgs[0], priv->msgs[priv->index++], entry);
969         } else {
970                 ret = HDB_ERR_NOENTRY;
971         }
972
973         if (ret != 0) {
974                 talloc_free(priv);
975                 db->hdb_openp = NULL;
976         } else {
977                 talloc_free(mem_ctx);
978         }
979
980         return ret;
981 }
982
983 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
984                                         hdb_entry *entry)
985 {
986         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
987         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
988         char *realm;
989         struct ldb_dn *realm_dn = NULL;
990         struct ldb_message **msgs = NULL;
991         struct ldb_message **realm_msgs = NULL;
992         krb5_error_code ret;
993         TALLOC_CTX *mem_ctx;
994
995         if (priv) {
996                 talloc_free(priv);
997                 db->hdb_openp = 0;
998         }
999
1000         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1001         if (!priv) {
1002                 krb5_set_error_string(context, "talloc: out of memory");
1003                 return ENOMEM;
1004         }
1005
1006         priv->ctx = ldb_ctx;
1007         priv->index = 0;
1008         priv->msgs = NULL;
1009         priv->realm_msgs = NULL;
1010         priv->count = 0;
1011
1012         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1013
1014         if (!mem_ctx) {
1015                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1016                 return ENOMEM;
1017         }
1018
1019         ret = krb5_get_default_realm(context, &realm);
1020         if (ret != 0) {
1021                 talloc_free(priv);
1022                 return ret;
1023         }
1024                 
1025         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1026                                mem_ctx, realm, &realm_msgs);
1027
1028         free(realm);
1029
1030         if (ret != 0) {
1031                 talloc_free(priv);
1032                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1033                 return HDB_ERR_NOENTRY;
1034         }
1035
1036         realm_dn = realm_msgs[0]->dn;
1037
1038         priv->realm_msgs = talloc_steal(priv, realm_msgs);
1039
1040         krb5_warnx(context, "LDB_firstkey: realm ok\n");
1041
1042         priv->count = ldb_search(ldb_ctx, realm_dn,
1043                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
1044                                  krb5_attrs, &msgs);
1045
1046         priv->msgs = talloc_steal(priv, msgs);
1047
1048         if (priv->count <= 0) {
1049                 talloc_free(priv);
1050                 return HDB_ERR_NOENTRY;
1051         }
1052
1053         db->hdb_openp = priv;
1054
1055         ret = LDB_seq(context, db, flags, entry);
1056         
1057         if (ret != 0) {
1058                 talloc_free(priv);
1059                 db->hdb_openp = NULL;
1060         } else {
1061                 talloc_free(mem_ctx);
1062         }
1063         return ret;
1064 }
1065
1066 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1067                                         hdb_entry *entry)
1068 {
1069         return LDB_seq(context, db, flags, entry);
1070 }
1071
1072 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1073 {
1074         talloc_free(db);
1075         return 0;
1076 }
1077
1078 krb5_error_code hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1079                                krb5_context context, struct HDB **db, const char *arg)
1080 {
1081         *db = talloc(mem_ctx, HDB);
1082         if (!*db) {
1083                 krb5_set_error_string(context, "malloc: out of memory");
1084                 return ENOMEM;
1085         }
1086
1087         (*db)->hdb_master_key_set = 0;
1088         (*db)->hdb_db = NULL;
1089
1090         /* Setup the link to LDB */
1091         (*db)->hdb_db = samdb_connect(db, system_session(db));
1092         if ((*db)->hdb_db == NULL) {
1093                 krb5_warnx(context, "hdb_ldb_create: samdb_connect failed!");
1094                 krb5_set_error_string(context, "samdb_connect failed!");
1095                 talloc_free(*db);
1096                 return HDB_ERR_NOENTRY;
1097         }
1098
1099         (*db)->hdb_openp = 0;
1100         (*db)->hdb_open = LDB_open;
1101         (*db)->hdb_close = LDB_close;
1102         (*db)->hdb_fetch = LDB_fetch;
1103         (*db)->hdb_store = LDB_store;
1104         (*db)->hdb_remove = LDB_remove;
1105         (*db)->hdb_firstkey = LDB_firstkey;
1106         (*db)->hdb_nextkey = LDB_nextkey;
1107         (*db)->hdb_lock = LDB_lock;
1108         (*db)->hdb_unlock = LDB_unlock;
1109         (*db)->hdb_rename = LDB_rename;
1110         /* we don't implement these, as we are not a lockable database */
1111         (*db)->hdb__get = NULL;
1112         (*db)->hdb__put = NULL;
1113         /* kadmin should not be used for deletes - use other tools instead */
1114         (*db)->hdb__del = NULL;
1115         (*db)->hdb_destroy = LDB_destroy;
1116
1117         return 0;
1118 }