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