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