s4-kdc/db_glue: use smb_krb5_keyblock_init_contents().
[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 "libcli/security/security.h"
26 #include "auth/auth.h"
27 #include "auth/auth_sam.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "dsdb/common/util.h"
30 #include "librpc/gen_ndr/ndr_drsblobs.h"
31 #include "param/param.h"
32 #include "../lib/crypto/md4.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include <hdb.h>
36 #include "kdc/samba_kdc.h"
37 #include "kdc/db-glue.h"
38
39 #define SAMBA_KVNO_GET_KRBTGT(kvno) \
40         ((uint16_t)(((uint32_t)kvno) >> 16))
41
42 #define SAMBA_KVNO_AND_KRBTGT(kvno, krbtgt) \
43         ((krb5_kvno)((((uint32_t)kvno) & 0xFFFF) | \
44          ((((uint32_t)krbtgt) << 16) & 0xFFFF0000)))
45
46 enum samba_kdc_ent_type
47 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
48   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
49
50 enum trust_direction {
51         UNKNOWN = 0,
52         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
53         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
54 };
55
56 static const char *trust_attrs[] = {
57         "trustPartner",
58         "trustAuthIncoming",
59         "trustAuthOutgoing",
60         "whenCreated",
61         "msDS-SupportedEncryptionTypes",
62         "trustAttributes",
63         "trustDirection",
64         "trustType",
65         NULL
66 };
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.locked_out = 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_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) {
162                 /*
163                  * this is confusing...
164                  *
165                  * UF_TRUSTED_FOR_DELEGATION
166                  * => ok_as_delegate
167                  *
168                  * and
169                  *
170                  * UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
171                  * => trusted_for_delegation
172                  */
173                 flags.trusted_for_delegation = 1;
174         }
175         if (!(userAccountControl & UF_NOT_DELEGATED)) {
176                 flags.forwardable = 1;
177                 flags.proxiable = 1;
178         }
179
180         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
181                 flags.require_preauth = 0;
182         } else {
183                 flags.require_preauth = 1;
184
185         }
186         return flags;
187 }
188
189 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
190 {
191     hdb_entry_ex *entry_ex = p->entry_ex;
192     free_hdb_entry(&entry_ex->entry);
193     return 0;
194 }
195
196 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
197 {
198         /* this function is called only from hdb_free_entry().
199          * Make sure we neutralize the destructor or we will
200          * get a double free later when hdb_free_entry() will
201          * try to call free_hdb_entry() */
202         talloc_set_destructor(entry_ex->ctx, NULL);
203
204         /* now proceed to free the talloc part */
205         talloc_free(entry_ex->ctx);
206 }
207
208 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
209                                                     struct samba_kdc_db_context *kdc_db_ctx,
210                                                     TALLOC_CTX *mem_ctx,
211                                                     struct ldb_message *msg,
212                                                     uint32_t rid,
213                                                     bool is_rodc,
214                                                     uint32_t userAccountControl,
215                                                     enum samba_kdc_ent_type ent_type,
216                                                     hdb_entry_ex *entry_ex)
217 {
218         krb5_error_code ret = 0;
219         enum ndr_err_code ndr_err;
220         struct samr_Password *hash;
221         const struct ldb_val *sc_val;
222         struct supplementalCredentialsBlob scb;
223         struct supplementalCredentialsPackage *scpk = NULL;
224         bool newer_keys = false;
225         struct package_PrimaryKerberosBlob _pkb;
226         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
227         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
228         uint16_t i;
229         uint16_t allocated_keys = 0;
230         int rodc_krbtgt_number = 0;
231         int kvno = 0;
232         uint32_t supported_enctypes
233                 = ldb_msg_find_attr_as_uint(msg,
234                                             "msDS-SupportedEncryptionTypes",
235                                             0);
236
237         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
238                 /* KDCs (and KDCs on RODCs) use AES */
239                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
240         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
241                 /* DCs and RODCs comptuer accounts use AES */
242                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
243         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
244                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
245                 /* for AS-REQ the client chooses the enc types it
246                  * supports, and this will vary between computers a
247                  * user logs in from.
248                  *
249                  * likewise for 'any' return as much as is supported,
250                  * to export into a keytab */
251                 supported_enctypes = ENC_ALL_TYPES;
252         }
253
254         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
255         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
256                 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
257         } else {
258                 /* Otherwise, add in the default enc types */
259                 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
260         }
261
262         /* Is this the krbtgt or a RODC krbtgt */
263         if (is_rodc) {
264                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
265
266                 if (rodc_krbtgt_number == -1) {
267                         return EINVAL;
268                 }
269         }
270
271         entry_ex->entry.keys.val = NULL;
272         entry_ex->entry.keys.len = 0;
273
274         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
275         if (is_rodc) {
276                 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
277         }
278         entry_ex->entry.kvno = kvno;
279
280         /* Get keys from the db */
281
282         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
283         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
284
285         /* unicodePwd for enctype 0x17 (23) if present */
286         if (hash) {
287                 allocated_keys++;
288         }
289
290         /* supplementalCredentials if present */
291         if (sc_val) {
292                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
293                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
294                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
295                         dump_data(0, sc_val->data, sc_val->length);
296                         ret = EINVAL;
297                         goto out;
298                 }
299
300                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
301                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
302                         ret = EINVAL;
303                         goto out;
304                 }
305
306                 for (i=0; i < scb.sub.num_packages; i++) {
307                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
308                                 scpk = &scb.sub.packages[i];
309                                 if (!scpk->data || !scpk->data[0]) {
310                                         scpk = NULL;
311                                         continue;
312                                 }
313                                 newer_keys = true;
314                                 break;
315                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
316                                 scpk = &scb.sub.packages[i];
317                                 if (!scpk->data || !scpk->data[0]) {
318                                         scpk = NULL;
319                                 }
320                                 /*
321                                  * we don't break here in hope to find
322                                  * a Kerberos-Newer-Keys package
323                                  */
324                         }
325                 }
326         }
327         /*
328          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
329          * of supplementalCredentials
330          */
331         if (scpk) {
332                 DATA_BLOB blob;
333
334                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
335                 if (!blob.data) {
336                         ret = ENOMEM;
337                         goto out;
338                 }
339
340                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
341                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
342                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
343                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
344                         ret = EINVAL;
345                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
346                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
347                         goto out;
348                 }
349
350                 if (newer_keys && _pkb.version != 4) {
351                         ret = EINVAL;
352                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
353                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
354                         goto out;
355                 }
356
357                 if (!newer_keys && _pkb.version != 3) {
358                         ret = EINVAL;
359                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
360                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
361                         goto out;
362                 }
363
364                 if (_pkb.version == 4) {
365                         pkb4 = &_pkb.ctr.ctr4;
366                         allocated_keys += pkb4->num_keys;
367                 } else if (_pkb.version == 3) {
368                         pkb3 = &_pkb.ctr.ctr3;
369                         allocated_keys += pkb3->num_keys;
370                 }
371         }
372
373         if (allocated_keys == 0) {
374                 if (kdc_db_ctx->rodc) {
375                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
376                         /* TODO:  We need to call a generalised version of auth_sam_trigger_repl_secret from here */
377                         return HDB_ERR_NOT_FOUND_HERE;
378                 }
379
380                 /* oh, no password.  Apparently (comment in
381                  * hdb-ldap.c) this violates the ASN.1, but this
382                  * allows an entry with no keys (yet). */
383                 return 0;
384         }
385
386         /* allocate space to decode into */
387         entry_ex->entry.keys.len = 0;
388         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
389         if (entry_ex->entry.keys.val == NULL) {
390                 ret = ENOMEM;
391                 goto out;
392         }
393
394         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
395                 Key key;
396
397                 key.mkvno = 0;
398                 key.salt = NULL; /* No salt for this enc type */
399
400                 ret = smb_krb5_keyblock_init_contents(context,
401                                                       ENCTYPE_ARCFOUR_HMAC,
402                                                       hash->hash,
403                                                       sizeof(hash->hash),
404                                                       &key.key);
405                 if (ret) {
406                         goto out;
407                 }
408
409                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
410                 entry_ex->entry.keys.len++;
411         }
412
413         if (pkb4) {
414                 for (i=0; i < pkb4->num_keys; i++) {
415                         Key key;
416
417                         if (!pkb4->keys[i].value) continue;
418
419                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
420                                 continue;
421                         }
422
423                         key.mkvno = 0;
424                         key.salt = NULL;
425
426                         if (pkb4->salt.string) {
427                                 DATA_BLOB salt;
428
429                                 salt = data_blob_string_const(pkb4->salt.string);
430
431                                 key.salt = calloc(1, sizeof(*key.salt));
432                                 if (key.salt == NULL) {
433                                         ret = ENOMEM;
434                                         goto out;
435                                 }
436
437                                 key.salt->type = hdb_pw_salt;
438
439                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
440                                 if (ret) {
441                                         free(key.salt);
442                                         key.salt = NULL;
443                                         goto out;
444                                 }
445                         }
446
447                         /* TODO: maybe pass the iteration_count somehow... */
448
449                         ret = smb_krb5_keyblock_init_contents(context,
450                                                               pkb4->keys[i].keytype,
451                                                               pkb4->keys[i].value->data,
452                                                               pkb4->keys[i].value->length,
453                                                               &key.key);
454                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
455                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
456                                          pkb4->keys[i].keytype));
457                                 ret = 0;
458                                 continue;
459                         }
460                         if (ret) {
461                                 if (key.salt) {
462                                         free_Salt(key.salt);
463                                         free(key.salt);
464                                         key.salt = NULL;
465                                 }
466                                 goto out;
467                         }
468
469                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
470                         entry_ex->entry.keys.len++;
471                 }
472         } else if (pkb3) {
473                 for (i=0; i < pkb3->num_keys; i++) {
474                         Key key;
475
476                         if (!pkb3->keys[i].value) continue;
477
478                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
479                                 continue;
480                         }
481
482                         key.mkvno = 0;
483                         key.salt = NULL;
484
485                         if (pkb3->salt.string) {
486                                 DATA_BLOB salt;
487
488                                 salt = data_blob_string_const(pkb3->salt.string);
489
490                                 key.salt = calloc(1, sizeof(*key.salt));
491                                 if (key.salt == NULL) {
492                                         ret = ENOMEM;
493                                         goto out;
494                                 }
495
496                                 key.salt->type = hdb_pw_salt;
497
498                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
499                                 if (ret) {
500                                         free(key.salt);
501                                         key.salt = NULL;
502                                         goto out;
503                                 }
504                         }
505
506                         ret = smb_krb5_keyblock_init_contents(context,
507                                                               pkb3->keys[i].keytype,
508                                                               pkb3->keys[i].value->data,
509                                                               pkb3->keys[i].value->length,
510                                                               &key.key);
511                         if (ret) {
512                                 if (key.salt) {
513                                         free_Salt(key.salt);
514                                         free(key.salt);
515                                         key.salt = NULL;
516                                 }
517                                 goto out;
518                         }
519
520                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
521                         entry_ex->entry.keys.len++;
522                 }
523         }
524
525 out:
526         if (ret != 0) {
527                 entry_ex->entry.keys.len = 0;
528         }
529         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
530                 free(entry_ex->entry.keys.val);
531                 entry_ex->entry.keys.val = NULL;
532         }
533         return ret;
534 }
535
536 /*
537  * Construct an hdb_entry from a directory entry.
538  */
539 static krb5_error_code samba_kdc_message2entry(krb5_context context,
540                                                struct samba_kdc_db_context *kdc_db_ctx,
541                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
542                                                enum samba_kdc_ent_type ent_type,
543                                                unsigned flags,
544                                                struct ldb_dn *realm_dn,
545                                                struct ldb_message *msg,
546                                                hdb_entry_ex *entry_ex)
547 {
548         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
549         uint32_t userAccountControl;
550         uint32_t msDS_User_Account_Control_Computed;
551         unsigned int i;
552         krb5_error_code ret = 0;
553         krb5_boolean is_computer = FALSE;
554
555         struct samba_kdc_entry *p;
556         NTTIME acct_expiry;
557         NTSTATUS status;
558
559         uint32_t rid;
560         bool is_rodc = false;
561         struct ldb_message_element *objectclasses;
562         struct ldb_val computer_val;
563         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
564         computer_val.data = discard_const_p(uint8_t,"computer");
565         computer_val.length = strlen((const char *)computer_val.data);
566
567         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
568                 is_rodc = true;
569         }
570
571         if (!samAccountName) {
572                 ret = ENOENT;
573                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
574                 goto out;
575         }
576
577         objectclasses = ldb_msg_find_element(msg, "objectClass");
578
579         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
580                 is_computer = TRUE;
581         }
582
583         memset(entry_ex, 0, sizeof(*entry_ex));
584
585         p = talloc(mem_ctx, struct samba_kdc_entry);
586         if (!p) {
587                 ret = ENOMEM;
588                 goto out;
589         }
590
591         p->kdc_db_ctx = kdc_db_ctx;
592         p->entry_ex = entry_ex;
593         p->realm_dn = talloc_reference(p, realm_dn);
594         if (!p->realm_dn) {
595                 ret = ENOMEM;
596                 goto out;
597         }
598
599         talloc_set_destructor(p, samba_kdc_entry_destructor);
600
601         /* make sure we do not have bogus data in there */
602         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
603
604         entry_ex->ctx = p;
605         entry_ex->free_entry = samba_kdc_free_entry;
606
607         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
608
609         msDS_User_Account_Control_Computed
610                 = ldb_msg_find_attr_as_uint(msg,
611                                             "msDS-User-Account-Control-Computed",
612                                             UF_ACCOUNTDISABLE);
613
614         /*
615          * This brings in the lockout flag, block the account if not
616          * found.  We need the weird UF_ACCOUNTDISABLE check because
617          * we do not want to fail open if the value is not returned,
618          * but 0 is a valid value (all OK)
619          */
620         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
621                 ret = EINVAL;
622                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
623                                 "no msDS-User-Account-Control-Computed present");
624                 goto out;
625         } else {
626                 userAccountControl |= msDS_User_Account_Control_Computed;
627         }
628
629         /* 
630          * If we are set to canonicalize, we get back the fixed UPPER
631          * case realm, and the real username (ie matching LDAP
632          * samAccountName) 
633          *
634          * Otherwise, if we are set to enterprise, we
635          * get back the whole principal as-sent 
636          *
637          * Finally, if we are not set to canonicalize, we get back the
638          * fixed UPPER case realm, but the as-sent username
639          */
640
641         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
642         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
643                 if (flags & (HDB_F_CANON)) {
644                         /*
645                          * When requested to do so, ensure that the
646                          * both realm values in the principal are set
647                          * to the upper case, canonical realm
648                          */
649                         ret = krb5_make_principal(context, &entry_ex->entry.principal,
650                                                   lpcfg_realm(lp_ctx), "krbtgt",
651                                                   lpcfg_realm(lp_ctx), NULL);
652                         if (ret) {
653                                 krb5_clear_error_message(context);
654                                 goto out;
655                         }
656                         krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
657                 } else {
658                         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
659                         if (ret) {
660                                 krb5_clear_error_message(context);
661                                 goto out;
662                         }
663                         /*
664                          * this appears to be required regardless of
665                          * the canonicalize flag from the client
666                          */
667                         ret = krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
668                         if (ret) {
669                                 krb5_clear_error_message(context);
670                                 goto out;
671                         }
672                 }
673
674         } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
675                 ret = krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
676                 if (ret) {
677                         krb5_clear_error_message(context);
678                         goto out;
679                 }
680         } else if (flags & HDB_F_CANON && flags & HDB_F_FOR_AS_REQ) {
681                 /*
682                  * HDB_F_CANON maps from the canonicalize flag in the
683                  * packet, and has a different meaning between AS-REQ
684                  * and TGS-REQ.  We only change the principal in the AS-REQ case
685                  */
686                 ret = krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
687                 if (ret) {
688                         krb5_clear_error_message(context);
689                         goto out;
690                 }
691         } else {
692                 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
693                 if (ret) {
694                         krb5_clear_error_message(context);
695                         goto out;
696                 }
697
698                 if (krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
699                         /* While we have copied the client principal, tests
700                          * show that Win2k3 returns the 'corrected' realm, not
701                          * the client-specified realm.  This code attempts to
702                          * replace the client principal's realm with the one
703                          * we determine from our records */
704                         
705                         /* this has to be with malloc() */
706                         ret = krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
707                         if (ret) {
708                                 krb5_clear_error_message(context);
709                                 goto out;
710                         }
711                 }
712         }
713
714         /* First try and figure out the flags based on the userAccountControl */
715         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
716
717         /* Windows 2008 seems to enforce this (very sensible) rule by
718          * default - don't allow offline attacks on a user's password
719          * by asking for a ticket to them as a service (encrypted with
720          * their probably patheticly insecure password) */
721
722         if (entry_ex->entry.flags.server
723             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
724                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
725                         entry_ex->entry.flags.server = 0;
726                 }
727         }
728         /*
729          * To give the correct type of error to the client, we must
730          * not just return the entry without .server set, we must
731          * pretend the principal does not exist.  Otherwise we may
732          * return ERR_POLICY instead of
733          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
734          */
735         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
736                 ret = HDB_ERR_NOENTRY;
737                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
738                 goto out;
739         }
740         if (flags & HDB_F_ADMIN_DATA) {
741                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
742                  * of the Heimdal KDC.  They are stored in a the traditional
743                  * DB for audit purposes, and still form part of the structure
744                  * we must return */
745
746                 /* use 'whenCreated' */
747                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
748                 /* use 'kadmin' for now (needed by mit_samba) */
749                 ret = krb5_make_principal(context,
750                                           &entry_ex->entry.created_by.principal,
751                                           lpcfg_realm(lp_ctx), "kadmin", NULL);
752                 if (ret) {
753                         krb5_clear_error_message(context);
754                         goto out;
755                 }
756
757                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
758                 if (entry_ex->entry.modified_by == NULL) {
759                         ret = ENOMEM;
760                         krb5_set_error_message(context, ret, "malloc: out of memory");
761                         goto out;
762                 }
763
764                 /* use 'whenChanged' */
765                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
766                 /* use 'kadmin' for now (needed by mit_samba) */
767                 ret = krb5_make_principal(context,
768                                           &entry_ex->entry.modified_by->principal,
769                                           lpcfg_realm(lp_ctx), "kadmin", NULL);
770                 if (ret) {
771                         krb5_clear_error_message(context);
772                         goto out;
773                 }
774         }
775
776
777         /* The lack of password controls etc applies to krbtgt by
778          * virtue of being that particular RID */
779         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
780
781         if (!NT_STATUS_IS_OK(status)) {
782                 ret = EINVAL;
783                 goto out;
784         }
785
786         if (rid == DOMAIN_RID_KRBTGT) {
787                 entry_ex->entry.valid_end = NULL;
788                 entry_ex->entry.pw_end = NULL;
789
790                 entry_ex->entry.flags.invalid = 0;
791                 entry_ex->entry.flags.server = 1;
792
793                 /* Don't mark all requests for the krbtgt/realm as
794                  * 'change password', as otherwise we could get into
795                  * trouble, and not enforce the password expirty.
796                  * Instead, only do it when request is for the kpasswd service */
797                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
798                     && principal->name.name_string.len == 2
799                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
800                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
801                     && lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)) {
802                         entry_ex->entry.flags.change_pw = 1;
803                 }
804                 entry_ex->entry.flags.client = 0;
805                 entry_ex->entry.flags.forwardable = 1;
806                 entry_ex->entry.flags.ok_as_delegate = 1;
807         } else if (is_rodc) {
808                 /* The RODC krbtgt account is like the main krbtgt,
809                  * but it does not have a changepw or kadmin
810                  * service */
811
812                 entry_ex->entry.valid_end = NULL;
813                 entry_ex->entry.pw_end = NULL;
814
815                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
816                 entry_ex->entry.flags.client = 0;
817                 entry_ex->entry.flags.invalid = 0;
818                 entry_ex->entry.flags.server = 1;
819
820                 entry_ex->entry.flags.client = 0;
821                 entry_ex->entry.flags.forwardable = 1;
822                 entry_ex->entry.flags.ok_as_delegate = 0;
823         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
824                 /* The account/password expiry only applies when the account is used as a
825                  * client (ie password login), not when used as a server */
826
827                 /* Make very well sure we don't use this for a client,
828                  * it could bypass the password restrictions */
829                 entry_ex->entry.flags.client = 0;
830
831                 entry_ex->entry.valid_end = NULL;
832                 entry_ex->entry.pw_end = NULL;
833
834         } else {
835                 NTTIME must_change_time
836                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
837                                                              realm_dn, msg);
838                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
839                         entry_ex->entry.pw_end = NULL;
840                 } else {
841                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
842                         if (entry_ex->entry.pw_end == NULL) {
843                                 ret = ENOMEM;
844                                 goto out;
845                         }
846                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
847                 }
848
849                 acct_expiry = samdb_result_account_expires(msg);
850                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
851                         entry_ex->entry.valid_end = NULL;
852                 } else {
853                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
854                         if (entry_ex->entry.valid_end == NULL) {
855                                 ret = ENOMEM;
856                                 goto out;
857                         }
858                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
859                 }
860         }
861
862         entry_ex->entry.valid_start = NULL;
863
864         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
865         if (entry_ex->entry.max_life == NULL) {
866                 ret = ENOMEM;
867                 goto out;
868         }
869
870         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
871                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
872         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
873                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
874         } else {
875                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
876                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
877         }
878
879         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
880         if (entry_ex->entry.max_renew == NULL) {
881                 ret = ENOMEM;
882                 goto out;
883         }
884
885         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
886
887         /* Get keys from the db */
888         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
889                                            rid, is_rodc, userAccountControl,
890                                            ent_type, entry_ex);
891         if (ret) {
892                 /* Could be bougus data in the entry, or out of memory */
893                 goto out;
894         }
895
896         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
897         if (entry_ex->entry.etypes == NULL) {
898                 krb5_clear_error_message(context);
899                 ret = ENOMEM;
900                 goto out;
901         }
902         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
903         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
904         if (entry_ex->entry.etypes->val == NULL) {
905                 krb5_clear_error_message(context);
906                 ret = ENOMEM;
907                 goto out;
908         }
909         for (i=0; i < entry_ex->entry.etypes->len; i++) {
910                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
911         }
912
913
914         p->msg = talloc_steal(p, msg);
915
916 out:
917         if (ret != 0) {
918                 /* This doesn't free ent itself, that is for the eventual caller to do */
919                 hdb_free_entry(context, entry_ex);
920         } else {
921                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
922         }
923
924         return ret;
925 }
926
927 /*
928  * Construct an hdb_entry from a directory entry.
929  * The kvno is what the remote client asked for
930  */
931 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
932                                                struct samba_kdc_db_context *kdc_db_ctx,
933                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
934                                                enum trust_direction direction,
935                                                struct ldb_dn *realm_dn,
936                                                unsigned flags,
937                                                uint32_t kvno,
938                                                struct ldb_message *msg,
939                                                hdb_entry_ex *entry_ex)
940 {
941         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
942         const char *dnsdomain;
943         const char *realm = lpcfg_realm(lp_ctx);
944         DATA_BLOB password_utf16 = data_blob_null;
945         DATA_BLOB password_utf8 = data_blob_null;
946         struct samr_Password _password_hash;
947         const struct samr_Password *password_hash = NULL;
948         const struct ldb_val *password_val;
949         struct trustAuthInOutBlob password_blob;
950         struct samba_kdc_entry *p;
951         bool use_previous;
952         uint32_t current_kvno;
953         uint32_t num_keys = 0;
954         enum ndr_err_code ndr_err;
955         int ret, trust_direction_flags;
956         unsigned int i;
957         struct AuthenticationInformationArray *auth_array;
958         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
959
960         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
961                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
962                                         "msDS-SupportedEncryptionTypes",
963                                         supported_enctypes);
964         }
965
966         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
967
968         if (direction == INBOUND) {
969                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
970
971         } else { /* OUTBOUND */
972                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
973                 /* replace realm */
974                 realm = strupper_talloc(mem_ctx, dnsdomain);
975                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
976         }
977
978         if (!password_val || !(trust_direction_flags & direction)) {
979                 krb5_clear_error_message(context);
980                 ret = HDB_ERR_NOENTRY;
981                 goto out;
982         }
983
984         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
985                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
986         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
987                 krb5_clear_error_message(context);
988                 ret = EINVAL;
989                 goto out;
990         }
991
992         p = talloc(mem_ctx, struct samba_kdc_entry);
993         if (!p) {
994                 ret = ENOMEM;
995                 goto out;
996         }
997
998         p->kdc_db_ctx = kdc_db_ctx;
999         p->entry_ex = entry_ex;
1000         p->realm_dn = realm_dn;
1001
1002         talloc_set_destructor(p, samba_kdc_entry_destructor);
1003
1004         /* make sure we do not have bogus data in there */
1005         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
1006
1007         entry_ex->ctx = p;
1008         entry_ex->free_entry = samba_kdc_free_entry;
1009
1010         /* use 'whenCreated' */
1011         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1012         /* use 'kadmin' for now (needed by mit_samba) */
1013         ret = krb5_make_principal(context,
1014                             &entry_ex->entry.created_by.principal,
1015                             realm, "kadmin", NULL);
1016         if (ret) {
1017                 krb5_clear_error_message(context);
1018                 goto out;
1019         }
1020
1021         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
1022         if (entry_ex->entry.principal == NULL) {
1023                 krb5_clear_error_message(context);
1024                 ret = ENOMEM;
1025                 goto out;
1026         }
1027
1028         ret = copy_Principal(principal, entry_ex->entry.principal);
1029         if (ret) {
1030                 krb5_clear_error_message(context);
1031                 goto out;
1032         }
1033
1034         /*
1035          * While we have copied the client principal, tests
1036          * show that Win2k3 returns the 'corrected' realm, not
1037          * the client-specified realm.  This code attempts to
1038          * replace the client principal's realm with the one
1039          * we determine from our records
1040          */
1041
1042         ret = krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
1043         if (ret) {
1044                 krb5_clear_error_message(context);
1045                 goto out;
1046         }
1047
1048         entry_ex->entry.valid_start = NULL;
1049
1050         /* we need to work out if we are going to use the current or
1051          * the previous password hash.
1052          * We base this on the kvno the client passes in. If the kvno
1053          * passed in is equal to the current kvno in our database then
1054          * we use the current structure. If it is the current kvno-1,
1055          * then we use the previous substrucure.
1056          */
1057
1058         /* first work out the current kvno */
1059         current_kvno = 0;
1060         for (i=0; i < password_blob.count; i++) {
1061                 if (password_blob.current.array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
1062                         current_kvno = password_blob.current.array[i].AuthInfo.version.version;
1063                 }
1064         }
1065
1066         /* work out whether we will use the previous or current
1067            password */
1068         if (password_blob.previous.count == 0) {
1069                 /* there is no previous password */
1070                 use_previous = false;
1071         } else if (!(flags & HDB_F_KVNO_SPECIFIED) ||
1072             kvno == current_kvno) {
1073                 use_previous = false;
1074         } else if ((kvno+1 == current_kvno) ||
1075                    (kvno == 255 && current_kvno == 0)) {
1076                 use_previous = true;
1077         } else {
1078                 DEBUG(1,(__location__ ": Request for unknown kvno %u - current kvno is %u\n",
1079                          kvno, current_kvno));
1080                 krb5_clear_error_message(context);
1081                 ret = HDB_ERR_NOENTRY;
1082                 goto out;
1083         }
1084
1085         if (use_previous) {
1086                 auth_array = &password_blob.previous;
1087         } else {
1088                 auth_array = &password_blob.current;
1089         }
1090
1091         /* use the kvno the client specified, if available */
1092         if (flags & HDB_F_KVNO_SPECIFIED) {
1093                 entry_ex->entry.kvno = kvno;
1094         } else {
1095                 entry_ex->entry.kvno = current_kvno;
1096         }
1097
1098         for (i=0; i < auth_array->count; i++) {
1099                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1100                         bool ok;
1101
1102                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1103                                                          auth_array->array[i].AuthInfo.clear.size);
1104                         if (password_utf16.length == 0) {
1105                                 break;
1106                         }
1107
1108                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1109                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1110                                 if (password_hash == NULL) {
1111                                         num_keys += 1;
1112                                 }
1113                                 password_hash = &_password_hash;
1114                         }
1115
1116                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1117                                 break;
1118                         }
1119
1120                         ok = convert_string_talloc(mem_ctx,
1121                                                    CH_UTF16MUNGED, CH_UTF8,
1122                                                    password_utf16.data,
1123                                                    password_utf16.length,
1124                                                    (void *)&password_utf8.data,
1125                                                    &password_utf8.length);
1126                         if (!ok) {
1127                                 krb5_clear_error_message(context);
1128                                 ret = ENOMEM;
1129                                 goto out;
1130                         }
1131
1132                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1133                                 num_keys += 1;
1134                         }
1135                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1136                                 num_keys += 1;
1137                         }
1138                         break;
1139                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1140                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1141                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1142                                 num_keys += 1;
1143                         }
1144                 }
1145         }
1146
1147         /* Must have found a cleartext or MD4 password */
1148         if (num_keys == 0) {
1149                 DEBUG(1,(__location__ ": no usable key found\n"));
1150                 krb5_clear_error_message(context);
1151                 ret = HDB_ERR_NOENTRY;
1152                 goto out;
1153         }
1154
1155         entry_ex->entry.keys.val = calloc(num_keys, sizeof(Key));
1156         if (entry_ex->entry.keys.val == NULL) {
1157                 krb5_clear_error_message(context);
1158                 ret = ENOMEM;
1159                 goto out;
1160         }
1161
1162         if (password_utf8.length != 0) {
1163                 Key key = {};
1164                 krb5_const_principal salt_principal = principal;
1165                 krb5_salt salt;
1166                 krb5_data cleartext_data;
1167
1168                 cleartext_data.data = password_utf8.data;
1169                 cleartext_data.length = password_utf8.length;
1170
1171                 ret = krb5_get_pw_salt(context,
1172                                        salt_principal,
1173                                        &salt);
1174                 if (ret != 0) {
1175                         goto out;
1176                 }
1177
1178                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1179                         ret = krb5_string_to_key_data_salt(context,
1180                                                            ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1181                                                            cleartext_data,
1182                                                            salt,
1183                                                            &key.key);
1184                         if (ret != 0) {
1185                                 krb5_free_salt(context, salt);
1186                                 goto out;
1187                         }
1188
1189                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1190                         entry_ex->entry.keys.len++;
1191                 }
1192
1193                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1194                         ret = krb5_string_to_key_data_salt(context,
1195                                                            ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1196                                                            cleartext_data,
1197                                                            salt,
1198                                                            &key.key);
1199                         if (ret != 0) {
1200                                 krb5_free_salt(context, salt);
1201                                 goto out;
1202                         }
1203
1204                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1205                         entry_ex->entry.keys.len++;
1206                 }
1207
1208                 krb5_free_salt(context, salt);
1209         }
1210
1211         if (password_hash != NULL) {
1212                 Key key = {};
1213
1214                 ret = smb_krb5_keyblock_init_contents(context,
1215                                                       ENCTYPE_ARCFOUR_HMAC,
1216                                                       password_hash->hash,
1217                                                       sizeof(password_hash->hash),
1218                                                       &key.key);
1219                 if (ret != 0) {
1220                         goto out;
1221                 }
1222
1223                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1224                 entry_ex->entry.keys.len++;
1225         }
1226
1227         entry_ex->entry.flags = int2HDBFlags(0);
1228         entry_ex->entry.flags.immutable = 1;
1229         entry_ex->entry.flags.invalid = 0;
1230         entry_ex->entry.flags.server = 1;
1231         entry_ex->entry.flags.require_preauth = 1;
1232
1233         entry_ex->entry.pw_end = NULL;
1234
1235         entry_ex->entry.max_life = NULL;
1236
1237         entry_ex->entry.max_renew = NULL;
1238
1239         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
1240         if (entry_ex->entry.etypes == NULL) {
1241                 krb5_clear_error_message(context);
1242                 ret = ENOMEM;
1243                 goto out;
1244         }
1245         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
1246         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
1247         if (entry_ex->entry.etypes->val == NULL) {
1248                 krb5_clear_error_message(context);
1249                 ret = ENOMEM;
1250                 goto out;
1251         }
1252         for (i=0; i < entry_ex->entry.etypes->len; i++) {
1253                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
1254         }
1255
1256
1257         p->msg = talloc_steal(p, msg);
1258
1259 out:
1260         if (ret != 0) {
1261                 /* This doesn't free ent itself, that is for the eventual caller to do */
1262                 hdb_free_entry(context, entry_ex);
1263         } else {
1264                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1265         }
1266
1267         return ret;
1268
1269 }
1270
1271 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1272                                         TALLOC_CTX *mem_ctx,
1273                                         const char *realm,
1274                                         struct ldb_dn *realm_dn,
1275                                         struct ldb_message **pmsg)
1276 {
1277         NTSTATUS status;
1278         const char * const *attrs = trust_attrs;
1279
1280         status = sam_get_results_trust(ldb_ctx,
1281                                        mem_ctx, realm, realm, attrs,
1282                                        pmsg);
1283         if (NT_STATUS_IS_OK(status)) {
1284                 return 0;
1285         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
1286                 return HDB_ERR_NOENTRY;
1287         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1288                 int ret = ENOMEM;
1289                 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1290                 return ret;
1291         } else {
1292                 int ret = EINVAL;
1293                 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1294                 return ret;
1295         }
1296 }
1297
1298 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1299                                                 struct samba_kdc_db_context *kdc_db_ctx,
1300                                                 TALLOC_CTX *mem_ctx,
1301                                                 krb5_const_principal principal,
1302                                                 const char **attrs,
1303                                                 struct ldb_dn **realm_dn,
1304                                                 struct ldb_message **msg) {
1305         NTSTATUS nt_status;
1306         char *principal_string;
1307
1308         if (krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1309                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1310                                                                       principal, 0);
1311                 if (principal_string == NULL) {
1312                         return ENOMEM;
1313                 }
1314                 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1315                                                       mem_ctx, principal_string, attrs,
1316                                                       realm_dn, msg);
1317                 TALLOC_FREE(principal_string);
1318         } else {
1319                 krb5_error_code ret;
1320                 ret = krb5_unparse_name(context, principal, &principal_string);
1321                 if (ret != 0) {
1322                         return ret;
1323                 }
1324                 nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1325                                                       mem_ctx, principal_string, attrs,
1326                                                       realm_dn, msg);
1327                 free(principal_string);
1328         }
1329
1330         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1331                 return HDB_ERR_NOENTRY;
1332         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1333                 return ENOMEM;
1334         } else if (!NT_STATUS_IS_OK(nt_status)) {
1335                 return EINVAL;
1336         }
1337
1338         return 0;
1339 }
1340
1341 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1342                                                struct samba_kdc_db_context *kdc_db_ctx,
1343                                                TALLOC_CTX *mem_ctx,
1344                                                krb5_const_principal principal,
1345                                                unsigned flags,
1346                                                hdb_entry_ex *entry_ex) {
1347         struct ldb_dn *realm_dn;
1348         krb5_error_code ret;
1349         struct ldb_message *msg = NULL;
1350
1351         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1352                                       mem_ctx, principal, user_attrs,
1353                                       &realm_dn, &msg);
1354         if (ret != 0) {
1355                 return ret;
1356         }
1357
1358         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1359                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1360                                       flags,
1361                                       realm_dn, msg, entry_ex);
1362         return ret;
1363 }
1364
1365 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1366                                               struct samba_kdc_db_context *kdc_db_ctx,
1367                                               TALLOC_CTX *mem_ctx,
1368                                               krb5_const_principal principal,
1369                                               unsigned flags,
1370                                               uint32_t kvno,
1371                                               hdb_entry_ex *entry_ex)
1372 {
1373         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1374         krb5_error_code ret;
1375         struct ldb_message *msg = NULL;
1376         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1377
1378         krb5_principal alloc_principal = NULL;
1379         if (principal->name.name_string.len != 2
1380             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1381                 /* Not a krbtgt */
1382                 return HDB_ERR_NOENTRY;
1383         }
1384
1385         /* krbtgt case.  Either us or a trusted realm */
1386
1387         if (lpcfg_is_my_domain_or_realm(lp_ctx, principal->realm)
1388             && lpcfg_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1389                 /* us, or someone quite like us */
1390                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1391                  * is in our db, then direct the caller at our primary
1392                  * krbtgt */
1393
1394                 int lret;
1395                 unsigned int krbtgt_number;
1396                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1397                    trust tickets. We don't yet know what this means, but we do
1398                    seem to need to treat it as unspecified */
1399                 if (flags & HDB_F_KVNO_SPECIFIED) {
1400                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1401                         if (kdc_db_ctx->rodc) {
1402                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1403                                         return HDB_ERR_NOT_FOUND_HERE;
1404                                 }
1405                         }
1406                 } else {
1407                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1408                 }
1409
1410                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1411                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1412                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1413                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1414                                                "(objectClass=user)");
1415                 } else {
1416                         /* We need to look up an RODC krbtgt (perhaps
1417                          * ours, if we are an RODC, perhaps another
1418                          * RODC if we are a read-write DC */
1419                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1420                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1421                                                krbtgt_attrs,
1422                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1423                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1424                 }
1425
1426                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1427                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1428                                    (unsigned)(krbtgt_number));
1429                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1430                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1431                                                (unsigned)(krbtgt_number));
1432                         return HDB_ERR_NOENTRY;
1433                 } else if (lret != LDB_SUCCESS) {
1434                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1435                                    (unsigned)(krbtgt_number));
1436                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1437                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1438                                                (unsigned)(krbtgt_number));
1439                         return HDB_ERR_NOENTRY;
1440                 }
1441
1442                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1443                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1444                                               flags, realm_dn, msg, entry_ex);
1445                 if (alloc_principal) {
1446                         /* This is again copied in the message2entry call */
1447                         krb5_free_principal(context, alloc_principal);
1448                 }
1449                 if (ret != 0) {
1450                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1451                 }
1452                 return ret;
1453
1454         } else {
1455                 enum trust_direction direction = UNKNOWN;
1456                 const char *realm = NULL;
1457
1458                 /* Either an inbound or outbound trust */
1459
1460                 if (strcasecmp(lpcfg_realm(lp_ctx), principal->realm) == 0) {
1461                         /* look for inbound trust */
1462                         direction = INBOUND;
1463                         realm = principal->name.name_string.val[1];
1464                 } else if (strcasecmp(lpcfg_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1465                         /* look for outbound trust */
1466                         direction = OUTBOUND;
1467                         realm = principal->realm;
1468                 } else {
1469                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1470                                    principal->realm, principal->name.name_string.val[1]);
1471                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1472                                                principal->realm, principal->name.name_string.val[1]);
1473                         return HDB_ERR_NOENTRY;
1474                 }
1475
1476                 /* Trusted domains are under CN=system */
1477
1478                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1479                                        mem_ctx,
1480                                        realm, realm_dn, &msg);
1481
1482                 if (ret != 0) {
1483                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1484                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1485                         return ret;
1486                 }
1487
1488                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1489                                                     principal, direction,
1490                                                     realm_dn, flags, kvno, msg, entry_ex);
1491                 if (ret != 0) {
1492                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1493                                    ldb_dn_get_linearized(msg->dn));
1494                         krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1495                                                "trust_message2entry failed for %s",
1496                                                ldb_dn_get_linearized(msg->dn));
1497                 }
1498                 return ret;
1499         }
1500
1501 }
1502
1503 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1504                                                struct samba_kdc_db_context *kdc_db_ctx,
1505                                                TALLOC_CTX *mem_ctx,
1506                                                krb5_const_principal principal,
1507                                                unsigned flags,
1508                                                const char **attrs,
1509                                                struct ldb_dn **realm_dn,
1510                                                struct ldb_message **msg)
1511 {
1512         krb5_error_code ret;
1513         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1514             && krb5_princ_size(context, principal) >= 2) {
1515                 /* 'normal server' case */
1516                 int ldb_ret;
1517                 NTSTATUS nt_status;
1518                 struct ldb_dn *user_dn;
1519                 char *principal_string;
1520
1521                 ret = krb5_unparse_name_flags(context, principal,
1522                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1523                                               &principal_string);
1524                 if (ret != 0) {
1525                         return ret;
1526                 }
1527
1528                 /* At this point we may find the host is known to be
1529                  * in a different realm, so we should generate a
1530                  * referral instead */
1531                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1532                                                          mem_ctx, principal_string,
1533                                                          &user_dn, realm_dn);
1534                 free(principal_string);
1535
1536                 if (!NT_STATUS_IS_OK(nt_status)) {
1537                         return HDB_ERR_NOENTRY;
1538                 }
1539
1540                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1541                                           mem_ctx,
1542                                           msg, user_dn, LDB_SCOPE_BASE,
1543                                           attrs,
1544                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1545                                           "(objectClass=*)");
1546                 if (ldb_ret != LDB_SUCCESS) {
1547                         return HDB_ERR_NOENTRY;
1548                 }
1549                 return 0;
1550         } else if (!(flags & HDB_F_FOR_AS_REQ)
1551                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1552                 /*
1553                  * The behaviour of accepting an
1554                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1555                  * containing a UPN only applies to TGS-REQ packets,
1556                  * not AS-REQ packets.
1557                  */
1558                 return samba_kdc_lookup_client(context, kdc_db_ctx,
1559                                                mem_ctx, principal, attrs,
1560                                                realm_dn, msg);
1561         } else {
1562                 /*
1563                  * This case is for:
1564                  *  - the AS-REQ, where we only accept
1565                  *    samAccountName based lookups for the server, no
1566                  *    matter if the name is an
1567                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
1568                  *  - for the TGS-REQ when we are not given an
1569                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1570                  *    only lookup samAccountName based names.
1571                  */
1572                 int lret;
1573                 char *short_princ;
1574                 krb5_principal enterprise_prinicpal = NULL;
1575
1576                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1577                         /* Need to reparse the enterprise principal to find the real target */
1578                         if (principal->name.name_string.len != 1) {
1579                                 ret = KRB5_PARSE_MALFORMED;
1580                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
1581                                                        "enterprise principal with wrong (%d) number of components",
1582                                                        principal->name.name_string.len);
1583                                 return ret;
1584                         }
1585                         ret = krb5_parse_name(context, principal->name.name_string.val[0],
1586                                               &enterprise_prinicpal);
1587                         if (ret) {
1588                                 talloc_free(mem_ctx);
1589                                 return ret;
1590                         }
1591                         principal = enterprise_prinicpal;
1592                 }
1593
1594                 /* server as client principal case, but we must not lookup userPrincipalNames */
1595                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1596
1597                 /* TODO: Check if it is our realm, otherwise give referral */
1598
1599                 ret = krb5_unparse_name_flags(context, principal,
1600                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
1601                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
1602                                               &short_princ);
1603
1604                 if (ret != 0) {
1605                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1606                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1607                         return ret;
1608                 }
1609
1610                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1611                                        *realm_dn, LDB_SCOPE_SUBTREE,
1612                                        attrs,
1613                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1614                                        "(&(objectClass=user)(samAccountName=%s))",
1615                                        ldb_binary_encode_string(mem_ctx, short_princ));
1616                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1617                         DEBUG(3, ("Failed to find an entry for %s\n", short_princ));
1618                         free(short_princ);
1619                         return HDB_ERR_NOENTRY;
1620                 }
1621                 if (lret != LDB_SUCCESS) {
1622                         DEBUG(3, ("Failed single search for %s - %s\n",
1623                                   short_princ, ldb_errstring(kdc_db_ctx->samdb)));
1624                         free(short_princ);
1625                         return HDB_ERR_NOENTRY;
1626                 }
1627                 free(short_princ);
1628                 return 0;
1629         }
1630         return HDB_ERR_NOENTRY;
1631 }
1632
1633
1634
1635 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1636                                               struct samba_kdc_db_context *kdc_db_ctx,
1637                                               TALLOC_CTX *mem_ctx,
1638                                               krb5_const_principal principal,
1639                                               unsigned flags,
1640                                               hdb_entry_ex *entry_ex)
1641 {
1642         krb5_error_code ret;
1643         struct ldb_dn *realm_dn;
1644         struct ldb_message *msg;
1645
1646         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1647                                       flags, server_attrs, &realm_dn, &msg);
1648         if (ret != 0) {
1649                 return ret;
1650         }
1651
1652         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1653                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1654                                       flags,
1655                                       realm_dn, msg, entry_ex);
1656         if (ret != 0) {
1657                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1658         }
1659
1660         return ret;
1661 }
1662
1663 krb5_error_code samba_kdc_fetch(krb5_context context,
1664                                 struct samba_kdc_db_context *kdc_db_ctx,
1665                                 krb5_const_principal principal,
1666                                 unsigned flags,
1667                                 krb5_kvno kvno,
1668                                 hdb_entry_ex *entry_ex)
1669 {
1670         krb5_error_code ret = HDB_ERR_NOENTRY;
1671         TALLOC_CTX *mem_ctx;
1672
1673         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1674         if (!mem_ctx) {
1675                 ret = ENOMEM;
1676                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1677                 return ret;
1678         }
1679
1680         if (flags & HDB_F_GET_CLIENT) {
1681                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1682                 if (ret != HDB_ERR_NOENTRY) goto done;
1683         }
1684         if (flags & HDB_F_GET_SERVER) {
1685                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1686                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1687                 if (ret != HDB_ERR_NOENTRY) goto done;
1688
1689                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1690                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
1691                 if (ret != HDB_ERR_NOENTRY) goto done;
1692         }
1693         if (flags & HDB_F_GET_KRBTGT) {
1694                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
1695                 if (ret != HDB_ERR_NOENTRY) goto done;
1696         }
1697
1698 done:
1699         talloc_free(mem_ctx);
1700         return ret;
1701 }
1702
1703 struct samba_kdc_seq {
1704         unsigned int index;
1705         unsigned int count;
1706         struct ldb_message **msgs;
1707         struct ldb_dn *realm_dn;
1708 };
1709
1710 static krb5_error_code samba_kdc_seq(krb5_context context,
1711                                      struct samba_kdc_db_context *kdc_db_ctx,
1712                                      hdb_entry_ex *entry)
1713 {
1714         krb5_error_code ret;
1715         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1716         TALLOC_CTX *mem_ctx;
1717
1718         if (!priv) {
1719                 return HDB_ERR_NOENTRY;
1720         }
1721
1722         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1723
1724         if (!mem_ctx) {
1725                 ret = ENOMEM;
1726                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1727                 return ret;
1728         }
1729
1730         if (priv->index < priv->count) {
1731                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1732                                               NULL, SAMBA_KDC_ENT_TYPE_ANY,
1733                                               HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
1734                                               priv->realm_dn, priv->msgs[priv->index++], entry);
1735         } else {
1736                 ret = HDB_ERR_NOENTRY;
1737         }
1738
1739         if (ret != 0) {
1740                 TALLOC_FREE(priv);
1741                 kdc_db_ctx->seq_ctx = NULL;
1742         } else {
1743                 talloc_free(mem_ctx);
1744         }
1745
1746         return ret;
1747 }
1748
1749 krb5_error_code samba_kdc_firstkey(krb5_context context,
1750                                    struct samba_kdc_db_context *kdc_db_ctx,
1751                                    hdb_entry_ex *entry)
1752 {
1753         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1754         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1755         char *realm;
1756         struct ldb_result *res = NULL;
1757         krb5_error_code ret;
1758         TALLOC_CTX *mem_ctx;
1759         int lret;
1760
1761         if (priv) {
1762                 TALLOC_FREE(priv);
1763                 kdc_db_ctx->seq_ctx = NULL;
1764         }
1765
1766         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1767         if (!priv) {
1768                 ret = ENOMEM;
1769                 krb5_set_error_message(context, ret, "talloc: out of memory");
1770                 return ret;
1771         }
1772
1773         priv->index = 0;
1774         priv->msgs = NULL;
1775         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1776         priv->count = 0;
1777
1778         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1779
1780         if (!mem_ctx) {
1781                 ret = ENOMEM;
1782                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1783                 return ret;
1784         }
1785
1786         ret = krb5_get_default_realm(context, &realm);
1787         if (ret != 0) {
1788                 TALLOC_FREE(priv);
1789                 return ret;
1790         }
1791         krb5_free_default_realm(context, realm);
1792
1793         lret = dsdb_search(ldb_ctx, priv, &res,
1794                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1795                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
1796                            "(objectClass=user)");
1797
1798         if (lret != LDB_SUCCESS) {
1799                 TALLOC_FREE(priv);
1800                 return HDB_ERR_NOENTRY;
1801         }
1802
1803         priv->count = res->count;
1804         priv->msgs = talloc_steal(priv, res->msgs);
1805         talloc_free(res);
1806
1807         kdc_db_ctx->seq_ctx = priv;
1808
1809         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1810
1811         if (ret != 0) {
1812                 TALLOC_FREE(priv);
1813                 kdc_db_ctx->seq_ctx = NULL;
1814         } else {
1815                 talloc_free(mem_ctx);
1816         }
1817         return ret;
1818 }
1819
1820 krb5_error_code samba_kdc_nextkey(krb5_context context,
1821                                   struct samba_kdc_db_context *kdc_db_ctx,
1822                                   hdb_entry_ex *entry)
1823 {
1824         return samba_kdc_seq(context, kdc_db_ctx, entry);
1825 }
1826
1827 /* Check if a given entry may delegate or do s4u2self to this target principal
1828  *
1829  * This is currently a very nasty hack - allowing only delegation to itself.
1830  */
1831 krb5_error_code
1832 samba_kdc_check_s4u2self(krb5_context context,
1833                          struct samba_kdc_db_context *kdc_db_ctx,
1834                          hdb_entry_ex *entry,
1835                          krb5_const_principal target_principal)
1836 {
1837         krb5_error_code ret;
1838         struct ldb_dn *realm_dn;
1839         struct ldb_message *msg;
1840         struct dom_sid *orig_sid;
1841         struct dom_sid *target_sid;
1842         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1843         const char *delegation_check_attrs[] = {
1844                 "objectSid", NULL
1845         };
1846
1847         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
1848
1849         if (!mem_ctx) {
1850                 ret = ENOMEM;
1851                 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
1852                 return ret;
1853         }
1854
1855         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1856                                       HDB_F_GET_CLIENT|HDB_F_GET_SERVER,
1857                                       delegation_check_attrs, &realm_dn, &msg);
1858
1859         if (ret != 0) {
1860                 talloc_free(mem_ctx);
1861                 return ret;
1862         }
1863
1864         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1865         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1866
1867         /* Allow delegation to the same principal, even if by a different
1868          * name.  The easy and safe way to prove this is by SID
1869          * comparison */
1870         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1871                 talloc_free(mem_ctx);
1872                 return KRB5KDC_ERR_BADOPTION;
1873         }
1874
1875         talloc_free(mem_ctx);
1876         return ret;
1877 }
1878
1879 /* Certificates printed by a the Certificate Authority might have a
1880  * slightly different form of the user principal name to that in the
1881  * database.  Allow a mismatch where they both refer to the same
1882  * SID */
1883
1884 krb5_error_code
1885 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1886                                     struct samba_kdc_db_context *kdc_db_ctx,
1887                                      hdb_entry_ex *entry,
1888                                      krb5_const_principal certificate_principal)
1889 {
1890         krb5_error_code ret;
1891         struct ldb_dn *realm_dn;
1892         struct ldb_message *msg;
1893         struct dom_sid *orig_sid;
1894         struct dom_sid *target_sid;
1895         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1896         const char *ms_upn_check_attrs[] = {
1897                 "objectSid", NULL
1898         };
1899
1900         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1901
1902         if (!mem_ctx) {
1903                 ret = ENOMEM;
1904                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1905                 return ret;
1906         }
1907
1908         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1909                                       mem_ctx, certificate_principal,
1910                                       ms_upn_check_attrs, &realm_dn, &msg);
1911
1912         if (ret != 0) {
1913                 talloc_free(mem_ctx);
1914                 return ret;
1915         }
1916
1917         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1918         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1919
1920         /* Consider these to be the same principal, even if by a different
1921          * name.  The easy and safe way to prove this is by SID
1922          * comparison */
1923         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1924                 talloc_free(mem_ctx);
1925                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1926         }
1927
1928         talloc_free(mem_ctx);
1929         return ret;
1930 }
1931
1932 /*
1933  * Check if a given entry may delegate to this target principal
1934  * with S4U2Proxy.
1935  */
1936 krb5_error_code
1937 samba_kdc_check_s4u2proxy(krb5_context context,
1938                           struct samba_kdc_db_context *kdc_db_ctx,
1939                           hdb_entry_ex *entry,
1940                           krb5_const_principal target_principal)
1941 {
1942         krb5_error_code ret;
1943         char *tmp = NULL;
1944         const char *client_dn = NULL;
1945         const char *target_principal_name = NULL;
1946         struct ldb_message_element *el;
1947         struct ldb_val val;
1948         unsigned int i;
1949         bool found = false;
1950         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1951
1952         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
1953
1954         if (!mem_ctx) {
1955                 ret = ENOMEM;
1956                 krb5_set_error_message(context, ret,
1957                                        "samba_kdc_check_s4u2proxy:"
1958                                        " talloc_named() failed!");
1959                 return ret;
1960         }
1961
1962         client_dn = ldb_dn_get_linearized(p->msg->dn);
1963         if (!client_dn) {
1964                 if (errno == 0) {
1965                         errno = ENOMEM;
1966                 }
1967                 ret = errno;
1968                 krb5_set_error_message(context, ret,
1969                                        "samba_kdc_check_s4u2proxy:"
1970                                        " ldb_dn_get_linearized() failed!");
1971                 return ret;
1972         }
1973
1974         /*
1975          * The main heimdal code already checked that the target_principal
1976          * belongs to the same realm as the client.
1977          *
1978          * So we just need the principal without the realm,
1979          * as that is what is configured in the "msDS-AllowedToDelegateTo"
1980          * attribute.
1981          */
1982         ret = krb5_unparse_name_flags(context, target_principal,
1983                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
1984         if (ret) {
1985                 talloc_free(mem_ctx);
1986                 krb5_set_error_message(context, ret,
1987                                        "samba_kdc_check_s4u2proxy:"
1988                                        " krb5_unparse_name() failed!");
1989                 return ret;
1990         }
1991         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
1992                  client_dn, tmp));
1993
1994         target_principal_name = talloc_strdup(mem_ctx, tmp);
1995         SAFE_FREE(tmp);
1996         if (target_principal_name == NULL) {
1997                 ret = ENOMEM;
1998                 krb5_set_error_message(context, ret,
1999                                        "samba_kdc_check_s4u2proxy:"
2000                                        " talloc_strdup() failed!");
2001                 return ret;
2002         }
2003
2004         el = ldb_msg_find_element(p->msg, "msDS-AllowedToDelegateTo");
2005         if (el == NULL) {
2006                 goto bad_option;
2007         }
2008
2009         val = data_blob_string_const(target_principal_name);
2010
2011         for (i=0; i<el->num_values; i++) {
2012                 struct ldb_val *val1 = &val;
2013                 struct ldb_val *val2 = &el->values[i];
2014                 int cmp;
2015
2016                 if (val1->length != val2->length) {
2017                         continue;
2018                 }
2019
2020                 cmp = strncasecmp((const char *)val1->data,
2021                                   (const char *)val2->data,
2022                                   val1->length);
2023                 if (cmp != 0) {
2024                         continue;
2025                 }
2026
2027                 found = true;
2028                 break;
2029         }
2030
2031         if (!found) {
2032                 goto bad_option;
2033         }
2034
2035         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2036                  client_dn, tmp));
2037         talloc_free(mem_ctx);
2038         return 0;
2039
2040 bad_option:
2041         krb5_set_error_message(context, ret,
2042                                "samba_kdc_check_s4u2proxy: client[%s] "
2043                                "not allowed for delegation to target[%s]",
2044                                client_dn,
2045                                target_principal_name);
2046         talloc_free(mem_ctx);
2047         return KRB5KDC_ERR_BADOPTION;
2048 }
2049
2050 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2051                                 struct samba_kdc_db_context **kdc_db_ctx_out)
2052 {
2053         int ldb_ret;
2054         struct ldb_message *msg;
2055         struct auth_session_info *session_info;
2056         struct samba_kdc_db_context *kdc_db_ctx;
2057         /* The idea here is very simple.  Using Kerberos to
2058          * authenticate the KDC to the LDAP server is higly likely to
2059          * be circular.
2060          *
2061          * In future we may set this up to use EXERNAL and SSL
2062          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2063         */
2064
2065         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2066         if (kdc_db_ctx == NULL) {
2067                 return NT_STATUS_NO_MEMORY;
2068         }
2069         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2070         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2071
2072         /* get default kdc policy */
2073         lpcfg_default_kdc_policy(base_ctx->lp_ctx,
2074                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
2075                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
2076                                  &kdc_db_ctx->policy.renewal_lifetime);
2077
2078         session_info = system_session(kdc_db_ctx->lp_ctx);
2079         if (session_info == NULL) {
2080                 return NT_STATUS_INTERNAL_ERROR;
2081         }
2082
2083         /* Setup the link to LDB */
2084         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
2085                                           base_ctx->lp_ctx, session_info, 0);
2086         if (kdc_db_ctx->samdb == NULL) {
2087                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2088                 talloc_free(kdc_db_ctx);
2089                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2090         }
2091
2092         /* Find out our own krbtgt kvno */
2093         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2094         if (ldb_ret != LDB_SUCCESS) {
2095                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2096                           ldb_errstring(kdc_db_ctx->samdb)));
2097                 talloc_free(kdc_db_ctx);
2098                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2099         }
2100         if (kdc_db_ctx->rodc) {
2101                 int my_krbtgt_number;
2102                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2103                 struct ldb_dn *account_dn;
2104                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2105                 if (!server_dn) {
2106                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2107                                   ldb_errstring(kdc_db_ctx->samdb)));
2108                         talloc_free(kdc_db_ctx);
2109                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2110                 }
2111
2112                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2113                                              "serverReference", &account_dn);
2114                 if (ldb_ret != LDB_SUCCESS) {
2115                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2116                                   ldb_errstring(kdc_db_ctx->samdb)));
2117                         talloc_free(kdc_db_ctx);
2118                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2119                 }
2120
2121                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2122                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2123                 talloc_free(account_dn);
2124                 if (ldb_ret != LDB_SUCCESS) {
2125                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2126                                   ldb_errstring(kdc_db_ctx->samdb)));
2127                         talloc_free(kdc_db_ctx);
2128                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2129                 }
2130
2131                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2132                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2133                                           secondary_keytab,
2134                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2135                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2136                 if (ldb_ret != LDB_SUCCESS) {
2137                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2138                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2139                                   ldb_errstring(kdc_db_ctx->samdb),
2140                                   ldb_strerror(ldb_ret)));
2141                         talloc_free(kdc_db_ctx);
2142                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2143                 }
2144                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2145                 if (my_krbtgt_number == -1) {
2146                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2147                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2148                                   my_krbtgt_number));
2149                         talloc_free(kdc_db_ctx);
2150                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2151                 }
2152                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2153
2154         } else {
2155                 kdc_db_ctx->my_krbtgt_number = 0;
2156                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2157                                           &msg,
2158                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
2159                                           LDB_SCOPE_SUBTREE,
2160                                           krbtgt_attrs,
2161                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2162                                           "(&(objectClass=user)(samAccountName=krbtgt))");
2163
2164                 if (ldb_ret != LDB_SUCCESS) {
2165                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2166                         talloc_free(kdc_db_ctx);
2167                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2168                 }
2169                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2170                 kdc_db_ctx->my_krbtgt_number = 0;
2171                 talloc_free(msg);
2172         }
2173         *kdc_db_ctx_out = kdc_db_ctx;
2174         return NT_STATUS_OK;
2175 }