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