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