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