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