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