f138373cc3ff3dc3a6cecf4fd23495bc10e36af7
[sfrench/samba-autobuild/.git] / source4 / kdc / hdb-ldb.c
1 /*
2  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3  * Copyright (c) 2004, Andrew Bartlett <abartlet@samba.org>.
4  * Copyright (c) 2004, Stefan Metzmacher <metze@samba.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * 3. Neither the name of PADL Software  nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "includes.h"
36 #include "kdc.h"
37 #include "ads.h"
38 #include "hdb.h"
39 #include "lib/ldb/include/ldb.h"
40 #include "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         char *p;
458
459         char *princ_str;
460         char *princ_str_talloc;
461         char *short_princ;
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(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         princ_str_talloc = talloc_strdup(mem_ctx, princ_str);
485         short_princ = talloc_strdup(mem_ctx, princ_str);
486         free(princ_str);
487         if (!short_princ || !princ_str_talloc) {
488                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
489                 return ENOMEM;
490         }
491
492         p = strchr(short_princ, '@');
493         if (p) {
494                 p[0] = '\0';
495         }
496
497         
498         switch (ent_type) {
499         case HDB_LDB_ENT_TYPE_KRBTGT:
500                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
501                                          KRB5_TGS_NAME);
502                 break;
503         case HDB_LDB_ENT_TYPE_CLIENT:
504                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(samAccountName=%s)(userPrincipalName=%s)))", 
505                                          short_princ, princ_str_talloc);
506                 break;
507         case HDB_LDB_ENT_TYPE_SERVER:
508                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(samAccountName=%s)(servicePrincipalName=%s)))", 
509                                          short_princ, short_princ);
510                 break;
511         case HDB_LDB_ENT_TYPE_ANY:
512                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(|(|(samAccountName=%s)(servicePrincipalName=%s))(userPrincipalName=%s)))", 
513                                          short_princ, short_princ, princ_str_talloc);
514                 break;
515         }
516
517         if (!filter) {
518                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
519                 return ENOMEM;
520         }
521
522         count = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, 
523                            princ_attrs, &msg);
524
525         realm_dn_str = ldb_dn_linearize(mem_ctx, realm_dn);
526
527         if (count < 1) {
528                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
529                            realm_dn_str, filter, count);
530                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' failed: %d", 
531                                       realm_dn_str, filter, count);
532                 return HDB_ERR_NOENTRY;
533         } else if (count > 1) {
534                 talloc_free(msg);
535                 krb5_warnx(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
536                            realm_dn_str, filter, count);
537                 krb5_set_error_string(context, "ldb_search: basedn: '%s' filter: '%s' more than 1 entry: %d", 
538                                       realm_dn_str, filter, count);
539                 return HDB_ERR_NOENTRY;
540         }
541         *pmsg = talloc_steal(mem_ctx, msg);
542         return 0;
543 }
544
545 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
546                                         TALLOC_CTX *mem_ctx,
547                                         const char *realm,
548                                         struct ldb_message ***pmsg)
549 {
550         int count;
551         struct ldb_dn *realm_dn;
552         const char *realm_dn_str;
553         char *cross_ref_filter;
554         struct ldb_message **cross_ref_msg;
555         struct ldb_message **msg;
556
557         const char *cross_ref_attrs[] = {
558                 "nCName", 
559                 NULL
560         };
561
562         const char *realm_attrs[] = {
563                 "dnsDomain", 
564                 "maxPwdAge",
565                 NULL
566         };
567
568         cross_ref_filter = talloc_asprintf(mem_ctx, 
569                                            "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
570                                            realm, realm);
571         if (!cross_ref_filter) {
572                 krb5_set_error_string(context, "asprintf: out of memory");
573                 return ENOMEM;
574         }
575
576         count = ldb_search(ldb_ctx, NULL, LDB_SCOPE_SUBTREE, cross_ref_filter, 
577                            cross_ref_attrs, &cross_ref_msg);
578
579         if (count < 1) {
580                 krb5_warnx(context, "ldb_search: filter: '%s' failed: %d", cross_ref_filter, count);
581                 krb5_set_error_string(context, "ldb_search: filter: '%s' failed: %d", cross_ref_filter, count);
582
583                 talloc_free(cross_ref_msg);
584                 return HDB_ERR_NOENTRY;
585         } else if (count > 1) {
586                 krb5_warnx(context, "ldb_search: filter: '%s' more than 1 entry: %d", cross_ref_filter, count);
587                 krb5_set_error_string(context, "ldb_search: filter: '%s' more than 1 entry: %d", cross_ref_filter, count);
588
589                 talloc_free(cross_ref_msg);
590                 return HDB_ERR_NOENTRY;
591         }
592
593         realm_dn_str = ldb_msg_find_string(cross_ref_msg[0], "nCName", NULL);
594         realm_dn = ldb_dn_explode(mem_ctx, realm_dn_str);
595
596         count = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_BASE, "(objectClass=domain)",
597                            realm_attrs, &msg);
598         if (pmsg) {
599                 *pmsg = talloc_steal(mem_ctx, msg);
600         } else {
601                 talloc_free(msg);
602         }
603
604         if (count < 1) {
605                 krb5_warnx(context, "ldb_search: dn: %s not found: %d", realm_dn_str, count);
606                 krb5_set_error_string(context, "ldb_search: dn: %s not found: %d", realm_dn_str, count);
607                 return HDB_ERR_NOENTRY;
608         } else if (count > 1) {
609                 krb5_warnx(context, "ldb_search: dn: '%s' more than 1 entry: %d", realm_dn_str, count);
610                 krb5_set_error_string(context, "ldb_search: dn: %s more than 1 entry: %d", realm_dn_str, count);
611                 return HDB_ERR_NOENTRY;
612         }
613
614         return 0;
615 }
616
617 static krb5_error_code LDB_lookup_spn_alias(krb5_context context, struct ldb_context *ldb_ctx, 
618                                             TALLOC_CTX *mem_ctx,
619                                             const struct ldb_dn *realm_dn,
620                                             const char *alias_from,
621                                             char **alias_to)
622 {
623         int i;
624         int count;
625         struct ldb_message **msg;
626         struct ldb_message_element *spnmappings;
627         struct ldb_dn *service_dn = ldb_dn_string_compose(mem_ctx, realm_dn,
628                                                 "CN=Directory Service,CN=Windows NT"
629                                                 ",CN=Services,CN=Configuration");
630         char *service_dn_str = ldb_dn_linearize(mem_ctx, service_dn);
631         const char *directory_attrs[] = {
632                 "sPNMappings", 
633                 NULL
634         };
635
636         count = ldb_search(ldb_ctx, service_dn, LDB_SCOPE_BASE, "(objectClass=nTDSService)",
637                            directory_attrs, &msg);
638         talloc_steal(mem_ctx, msg);
639
640         if (count < 1) {
641                 krb5_warnx(context, "ldb_search: dn: %s not found: %d", service_dn_str, count);
642                 krb5_set_error_string(context, "ldb_search: dn: %s not found: %d", service_dn_str, count);
643                 return HDB_ERR_NOENTRY;
644         } else if (count > 1) {
645                 krb5_warnx(context, "ldb_search: dn: %s found %d times!", service_dn_str, count);
646                 krb5_set_error_string(context, "ldb_search: dn: %s found %d times!", service_dn_str, count);
647                 return HDB_ERR_NOENTRY;
648         }
649         
650         spnmappings = ldb_msg_find_element(msg[0], "sPNMappings");
651         if (!spnmappings || spnmappings->num_values == 0) {
652                 krb5_warnx(context, "ldb_search: dn: %s no sPNMappings attribute", service_dn_str);
653                 krb5_set_error_string(context, "ldb_search: dn: %s no sPNMappings attribute", service_dn_str);
654                 return HDB_ERR_NOENTRY;
655         }
656
657         for (i = 0; i < spnmappings->num_values; i++) {
658                 char *mapping, *p, *str;
659                 mapping = talloc_strdup(mem_ctx, 
660                                         (const char *)spnmappings->values[i].data);
661                 if (!mapping) {
662                         krb5_warnx(context, "LDB_lookup_spn_alias: ldb_search: dn: %s did not have an sPNMapping", service_dn_str);
663                         krb5_set_error_string(context, "LDB_lookup_spn_alias: ldb_search: dn: %s did not have an sPNMapping", service_dn_str);
664                         return HDB_ERR_NOENTRY;
665                 }
666                 
667                 /* C string manipulation sucks */
668                 
669                 p = strchr(mapping, '=');
670                 if (!p) {
671                         krb5_warnx(context, "ldb_search: dn: %s sPNMapping malformed: %s", 
672                                    service_dn_str, mapping);
673                         krb5_set_error_string(context, "ldb_search: dn: %s sPNMapping malformed: %s", 
674                                               service_dn_str, mapping);
675                         return HDB_ERR_NOENTRY;
676                 }
677                 p[0] = '\0';
678                 p++;
679                 do {
680                         str = p;
681                         p = strchr(p, ',');
682                         if (p) {
683                                 p[0] = '\0';
684                                 p++;
685                         }
686                         if (strcasecmp(str, alias_from) == 0) {
687                                 *alias_to = mapping;
688                                 return 0;
689                         }
690                 } while (p);
691         }
692         krb5_warnx(context, "LDB_lookup_spn_alias: no alias for service %s applicable", alias_from);
693         return HDB_ERR_NOENTRY;
694 }
695
696 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
697 {
698         if (db->hdb_master_key_set) {
699                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
700                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
701                 return HDB_ERR_NOENTRY;
702         }               
703
704         return 0;
705 }
706
707 static krb5_error_code LDB_close(krb5_context context, HDB *db)
708 {
709         return 0;
710 }
711
712 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
713 {
714         return 0;
715 }
716
717 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
718 {
719         return 0;
720 }
721
722 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
723 {
724         return HDB_ERR_DB_INUSE;
725 }
726
727 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, unsigned flags,
728                                  krb5_const_principal principal,
729                                  enum hdb_ent_type ent_type,
730                                  hdb_entry *entry)
731 {
732         struct ldb_message **msg = NULL;
733         struct ldb_message **realm_msg = NULL;
734         struct ldb_message **realm_fixed_msg = NULL;
735         enum hdb_ldb_ent_type ldb_ent_type;
736         krb5_error_code ret;
737
738         const char *realm;
739         const struct ldb_dn *realm_dn;
740         TALLOC_CTX *mem_ctx = talloc_named(NULL, 0, "LDB_fetch context");
741
742         if (!mem_ctx) {
743                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
744                 return ENOMEM;
745         }
746
747         realm = krb5_principal_get_realm(context, principal);
748
749         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
750                                mem_ctx, realm, &realm_msg);
751         if (ret != 0) {
752                 krb5_warnx(context, "LDB_fetch: could not find realm");
753                 talloc_free(mem_ctx);
754                 return HDB_ERR_NOENTRY;
755         }
756
757         realm_dn = realm_msg[0]->dn;
758
759         /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
760          * is in our db, then direct the caller at our primary
761          * krgtgt */
762         
763         switch (ent_type) {
764         case HDB_ENT_TYPE_SERVER:
765                 if (principal->name.name_string.len == 2
766                     && (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) == 0)
767                     && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
768                                          mem_ctx, principal->name.name_string.val[1], &realm_fixed_msg) == 0)) {
769                         const char *dnsdomain = ldb_msg_find_string(realm_fixed_msg[0], "dnsDomain", NULL);
770                         char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
771                         if (!realm_fixed) {
772                                 krb5_set_error_string(context, "strupper_talloc: out of memory");
773                                 talloc_free(mem_ctx);
774                                 return ENOMEM;
775                         }
776
777                         free(principal->name.name_string.val[1]);
778                         principal->name.name_string.val[1] = strdup(realm_fixed);
779                         talloc_free(realm_fixed);
780                         if (!principal->name.name_string.val[1]) {
781                                 krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
782                                 talloc_free(mem_ctx);
783                                 return ENOMEM;
784                         }
785                         ldb_ent_type = HDB_LDB_ENT_TYPE_KRBTGT;
786                 } else {
787                         ldb_ent_type = HDB_LDB_ENT_TYPE_SERVER;
788                 }
789                 break;
790         case HDB_ENT_TYPE_CLIENT:
791                 ldb_ent_type = HDB_LDB_ENT_TYPE_CLIENT;
792                 break;
793         case HDB_ENT_TYPE_ANY:
794                 ldb_ent_type = HDB_LDB_ENT_TYPE_ANY;
795                 break;
796         default:
797                 krb5_warnx(context, "LDB_fetch: invalid ent_type specified!");
798                 talloc_free(mem_ctx);
799                 return HDB_ERR_NOENTRY;
800         }
801
802         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
803                                    mem_ctx, 
804                                    principal, ldb_ent_type, realm_dn, &msg);
805
806         if (ret != 0) {
807                 char *alias_from = principal->name.name_string.val[0];
808                 char *alias_to;
809                 Principal alias_principal;
810                 
811                 /* Try again with a servicePrincipal alias */
812                 if (ent_type != HDB_LDB_ENT_TYPE_SERVER && ent_type != HDB_LDB_ENT_TYPE_ANY) {
813                         talloc_free(mem_ctx);
814                         return ret;
815                 }
816                 if (principal->name.name_string.len < 2) {
817                         krb5_warnx(context, "LDB_fetch: could not find principal in DB, alias not applicable");
818                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB, alias not applicable");
819                         talloc_free(mem_ctx);
820                         return ret;
821                 }
822
823                 /* Look for the list of aliases */
824                 ret = LDB_lookup_spn_alias(context, 
825                                            (struct ldb_context *)db->hdb_db, mem_ctx, 
826                                            realm_dn, alias_from, 
827                                            &alias_to);
828                 if (ret != 0) {
829                         talloc_free(mem_ctx);
830                         return ret;
831                 }
832
833                 ret = copy_Principal(principal, &alias_principal);
834                 if (ret != 0) {
835                         krb5_warnx(context, "LDB_fetch: could not copy principal");
836                         krb5_set_error_string(context, "LDB_fetch: could not copy principal");
837                         talloc_free(mem_ctx);
838                         return ret;
839                 }
840
841                 /* ooh, very nasty playing around in the Principal... */
842                 free(alias_principal.name.name_string.val[0]);
843                 alias_principal.name.name_string.val[0] = strdup(alias_to);
844                 if (!alias_principal.name.name_string.val[0]) {
845                         krb5_warnx(context, "LDB_fetch: strdup() failed");
846                         krb5_set_error_string(context, "LDB_fetch: strdup() failed");
847                         ret = ENOMEM;
848                         talloc_free(mem_ctx);
849                         free_Principal(&alias_principal);
850                         return ret;
851                 }
852
853                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
854                                            mem_ctx, 
855                                            &alias_principal, ent_type, realm_dn, &msg);
856                 free_Principal(&alias_principal);
857
858                 if (ret != 0) {
859                         krb5_warnx(context, "LDB_fetch: could not find alias principal in DB");
860                         krb5_set_error_string(context, "LDB_fetch: could not find alias principal in DB");
861                         talloc_free(mem_ctx);
862                         return ret;
863                 }
864
865         }
866         if (ret == 0) {
867                 ret = LDB_message2entry(context, db, mem_ctx, 
868                                         principal, ldb_ent_type, 
869                                         realm_msg[0], msg[0], entry);
870                 if (ret != 0) {
871                         krb5_warnx(context, "LDB_fetch: message2entry failed\n");       
872                 }
873         }
874
875         talloc_free(mem_ctx);
876         return ret;
877 }
878
879 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
880 {
881         return HDB_ERR_DB_INUSE;
882 }
883
884 static krb5_error_code LDB_remove(krb5_context context, HDB *db, hdb_entry *entry)
885 {
886         return HDB_ERR_DB_INUSE;
887 }
888
889 struct hdb_ldb_seq {
890         struct ldb_context *ctx;
891         int index;
892         int count;
893         struct ldb_message **msgs;
894         struct ldb_message **realm_msgs;
895 };
896
897 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
898 {
899         krb5_error_code ret;
900         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
901         TALLOC_CTX *mem_ctx;
902         if (!priv) {
903                 return HDB_ERR_NOENTRY;
904         }
905
906         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
907
908         if (!mem_ctx) {
909                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
910                 return ENOMEM;
911         }
912
913         if (priv->index < priv->count) {
914                 ret = LDB_message2entry(context, db, mem_ctx, 
915                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
916                                         priv->realm_msgs[0], priv->msgs[priv->index++], entry);
917         } else {
918                 ret = HDB_ERR_NOENTRY;
919         }
920
921         if (ret != 0) {
922                 talloc_free(priv);
923                 db->hdb_openp = NULL;
924         } else {
925                 talloc_free(mem_ctx);
926         }
927
928         return ret;
929 }
930
931 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
932                                         hdb_entry *entry)
933 {
934         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
935         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
936         char *realm;
937         struct ldb_dn *realm_dn = NULL;
938         struct ldb_message **msgs = NULL;
939         struct ldb_message **realm_msgs = NULL;
940         krb5_error_code ret;
941         TALLOC_CTX *mem_ctx;
942
943         if (priv) {
944                 talloc_free(priv);
945                 db->hdb_openp = 0;
946         }
947
948         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
949         if (!priv) {
950                 krb5_set_error_string(context, "talloc: out of memory");
951                 return ENOMEM;
952         }
953
954         priv->ctx = ldb_ctx;
955         priv->index = 0;
956         priv->msgs = NULL;
957         priv->realm_msgs = NULL;
958         priv->count = 0;
959
960         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
961
962         if (!mem_ctx) {
963                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
964                 return ENOMEM;
965         }
966
967         ret = krb5_get_default_realm(context, &realm);
968         if (ret != 0) {
969                 talloc_free(priv);
970                 return ret;
971         }
972                 
973         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
974                                mem_ctx, realm, &realm_msgs);
975
976         free(realm);
977
978         if (ret != 0) {
979                 talloc_free(priv);
980                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
981                 return HDB_ERR_NOENTRY;
982         }
983
984         realm_dn = realm_msgs[0]->dn;
985
986         priv->realm_msgs = talloc_steal(priv, realm_msgs);
987
988         krb5_warnx(context, "LDB_firstkey: realm ok\n");
989
990         priv->count = ldb_search(ldb_ctx, realm_dn,
991                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
992                                  krb5_attrs, &msgs);
993
994         priv->msgs = talloc_steal(priv, msgs);
995
996         if (priv->count <= 0) {
997                 talloc_free(priv);
998                 return HDB_ERR_NOENTRY;
999         }
1000
1001         db->hdb_openp = priv;
1002
1003         ret = LDB_seq(context, db, flags, entry);
1004         
1005         if (ret != 0) {
1006                 talloc_free(priv);
1007                 db->hdb_openp = NULL;
1008         } else {
1009                 talloc_free(mem_ctx);
1010         }
1011         return ret;
1012 }
1013
1014 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1015                                         hdb_entry *entry)
1016 {
1017         return LDB_seq(context, db, flags, entry);
1018 }
1019
1020 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1021 {
1022         talloc_free(db);
1023         return 0;
1024 }
1025
1026 krb5_error_code hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1027                                krb5_context context, struct HDB **db, const char *arg)
1028 {
1029         *db = talloc(mem_ctx, HDB);
1030         if (!*db) {
1031                 krb5_set_error_string(context, "malloc: out of memory");
1032                 return ENOMEM;
1033         }
1034
1035         (*db)->hdb_master_key_set = 0;
1036         (*db)->hdb_db = NULL;
1037
1038         /* Setup the link to LDB */
1039         (*db)->hdb_db = samdb_connect(db);
1040         if ((*db)->hdb_db == NULL) {
1041                 krb5_warnx(context, "hdb_ldb_create: samdb_connect failed!");
1042                 krb5_set_error_string(context, "samdb_connect failed!");
1043                 talloc_free(*db);
1044                 return HDB_ERR_NOENTRY;
1045         }
1046
1047         (*db)->hdb_openp = 0;
1048         (*db)->hdb_open = LDB_open;
1049         (*db)->hdb_close = LDB_close;
1050         (*db)->hdb_fetch = LDB_fetch;
1051         (*db)->hdb_store = LDB_store;
1052         (*db)->hdb_remove = LDB_remove;
1053         (*db)->hdb_firstkey = LDB_firstkey;
1054         (*db)->hdb_nextkey = LDB_nextkey;
1055         (*db)->hdb_lock = LDB_lock;
1056         (*db)->hdb_unlock = LDB_unlock;
1057         (*db)->hdb_rename = LDB_rename;
1058         /* we don't implement these, as we are not a lockable database */
1059         (*db)->hdb__get = NULL;
1060         (*db)->hdb__put = NULL;
1061         /* kadmin should not be used for deletes - use other tools instead */
1062         (*db)->hdb__del = NULL;
1063         (*db)->hdb_destroy = LDB_destroy;
1064
1065         return 0;
1066 }