Don't use crossRef records to find our own domain
[metze/samba/wip.git] / source4 / kdc / hdb-samba4.c
1 /*
2  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3  * Copyright (c) 2004-2009, 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 "../lib/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 "librpc/gen_ndr/lsa.h"
49 #include "libcli/auth/libcli_auth.h"
50 #include "param/param.h"
51 #include "events/events.h"
52 #include "kdc/kdc.h"
53 #include "../lib/crypto/md4.h"
54
55 enum hdb_ldb_ent_type 
56 { HDB_SAMBA4_ENT_TYPE_CLIENT, HDB_SAMBA4_ENT_TYPE_SERVER, 
57   HDB_SAMBA4_ENT_TYPE_KRBTGT, HDB_SAMBA4_ENT_TYPE_TRUST, HDB_SAMBA4_ENT_TYPE_ANY };
58
59 enum trust_direction {
60         UNKNOWN = 0,
61         INBOUND = LSA_TRUST_DIRECTION_INBOUND, 
62         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
63 };
64
65 static const char *trust_attrs[] = {
66         "trustPartner",
67         "trustAuthIncoming",
68         "trustAuthOutgoing",
69         "whenCreated",
70         "msDS-SupportedEncryptionTypes",
71         "trustAttributes",
72         "trustDirection",
73         "trustType",
74         NULL
75 };
76
77 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
78 {
79     const char *tmp;
80     const char *gentime;
81     struct tm tm;
82
83     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
84     if (!gentime)
85         return default_val;
86
87     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
88     if (tmp == NULL) {
89             return default_val;
90     }
91
92     return timegm(&tm);
93 }
94
95 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
96 {
97         HDBFlags flags = int2HDBFlags(0);
98
99         /* we don't allow kadmin deletes */
100         flags.immutable = 1;
101
102         /* mark the principal as invalid to start with */
103         flags.invalid = 1;
104
105         flags.renewable = 1;
106
107         /* All accounts are servers, but this may be disabled again in the caller */
108         flags.server = 1;
109
110         /* Account types - clear the invalid bit if it turns out to be valid */
111         if (userAccountControl & UF_NORMAL_ACCOUNT) {
112                 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
113                         flags.client = 1;
114                 }
115                 flags.invalid = 0;
116         }
117         
118         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
119                 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
120                         flags.client = 1;
121                 }
122                 flags.invalid = 0;
123         }
124         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
125                 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
126                         flags.client = 1;
127                 }
128                 flags.invalid = 0;
129         }
130         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
131                 if (ent_type == HDB_SAMBA4_ENT_TYPE_CLIENT || ent_type == HDB_SAMBA4_ENT_TYPE_ANY) {
132                         flags.client = 1;
133                 }
134                 flags.invalid = 0;
135         }
136
137         /* Not permitted to act as a client if disabled */
138         if (userAccountControl & UF_ACCOUNTDISABLE) {
139                 flags.client = 0;
140         }
141         if (userAccountControl & UF_LOCKOUT) {
142                 flags.invalid = 1;
143         }
144 /*
145         if (userAccountControl & UF_PASSWORD_NOTREQD) {
146                 flags.invalid = 1;
147         }
148 */
149 /*
150         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
151 */
152         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
153                 flags.invalid = 1;
154         }
155
156 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
157
158 /*
159         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
160                 flags.invalid = 1;
161         }
162 */
163         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
164                 flags.require_hwauth = 1;
165         }
166         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
167                 flags.ok_as_delegate = 1;
168         }       
169         if (!(userAccountControl & UF_NOT_DELEGATED)) {
170                 flags.forwardable = 1;
171                 flags.proxiable = 1;
172         }
173
174         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
175                 flags.require_preauth = 0;
176         } else {
177                 flags.require_preauth = 1;
178
179         }
180         return flags;
181 }
182
183 static int hdb_ldb_destructor(struct hdb_ldb_private *p)
184 {
185     hdb_entry_ex *entry_ex = p->entry_ex;
186     free_hdb_entry(&entry_ex->entry);
187     return 0;
188 }
189
190 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
191 {
192         talloc_free(entry_ex->ctx);
193 }
194
195 static krb5_error_code LDB_message2entry_keys(krb5_context context,
196                                               struct smb_iconv_convenience *iconv_convenience,
197                                               TALLOC_CTX *mem_ctx,
198                                               struct ldb_message *msg,
199                                               unsigned int userAccountControl,
200                                               hdb_entry_ex *entry_ex)
201 {
202         krb5_error_code ret = 0;
203         enum ndr_err_code ndr_err;
204         struct samr_Password *hash;
205         const struct ldb_val *sc_val;
206         struct supplementalCredentialsBlob scb;
207         struct supplementalCredentialsPackage *scpk = NULL;
208         bool newer_keys = false;
209         struct package_PrimaryKerberosBlob _pkb;
210         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
211         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
212         uint32_t i;
213         uint32_t allocated_keys = 0;
214
215         entry_ex->entry.keys.val = NULL;
216         entry_ex->entry.keys.len = 0;
217
218         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
219
220         /* Get keys from the db */
221
222         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
223         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
224
225         /* unicodePwd for enctype 0x17 (23) if present */
226         if (hash) {
227                 allocated_keys++;
228         }
229
230         /* supplementalCredentials if present */
231         if (sc_val) {
232                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb,
233                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
234                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
235                         dump_data(0, sc_val->data, sc_val->length);
236                         ret = EINVAL;
237                         goto out;
238                 }
239
240                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
241                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
242                         ret = EINVAL;
243                         goto out;
244                 }
245
246                 for (i=0; i < scb.sub.num_packages; i++) {
247                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
248                                 scpk = &scb.sub.packages[i];
249                                 if (!scpk->data || !scpk->data[0]) {
250                                         scpk = NULL;
251                                         continue;
252                                 }
253                                 newer_keys = true;
254                                 break;
255                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
256                                 scpk = &scb.sub.packages[i];
257                                 if (!scpk->data || !scpk->data[0]) {
258                                         scpk = NULL;
259                                 }
260                                 /*
261                                  * we don't break here in hope to find
262                                  * a Kerberos-Newer-Keys package
263                                  */
264                         }
265                 }
266         }
267         /*
268          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
269          * of supplementalCredentials
270          */
271         if (scpk) {
272                 DATA_BLOB blob;
273
274                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
275                 if (!blob.data) {
276                         ret = ENOMEM;
277                         goto out;
278                 }
279
280                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
281                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb,
282                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
283                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
284                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
285                         krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
286                         ret = EINVAL;
287                         goto out;
288                 }
289
290                 if (newer_keys && _pkb.version != 4) {
291                         krb5_set_error_string(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
292                         krb5_warnx(context, "LDB_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
293                         ret = EINVAL;
294                         goto out;
295                 }
296
297                 if (!newer_keys && _pkb.version != 3) {
298                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
299                         krb5_warnx(context, "LDB_message2entry_keys: could not parse Primary:Kerberos not version 3");
300                         ret = EINVAL;
301                         goto out;
302                 }
303
304                 if (_pkb.version == 4) {
305                         pkb4 = &_pkb.ctr.ctr4;
306                         allocated_keys += pkb4->num_keys;
307                 } else if (_pkb.version == 3) {
308                         pkb3 = &_pkb.ctr.ctr3;
309                         allocated_keys += pkb3->num_keys;
310                 }
311         }
312
313         if (allocated_keys == 0) {
314                 /* oh, no password.  Apparently (comment in
315                  * hdb-ldap.c) this violates the ASN.1, but this
316                  * allows an entry with no keys (yet). */
317                 return 0;
318         }
319
320         /* allocate space to decode into */
321         entry_ex->entry.keys.len = 0;
322         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
323         if (entry_ex->entry.keys.val == NULL) {
324                 ret = ENOMEM;
325                 goto out;
326         }
327
328         if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
329                 Key key;
330
331                 key.mkvno = 0;
332                 key.salt = NULL; /* No salt for this enc type */
333
334                 ret = krb5_keyblock_init(context,
335                                          ENCTYPE_ARCFOUR_HMAC_MD5,
336                                          hash->hash, sizeof(hash->hash), 
337                                          &key.key);
338                 if (ret) {
339                         goto out;
340                 }
341
342                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
343                 entry_ex->entry.keys.len++;
344         }
345
346         if (pkb4) {
347                 for (i=0; i < pkb4->num_keys; i++) {
348                         bool use = true;
349                         Key key;
350
351                         if (!pkb4->keys[i].value) continue;
352
353                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
354                                 switch (pkb4->keys[i].keytype) {
355                                 case ENCTYPE_DES_CBC_CRC:
356                                 case ENCTYPE_DES_CBC_MD5:
357                                         break;
358                                 default:
359                                         use = false;
360                                         break;
361                                 }
362                         }
363
364                         if (!use) continue;
365
366                         key.mkvno = 0;
367                         key.salt = NULL;
368
369                         if (pkb4->salt.string) {
370                                 DATA_BLOB salt;
371
372                                 salt = data_blob_string_const(pkb4->salt.string);
373
374                                 key.salt = calloc(1, sizeof(*key.salt));
375                                 if (key.salt == NULL) {
376                                         ret = ENOMEM;
377                                         goto out;
378                                 }
379
380                                 key.salt->type = hdb_pw_salt;
381
382                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
383                                 if (ret) {
384                                         free(key.salt);
385                                         key.salt = NULL;
386                                         goto out;
387                                 }
388                         }
389
390                         /* TODO: maybe pass the iteration_count somehow... */
391
392                         ret = krb5_keyblock_init(context,
393                                                  pkb4->keys[i].keytype,
394                                                  pkb4->keys[i].value->data,
395                                                  pkb4->keys[i].value->length,
396                                                  &key.key);
397                         if (ret) {
398                                 if (key.salt) {
399                                         free_Salt(key.salt);
400                                         free(key.salt);
401                                         key.salt = NULL;
402                                 }
403                                 goto out;
404                         }
405
406                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
407                         entry_ex->entry.keys.len++;
408                 }
409         } else if (pkb3) {
410                 for (i=0; i < pkb3->num_keys; i++) {
411                         bool use = true;
412                         Key key;
413
414                         if (!pkb3->keys[i].value) continue;
415
416                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
417                                 switch (pkb3->keys[i].keytype) {
418                                 case ENCTYPE_DES_CBC_CRC:
419                                 case ENCTYPE_DES_CBC_MD5:
420                                         break;
421                                 default:
422                                         use = false;
423                                         break;
424                                 }
425                         }
426
427                         if (!use) continue;
428
429                         key.mkvno = 0;
430                         key.salt = NULL;
431
432                         if (pkb3->salt.string) {
433                                 DATA_BLOB salt;
434
435                                 salt = data_blob_string_const(pkb3->salt.string);
436
437                                 key.salt = calloc(1, sizeof(*key.salt));
438                                 if (key.salt == NULL) {
439                                         ret = ENOMEM;
440                                         goto out;
441                                 }
442
443                                 key.salt->type = hdb_pw_salt;
444
445                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
446                                 if (ret) {
447                                         free(key.salt);
448                                         key.salt = NULL;
449                                         goto out;
450                                 }
451                         }
452
453                         ret = krb5_keyblock_init(context,
454                                                  pkb3->keys[i].keytype,
455                                                  pkb3->keys[i].value->data,
456                                                  pkb3->keys[i].value->length,
457                                                  &key.key);
458                         if (ret) {
459                                 if (key.salt) {
460                                         free_Salt(key.salt);
461                                         free(key.salt);
462                                         key.salt = NULL;
463                                 }
464                                 goto out;
465                         }
466
467                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
468                         entry_ex->entry.keys.len++;
469                 }
470         }
471
472 out:
473         if (ret != 0) {
474                 entry_ex->entry.keys.len = 0;
475         }
476         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
477                 free(entry_ex->entry.keys.val);
478                 entry_ex->entry.keys.val = NULL;
479         }
480         return ret;
481 }
482
483 /*
484  * Construct an hdb_entry from a directory entry.
485  */
486 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
487                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
488                                          enum hdb_ldb_ent_type ent_type,
489                                          struct ldb_dn *realm_dn,
490                                          struct ldb_message *msg,
491                                          hdb_entry_ex *entry_ex)
492 {
493         unsigned int userAccountControl;
494         int i;
495         krb5_error_code ret = 0;
496         krb5_boolean is_computer = FALSE;
497         struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm");
498         char *realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
499
500         struct hdb_ldb_private *p;
501         NTTIME acct_expiry;
502
503         struct ldb_message_element *objectclasses;
504         struct ldb_val computer_val;
505         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
506         computer_val.data = discard_const_p(uint8_t,"computer");
507         computer_val.length = strlen((const char *)computer_val.data);
508         
509         if (!samAccountName) {
510                 krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
511                 ret = ENOENT;
512                 goto out;
513         }
514
515         objectclasses = ldb_msg_find_element(msg, "objectClass");
516         
517         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
518                 is_computer = TRUE;
519         }
520
521         memset(entry_ex, 0, sizeof(*entry_ex));
522
523         if (!realm) {
524                 krb5_set_error_string(context, "talloc_strdup: out of memory");
525                 ret = ENOMEM;
526                 goto out;
527         }
528                         
529         p = talloc(mem_ctx, struct hdb_ldb_private);
530         if (!p) {
531                 ret = ENOMEM;
532                 goto out;
533         }
534
535         p->entry_ex = entry_ex;
536         p->iconv_convenience = lp_iconv_convenience(lp_ctx);
537         p->lp_ctx = lp_ctx;
538         p->realm_dn = talloc_reference(p, realm_dn);
539         if (!p->realm_dn) {
540                 ret = ENOMEM;
541                 goto out;
542         }
543
544         talloc_set_destructor(p, hdb_ldb_destructor);
545
546         entry_ex->ctx = p;
547         entry_ex->free_entry = hdb_ldb_free_entry;
548
549         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
550
551         
552         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
553         if (ent_type == HDB_SAMBA4_ENT_TYPE_ANY && principal == NULL) {
554                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
555         } else {
556                 char *strdup_realm;
557                 ret = copy_Principal(principal, entry_ex->entry.principal);
558                 if (ret) {
559                         krb5_clear_error_string(context);
560                         goto out;
561                 }
562
563                 /* While we have copied the client principal, tests
564                  * show that Win2k3 returns the 'corrected' realm, not
565                  * the client-specified realm.  This code attempts to
566                  * replace the client principal's realm with the one
567                  * we determine from our records */
568                 
569                 /* this has to be with malloc() */
570                 strdup_realm = strdup(realm);
571                 if (!strdup_realm) {
572                         ret = ENOMEM;
573                         krb5_clear_error_string(context);
574                         goto out;
575                 }
576                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
577                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
578         }
579
580         /* First try and figure out the flags based on the userAccountControl */
581         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
582
583         if (ent_type == HDB_SAMBA4_ENT_TYPE_KRBTGT) {
584                 entry_ex->entry.flags.invalid = 0;
585                 entry_ex->entry.flags.server = 1;
586                 entry_ex->entry.flags.forwardable = 1;
587                 entry_ex->entry.flags.ok_as_delegate = 1;
588         }
589
590         /* Windows 2008 seems to enforce this (very sensible) rule by
591          * default - don't allow offline attacks on a user's password
592          * by asking for a ticket to them as a service (encrypted with
593          * their probably patheticly insecure password) */
594
595         if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
596                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
597                         entry_ex->entry.flags.server = 0;
598                 }
599         }
600
601         /* use 'whenCreated' */
602         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
603         /* use '???' */
604         entry_ex->entry.created_by.principal = NULL;
605
606         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
607         if (entry_ex->entry.modified_by == NULL) {
608                 krb5_set_error_string(context, "malloc: out of memory");
609                 ret = ENOMEM;
610                 goto out;
611         }
612
613         /* use 'whenChanged' */
614         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
615         /* use '???' */
616         entry_ex->entry.modified_by->principal = NULL;
617
618         entry_ex->entry.valid_start = NULL;
619
620         /* The account/password expiry only applies when the account is used as a
621          * client (ie password login), not when used as a server */
622         if (ent_type == HDB_SAMBA4_ENT_TYPE_KRBTGT || ent_type == HDB_SAMBA4_ENT_TYPE_SERVER) {
623                 /* Make very well sure we don't use this for a client,
624                  * it could bypass the above password restrictions */
625                 entry_ex->entry.flags.client = 0;
626                 entry_ex->entry.valid_end = NULL;
627                 entry_ex->entry.pw_end = NULL;
628
629         } else {
630                 NTTIME must_change_time
631                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
632                                                              realm_dn, msg);
633                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
634                         entry_ex->entry.pw_end = NULL;
635                 } else {
636                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
637                         if (entry_ex->entry.pw_end == NULL) {
638                                 ret = ENOMEM;
639                                 goto out;
640                         }
641                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
642                 }
643
644                 acct_expiry = samdb_result_account_expires(msg);
645                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
646                         entry_ex->entry.valid_end = NULL;
647                 } else {
648                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
649                         if (entry_ex->entry.valid_end == NULL) {
650                                 ret = ENOMEM;
651                                 goto out;
652                         }
653                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
654                 }
655         }
656                         
657         entry_ex->entry.max_life = NULL;
658
659         entry_ex->entry.max_renew = NULL;
660
661         entry_ex->entry.generation = NULL;
662
663         /* Get keys from the db */
664         ret = LDB_message2entry_keys(context, p->iconv_convenience, p, msg, userAccountControl, entry_ex);
665         if (ret) {
666                 /* Could be bougus data in the entry, or out of memory */
667                 goto out;
668         }
669
670         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
671         if (entry_ex->entry.etypes == NULL) {
672                 krb5_clear_error_string(context);
673                 ret = ENOMEM;
674                 goto out;
675         }
676         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
677         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
678         if (entry_ex->entry.etypes->val == NULL) {
679                 krb5_clear_error_string(context);
680                 ret = ENOMEM;
681                 goto out;
682         }
683         for (i=0; i < entry_ex->entry.etypes->len; i++) {
684                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
685         }
686
687
688         p->msg = talloc_steal(p, msg);
689         p->samdb = (struct ldb_context *)db->hdb_db;
690         
691 out:
692         if (ret != 0) {
693                 /* This doesn't free ent itself, that is for the eventual caller to do */
694                 hdb_free_entry(context, entry_ex);
695         } else {
696                 talloc_steal(db, entry_ex->ctx);
697         }
698
699         return ret;
700 }
701
702 /*
703  * Construct an hdb_entry from a directory entry.
704  */
705 static krb5_error_code LDB_trust_message2entry(krb5_context context, HDB *db, 
706                                                struct loadparm_context *lp_ctx,
707                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
708                                                enum trust_direction direction,
709                                                struct ldb_dn *realm_dn,
710                                                struct ldb_message *msg,
711                                                hdb_entry_ex *entry_ex)
712 {
713         
714         const char *dnsdomain;
715         char *realm;
716         char *strdup_realm;
717         DATA_BLOB password_utf16;
718         struct samr_Password password_hash;
719         const struct ldb_val *password_val;
720         struct trustAuthInOutBlob password_blob;
721         struct hdb_ldb_private *p;
722
723         enum ndr_err_code ndr_err;
724         int i, ret, trust_direction_flags;
725
726         p = talloc(mem_ctx, struct hdb_ldb_private);
727         if (!p) {
728                 ret = ENOMEM;
729                 goto out;
730         }
731
732         p->entry_ex = entry_ex;
733         p->iconv_convenience = lp_iconv_convenience(lp_ctx);
734         p->lp_ctx = lp_ctx;
735         p->realm_dn = realm_dn;
736
737         talloc_set_destructor(p, hdb_ldb_destructor);
738
739         entry_ex->ctx = p;
740         entry_ex->free_entry = hdb_ldb_free_entry;
741
742         /* use 'whenCreated' */
743         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
744         /* use '???' */
745         entry_ex->entry.created_by.principal = NULL;
746
747         entry_ex->entry.valid_start = NULL;
748
749         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
750
751         if (direction == INBOUND) {
752                 realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
753                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
754
755         } else { /* OUTBOUND */
756                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
757                 realm = strupper_talloc(mem_ctx, dnsdomain);
758                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
759         }
760
761         if (!password_val || !(trust_direction_flags & direction)) {
762                 ret = ENOENT;
763                 goto out;
764         }
765
766         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, p->iconv_convenience, &password_blob,
767                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
768         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
769                 ret = EINVAL;
770                 goto out;
771         }
772
773         entry_ex->entry.kvno = -1;
774         for (i=0; i < password_blob.count; i++) {
775                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
776                         entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
777                 }
778         }
779
780         for (i=0; i < password_blob.count; i++) {
781                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
782                         password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
783                                                          password_blob.current->array[i].AuthInfo.clear.size);
784                         /* In the future, generate all sorts of
785                          * hashes, but for now we can't safely convert
786                          * the random strings windows uses into
787                          * utf8 */
788
789                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
790                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
791                         break;
792                 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
793                         password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
794                         break;
795                 }
796         }
797         entry_ex->entry.keys.len = 0;
798         entry_ex->entry.keys.val = NULL;
799
800         if (i < password_blob.count) {
801                 Key key;
802                 /* Must have found a cleartext or MD4 password */
803                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
804
805                 key.mkvno = 0;
806                 key.salt = NULL; /* No salt for this enc type */
807
808                 if (entry_ex->entry.keys.val == NULL) {
809                         ret = ENOMEM;
810                         goto out;
811                 }
812                 
813                 ret = krb5_keyblock_init(context,
814                                          ENCTYPE_ARCFOUR_HMAC_MD5,
815                                          password_hash.hash, sizeof(password_hash.hash), 
816                                          &key.key);
817                 
818                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
819                 entry_ex->entry.keys.len++;
820         }
821                 
822         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
823
824         ret = copy_Principal(principal, entry_ex->entry.principal);
825         if (ret) {
826                 krb5_clear_error_string(context);
827                 goto out;
828         }
829         
830         /* While we have copied the client principal, tests
831          * show that Win2k3 returns the 'corrected' realm, not
832          * the client-specified realm.  This code attempts to
833          * replace the client principal's realm with the one
834          * we determine from our records */
835         
836         /* this has to be with malloc() */
837         strdup_realm = strdup(realm);
838         if (!strdup_realm) {
839                 ret = ENOMEM;
840                 krb5_clear_error_string(context);
841                 goto out;
842         }
843         free(*krb5_princ_realm(context, entry_ex->entry.principal));
844         krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
845         
846         entry_ex->entry.flags = int2HDBFlags(0);
847         entry_ex->entry.flags.immutable = 1;
848         entry_ex->entry.flags.invalid = 0;
849         entry_ex->entry.flags.server = 1;
850         entry_ex->entry.flags.require_preauth = 1;
851
852         entry_ex->entry.pw_end = NULL;
853                         
854         entry_ex->entry.max_life = NULL;
855
856         entry_ex->entry.max_renew = NULL;
857
858         entry_ex->entry.generation = NULL;
859
860         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
861         if (entry_ex->entry.etypes == NULL) {
862                 krb5_clear_error_string(context);
863                 ret = ENOMEM;
864                 goto out;
865         }
866         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
867         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
868         if (entry_ex->entry.etypes->val == NULL) {
869                 krb5_clear_error_string(context);
870                 ret = ENOMEM;
871                 goto out;
872         }
873         for (i=0; i < entry_ex->entry.etypes->len; i++) {
874                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
875         }
876
877
878         p->msg = talloc_steal(p, msg);
879         p->samdb = (struct ldb_context *)db->hdb_db;
880         
881 out:
882         if (ret != 0) {
883                 /* This doesn't free ent itself, that is for the eventual caller to do */
884                 hdb_free_entry(context, entry_ex);
885         } else {
886                 talloc_steal(db, entry_ex->ctx);
887         }
888
889         return ret;
890
891 }
892
893 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
894                                             TALLOC_CTX *mem_ctx,
895                                             krb5_const_principal principal,
896                                             enum hdb_ldb_ent_type ent_type,
897                                             struct ldb_dn *realm_dn,
898                                             struct ldb_message ***pmsg)
899 {
900         krb5_error_code ret;
901         int lret;
902         char *filter = NULL;
903         const char * const *princ_attrs = user_attrs;
904
905         char *short_princ;
906         char *short_princ_talloc;
907
908         struct ldb_result *res = NULL;
909
910         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
911
912         if (ret != 0) {
913                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
914                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
915                 return ret;
916         }
917
918         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
919         free(short_princ);
920         if (!short_princ_talloc) {
921                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
922                 return ENOMEM;
923         }
924
925         switch (ent_type) {
926         case HDB_SAMBA4_ENT_TYPE_CLIENT:
927         case HDB_SAMBA4_ENT_TYPE_TRUST:
928         case HDB_SAMBA4_ENT_TYPE_ANY:
929                 /* Can't happen */
930                 return EINVAL;
931         case HDB_SAMBA4_ENT_TYPE_KRBTGT:
932                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
933                                          KRB5_TGS_NAME);
934                 break;
935         case HDB_SAMBA4_ENT_TYPE_SERVER:
936                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
937                                          short_princ_talloc);
938                 break;
939         }
940
941         if (!filter) {
942                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
943                 return ENOMEM;
944         }
945
946         lret = ldb_search(ldb_ctx, mem_ctx, &res, realm_dn,
947                           LDB_SCOPE_SUBTREE, princ_attrs, "%s", filter);
948         if (lret != LDB_SUCCESS) {
949                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
950                 return HDB_ERR_NOENTRY;
951         } else if (res->count == 0 || res->count > 1) {
952                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
953                 talloc_free(res);
954                 return HDB_ERR_NOENTRY;
955         }
956         talloc_steal(mem_ctx, res->msgs);
957         *pmsg = res->msgs;
958         talloc_free(res);
959         return 0;
960 }
961
962 static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,                                      
963                                         TALLOC_CTX *mem_ctx,
964                                         const char *realm,
965                                         struct ldb_dn *realm_dn,
966                                         struct ldb_message ***pmsg)
967 {
968         int lret;
969         char *filter = NULL;
970         const char * const *attrs = trust_attrs;
971
972         struct ldb_result *res = NULL;
973         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
974
975         if (!filter) {
976                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
977                 return ENOMEM;
978         }
979
980         lret = ldb_search(ldb_ctx, mem_ctx, &res,
981                           ldb_get_default_basedn(ldb_ctx),
982                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
983         if (lret != LDB_SUCCESS) {
984                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
985                 return HDB_ERR_NOENTRY;
986         } else if (res->count == 0 || res->count > 1) {
987                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
988                 talloc_free(res);
989                 return HDB_ERR_NOENTRY;
990         }
991         talloc_steal(mem_ctx, res->msgs);
992         *pmsg = res->msgs;
993         talloc_free(res);
994         return 0;
995 }
996
997 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
998 {
999         if (db->hdb_master_key_set) {
1000                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
1001                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
1002                 return HDB_ERR_NOENTRY;
1003         }               
1004
1005         return 0;
1006 }
1007
1008 static krb5_error_code LDB_close(krb5_context context, HDB *db)
1009 {
1010         return 0;
1011 }
1012
1013 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
1014 {
1015         return 0;
1016 }
1017
1018 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
1019 {
1020         return 0;
1021 }
1022
1023 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
1024 {
1025         return HDB_ERR_DB_INUSE;
1026 }
1027
1028 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
1029                                         TALLOC_CTX *mem_ctx, 
1030                                         krb5_const_principal principal,
1031                                         unsigned flags,
1032                                         hdb_entry_ex *entry_ex) {
1033         NTSTATUS nt_status;
1034         char *principal_string;
1035         struct ldb_dn *realm_dn;
1036         krb5_error_code ret;
1037         struct ldb_message **msg = NULL;
1038
1039         ret = krb5_unparse_name(context, principal, &principal_string);
1040         
1041         if (ret != 0) {
1042                 return ret;
1043         }
1044         
1045         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
1046                                               mem_ctx, principal_string, 
1047                                               &realm_dn, &msg);
1048         free(principal_string);
1049         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1050                 return HDB_ERR_NOENTRY;
1051         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1052                 return ENOMEM;
1053         } else if (!NT_STATUS_IS_OK(nt_status)) {
1054                 return EINVAL;
1055         }
1056         
1057         ret = LDB_message2entry(context, db, mem_ctx, 
1058                                 principal, HDB_SAMBA4_ENT_TYPE_CLIENT,
1059                                 realm_dn, msg[0], entry_ex);
1060         return ret;
1061 }
1062
1063 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
1064                                         TALLOC_CTX *mem_ctx, 
1065                                         krb5_const_principal principal,
1066                                         unsigned flags,
1067                                         hdb_entry_ex *entry_ex)
1068 {
1069         krb5_error_code ret;
1070         struct ldb_message **msg = NULL;
1071         struct ldb_dn *realm_dn = ldb_get_default_basedn(db->hdb_db);
1072         const char *realm;
1073         struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context);
1074
1075         krb5_principal alloc_principal = NULL;
1076         if (principal->name.name_string.len != 2
1077             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1078                 /* Not a krbtgt */
1079                 return HDB_ERR_NOENTRY;
1080         }
1081
1082         /* krbtgt case.  Either us or a trusted realm */
1083
1084         if (lp_is_my_domain_or_realm(lp_ctx, principal->realm)
1085             && lp_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1086                 /* us */                
1087                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1088                  * is in our db, then direct the caller at our primary
1089                  * krbtgt */
1090                 
1091                 char *realm_fixed = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
1092                 if (!realm_fixed) {
1093                         krb5_set_error_string(context, "strupper_talloc: out of memory");
1094                         return ENOMEM;
1095                 }
1096                 
1097                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1098                 if (ret) {
1099                         return ret;
1100                 }
1101  
1102                 free(alloc_principal->name.name_string.val[1]);
1103                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1104                 talloc_free(realm_fixed);
1105                 if (!alloc_principal->name.name_string.val[1]) {
1106                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
1107                         return ENOMEM;
1108                 }
1109                 principal = alloc_principal;
1110
1111                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1112                                            mem_ctx, 
1113                                            principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, realm_dn, &msg);
1114                 
1115                 if (ret != 0) {
1116                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1117                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1118                         return ret;
1119                 }
1120                 
1121                 ret = LDB_message2entry(context, db, mem_ctx, 
1122                                         principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, 
1123                                         realm_dn, msg[0], entry_ex);
1124                 if (ret != 0) {
1125                         krb5_warnx(context, "LDB_fetch: self krbtgt message2entry failed");     
1126                 }
1127                 return ret;
1128
1129         } else {
1130                 enum trust_direction direction = UNKNOWN;
1131
1132                 /* Either an inbound or outbound trust */
1133
1134                 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1135                         /* look for inbound trust */
1136                         direction = INBOUND;
1137                         realm = principal->name.name_string.val[1];
1138                 }
1139
1140                 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1141                         /* look for outbound trust */
1142                         direction = OUTBOUND;
1143                         realm = principal->realm;
1144                 }
1145
1146                 /* Trusted domains are under CN=system */
1147                 
1148                 ret = LDB_lookup_trust(context, (struct ldb_context *)db->hdb_db, 
1149                                        mem_ctx, 
1150                                        realm, realm_dn, &msg);
1151                 
1152                 if (ret != 0) {
1153                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1154                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1155                         return ret;
1156                 }
1157                 
1158                 ret = LDB_trust_message2entry(context, db, lp_ctx, mem_ctx, 
1159                                               principal, direction, 
1160                                               realm_dn, msg[0], entry_ex);
1161                 if (ret != 0) {
1162                         krb5_warnx(context, "LDB_fetch: trust_message2entry failed");   
1163                 }
1164                 return ret;
1165
1166                 
1167                 /* we should lookup trusted domains */
1168                 return HDB_ERR_NOENTRY;
1169         }
1170
1171 }
1172
1173 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
1174                                         TALLOC_CTX *mem_ctx, 
1175                                         krb5_const_principal principal,
1176                                         unsigned flags,
1177                                         hdb_entry_ex *entry_ex)
1178 {
1179         krb5_error_code ret;
1180         const char *realm;
1181         struct ldb_message **msg = NULL;
1182         struct ldb_dn *realm_dn;
1183         if (principal->name.name_string.len >= 2) {
1184                 /* 'normal server' case */
1185                 int ldb_ret;
1186                 NTSTATUS nt_status;
1187                 struct ldb_dn *user_dn;
1188                 char *principal_string;
1189                 
1190                 ret = krb5_unparse_name_flags(context, principal, 
1191                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
1192                                               &principal_string);
1193                 if (ret != 0) {
1194                         return ret;
1195                 }
1196                 
1197                 /* At this point we may find the host is known to be
1198                  * in a different realm, so we should generate a
1199                  * referral instead */
1200                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
1201                                                          mem_ctx, principal_string, 
1202                                                          &user_dn, &realm_dn);
1203                 free(principal_string);
1204                 
1205                 if (!NT_STATUS_IS_OK(nt_status)) {
1206                         return HDB_ERR_NOENTRY;
1207                 }
1208                 
1209                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
1210                                           mem_ctx, user_dn, &msg, user_attrs);
1211                 
1212                 if (ldb_ret != 1) {
1213                         return HDB_ERR_NOENTRY;
1214                 }
1215                 
1216         } else {
1217                 /* server as client principal case, but we must not lookup userPrincipalNames */
1218                 realm_dn = ldb_get_default_basedn((struct ldb_context *)db->hdb_db);
1219                 realm = krb5_principal_get_realm(context, principal);
1220                 
1221                 /* Check if it is our realm, otherwise give referall */
1222
1223                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1224                                            mem_ctx, 
1225                                            principal, HDB_SAMBA4_ENT_TYPE_SERVER, realm_dn, &msg);
1226                 
1227                 if (ret != 0) {
1228                         return ret;
1229                 }
1230         }
1231
1232         ret = LDB_message2entry(context, db, mem_ctx, 
1233                                 principal, HDB_SAMBA4_ENT_TYPE_SERVER,
1234                                 realm_dn, msg[0], entry_ex);
1235         if (ret != 0) {
1236                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1237         }
1238
1239         return ret;
1240 }
1241                         
1242 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
1243                                  krb5_const_principal principal,
1244                                  unsigned flags,
1245                                  hdb_entry_ex *entry_ex)
1246 {
1247         krb5_error_code ret = HDB_ERR_NOENTRY;
1248
1249         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
1250
1251         if (!mem_ctx) {
1252                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
1253                 return ENOMEM;
1254         }
1255
1256         if (flags & HDB_F_GET_CLIENT) {
1257                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
1258                 if (ret != HDB_ERR_NOENTRY) goto done;
1259         }
1260         if (flags & HDB_F_GET_SERVER) {
1261                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1262                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1263                 if (ret != HDB_ERR_NOENTRY) goto done;
1264
1265                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1266                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
1267                 if (ret != HDB_ERR_NOENTRY) goto done;
1268         }
1269         if (flags & HDB_F_GET_KRBTGT) {
1270                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1271                 if (ret != HDB_ERR_NOENTRY) goto done;
1272         }
1273
1274 done:
1275         talloc_free(mem_ctx);
1276         return ret;
1277 }
1278
1279 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1280 {
1281         return HDB_ERR_DB_INUSE;
1282 }
1283
1284 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1285 {
1286         return HDB_ERR_DB_INUSE;
1287 }
1288
1289 struct hdb_ldb_seq {
1290         struct ldb_context *ctx;
1291         int index;
1292         int count;
1293         struct ldb_message **msgs;
1294         struct ldb_dn *realm_dn;
1295 };
1296
1297 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1298 {
1299         krb5_error_code ret;
1300         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1301         TALLOC_CTX *mem_ctx;
1302         hdb_entry_ex entry_ex;
1303         memset(&entry_ex, '\0', sizeof(entry_ex));
1304
1305         if (!priv) {
1306                 return HDB_ERR_NOENTRY;
1307         }
1308
1309         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
1310
1311         if (!mem_ctx) {
1312                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
1313                 return ENOMEM;
1314         }
1315
1316         if (priv->index < priv->count) {
1317                 ret = LDB_message2entry(context, db, mem_ctx, 
1318                                         NULL, HDB_SAMBA4_ENT_TYPE_ANY, 
1319                                         priv->realm_dn, priv->msgs[priv->index++], entry);
1320         } else {
1321                 ret = HDB_ERR_NOENTRY;
1322         }
1323
1324         if (ret != 0) {
1325                 talloc_free(priv);
1326                 db->hdb_dbc = NULL;
1327         } else {
1328                 talloc_free(mem_ctx);
1329         }
1330
1331         return ret;
1332 }
1333
1334 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1335                                         hdb_entry_ex *entry)
1336 {
1337         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1338         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1339         char *realm;
1340         struct ldb_result *res = NULL;
1341         krb5_error_code ret;
1342         TALLOC_CTX *mem_ctx;
1343         int lret;
1344
1345         if (priv) {
1346                 talloc_free(priv);
1347                 db->hdb_dbc = NULL;
1348         }
1349
1350         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1351         if (!priv) {
1352                 krb5_set_error_string(context, "talloc: out of memory");
1353                 return ENOMEM;
1354         }
1355
1356         priv->ctx = ldb_ctx;
1357         priv->index = 0;
1358         priv->msgs = NULL;
1359         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1360         priv->count = 0;
1361
1362         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1363
1364         if (!mem_ctx) {
1365                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1366                 return ENOMEM;
1367         }
1368
1369         ret = krb5_get_default_realm(context, &realm);
1370         if (ret != 0) {
1371                 talloc_free(priv);
1372                 return ret;
1373         }
1374                 
1375         lret = ldb_search(ldb_ctx, priv, &res,
1376                           priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1377                           "(objectClass=user)");
1378
1379         if (lret != LDB_SUCCESS) {
1380                 talloc_free(priv);
1381                 return HDB_ERR_NOENTRY;
1382         }
1383
1384         priv->count = res->count;
1385         priv->msgs = talloc_steal(priv, res->msgs);
1386         talloc_free(res);
1387
1388         db->hdb_dbc = priv;
1389
1390         ret = LDB_seq(context, db, flags, entry);
1391
1392         if (ret != 0) {
1393                 talloc_free(priv);
1394                 db->hdb_dbc = NULL;
1395         } else {
1396                 talloc_free(mem_ctx);
1397         }
1398         return ret;
1399 }
1400
1401 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1402                                    hdb_entry_ex *entry)
1403 {
1404         return LDB_seq(context, db, flags, entry);
1405 }
1406
1407 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1408 {
1409         talloc_free(db);
1410         return 0;
1411 }
1412
1413 /* This interface is to be called by the KDC, which is expecting Samba
1414  * calling conventions.  It is also called by a wrapper
1415  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1416  * code */
1417
1418 NTSTATUS kdc_hdb_samba4_create(TALLOC_CTX *mem_ctx, 
1419                             struct tevent_context *ev_ctx, 
1420                             struct loadparm_context *lp_ctx,
1421                             krb5_context context, struct HDB **db, const char *arg)
1422 {
1423         NTSTATUS nt_status;
1424         struct auth_session_info *session_info;
1425         *db = talloc(mem_ctx, HDB);
1426         if (!*db) {
1427                 krb5_set_error_string(context, "malloc: out of memory");
1428                 return NT_STATUS_NO_MEMORY;
1429         }
1430
1431         (*db)->hdb_master_key_set = 0;
1432         (*db)->hdb_db = NULL;
1433
1434         nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1435         if (!NT_STATUS_IS_OK(nt_status)) {
1436                 return nt_status;
1437         }
1438         
1439         /* The idea here is very simple.  Using Kerberos to
1440          * authenticate the KDC to the LDAP server is higly likely to
1441          * be circular.
1442          *
1443          * In future we may set this up to use EXERNAL and SSL
1444          * certificates, for now it will almost certainly be NTLMSSP
1445         */
1446         
1447         cli_credentials_set_kerberos_state(session_info->credentials, 
1448                                            CRED_DONT_USE_KERBEROS);
1449
1450         /* Setup the link to LDB */
1451         (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1452         if ((*db)->hdb_db == NULL) {
1453                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1454                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1455         }
1456
1457         (*db)->hdb_dbc = NULL;
1458         (*db)->hdb_open = LDB_open;
1459         (*db)->hdb_close = LDB_close;
1460         (*db)->hdb_fetch = LDB_fetch;
1461         (*db)->hdb_store = LDB_store;
1462         (*db)->hdb_remove = LDB_remove;
1463         (*db)->hdb_firstkey = LDB_firstkey;
1464         (*db)->hdb_nextkey = LDB_nextkey;
1465         (*db)->hdb_lock = LDB_lock;
1466         (*db)->hdb_unlock = LDB_unlock;
1467         (*db)->hdb_rename = LDB_rename;
1468         /* we don't implement these, as we are not a lockable database */
1469         (*db)->hdb__get = NULL;
1470         (*db)->hdb__put = NULL;
1471         /* kadmin should not be used for deletes - use other tools instead */
1472         (*db)->hdb__del = NULL;
1473         (*db)->hdb_destroy = LDB_destroy;
1474
1475         return NT_STATUS_OK;
1476 }
1477
1478 krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg)
1479 {
1480         NTSTATUS nt_status;
1481         /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1482         nt_status = kdc_hdb_samba4_create(kdc_mem_ctx, kdc_ev_ctx, kdc_lp_ctx,
1483                                           context, db, arg);
1484
1485         if (NT_STATUS_IS_OK(nt_status)) {
1486                 return 0;
1487         }
1488         return EINVAL;
1489 }