2cda04bca8fcc143f57ca48d44a53a92a4616b3b
[kai/samba.git] / source4 / kdc / db-glue.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Database Glue between Samba and the KDC
5
6    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
7    Copyright (C) Simo Sorce <idra@samba.org> 2010
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "system/time.h"
26 #include "../libds/common/flags.h"
27 #include "lib/ldb/include/ldb.h"
28 #include "librpc/gen_ndr/netlogon.h"
29 #include "libcli/security/security.h"
30 #include "auth/auth.h"
31 #include "auth/credentials/credentials.h"
32 #include "auth/auth_sam.h"
33 #include "../lib/util/util_ldb.h"
34 #include "dsdb/samdb/samdb.h"
35 #include "dsdb/common/util.h"
36 #include "librpc/ndr/libndr.h"
37 #include "librpc/gen_ndr/ndr_drsblobs.h"
38 #include "librpc/gen_ndr/lsa.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "param/param.h"
41 #include "../lib/crypto/md4.h"
42 #include "system/kerberos.h"
43 #include "auth/kerberos/kerberos.h"
44 #include <hdb.h>
45 #include "kdc/samba_kdc.h"
46 #include "kdc/db-glue.h"
47
48 enum samba_kdc_ent_type
49 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
50   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
51
52 enum trust_direction {
53         UNKNOWN = 0,
54         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
55         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
56 };
57
58 static const char *trust_attrs[] = {
59         "trustPartner",
60         "trustAuthIncoming",
61         "trustAuthOutgoing",
62         "whenCreated",
63         "msDS-SupportedEncryptionTypes",
64         "trustAttributes",
65         "trustDirection",
66         "trustType",
67         NULL
68 };
69
70 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime default_val)
71 {
72     const char *tmp;
73     const char *gentime;
74     struct tm tm;
75
76     gentime = ldb_msg_find_attr_as_string(msg, attr, NULL);
77     if (!gentime)
78         return default_val;
79
80     tmp = strptime(gentime, "%Y%m%d%H%M%SZ", &tm);
81     if (tmp == NULL) {
82             return default_val;
83     }
84
85     return timegm(&tm);
86 }
87
88 static HDBFlags uf2HDBFlags(krb5_context context, int userAccountControl, enum samba_kdc_ent_type ent_type)
89 {
90         HDBFlags flags = int2HDBFlags(0);
91
92         /* we don't allow kadmin deletes */
93         flags.immutable = 1;
94
95         /* mark the principal as invalid to start with */
96         flags.invalid = 1;
97
98         flags.renewable = 1;
99
100         /* All accounts are servers, but this may be disabled again in the caller */
101         flags.server = 1;
102
103         /* Account types - clear the invalid bit if it turns out to be valid */
104         if (userAccountControl & UF_NORMAL_ACCOUNT) {
105                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
106                         flags.client = 1;
107                 }
108                 flags.invalid = 0;
109         }
110
111         if (userAccountControl & UF_INTERDOMAIN_TRUST_ACCOUNT) {
112                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
113                         flags.client = 1;
114                 }
115                 flags.invalid = 0;
116         }
117         if (userAccountControl & UF_WORKSTATION_TRUST_ACCOUNT) {
118                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
119                         flags.client = 1;
120                 }
121                 flags.invalid = 0;
122         }
123         if (userAccountControl & UF_SERVER_TRUST_ACCOUNT) {
124                 if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT || ent_type == SAMBA_KDC_ENT_TYPE_ANY) {
125                         flags.client = 1;
126                 }
127                 flags.invalid = 0;
128         }
129
130         /* Not permitted to act as a client if disabled */
131         if (userAccountControl & UF_ACCOUNTDISABLE) {
132                 flags.client = 0;
133         }
134         if (userAccountControl & UF_LOCKOUT) {
135                 flags.invalid = 1;
136         }
137 /*
138         if (userAccountControl & UF_PASSWORD_NOTREQD) {
139                 flags.invalid = 1;
140         }
141 */
142 /*
143         UF_PASSWORD_CANT_CHANGE and UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED are irrelevent
144 */
145         if (userAccountControl & UF_TEMP_DUPLICATE_ACCOUNT) {
146                 flags.invalid = 1;
147         }
148
149 /* UF_DONT_EXPIRE_PASSWD and UF_USE_DES_KEY_ONLY handled in samba_kdc_message2entry() */
150
151 /*
152         if (userAccountControl & UF_MNS_LOGON_ACCOUNT) {
153                 flags.invalid = 1;
154         }
155 */
156         if (userAccountControl & UF_SMARTCARD_REQUIRED) {
157                 flags.require_hwauth = 1;
158         }
159         if (userAccountControl & UF_TRUSTED_FOR_DELEGATION) {
160                 flags.ok_as_delegate = 1;
161         }
162         if (!(userAccountControl & UF_NOT_DELEGATED)) {
163                 flags.forwardable = 1;
164                 flags.proxiable = 1;
165         }
166
167         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
168                 flags.require_preauth = 0;
169         } else {
170                 flags.require_preauth = 1;
171
172         }
173         return flags;
174 }
175
176 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
177 {
178     hdb_entry_ex *entry_ex = p->entry_ex;
179     free_hdb_entry(&entry_ex->entry);
180     return 0;
181 }
182
183 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
184 {
185         /* this function is called only from hdb_free_entry().
186          * Make sure we neutralize the destructor or we will
187          * get a double free later when hdb_free_entry() will
188          * try to call free_hdb_entry() */
189         talloc_set_destructor(entry_ex->ctx, NULL);
190
191         /* now proceed to free the talloc part */
192         talloc_free(entry_ex->ctx);
193 }
194
195 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
196                                                     TALLOC_CTX *mem_ctx,
197                                                     struct ldb_message *msg,
198                                                     uint32_t rid,
199                                                     unsigned int userAccountControl,
200                                                     enum samba_kdc_ent_type ent_type,
201                                                     hdb_entry_ex *entry_ex)
202 {
203         krb5_error_code ret = 0;
204         enum ndr_err_code ndr_err;
205         struct samr_Password *hash;
206         const struct ldb_val *sc_val;
207         struct supplementalCredentialsBlob scb;
208         struct supplementalCredentialsPackage *scpk = NULL;
209         bool newer_keys = false;
210         struct package_PrimaryKerberosBlob _pkb;
211         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
212         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
213         uint16_t i;
214         uint16_t allocated_keys = 0;
215         int rodc_krbtgt_number = 0;
216         bool is_rodc = false;
217
218         /* Supported Enc for this entry */
219         uint32_t supported_enctypes = ENC_ALL_TYPES; /* by default, we support all enc types */
220
221         /* However, if this is a TGS-REQ, then lock it down to a
222          * reasonable guess as to what the server can decode.  The
223          * krbtgt is special - default to use what is stored for the KDC */
224         if (rid != DOMAIN_RID_KRBTGT && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
225                 /* This is the standard set for a server that has not declared a msDS-SupportedEncryptionTypes */
226                 supported_enctypes = ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
227         }
228         supported_enctypes = ldb_msg_find_attr_as_uint(msg, "msDS-SupportedEncryptionTypes",
229                                                         supported_enctypes);
230         /* Is this the krbtgt or a RODC */
231
232         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
233                 is_rodc = true;
234
235                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
236
237                 if (rodc_krbtgt_number == -1) {
238                         return EINVAL;
239                 }
240         }
241
242         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
243                 /* Be double-sure never to use DES here */
244                 supported_enctypes &= ~(ENC_CRC32|ENC_RSA_MD5);
245         }
246
247         switch (ent_type) {
248         case SAMBA_KDC_ENT_TYPE_KRBTGT:
249         case SAMBA_KDC_ENT_TYPE_TRUST:
250                 /* Disallow krbtgt and trust tickets to be DES encrypted, it's just too dangerous */
251                 supported_enctypes &= ~(ENC_CRC32|ENC_RSA_MD5);
252                 break;
253         default:
254                 break;
255                 /* No further restrictions */
256         }
257
258         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
259         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
260                 /* However, don't allow use of DES, if we were told not to by msDS-SupportedEncTypes */
261                 supported_enctypes &= ENC_CRC32|ENC_RSA_MD5;
262         }
263
264         entry_ex->entry.keys.val = NULL;
265         entry_ex->entry.keys.len = 0;
266
267         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
268         if (is_rodc) {
269                 entry_ex->entry.kvno |= (rodc_krbtgt_number << 16);
270         }
271
272         /* Get keys from the db */
273
274         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
275         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
276
277         /* unicodePwd for enctype 0x17 (23) if present */
278         if (hash) {
279                 allocated_keys++;
280         }
281
282         /* supplementalCredentials if present */
283         if (sc_val) {
284                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
285                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
286                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
287                         dump_data(0, sc_val->data, sc_val->length);
288                         ret = EINVAL;
289                         goto out;
290                 }
291
292                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
293                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
294                         ret = EINVAL;
295                         goto out;
296                 }
297
298                 for (i=0; i < scb.sub.num_packages; i++) {
299                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
300                                 scpk = &scb.sub.packages[i];
301                                 if (!scpk->data || !scpk->data[0]) {
302                                         scpk = NULL;
303                                         continue;
304                                 }
305                                 newer_keys = true;
306                                 break;
307                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
308                                 scpk = &scb.sub.packages[i];
309                                 if (!scpk->data || !scpk->data[0]) {
310                                         scpk = NULL;
311                                 }
312                                 /*
313                                  * we don't break here in hope to find
314                                  * a Kerberos-Newer-Keys package
315                                  */
316                         }
317                 }
318         }
319         /*
320          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
321          * of supplementalCredentials
322          */
323         if (scpk) {
324                 DATA_BLOB blob;
325
326                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
327                 if (!blob.data) {
328                         ret = ENOMEM;
329                         goto out;
330                 }
331
332                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
333                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
334                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
335                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
336                         ret = EINVAL;
337                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
338                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
339                         goto out;
340                 }
341
342                 if (newer_keys && _pkb.version != 4) {
343                         ret = EINVAL;
344                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
345                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
346                         goto out;
347                 }
348
349                 if (!newer_keys && _pkb.version != 3) {
350                         ret = EINVAL;
351                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
352                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
353                         goto out;
354                 }
355
356                 if (_pkb.version == 4) {
357                         pkb4 = &_pkb.ctr.ctr4;
358                         allocated_keys += pkb4->num_keys;
359                 } else if (_pkb.version == 3) {
360                         pkb3 = &_pkb.ctr.ctr3;
361                         allocated_keys += pkb3->num_keys;
362                 }
363         }
364
365         if (allocated_keys == 0) {
366                 /* oh, no password.  Apparently (comment in
367                  * hdb-ldap.c) this violates the ASN.1, but this
368                  * allows an entry with no keys (yet). */
369                 return 0;
370         }
371
372         /* allocate space to decode into */
373         entry_ex->entry.keys.len = 0;
374         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
375         if (entry_ex->entry.keys.val == NULL) {
376                 ret = ENOMEM;
377                 goto out;
378         }
379
380         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
381                 Key key;
382
383                 key.mkvno = 0;
384                 key.salt = NULL; /* No salt for this enc type */
385
386                 ret = krb5_keyblock_init(context,
387                                          ENCTYPE_ARCFOUR_HMAC,
388                                          hash->hash, sizeof(hash->hash),
389                                          &key.key);
390                 if (ret) {
391                         goto out;
392                 }
393
394                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
395                 entry_ex->entry.keys.len++;
396         }
397
398         if (pkb4) {
399                 for (i=0; i < pkb4->num_keys; i++) {
400                         Key key;
401
402                         if (!pkb4->keys[i].value) continue;
403
404                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
405                                 continue;
406                         }
407
408                         key.mkvno = 0;
409                         key.salt = NULL;
410
411                         if (pkb4->salt.string) {
412                                 DATA_BLOB salt;
413
414                                 salt = data_blob_string_const(pkb4->salt.string);
415
416                                 key.salt = calloc(1, sizeof(*key.salt));
417                                 if (key.salt == NULL) {
418                                         ret = ENOMEM;
419                                         goto out;
420                                 }
421
422                                 key.salt->type = hdb_pw_salt;
423
424                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
425                                 if (ret) {
426                                         free(key.salt);
427                                         key.salt = NULL;
428                                         goto out;
429                                 }
430                         }
431
432                         /* TODO: maybe pass the iteration_count somehow... */
433
434                         ret = krb5_keyblock_init(context,
435                                                  pkb4->keys[i].keytype,
436                                                  pkb4->keys[i].value->data,
437                                                  pkb4->keys[i].value->length,
438                                                  &key.key);
439                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
440                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
441                                          pkb4->keys[i].keytype));
442                                 ret = 0;
443                                 continue;
444                         }
445                         if (ret) {
446                                 if (key.salt) {
447                                         free_Salt(key.salt);
448                                         free(key.salt);
449                                         key.salt = NULL;
450                                 }
451                                 goto out;
452                         }
453
454                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
455                         entry_ex->entry.keys.len++;
456                 }
457         } else if (pkb3) {
458                 for (i=0; i < pkb3->num_keys; i++) {
459                         Key key;
460
461                         if (!pkb3->keys[i].value) continue;
462
463                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
464                                 continue;
465                         }
466
467                         key.mkvno = 0;
468                         key.salt = NULL;
469
470                         if (pkb3->salt.string) {
471                                 DATA_BLOB salt;
472
473                                 salt = data_blob_string_const(pkb3->salt.string);
474
475                                 key.salt = calloc(1, sizeof(*key.salt));
476                                 if (key.salt == NULL) {
477                                         ret = ENOMEM;
478                                         goto out;
479                                 }
480
481                                 key.salt->type = hdb_pw_salt;
482
483                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
484                                 if (ret) {
485                                         free(key.salt);
486                                         key.salt = NULL;
487                                         goto out;
488                                 }
489                         }
490
491                         ret = krb5_keyblock_init(context,
492                                                  pkb3->keys[i].keytype,
493                                                  pkb3->keys[i].value->data,
494                                                  pkb3->keys[i].value->length,
495                                                  &key.key);
496                         if (ret) {
497                                 if (key.salt) {
498                                         free_Salt(key.salt);
499                                         free(key.salt);
500                                         key.salt = NULL;
501                                 }
502                                 goto out;
503                         }
504
505                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
506                         entry_ex->entry.keys.len++;
507                 }
508         }
509
510 out:
511         if (ret != 0) {
512                 entry_ex->entry.keys.len = 0;
513         }
514         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
515                 free(entry_ex->entry.keys.val);
516                 entry_ex->entry.keys.val = NULL;
517         }
518         return ret;
519 }
520
521 /*
522  * Construct an hdb_entry from a directory entry.
523  */
524 static krb5_error_code samba_kdc_message2entry(krb5_context context,
525                                          struct samba_kdc_db_context *kdc_db_ctx,
526                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
527                                          enum samba_kdc_ent_type ent_type,
528                                          struct ldb_dn *realm_dn,
529                                          struct ldb_message *msg,
530                                          hdb_entry_ex *entry_ex)
531 {
532         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
533         unsigned int userAccountControl;
534         unsigned int i;
535         krb5_error_code ret = 0;
536         krb5_boolean is_computer = FALSE;
537         char *realm = strupper_talloc(mem_ctx, lpcfg_realm(lp_ctx));
538
539         struct samba_kdc_entry *p;
540         NTTIME acct_expiry;
541         NTSTATUS status;
542
543         uint32_t rid;
544         struct ldb_message_element *objectclasses;
545         struct ldb_val computer_val;
546         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
547         computer_val.data = discard_const_p(uint8_t,"computer");
548         computer_val.length = strlen((const char *)computer_val.data);
549
550         if (!samAccountName) {
551                 ret = ENOENT;
552                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
553                 goto out;
554         }
555
556         objectclasses = ldb_msg_find_element(msg, "objectClass");
557
558         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
559                 is_computer = TRUE;
560         }
561
562         memset(entry_ex, 0, sizeof(*entry_ex));
563
564         if (!realm) {
565                 ret = ENOMEM;
566                 krb5_set_error_message(context, ret, "talloc_strdup: out of memory");
567                 goto out;
568         }
569
570         p = talloc(mem_ctx, struct samba_kdc_entry);
571         if (!p) {
572                 ret = ENOMEM;
573                 goto out;
574         }
575
576         p->kdc_db_ctx = kdc_db_ctx;
577         p->entry_ex = entry_ex;
578         p->realm_dn = talloc_reference(p, realm_dn);
579         if (!p->realm_dn) {
580                 ret = ENOMEM;
581                 goto out;
582         }
583
584         talloc_set_destructor(p, samba_kdc_entry_destructor);
585
586         /* make sure we do not have bogus data in there */
587         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
588
589         entry_ex->ctx = p;
590         entry_ex->free_entry = samba_kdc_free_entry;
591
592         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
593
594
595         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
596         if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
597                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
598         } else {
599                 ret = copy_Principal(principal, entry_ex->entry.principal);
600                 if (ret) {
601                         krb5_clear_error_message(context);
602                         goto out;
603                 }
604
605                 /* While we have copied the client principal, tests
606                  * show that Win2k3 returns the 'corrected' realm, not
607                  * the client-specified realm.  This code attempts to
608                  * replace the client principal's realm with the one
609                  * we determine from our records */
610
611                 /* this has to be with malloc() */
612                 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
613         }
614
615         /* First try and figure out the flags based on the userAccountControl */
616         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
617
618         /* Windows 2008 seems to enforce this (very sensible) rule by
619          * default - don't allow offline attacks on a user's password
620          * by asking for a ticket to them as a service (encrypted with
621          * their probably patheticly insecure password) */
622
623         if (entry_ex->entry.flags.server
624             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
625                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
626                         entry_ex->entry.flags.server = 0;
627                 }
628         }
629
630         {
631                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
632                  * of the Heimdal KDC.  They are stored in a the traditional
633                  * DB for audit purposes, and still form part of the structure
634                  * we must return */
635
636                 /* use 'whenCreated' */
637                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
638                 /* use 'kadmin' for now (needed by mit_samba) */
639                 krb5_make_principal(context,
640                                     &entry_ex->entry.created_by.principal,
641                                     realm, "kadmin", NULL);
642
643                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
644                 if (entry_ex->entry.modified_by == NULL) {
645                         ret = ENOMEM;
646                         krb5_set_error_message(context, ret, "malloc: out of memory");
647                         goto out;
648                 }
649
650                 /* use 'whenChanged' */
651                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
652                 /* use 'kadmin' for now (needed by mit_samba) */
653                 krb5_make_principal(context,
654                                     &entry_ex->entry.modified_by->principal,
655                                     realm, "kadmin", NULL);
656         }
657
658
659         /* The lack of password controls etc applies to krbtgt by
660          * virtue of being that particular RID */
661         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
662
663         if (!NT_STATUS_IS_OK(status)) {
664                 ret = EINVAL;
665                 goto out;
666         }
667
668         if (rid == DOMAIN_RID_KRBTGT) {
669                 entry_ex->entry.valid_end = NULL;
670                 entry_ex->entry.pw_end = NULL;
671
672                 entry_ex->entry.flags.invalid = 0;
673                 entry_ex->entry.flags.server = 1;
674
675                 /* Don't mark all requests for the krbtgt/realm as
676                  * 'change password', as otherwise we could get into
677                  * trouble, and not enforce the password expirty.
678                  * Instead, only do it when request is for the kpasswd service */
679                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
680                     && principal->name.name_string.len == 2
681                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
682                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
683                     && lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)) {
684                         entry_ex->entry.flags.change_pw = 1;
685                 }
686                 entry_ex->entry.flags.client = 0;
687                 entry_ex->entry.flags.forwardable = 1;
688                 entry_ex->entry.flags.ok_as_delegate = 1;
689         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
690                 /* The account/password expiry only applies when the account is used as a
691                  * client (ie password login), not when used as a server */
692
693                 /* Make very well sure we don't use this for a client,
694                  * it could bypass the password restrictions */
695                 entry_ex->entry.flags.client = 0;
696
697                 entry_ex->entry.valid_end = NULL;
698                 entry_ex->entry.pw_end = NULL;
699
700         } else {
701                 NTTIME must_change_time
702                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
703                                                              realm_dn, msg);
704                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
705                         entry_ex->entry.pw_end = NULL;
706                 } else {
707                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
708                         if (entry_ex->entry.pw_end == NULL) {
709                                 ret = ENOMEM;
710                                 goto out;
711                         }
712                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
713                 }
714
715                 acct_expiry = samdb_result_account_expires(msg);
716                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
717                         entry_ex->entry.valid_end = NULL;
718                 } else {
719                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
720                         if (entry_ex->entry.valid_end == NULL) {
721                                 ret = ENOMEM;
722                                 goto out;
723                         }
724                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
725                 }
726         }
727
728         entry_ex->entry.valid_start = NULL;
729
730         entry_ex->entry.max_life = NULL;
731
732         entry_ex->entry.max_renew = NULL;
733
734         entry_ex->entry.generation = NULL;
735
736         /* Get keys from the db */
737         ret = samba_kdc_message2entry_keys(context, p, msg, 
738                                            rid, userAccountControl,
739                                            ent_type, entry_ex);
740         if (ret) {
741                 /* Could be bougus data in the entry, or out of memory */
742                 goto out;
743         }
744
745         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
746         if (entry_ex->entry.etypes == NULL) {
747                 krb5_clear_error_message(context);
748                 ret = ENOMEM;
749                 goto out;
750         }
751         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
752         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
753         if (entry_ex->entry.etypes->val == NULL) {
754                 krb5_clear_error_message(context);
755                 ret = ENOMEM;
756                 goto out;
757         }
758         for (i=0; i < entry_ex->entry.etypes->len; i++) {
759                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
760         }
761
762
763         p->msg = talloc_steal(p, msg);
764
765 out:
766         if (ret != 0) {
767                 /* This doesn't free ent itself, that is for the eventual caller to do */
768                 hdb_free_entry(context, entry_ex);
769         } else {
770                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
771         }
772
773         return ret;
774 }
775
776 /*
777  * Construct an hdb_entry from a directory entry.
778  */
779 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
780                                                struct samba_kdc_db_context *kdc_db_ctx,
781                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
782                                                enum trust_direction direction,
783                                                struct ldb_dn *realm_dn,
784                                                struct ldb_message *msg,
785                                                hdb_entry_ex *entry_ex)
786 {
787         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
788         const char *dnsdomain;
789         char *realm = strupper_talloc(mem_ctx, lpcfg_realm(lp_ctx));
790         DATA_BLOB password_utf16;
791         struct samr_Password password_hash;
792         const struct ldb_val *password_val;
793         struct trustAuthInOutBlob password_blob;
794         struct samba_kdc_entry *p;
795
796         enum ndr_err_code ndr_err;
797         int ret, trust_direction_flags;
798         unsigned int i;
799
800         p = talloc(mem_ctx, struct samba_kdc_entry);
801         if (!p) {
802                 ret = ENOMEM;
803                 goto out;
804         }
805
806         p->kdc_db_ctx = kdc_db_ctx;
807         p->entry_ex = entry_ex;
808         p->realm_dn = realm_dn;
809
810         talloc_set_destructor(p, samba_kdc_entry_destructor);
811
812         /* make sure we do not have bogus data in there */
813         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
814
815         entry_ex->ctx = p;
816         entry_ex->free_entry = samba_kdc_free_entry;
817
818         /* use 'whenCreated' */
819         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
820         /* use 'kadmin' for now (needed by mit_samba) */
821         krb5_make_principal(context,
822                             &entry_ex->entry.created_by.principal,
823                             realm, "kadmin", NULL);
824
825         entry_ex->entry.valid_start = NULL;
826
827         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
828
829         if (direction == INBOUND) {
830                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
831
832         } else { /* OUTBOUND */
833                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
834                 /* replace realm */
835                 talloc_free(realm);
836                 realm = strupper_talloc(mem_ctx, dnsdomain);
837                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
838         }
839
840         if (!password_val || !(trust_direction_flags & direction)) {
841                 ret = ENOENT;
842                 goto out;
843         }
844
845         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
846                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
847         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
848                 ret = EINVAL;
849                 goto out;
850         }
851
852         entry_ex->entry.kvno = -1;
853         for (i=0; i < password_blob.count; i++) {
854                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
855                         entry_ex->entry.kvno = password_blob.current.array[i].AuthInfo.version.version;
856                 }
857         }
858
859         for (i=0; i < password_blob.count; i++) {
860                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
861                         password_utf16 = data_blob_const(password_blob.current.array[i].AuthInfo.clear.password,
862                                                          password_blob.current.array[i].AuthInfo.clear.size);
863                         /* In the future, generate all sorts of
864                          * hashes, but for now we can't safely convert
865                          * the random strings windows uses into
866                          * utf8 */
867
868                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
869                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
870                         break;
871                 } else if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
872                         password_hash = password_blob.current.array[i].AuthInfo.nt4owf.password;
873                         break;
874                 }
875         }
876
877         if (i < password_blob.count) {
878                 Key key;
879                 /* Must have found a cleartext or MD4 password */
880                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
881
882                 key.mkvno = 0;
883                 key.salt = NULL; /* No salt for this enc type */
884
885                 if (entry_ex->entry.keys.val == NULL) {
886                         ret = ENOMEM;
887                         goto out;
888                 }
889
890                 ret = krb5_keyblock_init(context,
891                                          ENCTYPE_ARCFOUR_HMAC,
892                                          password_hash.hash, sizeof(password_hash.hash),
893                                          &key.key);
894
895                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
896                 entry_ex->entry.keys.len++;
897         }
898
899         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
900
901         ret = copy_Principal(principal, entry_ex->entry.principal);
902         if (ret) {
903                 krb5_clear_error_message(context);
904                 goto out;
905         }
906
907         /* While we have copied the client principal, tests
908          * show that Win2k3 returns the 'corrected' realm, not
909          * the client-specified realm.  This code attempts to
910          * replace the client principal's realm with the one
911          * we determine from our records */
912
913         krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
914         entry_ex->entry.flags = int2HDBFlags(0);
915         entry_ex->entry.flags.immutable = 1;
916         entry_ex->entry.flags.invalid = 0;
917         entry_ex->entry.flags.server = 1;
918         entry_ex->entry.flags.require_preauth = 1;
919
920         entry_ex->entry.pw_end = NULL;
921
922         entry_ex->entry.max_life = NULL;
923
924         entry_ex->entry.max_renew = NULL;
925
926         entry_ex->entry.generation = NULL;
927
928         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
929         if (entry_ex->entry.etypes == NULL) {
930                 krb5_clear_error_message(context);
931                 ret = ENOMEM;
932                 goto out;
933         }
934         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
935         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
936         if (entry_ex->entry.etypes->val == NULL) {
937                 krb5_clear_error_message(context);
938                 ret = ENOMEM;
939                 goto out;
940         }
941         for (i=0; i < entry_ex->entry.etypes->len; i++) {
942                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
943         }
944
945
946         p->msg = talloc_steal(p, msg);
947
948 out:
949         if (ret != 0) {
950                 /* This doesn't free ent itself, that is for the eventual caller to do */
951                 hdb_free_entry(context, entry_ex);
952         } else {
953                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
954         }
955
956         return ret;
957
958 }
959
960 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
961                                         TALLOC_CTX *mem_ctx,
962                                         const char *realm,
963                                         struct ldb_dn *realm_dn,
964                                         struct ldb_message **pmsg)
965 {
966         int lret;
967         krb5_error_code ret;
968         char *filter = NULL;
969         const char * const *attrs = trust_attrs;
970
971         struct ldb_result *res = NULL;
972         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
973
974         if (!filter) {
975                 ret = ENOMEM;
976                 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
977                 return ret;
978         }
979
980         lret = ldb_search(ldb_ctx, mem_ctx, &res,
981                           ldb_get_default_basedn(ldb_ctx),
982                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
983         if (lret != LDB_SUCCESS) {
984                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
985                 return HDB_ERR_NOENTRY;
986         } else if (res->count == 0 || res->count > 1) {
987                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
988                 talloc_free(res);
989                 return HDB_ERR_NOENTRY;
990         }
991         talloc_steal(mem_ctx, res->msgs);
992         *pmsg = res->msgs[0];
993         talloc_free(res);
994         return 0;
995 }
996
997 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
998                                                 struct samba_kdc_db_context *kdc_db_ctx,
999                                                 TALLOC_CTX *mem_ctx,
1000                                                 krb5_const_principal principal,
1001                                                 const char **attrs,
1002                                                 struct ldb_dn **realm_dn,
1003                                                 struct ldb_message **msg) {
1004         NTSTATUS nt_status;
1005         char *principal_string;
1006         krb5_error_code ret;
1007
1008         ret = krb5_unparse_name(context, principal, &principal_string);
1009
1010         if (ret != 0) {
1011                 return ret;
1012         }
1013
1014         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1015                                               mem_ctx, principal_string, attrs,
1016                                               realm_dn, msg);
1017         free(principal_string);
1018         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1019                 return HDB_ERR_NOENTRY;
1020         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1021                 return ENOMEM;
1022         } else if (!NT_STATUS_IS_OK(nt_status)) {
1023                 return EINVAL;
1024         }
1025
1026         return ret;
1027 }
1028
1029 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1030                                                struct samba_kdc_db_context *kdc_db_ctx,
1031                                                TALLOC_CTX *mem_ctx,
1032                                                krb5_const_principal principal,
1033                                                hdb_entry_ex *entry_ex) {
1034         struct ldb_dn *realm_dn;
1035         krb5_error_code ret;
1036         struct ldb_message *msg = NULL;
1037
1038         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1039                                        mem_ctx, principal, user_attrs,
1040                                        &realm_dn, &msg);
1041         if (ret != 0) {
1042                 return ret;
1043         }
1044
1045         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1046                                        principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1047                                        realm_dn, msg, entry_ex);
1048         return ret;
1049 }
1050
1051 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1052                                         struct samba_kdc_db_context *kdc_db_ctx,
1053                                         TALLOC_CTX *mem_ctx,
1054                                         krb5_const_principal principal,
1055                                         hdb_entry_ex *entry_ex)
1056 {
1057         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1058         krb5_error_code ret;
1059         struct ldb_message *msg = NULL;
1060         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1061
1062         krb5_principal alloc_principal = NULL;
1063         if (principal->name.name_string.len != 2
1064             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1065                 /* Not a krbtgt */
1066                 return HDB_ERR_NOENTRY;
1067         }
1068
1069         /* krbtgt case.  Either us or a trusted realm */
1070
1071         if (lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)
1072             && lpcfg_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1073                 /* us */
1074                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1075                  * is in our db, then direct the caller at our primary
1076                  * krbtgt */
1077
1078                 int lret;
1079                 char *realm_fixed;
1080
1081                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1082                                        &msg, realm_dn, LDB_SCOPE_SUBTREE,
1083                                        krbtgt_attrs,
1084                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1085                                        "(&(objectClass=user)(samAccountName=krbtgt))");
1086                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1087                         krb5_warnx(context, "samba_kdc_fetch: could not find own KRBTGT in DB!");
1088                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: could not find own KRBTGT in DB!");
1089                         return HDB_ERR_NOENTRY;
1090                 } else if (lret != LDB_SUCCESS) {
1091                         krb5_warnx(context, "samba_kdc_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1092                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1093                         return HDB_ERR_NOENTRY;
1094                 }
1095
1096                 realm_fixed = strupper_talloc(mem_ctx, lpcfg_realm(lp_ctx));
1097                 if (!realm_fixed) {
1098                         ret = ENOMEM;
1099                         krb5_set_error_message(context, ret, "strupper_talloc: out of memory");
1100                         return ret;
1101                 }
1102
1103                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1104                 if (ret) {
1105                         return ret;
1106                 }
1107
1108                 free(alloc_principal->name.name_string.val[1]);
1109                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1110                 talloc_free(realm_fixed);
1111                 if (!alloc_principal->name.name_string.val[1]) {
1112                         ret = ENOMEM;
1113                         krb5_set_error_message(context, ret, "samba_kdc_fetch: strdup() failed!");
1114                         return ret;
1115                 }
1116                 principal = alloc_principal;
1117
1118                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1119                                         principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1120                                         realm_dn, msg, entry_ex);
1121                 if (ret != 0) {
1122                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1123                 }
1124                 return ret;
1125
1126         } else {
1127                 enum trust_direction direction = UNKNOWN;
1128                 const char *realm = NULL;
1129
1130                 /* Either an inbound or outbound trust */
1131
1132                 if (strcasecmp(lpcfg_realm(lp_ctx), principal->realm) == 0) {
1133                         /* look for inbound trust */
1134                         direction = INBOUND;
1135                         realm = principal->name.name_string.val[1];
1136                 } else if (strcasecmp(lpcfg_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1137                         /* look for outbound trust */
1138                         direction = OUTBOUND;
1139                         realm = principal->realm;
1140                 } else {
1141                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1142                                    principal->realm, principal->name.name_string.val[1]);
1143                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1144                                                principal->realm, principal->name.name_string.val[1]);
1145                         return HDB_ERR_NOENTRY;
1146                 }
1147
1148                 /* Trusted domains are under CN=system */
1149
1150                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1151                                        mem_ctx,
1152                                        realm, realm_dn, &msg);
1153
1154                 if (ret != 0) {
1155                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1156                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1157                         return ret;
1158                 }
1159
1160                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1161                                               principal, direction,
1162                                               realm_dn, msg, entry_ex);
1163                 if (ret != 0) {
1164                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed");
1165                 }
1166                 return ret;
1167         }
1168
1169 }
1170
1171 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1172                                                 struct samba_kdc_db_context *kdc_db_ctx,
1173                                                 TALLOC_CTX *mem_ctx,
1174                                                 krb5_const_principal principal,
1175                                                 const char **attrs,
1176                                                 struct ldb_dn **realm_dn,
1177                                                 struct ldb_message **msg)
1178 {
1179         krb5_error_code ret;
1180         const char *realm;
1181         if (principal->name.name_string.len >= 2) {
1182                 /* 'normal server' case */
1183                 int ldb_ret;
1184                 NTSTATUS nt_status;
1185                 struct ldb_dn *user_dn;
1186                 char *principal_string;
1187
1188                 ret = krb5_unparse_name_flags(context, principal,
1189                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1190                                               &principal_string);
1191                 if (ret != 0) {
1192                         return ret;
1193                 }
1194
1195                 /* At this point we may find the host is known to be
1196                  * in a different realm, so we should generate a
1197                  * referral instead */
1198                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1199                                                          mem_ctx, principal_string,
1200                                                          &user_dn, realm_dn);
1201                 free(principal_string);
1202
1203                 if (!NT_STATUS_IS_OK(nt_status)) {
1204                         return HDB_ERR_NOENTRY;
1205                 }
1206
1207                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1208                                           mem_ctx,
1209                                           msg, user_dn, LDB_SCOPE_BASE,
1210                                           attrs, DSDB_SEARCH_SHOW_EXTENDED_DN, "(objectClass=*)");
1211                 if (ldb_ret != LDB_SUCCESS) {
1212                         return HDB_ERR_NOENTRY;
1213                 }
1214
1215         } else {
1216                 int lret;
1217                 char *filter = NULL;
1218                 char *short_princ;
1219                 /* server as client principal case, but we must not lookup userPrincipalNames */
1220                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1221                 realm = krb5_principal_get_realm(context, principal);
1222
1223                 /* TODO: Check if it is our realm, otherwise give referall */
1224
1225                 ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1226
1227                 if (ret != 0) {
1228                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1229                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1230                         return ret;
1231                 }
1232
1233                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1234                                        *realm_dn, LDB_SCOPE_SUBTREE,
1235                                        attrs,
1236                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1237                                        "(&(objectClass=user)(samAccountName=%s))",
1238                                        ldb_binary_encode_string(mem_ctx, short_princ));
1239                 free(short_princ);
1240                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1241                         DEBUG(3, ("Failed find a entry for %s\n", filter));
1242                         return HDB_ERR_NOENTRY;
1243                 }
1244                 if (lret != LDB_SUCCESS) {
1245                         DEBUG(3, ("Failed single search for for %s - %s\n",
1246                                   filter, ldb_errstring(kdc_db_ctx->samdb)));
1247                         return HDB_ERR_NOENTRY;
1248                 }
1249         }
1250
1251         return 0;
1252 }
1253
1254 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1255                                                struct samba_kdc_db_context *kdc_db_ctx,
1256                                                TALLOC_CTX *mem_ctx,
1257                                                krb5_const_principal principal,
1258                                                hdb_entry_ex *entry_ex)
1259 {
1260         krb5_error_code ret;
1261         struct ldb_dn *realm_dn;
1262         struct ldb_message *msg;
1263
1264         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1265                                        server_attrs, &realm_dn, &msg);
1266         if (ret != 0) {
1267                 return ret;
1268         }
1269
1270         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1271                                 principal, SAMBA_KDC_ENT_TYPE_SERVER,
1272                                 realm_dn, msg, entry_ex);
1273         if (ret != 0) {
1274                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1275         }
1276
1277         return ret;
1278 }
1279
1280 krb5_error_code samba_kdc_fetch(krb5_context context,
1281                                 struct samba_kdc_db_context *kdc_db_ctx,
1282                                 krb5_const_principal principal,
1283                                 unsigned flags,
1284                                 hdb_entry_ex *entry_ex)
1285 {
1286         krb5_error_code ret = HDB_ERR_NOENTRY;
1287         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1288
1289         if (!mem_ctx) {
1290                 ret = ENOMEM;
1291                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1292                 return ret;
1293         }
1294
1295         if (flags & HDB_F_GET_CLIENT) {
1296                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1297                 if (ret != HDB_ERR_NOENTRY) goto done;
1298         }
1299         if (flags & HDB_F_GET_SERVER) {
1300                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1301                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1302                 if (ret != HDB_ERR_NOENTRY) goto done;
1303
1304                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1305                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1306                 if (ret != HDB_ERR_NOENTRY) goto done;
1307         }
1308         if (flags & HDB_F_GET_KRBTGT) {
1309                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1310                 if (ret != HDB_ERR_NOENTRY) goto done;
1311         }
1312
1313 done:
1314         talloc_free(mem_ctx);
1315         return ret;
1316 }
1317
1318 struct samba_kdc_seq {
1319         unsigned int index;
1320         unsigned int count;
1321         struct ldb_message **msgs;
1322         struct ldb_dn *realm_dn;
1323 };
1324
1325 static krb5_error_code samba_kdc_seq(krb5_context context,
1326                                      struct samba_kdc_db_context *kdc_db_ctx,
1327                                      hdb_entry_ex *entry)
1328 {
1329         krb5_error_code ret;
1330         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1331         TALLOC_CTX *mem_ctx;
1332         hdb_entry_ex entry_ex;
1333         memset(&entry_ex, '\0', sizeof(entry_ex));
1334
1335         if (!priv) {
1336                 return HDB_ERR_NOENTRY;
1337         }
1338
1339         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1340
1341         if (!mem_ctx) {
1342                 ret = ENOMEM;
1343                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1344                 return ret;
1345         }
1346
1347         if (priv->index < priv->count) {
1348                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1349                                         NULL, SAMBA_KDC_ENT_TYPE_ANY,
1350                                         priv->realm_dn, priv->msgs[priv->index++], entry);
1351         } else {
1352                 ret = HDB_ERR_NOENTRY;
1353         }
1354
1355         if (ret != 0) {
1356                 TALLOC_FREE(priv);
1357                 kdc_db_ctx->seq_ctx = NULL;
1358         } else {
1359                 talloc_free(mem_ctx);
1360         }
1361
1362         return ret;
1363 }
1364
1365 krb5_error_code samba_kdc_firstkey(krb5_context context,
1366                                    struct samba_kdc_db_context *kdc_db_ctx,
1367                                    hdb_entry_ex *entry)
1368 {
1369         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1370         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1371         char *realm;
1372         struct ldb_result *res = NULL;
1373         krb5_error_code ret;
1374         TALLOC_CTX *mem_ctx;
1375         int lret;
1376
1377         if (priv) {
1378                 TALLOC_FREE(priv);
1379                 kdc_db_ctx->seq_ctx = NULL;
1380         }
1381
1382         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1383         if (!priv) {
1384                 ret = ENOMEM;
1385                 krb5_set_error_message(context, ret, "talloc: out of memory");
1386                 return ret;
1387         }
1388
1389         priv->index = 0;
1390         priv->msgs = NULL;
1391         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1392         priv->count = 0;
1393
1394         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1395
1396         if (!mem_ctx) {
1397                 ret = ENOMEM;
1398                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1399                 return ret;
1400         }
1401
1402         ret = krb5_get_default_realm(context, &realm);
1403         if (ret != 0) {
1404                 TALLOC_FREE(priv);
1405                 return ret;
1406         }
1407
1408         lret = ldb_search(ldb_ctx, priv, &res,
1409                           priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1410                           "(objectClass=user)");
1411
1412         if (lret != LDB_SUCCESS) {
1413                 TALLOC_FREE(priv);
1414                 return HDB_ERR_NOENTRY;
1415         }
1416
1417         priv->count = res->count;
1418         priv->msgs = talloc_steal(priv, res->msgs);
1419         talloc_free(res);
1420
1421         kdc_db_ctx->seq_ctx = priv;
1422
1423         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1424
1425         if (ret != 0) {
1426                 TALLOC_FREE(priv);
1427                 kdc_db_ctx->seq_ctx = NULL;
1428         } else {
1429                 talloc_free(mem_ctx);
1430         }
1431         return ret;
1432 }
1433
1434 krb5_error_code samba_kdc_nextkey(krb5_context context,
1435                                   struct samba_kdc_db_context *kdc_db_ctx,
1436                                   hdb_entry_ex *entry)
1437 {
1438         return samba_kdc_seq(context, kdc_db_ctx, entry);
1439 }
1440
1441 /* Check if a given entry may delegate or do s4u2self to this target principal
1442  *
1443  * This is currently a very nasty hack - allowing only delegation to itself.
1444  *
1445  * This is shared between the constrained delegation and S4U2Self code.
1446  */
1447 krb5_error_code
1448 samba_kdc_check_identical_client_and_server(krb5_context context,
1449                                             struct samba_kdc_db_context *kdc_db_ctx,
1450                                             hdb_entry_ex *entry,
1451                                             krb5_const_principal target_principal)
1452 {
1453         krb5_error_code ret;
1454         krb5_principal enterprise_prinicpal = NULL;
1455         struct ldb_dn *realm_dn;
1456         struct ldb_message *msg;
1457         struct dom_sid *orig_sid;
1458         struct dom_sid *target_sid;
1459         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1460         const char *delegation_check_attrs[] = {
1461                 "objectSid", NULL
1462         };
1463
1464         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_constrained_delegation");
1465
1466         if (!mem_ctx) {
1467                 ret = ENOMEM;
1468                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1469                 return ret;
1470         }
1471
1472         if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1473                 /* Need to reparse the enterprise principal to find the real target */
1474                 if (target_principal->name.name_string.len != 1) {
1475                         ret = KRB5_PARSE_MALFORMED;
1476                         krb5_set_error_message(context, ret, "samba_kdc_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1477                                                target_principal->name.name_string.len);
1478                         talloc_free(mem_ctx);
1479                         return ret;
1480                 }
1481                 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1482                                       &enterprise_prinicpal);
1483                 if (ret) {
1484                         talloc_free(mem_ctx);
1485                         return ret;
1486                 }
1487                 target_principal = enterprise_prinicpal;
1488         }
1489
1490         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1491                                        delegation_check_attrs, &realm_dn, &msg);
1492
1493         krb5_free_principal(context, enterprise_prinicpal);
1494
1495         if (ret != 0) {
1496                 talloc_free(mem_ctx);
1497                 return ret;
1498         }
1499
1500         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1501         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1502
1503         /* Allow delegation to the same principal, even if by a different
1504          * name.  The easy and safe way to prove this is by SID
1505          * comparison */
1506         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1507                 talloc_free(mem_ctx);
1508                 return KRB5KDC_ERR_BADOPTION;
1509         }
1510
1511         talloc_free(mem_ctx);
1512         return ret;
1513 }
1514
1515 /* Certificates printed by a the Certificate Authority might have a
1516  * slightly different form of the user principal name to that in the
1517  * database.  Allow a mismatch where they both refer to the same
1518  * SID */
1519
1520 krb5_error_code
1521 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1522                                     struct samba_kdc_db_context *kdc_db_ctx,
1523                                      hdb_entry_ex *entry,
1524                                      krb5_const_principal certificate_principal)
1525 {
1526         krb5_error_code ret;
1527         struct ldb_dn *realm_dn;
1528         struct ldb_message *msg;
1529         struct dom_sid *orig_sid;
1530         struct dom_sid *target_sid;
1531         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1532         const char *ms_upn_check_attrs[] = {
1533                 "objectSid", NULL
1534         };
1535
1536         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1537
1538         if (!mem_ctx) {
1539                 ret = ENOMEM;
1540                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1541                 return ret;
1542         }
1543
1544         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1545                                        mem_ctx, certificate_principal,
1546                                        ms_upn_check_attrs, &realm_dn, &msg);
1547
1548         if (ret != 0) {
1549                 talloc_free(mem_ctx);
1550                 return ret;
1551         }
1552
1553         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1554         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1555
1556         /* Consider these to be the same principal, even if by a different
1557          * name.  The easy and safe way to prove this is by SID
1558          * comparison */
1559         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1560                 talloc_free(mem_ctx);
1561                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1562         }
1563
1564         talloc_free(mem_ctx);
1565         return ret;
1566 }
1567
1568 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
1569                                 struct samba_kdc_db_context **kdc_db_ctx_out)
1570 {
1571         NTSTATUS nt_status;
1572         int ldb_ret;
1573         struct ldb_message *msg;
1574         struct auth_session_info *session_info;
1575         struct samba_kdc_db_context *kdc_db_ctx;
1576         /* The idea here is very simple.  Using Kerberos to
1577          * authenticate the KDC to the LDAP server is higly likely to
1578          * be circular.
1579          *
1580          * In future we may set this up to use EXERNAL and SSL
1581          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
1582         */
1583
1584         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
1585         if (kdc_db_ctx == NULL) {
1586                 return NT_STATUS_NO_MEMORY;
1587         }
1588         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
1589         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
1590
1591 #if 1
1592         /* we would prefer to use system_session(), as that would
1593          * allow us to share the samdb backend context with other parts of the
1594          * system. For now we can't as we need to override the
1595          * credentials to set CRED_DONT_USE_KERBEROS, which would
1596          * break other users of the system_session */
1597         DEBUG(0,("FIXME: Using new system session for hdb\n"));
1598         nt_status = auth_system_session_info(kdc_db_ctx, base_ctx->lp_ctx, &session_info);
1599         if (!NT_STATUS_IS_OK(nt_status)) {
1600                return nt_status;
1601         }
1602 #else
1603         session_info = system_session(kdc_db_ctx->lp_ctx);
1604         if (session_info == NULL) {
1605                 return NT_STATUS_INTERNAL_ERROR;
1606         }
1607 #endif
1608
1609         cli_credentials_set_kerberos_state(session_info->credentials,
1610                                            CRED_DONT_USE_KERBEROS);
1611
1612         /* Setup the link to LDB */
1613         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
1614                                           base_ctx->lp_ctx, session_info);
1615         if (kdc_db_ctx->samdb == NULL) {
1616                 DEBUG(1, ("hdb_samba4_create: Cannot open samdb for KDC backend!"));
1617                 talloc_free(kdc_db_ctx);
1618                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1619         }
1620
1621         /* Find out our own krbtgt kvno */
1622         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
1623         if (ldb_ret != LDB_SUCCESS) {
1624                 DEBUG(1, ("hdb_samba4_create: Cannot determine if we are an RODC in KDC backend: %s\n",
1625                           ldb_errstring(kdc_db_ctx->samdb)));
1626                 talloc_free(kdc_db_ctx);
1627                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1628         }
1629         if (kdc_db_ctx->rodc) {
1630                 int my_krbtgt_number;
1631                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
1632                 struct ldb_dn *account_dn;
1633                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
1634                 if (!server_dn) {
1635                         DEBUG(1, ("hdb_samba4_create: Cannot determine server DN in KDC backend: %s\n",
1636                                   ldb_errstring(kdc_db_ctx->samdb)));
1637                         talloc_free(kdc_db_ctx);
1638                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1639                 }
1640
1641                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
1642                                              "serverReference", &account_dn);
1643                 if (ldb_ret != LDB_SUCCESS) {
1644                         DEBUG(1, ("hdb_samba4_create: Cannot determine server account in KDC backend: %s\n",
1645                                   ldb_errstring(kdc_db_ctx->samdb)));
1646                         talloc_free(kdc_db_ctx);
1647                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1648                 }
1649
1650                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
1651                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
1652                 talloc_free(account_dn);
1653                 if (ldb_ret != LDB_SUCCESS) {
1654                         DEBUG(1, ("hdb_samba4_create: Cannot determine RODC krbtgt account in KDC backend: %s\n",
1655                                   ldb_errstring(kdc_db_ctx->samdb)));
1656                         talloc_free(kdc_db_ctx);
1657                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1658                 }
1659
1660                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1661                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1662                                           secondary_keytab,
1663                                           0,
1664                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
1665                 if (ldb_ret != LDB_SUCCESS) {
1666                         DEBUG(1, ("hdb_samba4_create: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
1667                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1668                                   ldb_errstring(kdc_db_ctx->samdb),
1669                                   ldb_strerror(ldb_ret)));
1670                         talloc_free(kdc_db_ctx);
1671                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1672                 }
1673                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
1674                 if (my_krbtgt_number == -1) {
1675                         DEBUG(1, ("hdb_samba4_create: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
1676                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
1677                                   my_krbtgt_number));
1678                         talloc_free(kdc_db_ctx);
1679                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1680                 }
1681                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
1682
1683         } else {
1684                 kdc_db_ctx->my_krbtgt_number = 0;
1685                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
1686                                           &msg, NULL, LDB_SCOPE_SUBTREE,
1687                                           krbtgt_attrs,
1688                                           DSDB_SEARCH_SHOW_EXTENDED_DN,
1689                                           "(&(objectClass=user)(samAccountName=krbtgt))");
1690
1691                 if (ldb_ret != LDB_SUCCESS) {
1692                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
1693                         talloc_free(kdc_db_ctx);
1694                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1695                 }
1696                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
1697                 kdc_db_ctx->my_krbtgt_number = 0;
1698                 talloc_free(msg);
1699         }
1700         *kdc_db_ctx_out = kdc_db_ctx;
1701         return NT_STATUS_OK;
1702 }