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