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