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