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