r15497: I'm not really sure this is correct in terms of how we should be responding to
[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 "kdc.h"
37 #include "ads.h"
38 #include "hdb.h"
39 #include "lib/ldb/include/ldb.h"
40 #include "lib/ldb/include/ldb_errors.h"
41 #include "system/iconv.h"
42 #include "librpc/gen_ndr/netlogon.h"
43 #include "auth/auth.h"
44 #include "auth/auth_sam.h"
45 #include "db_wrap.h"
46 #include "dsdb/samdb/samdb.h"
47
48 enum hdb_ldb_ent_type 
49 { HDB_LDB_ENT_TYPE_CLIENT, HDB_LDB_ENT_TYPE_SERVER, 
50   HDB_LDB_ENT_TYPE_KRBTGT, HDB_LDB_ENT_TYPE_ANY };
51
52 static const char * const krb5_attrs[] = {
53         "objectClass",
54         "sAMAccountName",
55
56         "userPrincipalName",
57         "servicePrincipalName",
58
59         "krb5Key",
60
61         "userAccountControl",
62
63         "pwdLastSet",
64         "accountExpires",
65
66         "whenCreated",
67         "whenChanged",
68
69         "msDS-KeyVersionNumber",
70         NULL
71 };
72
73 static const char *realm_ref_attrs[] = {
74         "nCName", 
75         "dnsRoot", 
76         NULL
77 };
78
79 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
80 {
81     const char *tmp;
82     const char *gentime;
83     struct tm tm;
84
85     gentime = ldb_msg_find_string(msg, attr, NULL);
86     if (!gentime)
87         return default_val;
88
89     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
90     if (tmp == NULL) {
91             return default_val;
92     }
93
94     return timegm(&tm);
95 }
96
97 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum hdb_ldb_ent_type ent_type) 
98 {
99         HDBFlags flags = int2HDBFlags(0);
100
101         krb5_warnx(context, "uf2HDBFlags: userAccountControl: %08x\n", userAccountControl);
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         if (userAccountControl & UF_PASSWORD_CANT_CHANGE) {
155                 flags.invalid = 1;
156         }
157 */
158 /*
159         if (userAccountControl & UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED) {
160                 flags.invalid = 1;
161         }
162 */
163         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
164                 flags.invalid = 1;
165         }
166
167 /* UF_DONT_EXPIRE_PASSWD handled in LDB_message2entry() */
168
169 /*
170         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
171                 flags.invalid = 1;
172         }
173 */
174         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
175                 flags.require_hwauth = 1;
176         }
177         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
178                 flags.ok_as_delegate = 1;
179         }       
180         if (!(userAccountControl & UF_NOT_DELEGATED)) {
181                 flags.forwardable = 1;
182                 flags.proxiable = 1;
183         }
184
185 /*
186         if (userAccountControl & UF_SMARTCARD_USE_DES_KEY_ONLY) {
187                 flags.invalid = 1;
188         }
189 */
190         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
191                 flags.require_preauth = 0;
192         } else {
193                 flags.require_preauth = 1;
194
195         }
196
197         krb5_warnx(context, "uf2HDBFlags: HDBFlags: %08x\n", HDBFlags2int(flags));
198
199         return flags;
200 }
201
202 static int hdb_ldb_destrutor(void *ptr)
203 {
204     struct hdb_ldb_private *private = ptr;
205     hdb_entry_ex *entry_ex = private->entry_ex;
206     free_hdb_entry(&entry_ex->entry);
207     return 0;
208 }
209
210 static void hdb_ldb_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
211 {
212         talloc_free(entry_ex->ctx);
213 }
214
215 /*
216  * Construct an hdb_entry from a directory entry.
217  */
218 static krb5_error_code LDB_message2entry(krb5_context context, HDB *db, 
219                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
220                                          enum hdb_ldb_ent_type ent_type, 
221                                          struct ldb_message *msg,
222                                          struct ldb_message *realm_ref_msg,
223                                          hdb_entry_ex *entry_ex)
224 {
225         unsigned int userAccountControl;
226         int i;
227         krb5_error_code ret = 0;
228         krb5_boolean is_computer = FALSE;
229         const char *dnsdomain = ldb_msg_find_string(realm_ref_msg, "dnsRoot", NULL);
230         char *realm = strupper_talloc(mem_ctx, dnsdomain);
231         struct ldb_dn *domain_dn = samdb_result_dn(mem_ctx, realm_ref_msg, "nCName", ldb_dn_new(mem_ctx));
232
233         struct hdb_ldb_private *private;
234         NTTIME acct_expiry;
235         struct ldb_message_element *ldb_keys;
236
237         struct ldb_message_element *objectclasses;
238         struct ldb_val computer_val;
239         computer_val.data = discard_const_p(uint8_t,"computer");
240         computer_val.length = strlen((const char *)computer_val.data);
241         
242         objectclasses = ldb_msg_find_element(msg, "objectClass");
243         
244         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
245                 is_computer = TRUE;
246         }
247
248         memset(entry_ex, 0, sizeof(*entry_ex));
249
250         krb5_warnx(context, "LDB_message2entry:\n");
251
252         if (!realm) {
253                 krb5_set_error_string(context, "talloc_strdup: out of memory");
254                 ret = ENOMEM;
255                 goto out;
256         }
257                         
258         private = talloc(mem_ctx, struct hdb_ldb_private);
259         if (!private) {
260                 ret = ENOMEM;
261                 goto out;
262         }
263
264         private->entry_ex = entry_ex;
265
266         talloc_set_destructor(private, hdb_ldb_destrutor);
267
268         entry_ex->ctx = private;
269         entry_ex->free_entry = hdb_ldb_free_entry;
270
271         userAccountControl = ldb_msg_find_uint(msg, "userAccountControl", 0);
272
273         
274         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
275         if (ent_type == HDB_LDB_ENT_TYPE_ANY && principal == NULL) {
276                 const char *samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
277                 if (!samAccountName) {
278                         krb5_set_error_string(context, "LDB_message2entry: no samAccountName present");
279                         ret = ENOENT;
280                         goto out;
281                 }
282                 samAccountName = ldb_msg_find_string(msg, "samAccountName", NULL);
283                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
284         } else {
285                 char *strdup_realm;
286                 ret = copy_Principal(principal, entry_ex->entry.principal);
287                 if (ret) {
288                         krb5_clear_error_string(context);
289                         goto out;
290                 }
291
292                 /* While we have copied the client principal, tests
293                  * show that Win2k3 returns the 'corrected' realm, not
294                  * the client-specified realm.  This code attempts to
295                  * replace the client principal's realm with the one
296                  * we determine from our records */
297                 
298                 /* this has to be with malloc() */
299                 strdup_realm = strdup(realm);
300                 if (!strdup_realm) {
301                         ret = ENOMEM;
302                         krb5_clear_error_string(context);
303                         goto out;
304                 }
305                 free(*krb5_princ_realm(context, entry_ex->entry.principal));
306                 krb5_princ_set_realm(context, entry_ex->entry.principal, &strdup_realm);
307         }
308
309         entry_ex->entry.kvno = ldb_msg_find_int(msg, "msDS-KeyVersionNumber", 0);
310
311         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
312
313         if (ent_type == HDB_LDB_ENT_TYPE_KRBTGT) {
314                 entry_ex->entry.flags.invalid = 0;
315                 entry_ex->entry.flags.server = 1;
316                 entry_ex->entry.flags.forwardable = 1;
317                 entry_ex->entry.flags.ok_as_delegate = 1;
318         }
319
320         if (lp_parm_bool(-1, "kdc", "require spn for service", True)) {
321                 if (!is_computer && !ldb_msg_find_string(msg, "servicePrincipalName", NULL)) {
322                         entry_ex->entry.flags.server = 0;
323                 }
324         }
325
326         /* use 'whenCreated' */
327         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
328         /* use '???' */
329         entry_ex->entry.created_by.principal = NULL;
330
331         entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
332         if (entry_ex->entry.modified_by == NULL) {
333                 krb5_set_error_string(context, "malloc: out of memory");
334                 ret = ENOMEM;
335                 goto out;
336         }
337
338         /* use 'whenChanged' */
339         entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
340         /* use '???' */
341         entry_ex->entry.modified_by->principal = NULL;
342
343         entry_ex->entry.valid_start = NULL;
344
345         acct_expiry = samdb_result_nttime(msg, "accountExpires", (NTTIME)-1);
346         if ((acct_expiry == (NTTIME)-1) ||
347             (acct_expiry == 0x7FFFFFFFFFFFFFFFULL)) {
348                 entry_ex->entry.valid_end = NULL;
349         } else {
350                 entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
351                 if (entry_ex->entry.valid_end == NULL) {
352                         ret = ENOMEM;
353                         goto out;
354                 }
355                 *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
356         }
357
358         if (ent_type != HDB_LDB_ENT_TYPE_KRBTGT) {
359                 NTTIME must_change_time
360                         = samdb_result_force_password_change((struct ldb_context *)db->hdb_db, mem_ctx, 
361                                                              domain_dn, msg);
362                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
363                         entry_ex->entry.pw_end = NULL;
364                 } else {
365                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
366                         if (entry_ex->entry.pw_end == NULL) {
367                                 ret = ENOMEM;
368                                 goto out;
369                         }
370                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
371                 }
372         } else {
373                 entry_ex->entry.pw_end = NULL;
374         }
375                         
376         entry_ex->entry.max_life = NULL;
377
378         entry_ex->entry.max_renew = NULL;
379
380         entry_ex->entry.generation = NULL;
381
382         /* Get krb5Key from the db */
383
384         ldb_keys = ldb_msg_find_element(msg, "krb5Key");
385
386         if (!ldb_keys) {
387                 /* oh, no password.  Apparently (comment in
388                  * hdb-ldap.c) this violates the ASN.1, but this
389                  * allows an entry with no keys (yet). */
390                 entry_ex->entry.keys.val = NULL;
391                 entry_ex->entry.keys.len = 0;
392         } else {
393                 /* allocate space to decode into */
394                 entry_ex->entry.keys.val = calloc(ldb_keys->num_values, sizeof(Key));
395                 if (entry_ex->entry.keys.val == NULL) {
396                         ret = ENOMEM;
397                         goto out;
398                 }
399                 entry_ex->entry.keys.len = ldb_keys->num_values;
400
401                 /* Decode Kerberos keys into the hdb structure */
402                 for (i=0; i < entry_ex->entry.keys.len; i++) {
403                         size_t decode_len;
404                         ret = decode_Key(ldb_keys->values[i].data, ldb_keys->values[i].length, 
405                                          &entry_ex->entry.keys.val[i], &decode_len);
406                         if (ret) {
407                                 /* Could be bougus data in the entry, or out of memory */
408                                 goto out;
409                         }
410                 }
411         } 
412
413         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
414         if (entry_ex->entry.etypes == NULL) {
415                 krb5_clear_error_string(context);
416                 ret = ENOMEM;
417                 goto out;
418         }
419         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
420         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
421         if (entry_ex->entry.etypes->val == NULL) {
422                 krb5_clear_error_string(context);
423                 ret = ENOMEM;
424                 goto out;
425         }
426         for (i=0; i < entry_ex->entry.etypes->len; i++) {
427                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
428         }
429
430
431         private->msg = talloc_steal(private, msg);
432         private->realm_ref_msg = talloc_steal(private, realm_ref_msg);
433         private->samdb = (struct ldb_context *)db->hdb_db;
434         
435         entry_ex->check_client_access = hdb_ldb_check_client_access;
436         entry_ex->authz_data_tgs_req = hdb_ldb_authz_data_tgs_req;
437         entry_ex->authz_data_as_req = hdb_ldb_authz_data_as_req;
438
439 out:
440         if (ret != 0) {
441                 /* This doesn't free ent itself, that is for the eventual caller to do */
442                 hdb_free_entry(context, entry_ex);
443         } else {
444                 talloc_steal(db, entry_ex->ctx);
445         }
446
447         return ret;
448 }
449
450 static krb5_error_code LDB_lookup_principal(krb5_context context, struct ldb_context *ldb_ctx,                                  
451                                             TALLOC_CTX *mem_ctx,
452                                             krb5_const_principal principal,
453                                             enum hdb_ldb_ent_type ent_type,
454                                             const struct ldb_dn *realm_dn,
455                                             struct ldb_message ***pmsg)
456 {
457         krb5_error_code ret;
458         int lret;
459         char *filter = NULL;
460         const char * const *princ_attrs = krb5_attrs;
461
462         char *short_princ;
463         char *short_princ_talloc;
464
465         char *realm_dn_str;
466
467         struct ldb_result *res = NULL;
468
469         ret = krb5_unparse_name_norealm(context, principal, &short_princ);
470
471         if (ret != 0) {
472                 krb5_set_error_string(context, "LDB_lookup_principal: could not parse principal");
473                 krb5_warnx(context, "LDB_lookup_principal: could not parse principal");
474                 return ret;
475         }
476
477         short_princ_talloc = talloc_strdup(mem_ctx, short_princ);
478         free(short_princ);
479         if (!short_princ_talloc) {
480                 krb5_set_error_string(context, "LDB_lookup_principal: talloc_strdup() failed!");
481                 return ENOMEM;
482         }
483
484         switch (ent_type) {
485         case HDB_LDB_ENT_TYPE_CLIENT:
486                 /* Can't happen */
487                 return EINVAL;
488         case HDB_LDB_ENT_TYPE_ANY:
489                 /* Can't happen */
490                 return EINVAL;
491         case HDB_LDB_ENT_TYPE_KRBTGT:
492                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
493                                          KRB5_TGS_NAME);
494                 break;
495         case HDB_LDB_ENT_TYPE_SERVER:
496                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=user)(samAccountName=%s))", 
497                                          short_princ_talloc);
498                 break;
499         }
500
501         if (!filter) {
502                 krb5_set_error_string(context, "talloc_asprintf: out of memory");
503                 return ENOMEM;
504         }
505
506         lret = ldb_search(ldb_ctx, realm_dn, LDB_SCOPE_SUBTREE, filter, princ_attrs, &res);
507
508         realm_dn_str = ldb_dn_linearize(mem_ctx, realm_dn);
509
510         if (lret != LDB_SUCCESS) {
511                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
512                 return HDB_ERR_NOENTRY;
513         } else if (res->count == 0 || res->count > 1) {
514                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
515                 return HDB_ERR_NOENTRY;
516         }
517         talloc_steal(mem_ctx, res->msgs);
518         *pmsg = res->msgs;
519         talloc_free(res);
520         return 0;
521 }
522
523 static krb5_error_code LDB_lookup_realm(krb5_context context, struct ldb_context *ldb_ctx, 
524                                         TALLOC_CTX *mem_ctx,
525                                         const char *realm,
526                                         struct ldb_message ***pmsg)
527 {
528         int ret;
529         char *cross_ref_filter;
530         struct ldb_result *cross_ref_res;
531
532         cross_ref_filter = talloc_asprintf(mem_ctx, 
533                                            "(&(&(|(&(dnsRoot=%s)(nETBIOSName=*))(nETBIOSName=%s))(objectclass=crossRef))(ncName=*))",
534                                            realm, realm);
535         if (!cross_ref_filter) {
536                 krb5_set_error_string(context, "asprintf: out of memory");
537                 return ENOMEM;
538         }
539
540         ret = ldb_search(ldb_ctx, NULL, LDB_SCOPE_SUBTREE, cross_ref_filter, realm_ref_attrs, &cross_ref_res);
541
542         if (ret != LDB_SUCCESS) {
543                 DEBUG(3, ("Failed to search for %s: %s\n", cross_ref_filter, ldb_errstring(ldb_ctx)));
544                 talloc_free(cross_ref_res);
545                 return HDB_ERR_NOENTRY;
546         } else if (cross_ref_res->count == 0 || cross_ref_res->count > 1) {
547                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", cross_ref_filter, cross_ref_res->count));
548                 talloc_free(cross_ref_res);
549                 return HDB_ERR_NOENTRY;
550         }
551
552         if (pmsg) {
553                 *pmsg = cross_ref_res->msgs;
554                 talloc_steal(mem_ctx, cross_ref_res->msgs);
555         }
556         talloc_free(cross_ref_res);
557
558         return 0;
559 }
560
561
562 static krb5_error_code LDB_open(krb5_context context, HDB *db, int flags, mode_t mode)
563 {
564         if (db->hdb_master_key_set) {
565                 krb5_warnx(context, "LDB_open: use of a master key incompatible with LDB\n");
566                 krb5_set_error_string(context, "LDB_open: use of a master key incompatible with LDB\n");
567                 return HDB_ERR_NOENTRY;
568         }               
569
570         return 0;
571 }
572
573 static krb5_error_code LDB_close(krb5_context context, HDB *db)
574 {
575         return 0;
576 }
577
578 static krb5_error_code LDB_lock(krb5_context context, HDB *db, int operation)
579 {
580         return 0;
581 }
582
583 static krb5_error_code LDB_unlock(krb5_context context, HDB *db)
584 {
585         return 0;
586 }
587
588 static krb5_error_code LDB_rename(krb5_context context, HDB *db, const char *new_name)
589 {
590         return HDB_ERR_DB_INUSE;
591 }
592
593 static krb5_error_code LDB_fetch_client(krb5_context context, HDB *db, 
594                                         TALLOC_CTX *mem_ctx, 
595                                         krb5_const_principal principal,
596                                         unsigned flags,
597                                         hdb_entry_ex *entry_ex) {
598         NTSTATUS nt_status;
599         char *principal_string;
600         krb5_error_code ret;
601         struct ldb_message **msg = NULL;
602         struct ldb_message **realm_ref_msg = NULL;
603
604         ret = krb5_unparse_name(context, principal, &principal_string);
605         
606         if (ret != 0) {
607                 return ret;
608         }
609         
610         nt_status = sam_get_results_principal((struct ldb_context *)db->hdb_db,
611                                               mem_ctx, principal_string, 
612                                               &msg, &realm_ref_msg);
613         free(principal_string);
614         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
615                 talloc_free(mem_ctx);
616                 return HDB_ERR_NOENTRY;
617         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
618                 talloc_free(mem_ctx);
619                 return ENOMEM;
620         } else if (!NT_STATUS_IS_OK(nt_status)) {
621                 talloc_free(mem_ctx);
622                 return EINVAL;
623         }
624         
625         ret = LDB_message2entry(context, db, mem_ctx, 
626                                 principal, HDB_LDB_ENT_TYPE_CLIENT,
627                                 msg[0], realm_ref_msg[0], entry_ex);
628         return ret;
629 }
630
631 static krb5_error_code LDB_fetch_krbtgt(krb5_context context, HDB *db, 
632                                         TALLOC_CTX *mem_ctx, 
633                                         krb5_const_principal principal,
634                                         unsigned flags,
635                                         hdb_entry_ex *entry_ex)
636 {
637         krb5_error_code ret;
638         struct ldb_message **msg = NULL;
639         struct ldb_message **realm_ref_msg = NULL;
640         const struct ldb_dn *realm_dn;
641
642         krb5_principal alloc_principal = NULL;
643         if (principal->name.name_string.len != 2
644             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
645                 /* Not a krbtgt */
646                 return HDB_ERR_NOENTRY;
647         }
648
649         /* krbtgt case.  Either us or a trusted realm */
650         if ((LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db,
651                               mem_ctx, principal->name.name_string.val[1], &realm_ref_msg) == 0)) {
652                 /* us */
653                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
654                  * is in our db, then direct the caller at our primary
655                  * krgtgt */
656                 
657                 const char *dnsdomain = ldb_msg_find_string(realm_ref_msg[0], "dnsRoot", NULL);
658                 char *realm_fixed = strupper_talloc(mem_ctx, dnsdomain);
659                 if (!realm_fixed) {
660                         krb5_set_error_string(context, "strupper_talloc: out of memory");
661                         return ENOMEM;
662                 }
663                 
664                 ret = krb5_copy_principal(context, principal, &alloc_principal);
665                 if (ret) {
666                         return ret;
667                 }
668
669                 free(alloc_principal->name.name_string.val[1]);
670                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
671                 talloc_free(realm_fixed);
672                 if (!alloc_principal->name.name_string.val[1]) {
673                         krb5_set_error_string(context, "LDB_fetch: strdup() failed!");
674                         return ENOMEM;
675                 }
676                 principal = alloc_principal;
677                 realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
678                 
679         } else {
680                 /* we should lookup trusted domains */
681                 return HDB_ERR_NOENTRY;
682         }
683
684         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
685         
686         ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
687                                    mem_ctx, 
688                                    principal, HDB_LDB_ENT_TYPE_KRBTGT, realm_dn, &msg);
689         
690         if (ret != 0) {
691                 krb5_warnx(context, "LDB_fetch: could not find principal in DB");
692                 krb5_set_error_string(context, "LDB_fetch: could not find principal in DB");
693                 return ret;
694         }
695
696         ret = LDB_message2entry(context, db, mem_ctx, 
697                                 principal, HDB_LDB_ENT_TYPE_KRBTGT, 
698                                 msg[0], realm_ref_msg[0], entry_ex);
699         if (ret != 0) {
700                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
701         }
702         return ret;
703 }
704
705 static krb5_error_code LDB_fetch_server(krb5_context context, HDB *db, 
706                                         TALLOC_CTX *mem_ctx, 
707                                         krb5_const_principal principal,
708                                         unsigned flags,
709                                         hdb_entry_ex *entry_ex)
710 {
711         krb5_error_code ret;
712         const char *realm;
713         struct ldb_message **msg = NULL;
714         struct ldb_message **realm_ref_msg = NULL;
715         if (principal->name.name_string.len >= 2) {
716                 /* 'normal server' case */
717                 int ldb_ret;
718                 NTSTATUS nt_status;
719                 struct ldb_dn *user_dn, *domain_dn;
720                 char *principal_string;
721                 
722                 ret = krb5_unparse_name_norealm(context, principal, &principal_string);
723                 if (ret != 0) {
724                         return ret;
725                 }
726                 
727                 /* At this point we may find the host is known to be
728                  * in a different realm, so we should generate a
729                  * referral instead */
730                 nt_status = crack_service_principal_name((struct ldb_context *)db->hdb_db,
731                                                          mem_ctx, principal_string, 
732                                                          &user_dn, &domain_dn);
733                 free(principal_string);
734                 
735                 if (!NT_STATUS_IS_OK(nt_status)) {
736                         return HDB_ERR_NOENTRY;
737                 }
738                 
739                 ldb_ret = gendb_search_dn((struct ldb_context *)db->hdb_db,
740                                           mem_ctx, user_dn, &msg, krb5_attrs);
741                 
742                 if (ldb_ret != 1) {
743                         return HDB_ERR_NOENTRY;
744                 }
745                 
746                 ldb_ret = gendb_search((struct ldb_context *)db->hdb_db,
747                                        mem_ctx, NULL, &realm_ref_msg, realm_ref_attrs, 
748                                        "ncName=%s", ldb_dn_linearize(mem_ctx, domain_dn));
749                 
750                 if (ldb_ret != 1) {
751                         return HDB_ERR_NOENTRY;
752                 }
753                 
754         } else {
755                 const struct ldb_dn *realm_dn;
756                 /* server as client principal case, but we must not lookup userPrincipalNames */
757
758                 realm = krb5_principal_get_realm(context, principal);
759                 
760                 ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
761                                        mem_ctx, realm, &realm_ref_msg);
762                 if (ret != 0) {
763                         return HDB_ERR_NOENTRY;
764                 }
765                 
766                 realm_dn = samdb_result_dn(mem_ctx, realm_ref_msg[0], "nCName", NULL);
767                 
768                 ret = LDB_lookup_principal(context, (struct ldb_context *)db->hdb_db, 
769                                            mem_ctx, 
770                                            principal, HDB_LDB_ENT_TYPE_SERVER, realm_dn, &msg);
771                 
772                 if (ret != 0) {
773                         return ret;
774                 }
775         }
776
777         ret = LDB_message2entry(context, db, mem_ctx, 
778                                 principal, HDB_LDB_ENT_TYPE_SERVER,
779                                 msg[0], realm_ref_msg[0], entry_ex);
780         if (ret != 0) {
781                 krb5_warnx(context, "LDB_fetch: message2entry failed"); 
782         }
783
784         return ret;
785 }
786                         
787 static krb5_error_code LDB_fetch(krb5_context context, HDB *db, 
788                                  krb5_const_principal principal,
789                                  unsigned flags,
790                                  hdb_entry_ex *entry_ex)
791 {
792         krb5_error_code ret;
793
794         TALLOC_CTX *mem_ctx = talloc_named(db, 0, "LDB_fetch context");
795
796         if (!mem_ctx) {
797                 krb5_set_error_string(context, "LDB_fetch: talloc_named() failed!");
798                 return ENOMEM;
799         }
800
801         if (flags & HDB_F_GET_CLIENT) {
802                 ret = LDB_fetch_client(context, db, mem_ctx, principal, flags, entry_ex);
803                 if (ret != HDB_ERR_NOENTRY) {
804                         talloc_free(mem_ctx);
805                         return ret;
806                 }
807         }
808         if (flags & HDB_F_GET_SERVER) {
809                 ret = LDB_fetch_server(context, db, mem_ctx, principal, flags, entry_ex);
810                 if (ret != HDB_ERR_NOENTRY) {
811                         return ret;
812                 }
813                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
814                 if (ret != HDB_ERR_NOENTRY) {
815                         return ret;
816                 }
817         }
818         if (flags & HDB_F_GET_KRBTGT) {
819                 ret = LDB_fetch_krbtgt(context, db, mem_ctx, principal, flags, entry_ex);
820                 if (ret != HDB_ERR_NOENTRY) {
821                         return ret;
822                 }
823         }
824         return ret;
825 }
826
827 static krb5_error_code LDB_store(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
828 {
829         return HDB_ERR_DB_INUSE;
830 }
831
832 static krb5_error_code LDB_remove(krb5_context context, HDB *db, krb5_const_principal principal)
833 {
834         return HDB_ERR_DB_INUSE;
835 }
836
837 struct hdb_ldb_seq {
838         struct ldb_context *ctx;
839         int index;
840         int count;
841         struct ldb_message **msgs;
842         struct ldb_message **realm_ref_msgs;
843 };
844
845 static krb5_error_code LDB_seq(krb5_context context, HDB *db, unsigned flags, hdb_entry_ex *entry)
846 {
847         krb5_error_code ret;
848         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
849         TALLOC_CTX *mem_ctx;
850         hdb_entry_ex entry_ex;
851         memset(&entry_ex, '\0', sizeof(entry_ex));
852
853         if (!priv) {
854                 return HDB_ERR_NOENTRY;
855         }
856
857         mem_ctx = talloc_named(priv, 0, "LDB_seq context");
858
859         if (!mem_ctx) {
860                 krb5_set_error_string(context, "LDB_seq: talloc_named() failed!");
861                 return ENOMEM;
862         }
863
864         if (priv->index < priv->count) {
865                 ret = LDB_message2entry(context, db, mem_ctx, 
866                                         NULL, HDB_LDB_ENT_TYPE_ANY, 
867                                         priv->msgs[priv->index++], 
868                                         priv->realm_ref_msgs[0], entry);
869         } else {
870                 ret = HDB_ERR_NOENTRY;
871         }
872
873         if (ret != 0) {
874                 talloc_free(priv);
875                 db->hdb_openp = NULL;
876         } else {
877                 talloc_free(mem_ctx);
878         }
879
880         return ret;
881 }
882
883 static krb5_error_code LDB_firstkey(krb5_context context, HDB *db, unsigned flags,
884                                         hdb_entry_ex *entry)
885 {
886         struct ldb_context *ldb_ctx = (struct ldb_context *)db->hdb_db;
887         struct hdb_ldb_seq *priv = (struct hdb_ldb_seq *)db->hdb_openp;
888         char *realm;
889         struct ldb_dn *realm_dn = NULL;
890         struct ldb_result *res = NULL;
891         struct ldb_message **realm_ref_msgs = NULL;
892         krb5_error_code ret;
893         TALLOC_CTX *mem_ctx;
894         int lret;
895
896         if (priv) {
897                 talloc_free(priv);
898                 db->hdb_openp = 0;
899         }
900
901         priv = (struct hdb_ldb_seq *) talloc(db, struct hdb_ldb_seq);
902         if (!priv) {
903                 krb5_set_error_string(context, "talloc: out of memory");
904                 return ENOMEM;
905         }
906
907         priv->ctx = ldb_ctx;
908         priv->index = 0;
909         priv->msgs = NULL;
910         priv->realm_ref_msgs = NULL;
911         priv->count = 0;
912
913         mem_ctx = talloc_named(priv, 0, "LDB_firstkey context");
914
915         if (!mem_ctx) {
916                 krb5_set_error_string(context, "LDB_firstkey: talloc_named() failed!");
917                 return ENOMEM;
918         }
919
920         ret = krb5_get_default_realm(context, &realm);
921         if (ret != 0) {
922                 talloc_free(priv);
923                 return ret;
924         }
925                 
926         ret = LDB_lookup_realm(context, (struct ldb_context *)db->hdb_db, 
927                                mem_ctx, realm, &realm_ref_msgs);
928
929         free(realm);
930
931         if (ret != 0) {
932                 talloc_free(priv);
933                 krb5_warnx(context, "LDB_firstkey: could not find realm\n");
934                 return HDB_ERR_NOENTRY;
935         }
936
937         realm_dn = samdb_result_dn(mem_ctx, realm_ref_msgs[0], "nCName", NULL);
938
939         priv->realm_ref_msgs = talloc_steal(priv, realm_ref_msgs);
940
941         krb5_warnx(context, "LDB_firstkey: realm ok\n");
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         /* Disgusting, ugly hack, but it means one less private hook */
1048         nt_status = kdc_hdb_ldb_create(context->mem_ctx, context, db, arg);
1049
1050         if (NT_STATUS_IS_OK(nt_status)) {
1051                 return 0;
1052         }
1053         return EINVAL;
1054 }