Allow the PAC to be passed along during cross-realm authentication
[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         uint32_t kvno;
721
722         private = talloc(mem_ctx, struct hdb_ldb_private);
723         if (!private) {
724                 ret = ENOMEM;
725                 goto out;
726         }
727
728         private->entry_ex = entry_ex;
729         private->iconv_convenience = lp_iconv_convenience(lp_ctx);
730         private->netbios_name = lp_netbios_name(lp_ctx);
731
732         talloc_set_destructor(private, hdb_ldb_destructor);
733
734         entry_ex->ctx = private;
735         entry_ex->free_entry = hdb_ldb_free_entry;
736
737         /* use 'whenCreated' */
738         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
739         /* use '???' */
740         entry_ex->entry.created_by.principal = NULL;
741
742         entry_ex->entry.valid_start = NULL;
743
744         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
745
746         if (direction == INBOUND) {
747                 realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
748                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
749
750         } else { /* OUTBOUND */
751                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
752                 realm = strupper_talloc(mem_ctx, dnsdomain);
753                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
754         }
755
756         if (!password_val || !(trust_direction_flags & direction)) {
757                 ret = ENOENT;
758                 goto out;
759         }
760
761         ndr_err = ndr_pull_struct_blob_all(password_val, mem_ctx, private->iconv_convenience, &password_blob,
762                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
763         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
764                 ret = EINVAL;
765                 goto out;
766         }
767
768         for (i=0; i < password_blob.count; i++) {
769                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
770                         entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
771                 }
772         }
773
774         for (i=0; i < password_blob.count; i++) {
775                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
776                         password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
777                                                          password_blob.current->array[i].AuthInfo.clear.size);
778                         /* In the future, generate all sorts of
779                          * hashes, but for now we can't safely convert
780                          * the random strings windows uses into
781                          * utf8 */
782
783                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
784                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
785                         break;
786                 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
787                         password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
788                         break;
789                 }
790         }
791         entry_ex->entry.keys.len = 0;
792         entry_ex->entry.keys.val = NULL;
793
794         if (i < password_blob.count) {
795                 Key key;
796                 /* Must have found a cleartext or MD4 password */
797                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
798
799                 key.mkvno = 0;
800                 key.salt = NULL; /* No salt for this enc type */
801
802                 if (entry_ex->entry.keys.val == NULL) {
803                         ret = ENOMEM;
804                         goto out;
805                 }
806                 
807                 ret = krb5_keyblock_init(context,
808                                          ENCTYPE_ARCFOUR_HMAC_MD5,
809                                          password_hash.hash, sizeof(password_hash.hash), 
810                                          &key.key);
811                 
812                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
813                 entry_ex->entry.keys.len++;
814         }
815                 
816         ret = copy_Principal(principal, entry_ex->entry.principal);
817         if (ret) {
818                 krb5_clear_error_string(context);
819                 goto out;
820         }
821         
822         /* While we have copied the client principal, tests
823          * show that Win2k3 returns the 'corrected' realm, not
824          * the client-specified realm.  This code attempts to
825          * replace the client principal's realm with the one
826          * we determine from our records */
827         
828         /* this has to be with malloc() */
829         strdup_realm = strdup(realm);
830         if (!strdup_realm) {
831                 ret = ENOMEM;
832                 krb5_clear_error_string(context);
833                 goto out;
834         }
835         free(*krb5_princ_realm(context, entry_ex->entry.principal));
836         krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
837         
838         entry_ex->entry.flags = int2HDBFlags(0);
839         entry_ex->entry.flags.immutable = 1;
840         entry_ex->entry.flags.invalid = 0;
841         entry_ex->entry.flags.server = 1;
842         entry_ex->entry.flags.require_preauth = 1;
843
844         entry_ex->entry.pw_end = NULL;
845                         
846         entry_ex->entry.max_life = NULL;
847
848         entry_ex->entry.max_renew = NULL;
849
850         entry_ex->entry.generation = NULL;
851
852         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
853         if (entry_ex->entry.etypes == NULL) {
854                 krb5_clear_error_string(context);
855                 ret = ENOMEM;
856                 goto out;
857         }
858         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
859         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
860         if (entry_ex->entry.etypes->val == NULL) {
861                 krb5_clear_error_string(context);
862                 ret = ENOMEM;
863                 goto out;
864         }
865         for (i=0; i < entry_ex->entry.etypes->len; i++) {
866                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
867         }
868
869
870         private->msg = talloc_steal(private, msg);
871         private->realm_ref_msg = NULL;
872         private->samdb = (struct ldb_context *)db->hdb_db;
873         
874 out:
875         if (ret != 0) {
876                 /* This doesn't free ent itself, that is for the eventual caller to do */
877                 hdb_free_entry(context, entry_ex);
878         } else {
879                 talloc_steal(db, entry_ex->ctx);
880         }
881
882         return ret;
883
884 }
885
886 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
887                                             TALLOC_CTX *mem_ctx,
888                                             krb5_const_principal principal,
889                                             enum hdb_ldb_ent_type ent_type,
890                                             struct ldb_dn *realm_dn,
891                                             struct ldb_message ***pmsg)
892 {
893         krb5_error_code ret;
894         int lret;
895         char *filter = NULL;
896         const char * const *princ_attrs = user_attrs;
897
898         char *short_princ;
899         char *short_princ_talloc;
900
901         struct ldb_result *res = NULL;
902
903         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
904
905         if (ret != 0) {
906                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
907                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
908                 return ret;
909         }
910
911         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
912         free(short_princ);
913         if (!short_princ_talloc) {
914                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
915                 return ENOMEM;
916         }
917
918         switch (ent_type) {
919         case HDB_SAMBA4_ENT_TYPE_CLIENT:
920         case HDB_SAMBA4_ENT_TYPE_TRUST:
921         case HDB_SAMBA4_ENT_TYPE_ANY:
922                 /* Can't happen */
923                 return EINVAL;
924         case HDB_SAMBA4_ENT_TYPE_KRBTGT:
925                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
926                                          KRB5_TGS_NAME);
927                 break;
928         case HDB_SAMBA4_ENT_TYPE_SERVER:
929                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
930                                          short_princ_talloc);
931                 break;
932         }
933
934         if (!filter) {
935                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
936                 return ENOMEM;
937         }
938
939         lret = ldb_search(ldb_ctx, mem_ctx, &res, realm_dn,
940                           LDB_SCOPE_SUBTREE, princ_attrs, "%s", filter);
941         if (lret != LDB_SUCCESS) {
942                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
943                 return HDB_ERR_NOENTRY;
944         } else if (res->count == 0 || res->count > 1) {
945                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
946                 talloc_free(res);
947                 return HDB_ERR_NOENTRY;
948         }
949         talloc_steal(mem_ctx, res->msgs);
950         *pmsg = res->msgs;
951         talloc_free(res);
952         return 0;
953 }
954
955 static krb5_error_code LDB_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,                                      
956                                         TALLOC_CTX *mem_ctx,
957                                         const char *realm,
958                                         struct ldb_dn *realm_dn,
959                                         struct ldb_message ***pmsg)
960 {
961         int lret;
962         char *filter = NULL;
963         const char * const *attrs = trust_attrs;
964
965         struct ldb_result *res = NULL;
966         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
967
968         if (!filter) {
969                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
970                 return ENOMEM;
971         }
972
973         lret = ldb_search(ldb_ctx, mem_ctx, &res,
974                           ldb_get_default_basedn(ldb_ctx),
975                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
976         if (lret != LDB_SUCCESS) {
977                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
978                 return HDB_ERR_NOENTRY;
979         } else if (res->count == 0 || res->count > 1) {
980                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
981                 talloc_free(res);
982                 return HDB_ERR_NOENTRY;
983         }
984         talloc_steal(mem_ctx, res->msgs);
985         *pmsg = res->msgs;
986         talloc_free(res);
987         return 0;
988 }
989
990 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
991                                         TALLOC_CTX *mem_ctx,
992                                         const char *realm,
993                                         struct ldb_message ***pmsg)
994 {
995         int ret;
996         struct ldb_result *cross_ref_res;
997         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
998
999         ret = ldb_search(ldb_ctx, mem_ctx, &cross_ref_res,
1000                         partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs,
1001                         "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
1002                         realm, realm);
1003
1004         if (ret != LDB_SUCCESS) {
1005                 DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx)));
1006                 talloc_free(cross_ref_res);
1007                 return HDB_ERR_NOENTRY;
1008         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
1009                 DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count));
1010                 talloc_free(cross_ref_res);
1011                 return HDB_ERR_NOENTRY;
1012         }
1013
1014         if (pmsg) {
1015                 *pmsg = cross_ref_res->msgs;
1016                 talloc_steal(mem_ctx, cross_ref_res->msgs);
1017         }
1018         talloc_free(cross_ref_res);
1019
1020         return 0;
1021 }
1022
1023
1024 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
1025 {
1026         if (db->hdb_master_key_set) {
1027                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
1028                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
1029                 return HDB_ERR_NOENTRY;
1030         }               
1031
1032         return 0;
1033 }
1034
1035 static krb5_error_code LDB_close(krb5_context context, HDB *db)
1036 {
1037         return 0;
1038 }
1039
1040 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
1041 {
1042         return 0;
1043 }
1044
1045 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
1046 {
1047         return 0;
1048 }
1049
1050 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
1051 {
1052         return HDB_ERR_DB_INUSE;
1053 }
1054
1055 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
1056                                         TALLOC_CTX *mem_ctx, 
1057                                         krb5_const_principal principal,
1058                                         unsigned flags,
1059                                         hdb_entry_ex *entry_ex) {
1060         NTSTATUS nt_status;
1061         char *principal_string;
1062         krb5_error_code ret;
1063         struct ldb_message **msg = NULL;
1064         struct ldb_message **realm_ref_msg = NULL;
1065
1066         ret = krb5_unparse_name(context, principal, &principal_string);
1067         
1068         if (ret != 0) {
1069                 return ret;
1070         }
1071         
1072         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
1073                                               mem_ctx, principal_string, 
1074                                               &msg, &realm_ref_msg);
1075         free(principal_string);
1076         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1077                 return HDB_ERR_NOENTRY;
1078         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1079                 return ENOMEM;
1080         } else if (!NT_STATUS_IS_OK(nt_status)) {
1081                 return EINVAL;
1082         }
1083         
1084         ret = LDB_message2entry(context, db, mem_ctx, 
1085                                 principal, HDB_SAMBA4_ENT_TYPE_CLIENT,
1086                                 msg[0], realm_ref_msg[0], entry_ex);
1087         return ret;
1088 }
1089
1090 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
1091                                         TALLOC_CTX *mem_ctx, 
1092                                         krb5_const_principal principal,
1093                                         unsigned flags,
1094                                         hdb_entry_ex *entry_ex)
1095 {
1096         krb5_error_code ret;
1097         struct ldb_message **msg = NULL;
1098         struct ldb_message **realm_ref_msg_1 = NULL;
1099         struct ldb_message **realm_ref_msg_2 = NULL;
1100         struct ldb_dn *realm_dn;
1101         const char *realm;
1102
1103         krb5_principal alloc_principal = NULL;
1104         if (principal->name.name_string.len != 2
1105             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1106                 /* Not a krbtgt */
1107                 return HDB_ERR_NOENTRY;
1108         }
1109
1110         /* krbtgt case.  Either us or a trusted realm */
1111
1112         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
1113                               mem_ctx, principal->realm, &realm_ref_msg_1) == 0)
1114             && (LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
1115                                  mem_ctx, principal->name.name_string.val[1], &realm_ref_msg_2) == 0)
1116             && (ldb_dn_compare(realm_ref_msg_1[0]->dn, realm_ref_msg_1[0]->dn) == 0)) {
1117                 /* us */                
1118                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1119                  * is in our db, then direct the caller at our primary
1120                  * krbtgt */
1121                 
1122                 const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg_1[0], "dnsRoot", NULL);
1123                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
1124                 if (!realm_fixed) {
1125                         krb5_set_error_string(context, "strupper_talloc: out of memory");
1126                         return ENOMEM;
1127                 }
1128                 
1129                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1130                 if (ret) {
1131                         return ret;
1132                 }
1133  
1134                 free(alloc_principal->name.name_string.val[1]);
1135                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1136                 talloc_free(realm_fixed);
1137                 if (!alloc_principal->name.name_string.val[1]) {
1138                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
1139                         return ENOMEM;
1140                 }
1141                 principal = alloc_principal;
1142                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg_1[0], "nCName", NULL);
1143                 
1144                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1145                                            mem_ctx, 
1146                                            principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, realm_dn, &msg);
1147                 
1148                 if (ret != 0) {
1149                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1150                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1151                         return ret;
1152                 }
1153                 
1154                 ret = LDB_message2entry(context, db, mem_ctx, 
1155                                         principal, HDB_SAMBA4_ENT_TYPE_KRBTGT, 
1156                                         msg[0], realm_ref_msg_1[0], entry_ex);
1157                 if (ret != 0) {
1158                         krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1159                 }
1160                 return ret;
1161
1162         } else {
1163                 enum trust_direction direction = UNKNOWN;
1164
1165                 struct loadparm_context *lp_ctx = talloc_get_type(ldb_get_opaque(db->hdb_db, "loadparm"), struct loadparm_context);
1166                 /* Either an inbound or outbound trust */
1167
1168                 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1169                         /* look for inbound trust */
1170                         direction = INBOUND;
1171                         realm = principal->name.name_string.val[1];
1172                 }
1173
1174                 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1175                         /* look for outbound trust */
1176                         direction = OUTBOUND;
1177                         realm = principal->realm;
1178                 }
1179
1180                 /* Trusted domains are under CN=system */
1181                 
1182                 ret = LDB_lookup_trust(context, (struct ldb_context *)db->hdb_db, 
1183                                        mem_ctx, 
1184                                        realm, realm_dn, &msg);
1185                 
1186                 if (ret != 0) {
1187                         krb5_warnx(context, "LDB_fetch: could not find principal in DB");
1188                         krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
1189                         return ret;
1190                 }
1191                 
1192                 ret = LDB_trust_message2entry(context, db, lp_ctx, mem_ctx, 
1193                                               principal, direction, 
1194                                               msg[0], entry_ex);
1195                 if (ret != 0) {
1196                         krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1197                 }
1198                 return ret;
1199
1200                 
1201                 /* we should lookup trusted domains */
1202                 return HDB_ERR_NOENTRY;
1203         }
1204
1205 }
1206
1207 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
1208                                         TALLOC_CTX *mem_ctx, 
1209                                         krb5_const_principal principal,
1210                                         unsigned flags,
1211                                         hdb_entry_ex *entry_ex)
1212 {
1213         krb5_error_code ret;
1214         const char *realm;
1215         struct ldb_message **msg = NULL;
1216         struct ldb_message **realm_ref_msg = NULL;
1217         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
1218         if (principal->name.name_string.len >= 2) {
1219                 /* 'normal server' case */
1220                 int ldb_ret;
1221                 NTSTATUS nt_status;
1222                 struct ldb_dn *user_dn, *domain_dn;
1223                 char *principal_string;
1224                 
1225                 ret = krb5_unparse_name_flags(context, principal, 
1226                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
1227                                               &principal_string);
1228                 if (ret != 0) {
1229                         return ret;
1230                 }
1231                 
1232                 /* At this point we may find the host is known to be
1233                  * in a different realm, so we should generate a
1234                  * referral instead */
1235                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
1236                                                          mem_ctx, principal_string, 
1237                                                          &user_dn, &domain_dn);
1238                 free(principal_string);
1239                 
1240                 if (!NT_STATUS_IS_OK(nt_status)) {
1241                         return HDB_ERR_NOENTRY;
1242                 }
1243                 
1244                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
1245                                           mem_ctx, user_dn, &msg, user_attrs);
1246                 
1247                 if (ldb_ret != 1) {
1248                         return HDB_ERR_NOENTRY;
1249                 }
1250                 
1251                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
1252                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
1253                                        "ncName=%s", ldb_dn_get_linearized(domain_dn));
1254                 
1255                 if (ldb_ret != 1) {
1256                         return HDB_ERR_NOENTRY;
1257                 }
1258                 
1259         } else {
1260                 struct ldb_dn *realm_dn;
1261                 /* server as client principal case, but we must not lookup userPrincipalNames */
1262
1263                 realm = krb5_principal_get_realm(context, principal);
1264                 
1265                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1266                                        mem_ctx, realm, &realm_ref_msg);
1267                 if (ret != 0) {
1268                         return HDB_ERR_NOENTRY;
1269                 }
1270                 
1271                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
1272                 
1273                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
1274                                            mem_ctx, 
1275                                            principal, HDB_SAMBA4_ENT_TYPE_SERVER, realm_dn, &msg);
1276                 
1277                 if (ret != 0) {
1278                         return ret;
1279                 }
1280         }
1281
1282         ret = LDB_message2entry(context, db, mem_ctx, 
1283                                 principal, HDB_SAMBA4_ENT_TYPE_SERVER,
1284                                 msg[0], realm_ref_msg[0], entry_ex);
1285         if (ret != 0) {
1286                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
1287         }
1288
1289         return ret;
1290 }
1291                         
1292 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
1293                                  krb5_const_principal principal,
1294                                  unsigned flags,
1295                                  hdb_entry_ex *entry_ex)
1296 {
1297         krb5_error_code ret = HDB_ERR_NOENTRY;
1298
1299         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
1300
1301         if (!mem_ctx) {
1302                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
1303                 return ENOMEM;
1304         }
1305
1306         if (flags & HDB_F_GET_CLIENT) {
1307                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
1308                 if (ret != HDB_ERR_NOENTRY) goto done;
1309         }
1310         if (flags & HDB_F_GET_SERVER) {
1311                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1312                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1313                 if (ret != HDB_ERR_NOENTRY) goto done;
1314
1315                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1316                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
1317                 if (ret != HDB_ERR_NOENTRY) goto done;
1318         }
1319         if (flags & HDB_F_GET_KRBTGT) {
1320                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
1321                 if (ret != HDB_ERR_NOENTRY) goto done;
1322         }
1323
1324 done:
1325         talloc_free(mem_ctx);
1326         return ret;
1327 }
1328
1329 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1330 {
1331         return HDB_ERR_DB_INUSE;
1332 }
1333
1334 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
1335 {
1336         return HDB_ERR_DB_INUSE;
1337 }
1338
1339 struct hdb_ldb_seq {
1340         struct ldb_context *ctx;
1341         int index;
1342         int count;
1343         struct ldb_message **msgs;
1344         struct ldb_message **realm_ref_msgs;
1345 };
1346
1347 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
1348 {
1349         krb5_error_code ret;
1350         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1351         TALLOC_CTX *mem_ctx;
1352         hdb_entry_ex entry_ex;
1353         memset(&entry_ex, '\0', sizeof(entry_ex));
1354
1355         if (!priv) {
1356                 return HDB_ERR_NOENTRY;
1357         }
1358
1359         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
1360
1361         if (!mem_ctx) {
1362                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
1363                 return ENOMEM;
1364         }
1365
1366         if (priv->index < priv->count) {
1367                 ret = LDB_message2entry(context, db, mem_ctx, 
1368                                         NULL, HDB_SAMBA4_ENT_TYPE_ANY, 
1369                                         priv->msgs[priv->index++], 
1370                                         priv->realm_ref_msgs[0], entry);
1371         } else {
1372                 ret = HDB_ERR_NOENTRY;
1373         }
1374
1375         if (ret != 0) {
1376                 talloc_free(priv);
1377                 db->hdb_dbc = NULL;
1378         } else {
1379                 talloc_free(mem_ctx);
1380         }
1381
1382         return ret;
1383 }
1384
1385 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1386                                         hdb_entry_ex *entry)
1387 {
1388         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1389         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1390         char *realm;
1391         struct ldb_dn *realm_dn = NULL;
1392         struct ldb_result *res = NULL;
1393         struct ldb_message **realm_ref_msgs = NULL;
1394         krb5_error_code ret;
1395         TALLOC_CTX *mem_ctx;
1396         int lret;
1397
1398         if (priv) {
1399                 talloc_free(priv);
1400                 db->hdb_dbc = NULL;
1401         }
1402
1403         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1404         if (!priv) {
1405                 krb5_set_error_string(context, "talloc: out of memory");
1406                 return ENOMEM;
1407         }
1408
1409         priv->ctx = ldb_ctx;
1410         priv->index = 0;
1411         priv->msgs = NULL;
1412         priv->realm_ref_msgs = NULL;
1413         priv->count = 0;
1414
1415         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1416
1417         if (!mem_ctx) {
1418                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1419                 return ENOMEM;
1420         }
1421
1422         ret = krb5_get_default_realm(context, &realm);
1423         if (ret != 0) {
1424                 talloc_free(priv);
1425                 return ret;
1426         }
1427                 
1428         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1429                                mem_ctx, realm, &realm_ref_msgs);
1430
1431         free(realm);
1432
1433         if (ret != 0) {
1434                 talloc_free(priv);
1435                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1436                 return HDB_ERR_NOENTRY;
1437         }
1438
1439         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
1440
1441         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
1442
1443         lret = ldb_search(ldb_ctx, priv, &res,
1444                           realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1445                           "(objectClass=user)");
1446
1447         if (lret != LDB_SUCCESS) {
1448                 talloc_free(priv);
1449                 return HDB_ERR_NOENTRY;
1450         }
1451
1452         priv->count = res->count;
1453         priv->msgs = talloc_steal(priv, res->msgs);
1454         talloc_free(res);
1455
1456         db->hdb_dbc = priv;
1457
1458         ret = LDB_seq(context, db, flags, entry);
1459
1460         if (ret != 0) {
1461                 talloc_free(priv);
1462                 db->hdb_dbc = NULL;
1463         } else {
1464                 talloc_free(mem_ctx);
1465         }
1466         return ret;
1467 }
1468
1469 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1470                                    hdb_entry_ex *entry)
1471 {
1472         return LDB_seq(context, db, flags, entry);
1473 }
1474
1475 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1476 {
1477         talloc_free(db);
1478         return 0;
1479 }
1480
1481 /* This interface is to be called by the KDC, which is expecting Samba
1482  * calling conventions.  It is also called by a wrapper
1483  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1484  * code */
1485
1486 NTSTATUS kdc_hdb_samba4_create(TALLOC_CTX *mem_ctx, 
1487                             struct event_context *ev_ctx, 
1488                             struct loadparm_context *lp_ctx,
1489                             krb5_context context, struct HDB **db, const char *arg)
1490 {
1491         NTSTATUS nt_status;
1492         struct auth_session_info *session_info;
1493         *db = talloc(mem_ctx, HDB);
1494         if (!*db) {
1495                 krb5_set_error_string(context, "malloc: out of memory");
1496                 return NT_STATUS_NO_MEMORY;
1497         }
1498
1499         (*db)->hdb_master_key_set = 0;
1500         (*db)->hdb_db = NULL;
1501
1502         nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1503         if (!NT_STATUS_IS_OK(nt_status)) {
1504                 return nt_status;
1505         }
1506         
1507         /* The idea here is very simple.  Using Kerberos to
1508          * authenticate the KDC to the LDAP server is higly likely to
1509          * be circular.
1510          *
1511          * In future we may set this up to use EXERNAL and SSL
1512          * certificates, for now it will almost certainly be NTLMSSP
1513         */
1514         
1515         cli_credentials_set_kerberos_state(session_info->credentials, 
1516                                            CRED_DONT_USE_KERBEROS);
1517
1518         /* Setup the link to LDB */
1519         (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1520         if ((*db)->hdb_db == NULL) {
1521                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1522                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1523         }
1524
1525         (*db)->hdb_dbc = NULL;
1526         (*db)->hdb_open = LDB_open;
1527         (*db)->hdb_close = LDB_close;
1528         (*db)->hdb_fetch = LDB_fetch;
1529         (*db)->hdb_store = LDB_store;
1530         (*db)->hdb_remove = LDB_remove;
1531         (*db)->hdb_firstkey = LDB_firstkey;
1532         (*db)->hdb_nextkey = LDB_nextkey;
1533         (*db)->hdb_lock = LDB_lock;
1534         (*db)->hdb_unlock = LDB_unlock;
1535         (*db)->hdb_rename = LDB_rename;
1536         /* we don't implement these, as we are not a lockable database */
1537         (*db)->hdb__get = NULL;
1538         (*db)->hdb__put = NULL;
1539         /* kadmin should not be used for deletes - use other tools instead */
1540         (*db)->hdb__del = NULL;
1541         (*db)->hdb_destroy = LDB_destroy;
1542
1543         return NT_STATUS_OK;
1544 }
1545
1546 krb5_error_code hdb_samba4_create(krb5_context context, struct HDB **db, const char *arg)
1547 {
1548         NTSTATUS nt_status;
1549         /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1550         nt_status = kdc_hdb_samba4_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
1551                                           context, db, arg);
1552
1553         if (NT_STATUS_IS_OK(nt_status)) {
1554                 return 0;
1555         }
1556         return EINVAL;
1557 }