r23503: use hdb_dbc not hdb_openp.
[kai/samba.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 "system/time.h"
37 #include "kdc.h"
38 #include "dsdb/common/flags.h"
39 #include "hdb.h"
40 #include "krb5_locl.h"
41 #include "lib/ldb/include/ldb.h"
42 #include "lib/ldb/include/ldb_errors.h"
43 #include "librpc/gen_ndr/netlogon.h"
44 #include "auth/auth.h"
45 #include "auth/credentials/credentials.h"
46 #include "auth/auth_sam.h"
47 #include "db_wrap.h"
48 #include "dsdb/samdb/samdb.h"
49 #include "librpc/ndr/libndr.h"
50 #include "librpc/gen_ndr/ndr_drsblobs.h"
51 #include "libcli/auth/libcli_auth.h"
52
53 enum hdb_ldb_ent_type 
54 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
55   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
56
57 static const char * const krb5_attrs[] = {
58         "objectClass",
59         "sAMAccountName",
60
61         "userPrincipalName",
62         "servicePrincipalName",
63
64         "userAccountControl",
65
66         "pwdLastSet",
67         "accountExpires",
68
69         "whenCreated",
70         "whenChanged",
71
72         "msDS-KeyVersionNumber",
73
74         "unicodePwd",
75         "supplementalCredentials",
76
77         NULL
78 };
79
80 static const char *realm_ref_attrs[] = {
81         "nCName", 
82         "dnsRoot", 
83         NULL
84 };
85
86 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
87 {
88     const char *tmp;
89     const char *gentime;
90     struct tm tm;
91
92     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
93     if (!gentime)
94         return default_val;
95
96     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
97     if (tmp == NULL) {
98             return default_val;
99     }
100
101     return timegm(&tm);
102 }
103
104 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
105 {
106         HDBFlags flags = int2HDBFlags(0);
107
108         /* we don't allow kadmin deletes */
109         flags.immutable = 1;
110
111         /* mark the principal as invalid to start with */
112         flags.invalid = 1;
113
114         flags.renewable = 1;
115
116         /* All accounts are servers, but this may be disabled again in the caller */
117         flags.server = 1;
118
119         /* Account types - clear the invalid bit if it turns out to be valid */
120         if (userAccountControl & UF_NORMAL_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         
127         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
128                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
129                         flags.client = 1;
130                 }
131                 flags.invalid = 0;
132         }
133         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
134                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
135                         flags.client = 1;
136                 }
137                 flags.invalid = 0;
138         }
139         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
140                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
141                         flags.client = 1;
142                 }
143                 flags.invalid = 0;
144         }
145
146         /* Not permitted to act as a client if disabled */
147         if (userAccountControl & UF_ACCOUNTDISABLE) {
148                 flags.client = 0;
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         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
160 */
161         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
162                 flags.invalid = 1;
163         }
164
165 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
166
167 /*
168         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
169                 flags.invalid = 1;
170         }
171 */
172         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
173                 flags.require_hwauth = 1;
174         }
175         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
176                 flags.ok_as_delegate = 1;
177         }       
178         if (!(userAccountControl & UF_NOT_DELEGATED)) {
179                 flags.forwardable = 1;
180                 flags.proxiable = 1;
181         }
182
183         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
184                 flags.require_preauth = 0;
185         } else {
186                 flags.require_preauth = 1;
187
188         }
189         return flags;
190 }
191
192 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
193 {
194     hdb_entry_ex *entry_ex = private->entry_ex;
195     free_hdb_entry(&entry_ex->entry);
196     return 0;
197 }
198
199 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
200 {
201         talloc_free(entry_ex->ctx);
202 }
203
204 static krb5_error_code LDB_message2entry_keys(krb5_context context,
205                                               TALLOC_CTX *mem_ctx,
206                                               struct ldb_message *msg,
207                                               unsigned int userAccountControl,
208                                               hdb_entry_ex *entry_ex)
209 {
210         krb5_error_code ret = 0;
211         NTSTATUS status;
212         struct samr_Password *hash;
213         const struct ldb_val *sc_val;
214         struct supplementalCredentialsBlob scb;
215         struct supplementalCredentialsPackage *scp = NULL;
216         struct package_PrimaryKerberosBlob _pkb;
217         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
218         uint32_t i;
219         uint32_t allocated_keys = 0;
220
221         entry_ex->entry.keys.val = NULL;
222         entry_ex->entry.keys.len = 0;
223
224         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
225
226         /* Get keys from the db */
227
228         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
229         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
230
231         /* unicodePwd for enctype 0x17 (23) if present */
232         if (hash) {
233                 allocated_keys++;
234         }
235
236         /* supplementalCredentials if present */
237         if (sc_val) {
238                 status = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
239                                                   (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
240                 if (!NT_STATUS_IS_OK(status)) {
241                         dump_data(0, sc_val->data, sc_val->length);
242                         ret = EINVAL;
243                         goto out;
244                 }
245
246                 for (i=0; i < scb.sub.num_packages; i++) {
247                         if (scb.sub.packages[i].unknown1 != 0x00000001) {
248                                 continue;
249                         }
250
251                         if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) != 0) {
252                                 continue;
253                         }
254
255                         if (!scb.sub.packages[i].data || !scb.sub.packages[i].data[0]) {
256                                 continue;
257                         }
258
259                         scp = &scb.sub.packages[i];
260                         break;
261                 }
262         }
263         /* Primary:Kerberos element of supplementalCredentials */
264         if (scp) {
265                 DATA_BLOB blob;
266
267                 blob = strhex_to_data_blob(scp->data);
268                 if (!blob.data) {
269                         ret = ENOMEM;
270                         goto out;
271                 }
272                 talloc_steal(mem_ctx, blob.data);
273
274                 /* TODO: use ndr_pull_struct_blob_all(), when the ndr layer handles it correct with relative pointers */
275                 status = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
276                                               (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
277                 if (!NT_STATUS_IS_OK(status)) {
278                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
279                         krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
280                         ret = EINVAL;
281                         goto out;
282                 }
283
284                 if (_pkb.version != 3) {
285                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse PrimaryKerberos not version 3");
286                         krb5_warnx(context, "LDB_message2entry_keys: could not parse PrimaryKerberos not version 3");
287                         ret = EINVAL;
288                         goto out;
289                 }
290                 
291                 pkb3 = &_pkb.ctr.ctr3;
292
293                 allocated_keys += pkb3->num_keys;
294         }
295
296         if (allocated_keys == 0) {
297                 /* oh, no password.  Apparently (comment in
298                  * hdb-ldap.c) this violates the ASN.1, but this
299                  * allows an entry with no keys (yet). */
300                 return 0;
301         }
302
303         /* allocate space to decode into */
304         entry_ex->entry.keys.len = 0;
305         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
306         if (entry_ex->entry.keys.val == NULL) {
307                 ret = ENOMEM;
308                 goto out;
309         }
310
311         if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
312                 Key key;
313
314                 key.mkvno = 0;
315                 key.salt = NULL; /* No salt for this enc type */
316
317                 ret = krb5_keyblock_init(context,
318                                          ENCTYPE_ARCFOUR_HMAC_MD5,
319                                          hash->hash, sizeof(hash->hash), 
320                                          &key.key);
321                 if (ret) {
322                         goto out;
323                 }
324
325                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
326                 entry_ex->entry.keys.len++;
327         }
328
329         if (pkb3) {
330                 for (i=0; i < pkb3->num_keys; i++) {
331                         bool use = true;
332                         Key key;
333
334                         if (!pkb3->keys[i].value) continue;
335
336                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
337                                 switch (pkb3->keys[i].keytype) {
338                                 case ENCTYPE_DES_CBC_CRC:
339                                 case ENCTYPE_DES_CBC_MD5:
340                                         break;
341                                 default:
342                                         use = false;
343                                         break;
344                                 }
345                         }
346
347                         if (!use) continue;
348
349                         key.mkvno = 0;
350
351                         if (pkb3->salt.string) {
352                                 DATA_BLOB salt;
353
354                                 salt = data_blob_string_const(pkb3->salt.string);
355
356                                 key.salt = calloc(1, sizeof(*key.salt));
357                                 if (key.salt == NULL) {
358                                         ret = ENOMEM;
359                                         goto out;
360                                 }
361
362                                 key.salt->type = hdb_pw_salt;
363
364                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
365                                 if (ret) {
366                                         free(key.salt);
367                                         key.salt = NULL;
368                                         goto out;
369                                 }
370                         }
371
372                         ret = krb5_keyblock_init(context,
373                                                  pkb3->keys[i].keytype,
374                                                  pkb3->keys[i].value->data,
375                                                  pkb3->keys[i].value->length,
376                                                  &key.key);
377                         if (ret) {
378                                 if (key.salt) {
379                                         free_Salt(key.salt);
380                                         free(key.salt);
381                                         key.salt = NULL;
382                                 }
383                                 goto out;
384                         }
385
386                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
387                         entry_ex->entry.keys.len++;
388                 }
389         }
390
391 out:
392         if (ret != 0) {
393                 entry_ex->entry.keys.len = 0;
394         }
395         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
396                 free(entry_ex->entry.keys.val);
397                 entry_ex->entry.keys.val = NULL;
398         }
399         return ret;
400 }
401
402 /*
403  * Construct an hdb_entry from a directory entry.
404  */
405 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
406                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
407                                          enum hdb_ldb_ent_type ent_type, 
408                                          struct ldb_message *msg,
409                                          struct ldb_message *realm_ref_msg,
410                                          hdb_entry_ex *entry_ex)
411 {
412         unsigned int userAccountControl;
413         int i;
414         krb5_error_code ret = 0;
415         krb5_boolean is_computer = FALSE;
416         const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL);
417         char *realm = strupper_talloc(mem_ctx, dnsdomain);
418         struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db,
419                                                         mem_ctx,
420                                                         realm_ref_msg,
421                                                         "nCName",
422                                                         ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL));
423
424         struct hdb_ldb_private *private;
425         NTTIME acct_expiry;
426
427         struct ldb_message_element *objectclasses;
428         struct ldb_val computer_val;
429         computer_val.data = discard_const_p(uint8_t,"computer");
430         computer_val.length = strlen((const char *)computer_val.data);
431         
432         objectclasses = ldb_msg_find_element(msg, "objectClass");
433         
434         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
435                 is_computer = TRUE;
436         }
437
438         memset(entry_ex, 0, sizeof(*entry_ex));
439
440         if (!realm) {
441                 krb5_set_error_string(context, "talloc_strdup: out of memory");
442                 ret = ENOMEM;
443                 goto out;
444         }
445                         
446         private = talloc(mem_ctx, struct hdb_ldb_private);
447         if (!private) {
448                 ret = ENOMEM;
449                 goto out;
450         }
451
452         private->entry_ex = entry_ex;
453
454         talloc_set_destructor(private, hdb_ldb_destrutor);
455
456         entry_ex->ctx = private;
457         entry_ex->free_entry = hdb_ldb_free_entry;
458
459         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
460
461         
462         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
463         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
464                 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
465                 if (!samAccountName) {
466                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
467                         ret = ENOENT;
468                         goto out;
469                 }
470                 samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
471                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
472         } else {
473                 char *strdup_realm;
474                 ret = copy_Principal(principal, entry_ex->entry.principal);
475                 if (ret) {
476                         krb5_clear_error_string(context);
477                         goto out;
478                 }
479
480                 /* While we have copied the client principal, tests
481                  * show that Win2k3 returns the 'corrected' realm, not
482                  * the client-specified realm.  This code attempts to
483                  * replace the client principal's realm with the one
484                  * we determine from our records */
485                 
486                 /* this has to be with malloc() */
487                 strdup_realm = strdup(realm);
488                 if (!strdup_realm) {
489                         ret = ENOMEM;
490                         krb5_clear_error_string(context);
491                         goto out;
492                 }
493                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
494                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
495         }
496
497         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
498
499         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
500                 entry_ex->entry.flags.invalid = 0;
501                 entry_ex->entry.flags.server = 1;
502                 entry_ex->entry.flags.forwardable = 1;
503                 entry_ex->entry.flags.ok_as_delegate = 1;
504         }
505
506         if (lp_parm_bool(-1, "kdc", "require spn for service", True)) {
507                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
508                         entry_ex->entry.flags.server = 0;
509                 }
510         }
511
512         /* use 'whenCreated' */
513         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
514         /* use '???' */
515         entry_ex->entry.created_by.principal = NULL;
516
517         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
518         if (entry_ex->entry.modified_by == NULL) {
519                 krb5_set_error_string(context, "malloc: out of memory");
520                 ret = ENOMEM;
521                 goto out;
522         }
523
524         /* use 'whenChanged' */
525         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
526         /* use '???' */
527         entry_ex->entry.modified_by->principal = NULL;
528
529         entry_ex->entry.valid_start = NULL;
530
531         acct_expiry = samdb_result_nttime(msg, "accountExpires", (NTTIME)-1);
532         if ((acct_expiry == (NTTIME)-1) ||
533             (acct_expiry == 0x7FFFFFFFFFFFFFFFULL)) {
534                 entry_ex->entry.valid_end = NULL;
535         } else {
536                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
537                 if (entry_ex->entry.valid_end == NULL) {
538                         ret = ENOMEM;
539                         goto out;
540                 }
541                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
542         }
543
544         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
545                 NTTIME must_change_time
546                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
547                                                              domain_dn, msg);
548                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
549                         entry_ex->entry.pw_end = NULL;
550                 } else {
551                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
552                         if (entry_ex->entry.pw_end == NULL) {
553                                 ret = ENOMEM;
554                                 goto out;
555                         }
556                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
557                 }
558         } else {
559                 entry_ex->entry.pw_end = NULL;
560         }
561                         
562         entry_ex->entry.max_life = NULL;
563
564         entry_ex->entry.max_renew = NULL;
565
566         entry_ex->entry.generation = NULL;
567
568         /* Get keys from the db */
569         ret = LDB_message2entry_keys(context, private, msg, userAccountControl, entry_ex);
570         if (ret) {
571                 /* Could be bougus data in the entry, or out of memory */
572                 goto out;
573         }
574
575         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
576         if (entry_ex->entry.etypes == NULL) {
577                 krb5_clear_error_string(context);
578                 ret = ENOMEM;
579                 goto out;
580         }
581         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
582         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
583         if (entry_ex->entry.etypes->val == NULL) {
584                 krb5_clear_error_string(context);
585                 ret = ENOMEM;
586                 goto out;
587         }
588         for (i=0; i < entry_ex->entry.etypes->len; i++) {
589                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
590         }
591
592
593         private->msg = talloc_steal(private, msg);
594         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
595         private->samdb = (struct ldb_context *)db->hdb_db;
596         
597 out:
598         if (ret != 0) {
599                 /* This doesn't free ent itself, that is for the eventual caller to do */
600                 hdb_free_entry(context, entry_ex);
601         } else {
602                 talloc_steal(db, entry_ex->ctx);
603         }
604
605         return ret;
606 }
607
608 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
609                                             TALLOC_CTX *mem_ctx,
610                                             krb5_const_principal principal,
611                                             enum hdb_ldb_ent_type ent_type,
612                                             struct ldb_dn *realm_dn,
613                                             struct ldb_message ***pmsg)
614 {
615         krb5_error_code ret;
616         int lret;
617         char *filter = NULL;
618         const char * const *princ_attrs = krb5_attrs;
619
620         char *short_princ;
621         char *short_princ_talloc;
622
623         struct ldb_result *res = NULL;
624
625         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
626
627         if (ret != 0) {
628                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
629                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
630                 return ret;
631         }
632
633         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
634         free(short_princ);
635         if (!short_princ_talloc) {
636                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
637                 return ENOMEM;
638         }
639
640         switch (ent_type) {
641         case HDB_LDB_ENT_TYPE_CLIENT:
642                 /* Can't happen */
643                 return EINVAL;
644         case HDB_LDB_ENT_TYPE_ANY:
645                 /* Can't happen */
646                 return EINVAL;
647         case HDB_LDB_ENT_TYPE_KRBTGT:
648                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
649                                          KRB5_TGS_NAME);
650                 break;
651         case HDB_LDB_ENT_TYPE_SERVER:
652                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
653                                          short_princ_talloc);
654                 break;
655         }
656
657         if (!filter) {
658                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
659                 return ENOMEM;
660         }
661
662         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
663
664         if (lret != LDB_SUCCESS) {
665                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
666                 return HDB_ERR_NOENTRY;
667         } else if (res->count == 0 || res->count > 1) {
668                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
669                 talloc_free(res);
670                 return HDB_ERR_NOENTRY;
671         }
672         talloc_steal(mem_ctx, res->msgs);
673         *pmsg = res->msgs;
674         talloc_free(res);
675         return 0;
676 }
677
678 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
679                                         TALLOC_CTX *mem_ctx,
680                                         const char *realm,
681                                         struct ldb_message ***pmsg)
682 {
683         int ret;
684         struct ldb_result *cross_ref_res;
685         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
686
687         ret = ldb_search_exp_fmt(ldb_ctx, mem_ctx, &cross_ref_res,
688                         partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs,
689                         "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
690                         realm, realm);
691
692         if (ret != LDB_SUCCESS) {
693                 DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx)));
694                 talloc_free(cross_ref_res);
695                 return HDB_ERR_NOENTRY;
696         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
697                 DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count));
698                 talloc_free(cross_ref_res);
699                 return HDB_ERR_NOENTRY;
700         }
701
702         if (pmsg) {
703                 *pmsg = cross_ref_res->msgs;
704                 talloc_steal(mem_ctx, cross_ref_res->msgs);
705         }
706         talloc_free(cross_ref_res);
707
708         return 0;
709 }
710
711
712 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
713 {
714         if (db->hdb_master_key_set) {
715                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
716                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
717                 return HDB_ERR_NOENTRY;
718         }               
719
720         return 0;
721 }
722
723 static krb5_error_code LDB_close(krb5_context context, HDB *db)
724 {
725         return 0;
726 }
727
728 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
729 {
730         return 0;
731 }
732
733 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
734 {
735         return 0;
736 }
737
738 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
739 {
740         return HDB_ERR_DB_INUSE;
741 }
742
743 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
744                                         TALLOC_CTX *mem_ctx, 
745                                         krb5_const_principal principal,
746                                         unsigned flags,
747                                         hdb_entry_ex *entry_ex) {
748         NTSTATUS nt_status;
749         char *principal_string;
750         krb5_error_code ret;
751         struct ldb_message **msg = NULL;
752         struct ldb_message **realm_ref_msg = NULL;
753
754         ret = krb5_unparse_name(context, principal, &principal_string);
755         
756         if (ret != 0) {
757                 return ret;
758         }
759         
760         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
761                                               mem_ctx, principal_string, 
762                                               &msg, &realm_ref_msg);
763         free(principal_string);
764         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
765                 return HDB_ERR_NOENTRY;
766         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
767                 return ENOMEM;
768         } else if (!NT_STATUS_IS_OK(nt_status)) {
769                 return EINVAL;
770         }
771         
772         ret = LDB_message2entry(context, db, mem_ctx, 
773                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
774                                 msg[0], realm_ref_msg[0], entry_ex);
775         return ret;
776 }
777
778 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
779                                         TALLOC_CTX *mem_ctx, 
780                                         krb5_const_principal principal,
781                                         unsigned flags,
782                                         hdb_entry_ex *entry_ex)
783 {
784         krb5_error_code ret;
785         struct ldb_message **msg = NULL;
786         struct ldb_message **realm_ref_msg = NULL;
787         struct ldb_dn *realm_dn;
788
789         krb5_principal alloc_principal = NULL;
790         if (principal->name.name_string.len != 2
791             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
792                 /* Not a krbtgt */
793                 return HDB_ERR_NOENTRY;
794         }
795
796         /* krbtgt case.  Either us or a trusted realm */
797         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
798                               mem_ctx, principal->name.name_string.val[1], &realm_ref_msg) == 0)) {
799                 /* us */                
800                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
801                  * is in our db, then direct the caller at our primary
802                  * krgtgt */
803                 
804                 const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg[0], "dnsRoot", NULL);
805                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
806                 if (!realm_fixed) {
807                         krb5_set_error_string(context, "strupper_talloc: out of memory");
808                         return ENOMEM;
809                 }
810                 
811                 ret = krb5_copy_principal(context, principal, &alloc_principal);
812                 if (ret) {
813                         return ret;
814                 }
815  
816                 free(alloc_principal->name.name_string.val[1]);
817                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
818                 talloc_free(realm_fixed);
819                 if (!alloc_principal->name.name_string.val[1]) {
820                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
821                         return ENOMEM;
822                 }
823                 principal = alloc_principal;
824                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
825         } else {
826                 /* we should lookup trusted domains */
827                 return HDB_ERR_NOENTRY;
828         }
829
830         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
831         
832         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
833                                    mem_ctx, 
834                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
835         
836         if (ret != 0) {
837                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
838                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
839                 return ret;
840         }
841
842         ret = LDB_message2entry(context, db, mem_ctx, 
843                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
844                                 msg[0], realm_ref_msg[0], entry_ex);
845         if (ret != 0) {
846                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
847         }
848         return ret;
849 }
850
851 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
852                                         TALLOC_CTX *mem_ctx, 
853                                         krb5_const_principal principal,
854                                         unsigned flags,
855                                         hdb_entry_ex *entry_ex)
856 {
857         krb5_error_code ret;
858         const char *realm;
859         struct ldb_message **msg = NULL;
860         struct ldb_message **realm_ref_msg = NULL;
861         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
862         if (principal->name.name_string.len >= 2) {
863                 /* 'normal server' case */
864                 int ldb_ret;
865                 NTSTATUS nt_status;
866                 struct ldb_dn *user_dn, *domain_dn;
867                 char *principal_string;
868                 
869                 ret = krb5_unparse_name_flags(context, principal, 
870                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
871                                               &principal_string);
872                 if (ret != 0) {
873                         return ret;
874                 }
875                 
876                 /* At this point we may find the host is known to be
877                  * in a different realm, so we should generate a
878                  * referral instead */
879                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
880                                                          mem_ctx, principal_string, 
881                                                          &user_dn, &domain_dn);
882                 free(principal_string);
883                 
884                 if (!NT_STATUS_IS_OK(nt_status)) {
885                         return HDB_ERR_NOENTRY;
886                 }
887                 
888                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
889                                           mem_ctx, user_dn, &msg, krb5_attrs);
890                 
891                 if (ldb_ret != 1) {
892                         return HDB_ERR_NOENTRY;
893                 }
894                 
895                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
896                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
897                                        "ncName=%s", ldb_dn_get_linearized(domain_dn));
898                 
899                 if (ldb_ret != 1) {
900                         return HDB_ERR_NOENTRY;
901                 }
902                 
903         } else {
904                 struct ldb_dn *realm_dn;
905                 /* server as client principal case, but we must not lookup userPrincipalNames */
906
907                 realm = krb5_principal_get_realm(context, principal);
908                 
909                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
910                                        mem_ctx, realm, &realm_ref_msg);
911                 if (ret != 0) {
912                         return HDB_ERR_NOENTRY;
913                 }
914                 
915                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
916                 
917                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
918                                            mem_ctx, 
919                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
920                 
921                 if (ret != 0) {
922                         return ret;
923                 }
924         }
925
926         ret = LDB_message2entry(context, db, mem_ctx, 
927                                 principal, HDB_LDB_ENT_TYPE_SERVER,
928                                 msg[0], realm_ref_msg[0], entry_ex);
929         if (ret != 0) {
930                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
931         }
932
933         return ret;
934 }
935                         
936 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
937                                  krb5_const_principal principal,
938                                  unsigned flags,
939                                  hdb_entry_ex *entry_ex)
940 {
941         krb5_error_code ret = HDB_ERR_NOENTRY;
942
943         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
944
945         if (!mem_ctx) {
946                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
947                 return ENOMEM;
948         }
949
950         if (flags & HDB_F_GET_CLIENT) {
951                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
952                 if (ret != HDB_ERR_NOENTRY) goto done;
953         }
954         if (flags & HDB_F_GET_SERVER) {
955                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
956                 if (ret != HDB_ERR_NOENTRY) goto done;
957                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
958                 if (ret != HDB_ERR_NOENTRY) goto done;
959         }
960         if (flags & HDB_F_GET_KRBTGT) {
961                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
962                 if (ret != HDB_ERR_NOENTRY) goto done;
963         }
964
965 done:
966         talloc_free(mem_ctx);
967         return ret;
968 }
969
970 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
971 {
972         return HDB_ERR_DB_INUSE;
973 }
974
975 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
976 {
977         return HDB_ERR_DB_INUSE;
978 }
979
980 struct hdb_ldb_seq {
981         struct ldb_context *ctx;
982         int index;
983         int count;
984         struct ldb_message **msgs;
985         struct ldb_message **realm_ref_msgs;
986 };
987
988 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
989 {
990         krb5_error_code ret;
991         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
992         TALLOC_CTX *mem_ctx;
993         hdb_entry_ex entry_ex;
994         memset(&entry_ex, '\0', sizeof(entry_ex));
995
996         if (!priv) {
997                 return HDB_ERR_NOENTRY;
998         }
999
1000         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
1001
1002         if (!mem_ctx) {
1003                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
1004                 return ENOMEM;
1005         }
1006
1007         if (priv->index < priv->count) {
1008                 ret = LDB_message2entry(context, db, mem_ctx, 
1009                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
1010                                         priv->msgs[priv->index++], 
1011                                         priv->realm_ref_msgs[0], entry);
1012         } else {
1013                 ret = HDB_ERR_NOENTRY;
1014         }
1015
1016         if (ret != 0) {
1017                 talloc_free(priv);
1018                 db->hdb_dbc = NULL;
1019         } else {
1020                 talloc_free(mem_ctx);
1021         }
1022
1023         return ret;
1024 }
1025
1026 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1027                                         hdb_entry_ex *entry)
1028 {
1029         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1030         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1031         char *realm;
1032         struct ldb_dn *realm_dn = NULL;
1033         struct ldb_result *res = NULL;
1034         struct ldb_message **realm_ref_msgs = NULL;
1035         krb5_error_code ret;
1036         TALLOC_CTX *mem_ctx;
1037         int lret;
1038
1039         if (priv) {
1040                 talloc_free(priv);
1041                 db->hdb_dbc = NULL;
1042         }
1043
1044         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1045         if (!priv) {
1046                 krb5_set_error_string(context, "talloc: out of memory");
1047                 return ENOMEM;
1048         }
1049
1050         priv->ctx = ldb_ctx;
1051         priv->index = 0;
1052         priv->msgs = NULL;
1053         priv->realm_ref_msgs = NULL;
1054         priv->count = 0;
1055
1056         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1057
1058         if (!mem_ctx) {
1059                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1060                 return ENOMEM;
1061         }
1062
1063         ret = krb5_get_default_realm(context, &realm);
1064         if (ret != 0) {
1065                 talloc_free(priv);
1066                 return ret;
1067         }
1068                 
1069         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1070                                mem_ctx, realm, &realm_ref_msgs);
1071
1072         free(realm);
1073
1074         if (ret != 0) {
1075                 talloc_free(priv);
1076                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1077                 return HDB_ERR_NOENTRY;
1078         }
1079
1080         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
1081
1082         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
1083
1084         lret = ldb_search(ldb_ctx, realm_dn,
1085                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
1086                                  krb5_attrs, &res);
1087
1088         if (lret != LDB_SUCCESS) {
1089                 talloc_free(priv);
1090                 return HDB_ERR_NOENTRY;
1091         }
1092
1093         priv->count = res->count;
1094         priv->msgs = talloc_steal(priv, res->msgs);
1095         talloc_free(res);
1096
1097         db->hdb_dbc = priv;
1098
1099         ret = LDB_seq(context, db, flags, entry);
1100
1101         if (ret != 0) {
1102                 talloc_free(priv);
1103                 db->hdb_dbc = NULL;
1104         } else {
1105                 talloc_free(mem_ctx);
1106         }
1107         return ret;
1108 }
1109
1110 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1111                                    hdb_entry_ex *entry)
1112 {
1113         return LDB_seq(context, db, flags, entry);
1114 }
1115
1116 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1117 {
1118         talloc_free(db);
1119         return 0;
1120 }
1121
1122 /* This interface is to be called by the KDC, which is expecting Samba
1123  * calling conventions.  It is also called by a wrapper
1124  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1125  * code */
1126
1127 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1128                             krb5_context context, struct HDB **db, const char *arg)
1129 {
1130         NTSTATUS nt_status;
1131         struct auth_session_info *session_info;
1132         *db = talloc(mem_ctx, HDB);
1133         if (!*db) {
1134                 krb5_set_error_string(context, "malloc: out of memory");
1135                 return NT_STATUS_NO_MEMORY;
1136         }
1137
1138         (*db)->hdb_master_key_set = 0;
1139         (*db)->hdb_db = NULL;
1140
1141         nt_status = auth_system_session_info(*db, &session_info);
1142         if (!NT_STATUS_IS_OK(nt_status)) {
1143                 return nt_status;
1144         }
1145         
1146         /* The idea here is very simple.  Using Kerberos to
1147          * authenticate the KDC to the LDAP server is higly likely to
1148          * be circular.
1149          *
1150          * In future we may set this up to use EXERNAL and SSL
1151          * certificates, for now it will almost certainly be NTLMSSP
1152         */
1153         
1154         cli_credentials_set_kerberos_state(session_info->credentials, 
1155                                            CRED_DONT_USE_KERBEROS);
1156
1157         /* Setup the link to LDB */
1158         (*db)->hdb_db = samdb_connect(*db, session_info);
1159         if ((*db)->hdb_db == NULL) {
1160                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1161                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1162         }
1163
1164         (*db)->hdb_dbc = NULL;
1165         (*db)->hdb_open = LDB_open;
1166         (*db)->hdb_close = LDB_close;
1167         (*db)->hdb_fetch = LDB_fetch;
1168         (*db)->hdb_store = LDB_store;
1169         (*db)->hdb_remove = LDB_remove;
1170         (*db)->hdb_firstkey = LDB_firstkey;
1171         (*db)->hdb_nextkey = LDB_nextkey;
1172         (*db)->hdb_lock = LDB_lock;
1173         (*db)->hdb_unlock = LDB_unlock;
1174         (*db)->hdb_rename = LDB_rename;
1175         /* we don't implement these, as we are not a lockable database */
1176         (*db)->hdb__get = NULL;
1177         (*db)->hdb__put = NULL;
1178         /* kadmin should not be used for deletes - use other tools instead */
1179         (*db)->hdb__del = NULL;
1180         (*db)->hdb_destroy = LDB_destroy;
1181
1182         return NT_STATUS_OK;
1183 }
1184
1185 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1186 {
1187         NTSTATUS nt_status;
1188         /* The global kdc_mem_ctx, Disgusting, ugly hack, but it means one less private hook */
1189         nt_status = kdc_hdb_ldb_create(kdc_mem_ctx, context, db, arg);
1190
1191         if (NT_STATUS_IS_OK(nt_status)) {
1192                 return 0;
1193         }
1194         return EINVAL;
1195 }