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