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