hdb-ldb: check the SUPPLEMENTAL_CREDENTIALS_SIGNATURE
[nivanova/samba-autobuild/.git] / source4 / kdc / hdb-ldb.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 "libcli/auth/libcli_auth.h"
49 #include "param/param.h"
50 #include "events/events.h"
51 #include "kdc/kdc.h"
52
53 enum hdb_ldb_ent_type 
54 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
55   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
56
57 static const char *realm_ref_attrs[] = {
58         "nCName", 
59         "dnsRoot", 
60         NULL
61 };
62
63 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
64 {
65     const char *tmp;
66     const char *gentime;
67     struct tm tm;
68
69     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
70     if (!gentime)
71         return default_val;
72
73     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
74     if (tmp == NULL) {
75             return default_val;
76     }
77
78     return timegm(&tm);
79 }
80
81 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
82 {
83         HDBFlags flags = int2HDBFlags(0);
84
85         /* we don't allow kadmin deletes */
86         flags.immutable = 1;
87
88         /* mark the principal as invalid to start with */
89         flags.invalid = 1;
90
91         flags.renewable = 1;
92
93         /* All accounts are servers, but this may be disabled again in the caller */
94         flags.server = 1;
95
96         /* Account types - clear the invalid bit if it turns out to be valid */
97         if (userAccountControl & UF_NORMAL_ACCOUNT) {
98                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
99                         flags.client = 1;
100                 }
101                 flags.invalid = 0;
102         }
103         
104         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
105                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
106                         flags.client = 1;
107                 }
108                 flags.invalid = 0;
109         }
110         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
111                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
112                         flags.client = 1;
113                 }
114                 flags.invalid = 0;
115         }
116         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
117                 if (ent_type == HDB_LDB_ENT_TYPE_CLIENT || ent_type == HDB_LDB_ENT_TYPE_ANY) {
118                         flags.client = 1;
119                 }
120                 flags.invalid = 0;
121         }
122
123         /* Not permitted to act as a client if disabled */
124         if (userAccountControl & UF_ACCOUNTDISABLE) {
125                 flags.client = 0;
126         }
127         if (userAccountControl & UF_LOCKOUT) {
128                 flags.invalid = 1;
129         }
130 /*
131         if (userAccountControl & UF_PASSWORD_NOTREQD) {
132                 flags.invalid = 1;
133         }
134 */
135 /*
136         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
137 */
138         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
139                 flags.invalid = 1;
140         }
141
142 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in LDB_message2entry() */
143
144 /*
145         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
146                 flags.invalid = 1;
147         }
148 */
149         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
150                 flags.require_hwauth = 1;
151         }
152         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
153                 flags.ok_as_delegate = 1;
154         }       
155         if (!(userAccountControl & UF_NOT_DELEGATED)) {
156                 flags.forwardable = 1;
157                 flags.proxiable = 1;
158         }
159
160         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
161                 flags.require_preauth = 0;
162         } else {
163                 flags.require_preauth = 1;
164
165         }
166         return flags;
167 }
168
169 static int hdb_ldb_destrutor(struct hdb_ldb_private *private)
170 {
171     hdb_entry_ex *entry_ex = private->entry_ex;
172     free_hdb_entry(&entry_ex->entry);
173     return 0;
174 }
175
176 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
177 {
178         talloc_free(entry_ex->ctx);
179 }
180
181 static krb5_error_code LDB_message2entry_keys(krb5_context context,
182                                               struct smb_iconv_convenience *iconv_convenience,
183                                               TALLOC_CTX *mem_ctx,
184                                               struct ldb_message *msg,
185                                               unsigned int userAccountControl,
186                                               hdb_entry_ex *entry_ex)
187 {
188         krb5_error_code ret = 0;
189         enum ndr_err_code ndr_err;
190         struct samr_Password *hash;
191         const struct ldb_val *sc_val;
192         struct supplementalCredentialsBlob scb;
193         struct supplementalCredentialsPackage *scp = NULL;
194         struct package_PrimaryKerberosBlob _pkb;
195         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
196         uint32_t i;
197         uint32_t allocated_keys = 0;
198
199         entry_ex->entry.keys.val = NULL;
200         entry_ex->entry.keys.len = 0;
201
202         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
203
204         /* Get keys from the db */
205
206         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
207         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
208
209         /* unicodePwd for enctype 0x17 (23) if present */
210         if (hash) {
211                 allocated_keys++;
212         }
213
214         /* supplementalCredentials if present */
215         if (sc_val) {
216                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, iconv_convenience, &scb,
217                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
218                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
219                         dump_data(0, sc_val->data, sc_val->length);
220                         ret = EINVAL;
221                         goto out;
222                 }
223
224                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
225                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
226                         ret = EINVAL;
227                         goto out;
228                 }
229
230                 for (i=0; i < scb.sub.num_packages; i++) {
231                         if (scb.sub.packages[i].unknown1 != 0x00000001) {
232                                 continue;
233                         }
234
235                         if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) != 0) {
236                                 continue;
237                         }
238
239                         if (!scb.sub.packages[i].data || !scb.sub.packages[i].data[0]) {
240                                 continue;
241                         }
242
243                         scp = &scb.sub.packages[i];
244                         break;
245                 }
246         }
247         /* Primary:Kerberos element of supplementalCredentials */
248         if (scp) {
249                 DATA_BLOB blob;
250
251                 blob = strhex_to_data_blob(scp->data);
252                 if (!blob.data) {
253                         ret = ENOMEM;
254                         goto out;
255                 }
256                 talloc_steal(mem_ctx, blob.data);
257
258                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
259                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, iconv_convenience, &_pkb,
260                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
261                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
262                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
263                         krb5_warnx(context, "LDB_message2entry_keys: could not parse package_PrimaryKerberosBlob");
264                         ret = EINVAL;
265                         goto out;
266                 }
267
268                 if (_pkb.version != 3) {
269                         krb5_set_error_string(context, "LDB_message2entry_keys: could not parse PrimaryKerberos not version 3");
270                         krb5_warnx(context, "LDB_message2entry_keys: could not parse PrimaryKerberos not version 3");
271                         ret = EINVAL;
272                         goto out;
273                 }
274                 
275                 pkb3 = &_pkb.ctr.ctr3;
276
277                 allocated_keys += pkb3->num_keys;
278         }
279
280         if (allocated_keys == 0) {
281                 /* oh, no password.  Apparently (comment in
282                  * hdb-ldap.c) this violates the ASN.1, but this
283                  * allows an entry with no keys (yet). */
284                 return 0;
285         }
286
287         /* allocate space to decode into */
288         entry_ex->entry.keys.len = 0;
289         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
290         if (entry_ex->entry.keys.val == NULL) {
291                 ret = ENOMEM;
292                 goto out;
293         }
294
295         if (hash && !(userAccountControl & UF_USE_DES_KEY_ONLY)) {
296                 Key key;
297
298                 key.mkvno = 0;
299                 key.salt = NULL; /* No salt for this enc type */
300
301                 ret = krb5_keyblock_init(context,
302                                          ENCTYPE_ARCFOUR_HMAC_MD5,
303                                          hash->hash, sizeof(hash->hash), 
304                                          &key.key);
305                 if (ret) {
306                         goto out;
307                 }
308
309                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
310                 entry_ex->entry.keys.len++;
311         }
312
313         if (pkb3) {
314                 for (i=0; i < pkb3->num_keys; i++) {
315                         bool use = true;
316                         Key key;
317
318                         if (!pkb3->keys[i].value) continue;
319
320                         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
321                                 switch (pkb3->keys[i].keytype) {
322                                 case ENCTYPE_DES_CBC_CRC:
323                                 case ENCTYPE_DES_CBC_MD5:
324                                         break;
325                                 default:
326                                         use = false;
327                                         break;
328                                 }
329                         }
330
331                         if (!use) continue;
332
333                         key.mkvno = 0;
334                         key.salt = NULL;
335
336                         if (pkb3->salt.string) {
337                                 DATA_BLOB salt;
338
339                                 salt = data_blob_string_const(pkb3->salt.string);
340
341                                 key.salt = calloc(1, sizeof(*key.salt));
342                                 if (key.salt == NULL) {
343                                         ret = ENOMEM;
344                                         goto out;
345                                 }
346
347                                 key.salt->type = hdb_pw_salt;
348
349                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
350                                 if (ret) {
351                                         free(key.salt);
352                                         key.salt = NULL;
353                                         goto out;
354                                 }
355                         }
356
357                         ret = krb5_keyblock_init(context,
358                                                  pkb3->keys[i].keytype,
359                                                  pkb3->keys[i].value->data,
360                                                  pkb3->keys[i].value->length,
361                                                  &key.key);
362                         if (ret) {
363                                 if (key.salt) {
364                                         free_Salt(key.salt);
365                                         free(key.salt);
366                                         key.salt = NULL;
367                                 }
368                                 goto out;
369                         }
370
371                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
372                         entry_ex->entry.keys.len++;
373                 }
374         }
375
376 out:
377         if (ret != 0) {
378                 entry_ex->entry.keys.len = 0;
379         }
380         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
381                 free(entry_ex->entry.keys.val);
382                 entry_ex->entry.keys.val = NULL;
383         }
384         return ret;
385 }
386
387 /*
388  * Construct an hdb_entry from a directory entry.
389  */
390 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
391                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
392                                          enum hdb_ldb_ent_type ent_type, 
393                                          struct ldb_message *msg,
394                                          struct ldb_message *realm_ref_msg,
395                                          hdb_entry_ex *entry_ex)
396 {
397         unsigned int userAccountControl;
398         int i;
399         krb5_error_code ret = 0;
400         krb5_boolean is_computer = FALSE;
401         const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg, "dnsRoot", NULL);
402         char *realm = strupper_talloc(mem_ctx, dnsdomain);
403         struct loadparm_context *lp_ctx = ldb_get_opaque((struct ldb_context *)db->hdb_db, "loadparm");
404         struct ldb_dn *domain_dn = samdb_result_dn((struct ldb_context *)db->hdb_db,
405                                                         mem_ctx,
406                                                         realm_ref_msg,
407                                                         "nCName",
408                                                         ldb_dn_new(mem_ctx, (struct ldb_context *)db->hdb_db, NULL));
409
410         struct hdb_ldb_private *private;
411         NTTIME acct_expiry;
412
413         struct ldb_message_element *objectclasses;
414         struct ldb_val computer_val;
415         computer_val.data = discard_const_p(uint8_t,"computer");
416         computer_val.length = strlen((const char *)computer_val.data);
417         
418         objectclasses = ldb_msg_find_element(msg, "objectClass");
419         
420         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
421                 is_computer = TRUE;
422         }
423
424         memset(entry_ex, 0, sizeof(*entry_ex));
425
426         if (!realm) {
427                 krb5_set_error_string(context, "talloc_strdup: out of memory");
428                 ret = ENOMEM;
429                 goto out;
430         }
431                         
432         private = talloc(mem_ctx, struct hdb_ldb_private);
433         if (!private) {
434                 ret = ENOMEM;
435                 goto out;
436         }
437
438         private->entry_ex = entry_ex;
439         private->iconv_convenience = lp_iconv_convenience(lp_ctx);
440         private->netbios_name = lp_netbios_name(lp_ctx);
441
442         talloc_set_destructor(private, hdb_ldb_destrutor);
443
444         entry_ex->ctx = private;
445         entry_ex->free_entry = hdb_ldb_free_entry;
446
447         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
448
449         
450         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
451         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
452                 const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
453                 if (!samAccountName) {
454                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
455                         ret = ENOENT;
456                         goto out;
457                 }
458                 samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
459                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
460         } else {
461                 char *strdup_realm;
462                 ret = copy_Principal(principal, entry_ex->entry.principal);
463                 if (ret) {
464                         krb5_clear_error_string(context);
465                         goto out;
466                 }
467
468                 /* While we have copied the client principal, tests
469                  * show that Win2k3 returns the 'corrected' realm, not
470                  * the client-specified realm.  This code attempts to
471                  * replace the client principal's realm with the one
472                  * we determine from our records */
473                 
474                 /* this has to be with malloc() */
475                 strdup_realm = strdup(realm);
476                 if (!strdup_realm) {
477                         ret = ENOMEM;
478                         krb5_clear_error_string(context);
479                         goto out;
480                 }
481                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
482                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
483         }
484
485         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
486
487         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
488                 entry_ex->entry.flags.invalid = 0;
489                 entry_ex->entry.flags.server = 1;
490                 entry_ex->entry.flags.forwardable = 1;
491                 entry_ex->entry.flags.ok_as_delegate = 1;
492         }
493
494         if (lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
495                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
496                         entry_ex->entry.flags.server = 0;
497                 }
498         }
499
500         /* use 'whenCreated' */
501         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
502         /* use '???' */
503         entry_ex->entry.created_by.principal = NULL;
504
505         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
506         if (entry_ex->entry.modified_by == NULL) {
507                 krb5_set_error_string(context, "malloc: out of memory");
508                 ret = ENOMEM;
509                 goto out;
510         }
511
512         /* use 'whenChanged' */
513         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
514         /* use '???' */
515         entry_ex->entry.modified_by->principal = NULL;
516
517         entry_ex->entry.valid_start = NULL;
518
519         acct_expiry = samdb_result_account_expires(msg);
520         if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
521                 entry_ex->entry.valid_end = NULL;
522         } else {
523                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
524                 if (entry_ex->entry.valid_end == NULL) {
525                         ret = ENOMEM;
526                         goto out;
527                 }
528                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
529         }
530
531         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
532                 NTTIME must_change_time
533                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
534                                                              domain_dn, msg);
535                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
536                         entry_ex->entry.pw_end = NULL;
537                 } else {
538                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
539                         if (entry_ex->entry.pw_end == NULL) {
540                                 ret = ENOMEM;
541                                 goto out;
542                         }
543                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
544                 }
545         } else {
546                 entry_ex->entry.pw_end = NULL;
547         }
548                         
549         entry_ex->entry.max_life = NULL;
550
551         entry_ex->entry.max_renew = NULL;
552
553         entry_ex->entry.generation = NULL;
554
555         /* Get keys from the db */
556         ret = LDB_message2entry_keys(context, private->iconv_convenience, private, msg, userAccountControl, entry_ex);
557         if (ret) {
558                 /* Could be bougus data in the entry, or out of memory */
559                 goto out;
560         }
561
562         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
563         if (entry_ex->entry.etypes == NULL) {
564                 krb5_clear_error_string(context);
565                 ret = ENOMEM;
566                 goto out;
567         }
568         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
569         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
570         if (entry_ex->entry.etypes->val == NULL) {
571                 krb5_clear_error_string(context);
572                 ret = ENOMEM;
573                 goto out;
574         }
575         for (i=0; i < entry_ex->entry.etypes->len; i++) {
576                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
577         }
578
579
580         private->msg = talloc_steal(private, msg);
581         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
582         private->samdb = (struct ldb_context *)db->hdb_db;
583         
584 out:
585         if (ret != 0) {
586                 /* This doesn't free ent itself, that is for the eventual caller to do */
587                 hdb_free_entry(context, entry_ex);
588         } else {
589                 talloc_steal(db, entry_ex->ctx);
590         }
591
592         return ret;
593 }
594
595 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
596                                             TALLOC_CTX *mem_ctx,
597                                             krb5_const_principal principal,
598                                             enum hdb_ldb_ent_type ent_type,
599                                             struct ldb_dn *realm_dn,
600                                             struct ldb_message ***pmsg)
601 {
602         krb5_error_code ret;
603         int lret;
604         char *filter = NULL;
605         const char * const *princ_attrs = user_attrs;
606
607         char *short_princ;
608         char *short_princ_talloc;
609
610         struct ldb_result *res = NULL;
611
612         ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
613
614         if (ret != 0) {
615                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
616                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
617                 return ret;
618         }
619
620         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
621         free(short_princ);
622         if (!short_princ_talloc) {
623                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
624                 return ENOMEM;
625         }
626
627         switch (ent_type) {
628         case HDB_LDB_ENT_TYPE_CLIENT:
629                 /* Can't happen */
630                 return EINVAL;
631         case HDB_LDB_ENT_TYPE_ANY:
632                 /* Can't happen */
633                 return EINVAL;
634         case HDB_LDB_ENT_TYPE_KRBTGT:
635                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
636                                          KRB5_TGS_NAME);
637                 break;
638         case HDB_LDB_ENT_TYPE_SERVER:
639                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
640                                          short_princ_talloc);
641                 break;
642         }
643
644         if (!filter) {
645                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
646                 return ENOMEM;
647         }
648
649         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
650
651         if (lret != LDB_SUCCESS) {
652                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
653                 return HDB_ERR_NOENTRY;
654         } else if (res->count == 0 || res->count > 1) {
655                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
656                 talloc_free(res);
657                 return HDB_ERR_NOENTRY;
658         }
659         talloc_steal(mem_ctx, res->msgs);
660         *pmsg = res->msgs;
661         talloc_free(res);
662         return 0;
663 }
664
665 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
666                                         TALLOC_CTX *mem_ctx,
667                                         const char *realm,
668                                         struct ldb_message ***pmsg)
669 {
670         int ret;
671         struct ldb_result *cross_ref_res;
672         struct ldb_dn *partitions_basedn = samdb_partitions_dn(ldb_ctx, mem_ctx);
673
674         ret = ldb_search_exp_fmt(ldb_ctx, mem_ctx, &cross_ref_res,
675                         partitions_basedn, LDB_SCOPE_SUBTREE, realm_ref_attrs,
676                         "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
677                         realm, realm);
678
679         if (ret != LDB_SUCCESS) {
680                 DEBUG(3, ("Failed to search to lookup realm(%s): %s\n", realm, ldb_errstring(ldb_ctx)));
681                 talloc_free(cross_ref_res);
682                 return HDB_ERR_NOENTRY;
683         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
684                 DEBUG(3, ("Failed find a single entry for realm %s: got %d\n", realm, cross_ref_res->count));
685                 talloc_free(cross_ref_res);
686                 return HDB_ERR_NOENTRY;
687         }
688
689         if (pmsg) {
690                 *pmsg = cross_ref_res->msgs;
691                 talloc_steal(mem_ctx, cross_ref_res->msgs);
692         }
693         talloc_free(cross_ref_res);
694
695         return 0;
696 }
697
698
699 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
700 {
701         if (db->hdb_master_key_set) {
702                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
703                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
704                 return HDB_ERR_NOENTRY;
705         }               
706
707         return 0;
708 }
709
710 static krb5_error_code LDB_close(krb5_context context, HDB *db)
711 {
712         return 0;
713 }
714
715 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
716 {
717         return 0;
718 }
719
720 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
721 {
722         return 0;
723 }
724
725 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
726 {
727         return HDB_ERR_DB_INUSE;
728 }
729
730 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
731                                         TALLOC_CTX *mem_ctx, 
732                                         krb5_const_principal principal,
733                                         unsigned flags,
734                                         hdb_entry_ex *entry_ex) {
735         NTSTATUS nt_status;
736         char *principal_string;
737         krb5_error_code ret;
738         struct ldb_message **msg = NULL;
739         struct ldb_message **realm_ref_msg = NULL;
740
741         ret = krb5_unparse_name(context, principal, &principal_string);
742         
743         if (ret != 0) {
744                 return ret;
745         }
746         
747         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
748                                               mem_ctx, principal_string, 
749                                               &msg, &realm_ref_msg);
750         free(principal_string);
751         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
752                 return HDB_ERR_NOENTRY;
753         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
754                 return ENOMEM;
755         } else if (!NT_STATUS_IS_OK(nt_status)) {
756                 return EINVAL;
757         }
758         
759         ret = LDB_message2entry(context, db, mem_ctx, 
760                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
761                                 msg[0], realm_ref_msg[0], entry_ex);
762         return ret;
763 }
764
765 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
766                                         TALLOC_CTX *mem_ctx, 
767                                         krb5_const_principal principal,
768                                         unsigned flags,
769                                         hdb_entry_ex *entry_ex)
770 {
771         krb5_error_code ret;
772         struct ldb_message **msg = NULL;
773         struct ldb_message **realm_ref_msg = NULL;
774         struct ldb_dn *realm_dn;
775
776         krb5_principal alloc_principal = NULL;
777         if (principal->name.name_string.len != 2
778             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
779                 /* Not a krbtgt */
780                 return HDB_ERR_NOENTRY;
781         }
782
783         /* krbtgt case.  Either us or a trusted realm */
784         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
785                               mem_ctx, principal->name.name_string.val[1], &realm_ref_msg) == 0)) {
786                 /* us */                
787                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
788                  * is in our db, then direct the caller at our primary
789                  * krgtgt */
790                 
791                 const char *dnsdomain = ldb_msg_find_attr_as_string(realm_ref_msg[0], "dnsRoot", NULL);
792                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
793                 if (!realm_fixed) {
794                         krb5_set_error_string(context, "strupper_talloc: out of memory");
795                         return ENOMEM;
796                 }
797                 
798                 ret = krb5_copy_principal(context, principal, &alloc_principal);
799                 if (ret) {
800                         return ret;
801                 }
802  
803                 free(alloc_principal->name.name_string.val[1]);
804                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
805                 talloc_free(realm_fixed);
806                 if (!alloc_principal->name.name_string.val[1]) {
807                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
808                         return ENOMEM;
809                 }
810                 principal = alloc_principal;
811                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
812         } else {
813                 /* we should lookup trusted domains */
814                 return HDB_ERR_NOENTRY;
815         }
816
817         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
818         
819         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
820                                    mem_ctx, 
821                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
822         
823         if (ret != 0) {
824                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
825                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
826                 return ret;
827         }
828
829         ret = LDB_message2entry(context, db, mem_ctx, 
830                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
831                                 msg[0], realm_ref_msg[0], entry_ex);
832         if (ret != 0) {
833                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
834         }
835         return ret;
836 }
837
838 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
839                                         TALLOC_CTX *mem_ctx, 
840                                         krb5_const_principal principal,
841                                         unsigned flags,
842                                         hdb_entry_ex *entry_ex)
843 {
844         krb5_error_code ret;
845         const char *realm;
846         struct ldb_message **msg = NULL;
847         struct ldb_message **realm_ref_msg = NULL;
848         struct ldb_dn *partitions_basedn = samdb_partitions_dn(db->hdb_db, mem_ctx);
849         if (principal->name.name_string.len >= 2) {
850                 /* 'normal server' case */
851                 int ldb_ret;
852                 NTSTATUS nt_status;
853                 struct ldb_dn *user_dn, *domain_dn;
854                 char *principal_string;
855                 
856                 ret = krb5_unparse_name_flags(context, principal, 
857                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM, 
858                                               &principal_string);
859                 if (ret != 0) {
860                         return ret;
861                 }
862                 
863                 /* At this point we may find the host is known to be
864                  * in a different realm, so we should generate a
865                  * referral instead */
866                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
867                                                          mem_ctx, principal_string, 
868                                                          &user_dn, &domain_dn);
869                 free(principal_string);
870                 
871                 if (!NT_STATUS_IS_OK(nt_status)) {
872                         return HDB_ERR_NOENTRY;
873                 }
874                 
875                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
876                                           mem_ctx, user_dn, &msg, user_attrs);
877                 
878                 if (ldb_ret != 1) {
879                         return HDB_ERR_NOENTRY;
880                 }
881                 
882                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
883                                        mem_ctx, partitions_basedn, &realm_ref_msg, realm_ref_attrs, 
884                                        "ncName=%s", ldb_dn_get_linearized(domain_dn));
885                 
886                 if (ldb_ret != 1) {
887                         return HDB_ERR_NOENTRY;
888                 }
889                 
890         } else {
891                 struct ldb_dn *realm_dn;
892                 /* server as client principal case, but we must not lookup userPrincipalNames */
893
894                 realm = krb5_principal_get_realm(context, principal);
895                 
896                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
897                                        mem_ctx, realm, &realm_ref_msg);
898                 if (ret != 0) {
899                         return HDB_ERR_NOENTRY;
900                 }
901                 
902                 realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msg[0], "nCName", NULL);
903                 
904                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
905                                            mem_ctx, 
906                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
907                 
908                 if (ret != 0) {
909                         return ret;
910                 }
911         }
912
913         ret = LDB_message2entry(context, db, mem_ctx, 
914                                 principal, HDB_LDB_ENT_TYPE_SERVER,
915                                 msg[0], realm_ref_msg[0], entry_ex);
916         if (ret != 0) {
917                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
918         }
919
920         return ret;
921 }
922                         
923 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
924                                  krb5_const_principal principal,
925                                  unsigned flags,
926                                  hdb_entry_ex *entry_ex)
927 {
928         krb5_error_code ret = HDB_ERR_NOENTRY;
929
930         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
931
932         if (!mem_ctx) {
933                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
934                 return ENOMEM;
935         }
936
937         if (flags & HDB_F_GET_CLIENT) {
938                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
939                 if (ret != HDB_ERR_NOENTRY) goto done;
940         }
941         if (flags & HDB_F_GET_SERVER) {
942                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
943                 if (ret != HDB_ERR_NOENTRY) goto done;
944                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
945                 if (ret != HDB_ERR_NOENTRY) goto done;
946         }
947         if (flags & HDB_F_GET_KRBTGT) {
948                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
949                 if (ret != HDB_ERR_NOENTRY) goto done;
950         }
951
952 done:
953         talloc_free(mem_ctx);
954         return ret;
955 }
956
957 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
958 {
959         return HDB_ERR_DB_INUSE;
960 }
961
962 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
963 {
964         return HDB_ERR_DB_INUSE;
965 }
966
967 struct hdb_ldb_seq {
968         struct ldb_context *ctx;
969         int index;
970         int count;
971         struct ldb_message **msgs;
972         struct ldb_message **realm_ref_msgs;
973 };
974
975 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
976 {
977         krb5_error_code ret;
978         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
979         TALLOC_CTX *mem_ctx;
980         hdb_entry_ex entry_ex;
981         memset(&entry_ex, '\0', sizeof(entry_ex));
982
983         if (!priv) {
984                 return HDB_ERR_NOENTRY;
985         }
986
987         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
988
989         if (!mem_ctx) {
990                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
991                 return ENOMEM;
992         }
993
994         if (priv->index < priv->count) {
995                 ret = LDB_message2entry(context, db, mem_ctx, 
996                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
997                                         priv->msgs[priv->index++], 
998                                         priv->realm_ref_msgs[0], entry);
999         } else {
1000                 ret = HDB_ERR_NOENTRY;
1001         }
1002
1003         if (ret != 0) {
1004                 talloc_free(priv);
1005                 db->hdb_dbc = NULL;
1006         } else {
1007                 talloc_free(mem_ctx);
1008         }
1009
1010         return ret;
1011 }
1012
1013 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
1014                                         hdb_entry_ex *entry)
1015 {
1016         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
1017         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_dbc;
1018         char *realm;
1019         struct ldb_dn *realm_dn = NULL;
1020         struct ldb_result *res = NULL;
1021         struct ldb_message **realm_ref_msgs = NULL;
1022         krb5_error_code ret;
1023         TALLOC_CTX *mem_ctx;
1024         int lret;
1025
1026         if (priv) {
1027                 talloc_free(priv);
1028                 db->hdb_dbc = NULL;
1029         }
1030
1031         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
1032         if (!priv) {
1033                 krb5_set_error_string(context, "talloc: out of memory");
1034                 return ENOMEM;
1035         }
1036
1037         priv->ctx = ldb_ctx;
1038         priv->index = 0;
1039         priv->msgs = NULL;
1040         priv->realm_ref_msgs = NULL;
1041         priv->count = 0;
1042
1043         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
1044
1045         if (!mem_ctx) {
1046                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
1047                 return ENOMEM;
1048         }
1049
1050         ret = krb5_get_default_realm(context, &realm);
1051         if (ret != 0) {
1052                 talloc_free(priv);
1053                 return ret;
1054         }
1055                 
1056         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
1057                                mem_ctx, realm, &realm_ref_msgs);
1058
1059         free(realm);
1060
1061         if (ret != 0) {
1062                 talloc_free(priv);
1063                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
1064                 return HDB_ERR_NOENTRY;
1065         }
1066
1067         realm_dn = samdb_result_dn((struct ldb_context *)db->hdb_db, mem_ctx, realm_ref_msgs[0], "nCName", NULL);
1068
1069         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
1070
1071         lret = ldb_search(ldb_ctx, realm_dn,
1072                                  LDB_SCOPE_SUBTREE, "(objectClass=user)",
1073                                  user_attrs, &res);
1074
1075         if (lret != LDB_SUCCESS) {
1076                 talloc_free(priv);
1077                 return HDB_ERR_NOENTRY;
1078         }
1079
1080         priv->count = res->count;
1081         priv->msgs = talloc_steal(priv, res->msgs);
1082         talloc_free(res);
1083
1084         db->hdb_dbc = priv;
1085
1086         ret = LDB_seq(context, db, flags, entry);
1087
1088         if (ret != 0) {
1089                 talloc_free(priv);
1090                 db->hdb_dbc = NULL;
1091         } else {
1092                 talloc_free(mem_ctx);
1093         }
1094         return ret;
1095 }
1096
1097 static krb5_error_code LDB_nextkey(krb5_context context, HDB *db, unsigned flags,
1098                                    hdb_entry_ex *entry)
1099 {
1100         return LDB_seq(context, db, flags, entry);
1101 }
1102
1103 static krb5_error_code LDB_destroy(krb5_context context, HDB *db)
1104 {
1105         talloc_free(db);
1106         return 0;
1107 }
1108
1109 /* This interface is to be called by the KDC, which is expecting Samba
1110  * calling conventions.  It is also called by a wrapper
1111  * (hdb_ldb_create) from the kpasswdd -> krb5 -> keytab_hdb -> hdb
1112  * code */
1113
1114 NTSTATUS kdc_hdb_ldb_create(TALLOC_CTX *mem_ctx, 
1115                             struct event_context *ev_ctx, 
1116                             struct loadparm_context *lp_ctx,
1117                             krb5_context context, struct HDB **db, const char *arg)
1118 {
1119         NTSTATUS nt_status;
1120         struct auth_session_info *session_info;
1121         *db = talloc(mem_ctx, HDB);
1122         if (!*db) {
1123                 krb5_set_error_string(context, "malloc: out of memory");
1124                 return NT_STATUS_NO_MEMORY;
1125         }
1126
1127         (*db)->hdb_master_key_set = 0;
1128         (*db)->hdb_db = NULL;
1129
1130         nt_status = auth_system_session_info(*db, lp_ctx, &session_info);
1131         if (!NT_STATUS_IS_OK(nt_status)) {
1132                 return nt_status;
1133         }
1134         
1135         /* The idea here is very simple.  Using Kerberos to
1136          * authenticate the KDC to the LDAP server is higly likely to
1137          * be circular.
1138          *
1139          * In future we may set this up to use EXERNAL and SSL
1140          * certificates, for now it will almost certainly be NTLMSSP
1141         */
1142         
1143         cli_credentials_set_kerberos_state(session_info->credentials, 
1144                                            CRED_DONT_USE_KERBEROS);
1145
1146         /* Setup the link to LDB */
1147         (*db)->hdb_db = samdb_connect(*db, ev_ctx, lp_ctx, session_info);
1148         if ((*db)->hdb_db == NULL) {
1149                 DEBUG(1, ("hdb_ldb_create: Cannot open samdb for KDC backend!"));
1150                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1151         }
1152
1153         (*db)->hdb_dbc = NULL;
1154         (*db)->hdb_open = LDB_open;
1155         (*db)->hdb_close = LDB_close;
1156         (*db)->hdb_fetch = LDB_fetch;
1157         (*db)->hdb_store = LDB_store;
1158         (*db)->hdb_remove = LDB_remove;
1159         (*db)->hdb_firstkey = LDB_firstkey;
1160         (*db)->hdb_nextkey = LDB_nextkey;
1161         (*db)->hdb_lock = LDB_lock;
1162         (*db)->hdb_unlock = LDB_unlock;
1163         (*db)->hdb_rename = LDB_rename;
1164         /* we don't implement these, as we are not a lockable database */
1165         (*db)->hdb__get = NULL;
1166         (*db)->hdb__put = NULL;
1167         /* kadmin should not be used for deletes - use other tools instead */
1168         (*db)->hdb__del = NULL;
1169         (*db)->hdb_destroy = LDB_destroy;
1170
1171         return NT_STATUS_OK;
1172 }
1173
1174 krb5_error_code hdb_ldb_create(krb5_context context, struct HDB **db, const char *arg)
1175 {
1176         NTSTATUS nt_status;
1177         /* The global kdc_mem_ctx and kdc_lp_ctx, Disgusting, ugly hack, but it means one less private hook */
1178         nt_status = kdc_hdb_ldb_create(kdc_mem_ctx, event_context_find(kdc_mem_ctx), kdc_lp_ctx, 
1179                                        context, db, arg);
1180
1181         if (NT_STATUS_IS_OK(nt_status)) {
1182                 return 0;
1183         }
1184         return EINVAL;
1185 }