s4-kdc: Fix a casting warning
[amitay/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 time_t ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, time_t 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         if (p->entry_ex != NULL) {
192                 hdb_entry_ex *entry_ex = p->entry_ex;
193                 free_hdb_entry(&entry_ex->entry);
194         }
195
196         return 0;
197 }
198
199 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
200 {
201         /* this function is called only from hdb_free_entry().
202          * Make sure we neutralize the destructor or we will
203          * get a double free later when hdb_free_entry() will
204          * try to call free_hdb_entry() */
205         talloc_set_destructor(entry_ex->ctx, NULL);
206
207         /* now proceed to free the talloc part */
208         talloc_free(entry_ex->ctx);
209 }
210
211 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
212                                                     struct samba_kdc_db_context *kdc_db_ctx,
213                                                     TALLOC_CTX *mem_ctx,
214                                                     struct ldb_message *msg,
215                                                     uint32_t rid,
216                                                     bool is_rodc,
217                                                     uint32_t userAccountControl,
218                                                     enum samba_kdc_ent_type ent_type,
219                                                     hdb_entry_ex *entry_ex)
220 {
221         krb5_error_code ret = 0;
222         enum ndr_err_code ndr_err;
223         struct samr_Password *hash;
224         const struct ldb_val *sc_val;
225         struct supplementalCredentialsBlob scb;
226         struct supplementalCredentialsPackage *scpk = NULL;
227         bool newer_keys = false;
228         struct package_PrimaryKerberosBlob _pkb;
229         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
230         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
231         uint16_t i;
232         uint16_t allocated_keys = 0;
233         int rodc_krbtgt_number = 0;
234         int kvno = 0;
235         uint32_t supported_enctypes
236                 = ldb_msg_find_attr_as_uint(msg,
237                                             "msDS-SupportedEncryptionTypes",
238                                             0);
239
240         if (rid == DOMAIN_RID_KRBTGT || is_rodc) {
241                 /* KDCs (and KDCs on RODCs) use AES */
242                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
243         } else if (userAccountControl & (UF_PARTIAL_SECRETS_ACCOUNT|UF_SERVER_TRUST_ACCOUNT)) {
244                 /* DCs and RODCs comptuer accounts use AES */
245                 supported_enctypes |= ENC_HMAC_SHA1_96_AES128 | ENC_HMAC_SHA1_96_AES256;
246         } else if (ent_type == SAMBA_KDC_ENT_TYPE_CLIENT ||
247                    (ent_type == SAMBA_KDC_ENT_TYPE_ANY)) {
248                 /* for AS-REQ the client chooses the enc types it
249                  * supports, and this will vary between computers a
250                  * user logs in from.
251                  *
252                  * likewise for 'any' return as much as is supported,
253                  * to export into a keytab */
254                 supported_enctypes = ENC_ALL_TYPES;
255         }
256
257         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
258         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
259                 supported_enctypes = ENC_CRC32|ENC_RSA_MD5;
260         } else {
261                 /* Otherwise, add in the default enc types */
262                 supported_enctypes |= ENC_CRC32 | ENC_RSA_MD5 | ENC_RC4_HMAC_MD5;
263         }
264
265         /* Is this the krbtgt or a RODC krbtgt */
266         if (is_rodc) {
267                 rodc_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
268
269                 if (rodc_krbtgt_number == -1) {
270                         return EINVAL;
271                 }
272         }
273
274         entry_ex->entry.keys.val = NULL;
275         entry_ex->entry.keys.len = 0;
276
277         kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
278         if (is_rodc) {
279                 kvno = SAMBA_KVNO_AND_KRBTGT(kvno, rodc_krbtgt_number);
280         }
281         entry_ex->entry.kvno = kvno;
282
283         /* Get keys from the db */
284
285         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
286         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
287
288         /* unicodePwd for enctype 0x17 (23) if present */
289         if (hash) {
290                 allocated_keys++;
291         }
292
293         /* supplementalCredentials if present */
294         if (sc_val) {
295                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
296                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
297                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
298                         dump_data(0, sc_val->data, sc_val->length);
299                         ret = EINVAL;
300                         goto out;
301                 }
302
303                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
304                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
305                         ret = EINVAL;
306                         goto out;
307                 }
308
309                 for (i=0; i < scb.sub.num_packages; i++) {
310                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
311                                 scpk = &scb.sub.packages[i];
312                                 if (!scpk->data || !scpk->data[0]) {
313                                         scpk = NULL;
314                                         continue;
315                                 }
316                                 newer_keys = true;
317                                 break;
318                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
319                                 scpk = &scb.sub.packages[i];
320                                 if (!scpk->data || !scpk->data[0]) {
321                                         scpk = NULL;
322                                 }
323                                 /*
324                                  * we don't break here in hope to find
325                                  * a Kerberos-Newer-Keys package
326                                  */
327                         }
328                 }
329         }
330         /*
331          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
332          * of supplementalCredentials
333          */
334         if (scpk) {
335                 DATA_BLOB blob;
336
337                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
338                 if (!blob.data) {
339                         ret = ENOMEM;
340                         goto out;
341                 }
342
343                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
344                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
345                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
346                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
347                         ret = EINVAL;
348                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
349                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
350                         goto out;
351                 }
352
353                 if (newer_keys && _pkb.version != 4) {
354                         ret = EINVAL;
355                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
356                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
357                         goto out;
358                 }
359
360                 if (!newer_keys && _pkb.version != 3) {
361                         ret = EINVAL;
362                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
363                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
364                         goto out;
365                 }
366
367                 if (_pkb.version == 4) {
368                         pkb4 = &_pkb.ctr.ctr4;
369                         allocated_keys += pkb4->num_keys;
370                 } else if (_pkb.version == 3) {
371                         pkb3 = &_pkb.ctr.ctr3;
372                         allocated_keys += pkb3->num_keys;
373                 }
374         }
375
376         if (allocated_keys == 0) {
377                 if (kdc_db_ctx->rodc) {
378                         /* We are on an RODC, but don't have keys for this account.  Signal this to the caller */
379                         /* TODO:  We need to call a generalised version of auth_sam_trigger_repl_secret from here */
380                         return HDB_ERR_NOT_FOUND_HERE;
381                 }
382
383                 /* oh, no password.  Apparently (comment in
384                  * hdb-ldap.c) this violates the ASN.1, but this
385                  * allows an entry with no keys (yet). */
386                 return 0;
387         }
388
389         /* allocate space to decode into */
390         entry_ex->entry.keys.len = 0;
391         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
392         if (entry_ex->entry.keys.val == NULL) {
393                 ret = ENOMEM;
394                 goto out;
395         }
396
397         if (hash && (supported_enctypes & ENC_RC4_HMAC_MD5)) {
398                 Key key;
399
400                 key.mkvno = 0;
401                 key.salt = NULL; /* No salt for this enc type */
402
403                 ret = smb_krb5_keyblock_init_contents(context,
404                                                       ENCTYPE_ARCFOUR_HMAC,
405                                                       hash->hash,
406                                                       sizeof(hash->hash),
407                                                       &key.key);
408                 if (ret) {
409                         goto out;
410                 }
411
412                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
413                 entry_ex->entry.keys.len++;
414         }
415
416         if (pkb4) {
417                 for (i=0; i < pkb4->num_keys; i++) {
418                         Key key;
419
420                         if (!pkb4->keys[i].value) continue;
421
422                         if (!(kerberos_enctype_to_bitmap(pkb4->keys[i].keytype) & supported_enctypes)) {
423                                 continue;
424                         }
425
426                         key.mkvno = 0;
427                         key.salt = NULL;
428
429                         if (pkb4->salt.string) {
430                                 DATA_BLOB salt;
431
432                                 salt = data_blob_string_const(pkb4->salt.string);
433
434                                 key.salt = calloc(1, sizeof(*key.salt));
435                                 if (key.salt == NULL) {
436                                         ret = ENOMEM;
437                                         goto out;
438                                 }
439
440                                 key.salt->type = KRB5_PW_SALT;
441
442                                 ret = krb5_copy_data_contents(&key.salt->salt,
443                                                               salt.data,
444                                                               salt.length);
445                                 if (ret) {
446                                         free(key.salt);
447                                         key.salt = NULL;
448                                         goto out;
449                                 }
450                         }
451
452                         /* TODO: maybe pass the iteration_count somehow... */
453
454                         ret = smb_krb5_keyblock_init_contents(context,
455                                                               pkb4->keys[i].keytype,
456                                                               pkb4->keys[i].value->data,
457                                                               pkb4->keys[i].value->length,
458                                                               &key.key);
459                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
460                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
461                                          pkb4->keys[i].keytype));
462                                 ret = 0;
463                                 continue;
464                         }
465                         if (ret) {
466                                 if (key.salt) {
467                                         free_Salt(key.salt);
468                                         free(key.salt);
469                                         key.salt = NULL;
470                                 }
471                                 goto out;
472                         }
473
474                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
475                         entry_ex->entry.keys.len++;
476                 }
477         } else if (pkb3) {
478                 for (i=0; i < pkb3->num_keys; i++) {
479                         Key key;
480
481                         if (!pkb3->keys[i].value) continue;
482
483                         if (!(kerberos_enctype_to_bitmap(pkb3->keys[i].keytype) & supported_enctypes)) {
484                                 continue;
485                         }
486
487                         key.mkvno = 0;
488                         key.salt = NULL;
489
490                         if (pkb3->salt.string) {
491                                 DATA_BLOB salt;
492
493                                 salt = data_blob_string_const(pkb3->salt.string);
494
495                                 key.salt = calloc(1, sizeof(*key.salt));
496                                 if (key.salt == NULL) {
497                                         ret = ENOMEM;
498                                         goto out;
499                                 }
500
501                                 key.salt->type = KRB5_PW_SALT;
502
503                                 ret = krb5_copy_data_contents(&key.salt->salt,
504                                                               salt.data,
505                                                               salt.length);
506                                 if (ret) {
507                                         free(key.salt);
508                                         key.salt = NULL;
509                                         goto out;
510                                 }
511                         }
512
513                         ret = smb_krb5_keyblock_init_contents(context,
514                                                               pkb3->keys[i].keytype,
515                                                               pkb3->keys[i].value->data,
516                                                               pkb3->keys[i].value->length,
517                                                               &key.key);
518                         if (ret) {
519                                 if (key.salt) {
520                                         free_Salt(key.salt);
521                                         free(key.salt);
522                                         key.salt = NULL;
523                                 }
524                                 goto out;
525                         }
526
527                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
528                         entry_ex->entry.keys.len++;
529                 }
530         }
531
532 out:
533         if (ret != 0) {
534                 entry_ex->entry.keys.len = 0;
535         }
536         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
537                 free(entry_ex->entry.keys.val);
538                 entry_ex->entry.keys.val = NULL;
539         }
540         return ret;
541 }
542
543 static int principal_comp_strcmp_int(krb5_context context,
544                                      krb5_const_principal principal,
545                                      unsigned int component,
546                                      const char *string,
547                                      bool do_strcasecmp)
548 {
549         const char *p;
550         size_t len;
551
552 #if defined(HAVE_KRB5_PRINCIPAL_GET_COMP_STRING)
553         p = krb5_principal_get_comp_string(context, principal, component);
554         if (p == NULL) {
555                 return -1;
556         }
557         len = strlen(p);
558 #else
559         krb5_data *d;
560         if (component >= krb5_princ_size(context, principal)) {
561                 return -1;
562         }
563
564         d = krb5_princ_component(context, principal, component);
565         if (d == NULL) {
566                 return -1;
567         }
568
569         p = d->data;
570         len = d->length;
571 #endif
572         if (do_strcasecmp) {
573                 return strncasecmp(p, string, len);
574         } else {
575                 return strncmp(p, string, len);
576         }
577 }
578
579 static int principal_comp_strcasecmp(krb5_context context,
580                                      krb5_const_principal principal,
581                                      unsigned int component,
582                                      const char *string)
583 {
584         return principal_comp_strcmp_int(context, principal,
585                                          component, string, true);
586 }
587
588 static int principal_comp_strcmp(krb5_context context,
589                                  krb5_const_principal principal,
590                                  unsigned int component,
591                                  const char *string)
592 {
593         return principal_comp_strcmp_int(context, principal,
594                                          component, string, false);
595 }
596
597 /*
598  * Construct an hdb_entry from a directory entry.
599  */
600 static krb5_error_code samba_kdc_message2entry(krb5_context context,
601                                                struct samba_kdc_db_context *kdc_db_ctx,
602                                                TALLOC_CTX *mem_ctx,
603                                                krb5_const_principal principal,
604                                                enum samba_kdc_ent_type ent_type,
605                                                unsigned flags,
606                                                struct ldb_dn *realm_dn,
607                                                struct ldb_message *msg,
608                                                hdb_entry_ex *entry_ex)
609 {
610         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
611         uint32_t userAccountControl;
612         uint32_t msDS_User_Account_Control_Computed;
613         unsigned int i;
614         krb5_error_code ret = 0;
615         krb5_boolean is_computer = FALSE;
616
617         struct samba_kdc_entry *p;
618         NTTIME acct_expiry;
619         NTSTATUS status;
620
621         uint32_t rid;
622         bool is_rodc = false;
623         struct ldb_message_element *objectclasses;
624         struct ldb_val computer_val;
625         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
626         computer_val.data = discard_const_p(uint8_t,"computer");
627         computer_val.length = strlen((const char *)computer_val.data);
628
629         if (ldb_msg_find_element(msg, "msDS-SecondaryKrbTgtNumber")) {
630                 is_rodc = true;
631         }
632
633         if (!samAccountName) {
634                 ret = ENOENT;
635                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
636                 goto out;
637         }
638
639         objectclasses = ldb_msg_find_element(msg, "objectClass");
640
641         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
642                 is_computer = TRUE;
643         }
644
645         ZERO_STRUCTP(entry_ex);
646
647         p = talloc_zero(mem_ctx, struct samba_kdc_entry);
648         if (!p) {
649                 ret = ENOMEM;
650                 goto out;
651         }
652
653         p->kdc_db_ctx = kdc_db_ctx;
654         p->entry_ex = entry_ex;
655         p->realm_dn = talloc_reference(p, realm_dn);
656         if (!p->realm_dn) {
657                 ret = ENOMEM;
658                 goto out;
659         }
660
661         talloc_set_destructor(p, samba_kdc_entry_destructor);
662
663         /* make sure we do not have bogus data in there */
664         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
665
666         entry_ex->ctx = p;
667         entry_ex->free_entry = samba_kdc_free_entry;
668
669         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
670
671         msDS_User_Account_Control_Computed
672                 = ldb_msg_find_attr_as_uint(msg,
673                                             "msDS-User-Account-Control-Computed",
674                                             UF_ACCOUNTDISABLE);
675
676         /*
677          * This brings in the lockout flag, block the account if not
678          * found.  We need the weird UF_ACCOUNTDISABLE check because
679          * we do not want to fail open if the value is not returned,
680          * but 0 is a valid value (all OK)
681          */
682         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
683                 ret = EINVAL;
684                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
685                                 "no msDS-User-Account-Control-Computed present");
686                 goto out;
687         } else {
688                 userAccountControl |= msDS_User_Account_Control_Computed;
689         }
690
691         /* 
692          * If we are set to canonicalize, we get back the fixed UPPER
693          * case realm, and the real username (ie matching LDAP
694          * samAccountName) 
695          *
696          * Otherwise, if we are set to enterprise, we
697          * get back the whole principal as-sent 
698          *
699          * Finally, if we are not set to canonicalize, we get back the
700          * fixed UPPER case realm, but the as-sent username
701          */
702
703         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
704                 if (flags & (HDB_F_CANON)) {
705                         /*
706                          * When requested to do so, ensure that the
707                          * both realm values in the principal are set
708                          * to the upper case, canonical realm
709                          */
710                         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
711                                                       lpcfg_realm(lp_ctx), "krbtgt",
712                                                       lpcfg_realm(lp_ctx), NULL);
713                         if (ret) {
714                                 krb5_clear_error_message(context);
715                                 goto out;
716                         }
717                         smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
718                 } else {
719                         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
720                         if (ret) {
721                                 krb5_clear_error_message(context);
722                                 goto out;
723                         }
724                         /*
725                          * this appears to be required regardless of
726                          * the canonicalize flag from the client
727                          */
728                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
729                         if (ret) {
730                                 krb5_clear_error_message(context);
731                                 goto out;
732                         }
733                 }
734
735         } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
736                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
737                 if (ret) {
738                         krb5_clear_error_message(context);
739                         goto out;
740                 }
741         } else if (flags & HDB_F_CANON && flags & HDB_F_FOR_AS_REQ) {
742                 /*
743                  * HDB_F_CANON maps from the canonicalize flag in the
744                  * packet, and has a different meaning between AS-REQ
745                  * and TGS-REQ.  We only change the principal in the AS-REQ case
746                  */
747                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
748                 if (ret) {
749                         krb5_clear_error_message(context);
750                         goto out;
751                 }
752         } else {
753                 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
754                 if (ret) {
755                         krb5_clear_error_message(context);
756                         goto out;
757                 }
758
759                 if (smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
760                         /* While we have copied the client principal, tests
761                          * show that Win2k3 returns the 'corrected' realm, not
762                          * the client-specified realm.  This code attempts to
763                          * replace the client principal's realm with the one
764                          * we determine from our records */
765                         
766                         /* this has to be with malloc() */
767                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
768                         if (ret) {
769                                 krb5_clear_error_message(context);
770                                 goto out;
771                         }
772                 }
773         }
774
775         /* First try and figure out the flags based on the userAccountControl */
776         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
777
778         /* Windows 2008 seems to enforce this (very sensible) rule by
779          * default - don't allow offline attacks on a user's password
780          * by asking for a ticket to them as a service (encrypted with
781          * their probably patheticly insecure password) */
782
783         if (entry_ex->entry.flags.server
784             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
785                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
786                         entry_ex->entry.flags.server = 0;
787                 }
788         }
789         /*
790          * To give the correct type of error to the client, we must
791          * not just return the entry without .server set, we must
792          * pretend the principal does not exist.  Otherwise we may
793          * return ERR_POLICY instead of
794          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
795          */
796         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
797                 ret = HDB_ERR_NOENTRY;
798                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
799                 goto out;
800         }
801         if (flags & HDB_F_ADMIN_DATA) {
802                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
803                  * of the Heimdal KDC.  They are stored in a the traditional
804                  * DB for audit purposes, and still form part of the structure
805                  * we must return */
806
807                 /* use 'whenCreated' */
808                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
809                 /* use 'kadmin' for now (needed by mit_samba) */
810
811                 ret = smb_krb5_make_principal(context,
812                                               &entry_ex->entry.created_by.principal,
813                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
814                 if (ret) {
815                         krb5_clear_error_message(context);
816                         goto out;
817                 }
818
819                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
820                 if (entry_ex->entry.modified_by == NULL) {
821                         ret = ENOMEM;
822                         krb5_set_error_message(context, ret, "malloc: out of memory");
823                         goto out;
824                 }
825
826                 /* use 'whenChanged' */
827                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
828                 /* use 'kadmin' for now (needed by mit_samba) */
829                 ret = smb_krb5_make_principal(context,
830                                               &entry_ex->entry.modified_by->principal,
831                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
832                 if (ret) {
833                         krb5_clear_error_message(context);
834                         goto out;
835                 }
836         }
837
838
839         /* The lack of password controls etc applies to krbtgt by
840          * virtue of being that particular RID */
841         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
842
843         if (!NT_STATUS_IS_OK(status)) {
844                 ret = EINVAL;
845                 goto out;
846         }
847
848         if (rid == DOMAIN_RID_KRBTGT) {
849                 char *realm = NULL;
850
851                 entry_ex->entry.valid_end = NULL;
852                 entry_ex->entry.pw_end = NULL;
853
854                 entry_ex->entry.flags.invalid = 0;
855                 entry_ex->entry.flags.server = 1;
856
857                 realm = smb_krb5_principal_get_realm(context, principal);
858                 if (realm == NULL) {
859                         ret = ENOMEM;
860                         goto out;
861                 }
862
863                 /* Don't mark all requests for the krbtgt/realm as
864                  * 'change password', as otherwise we could get into
865                  * trouble, and not enforce the password expirty.
866                  * Instead, only do it when request is for the kpasswd service */
867                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
868                     && krb5_princ_size(context, principal) == 2
869                     && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
870                     && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
871                     && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
872                         entry_ex->entry.flags.change_pw = 1;
873                 }
874
875                 SAFE_FREE(realm);
876
877                 entry_ex->entry.flags.client = 0;
878                 entry_ex->entry.flags.forwardable = 1;
879                 entry_ex->entry.flags.ok_as_delegate = 1;
880         } else if (is_rodc) {
881                 /* The RODC krbtgt account is like the main krbtgt,
882                  * but it does not have a changepw or kadmin
883                  * service */
884
885                 entry_ex->entry.valid_end = NULL;
886                 entry_ex->entry.pw_end = NULL;
887
888                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
889                 entry_ex->entry.flags.client = 0;
890                 entry_ex->entry.flags.invalid = 0;
891                 entry_ex->entry.flags.server = 1;
892
893                 entry_ex->entry.flags.client = 0;
894                 entry_ex->entry.flags.forwardable = 1;
895                 entry_ex->entry.flags.ok_as_delegate = 0;
896         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
897                 /* The account/password expiry only applies when the account is used as a
898                  * client (ie password login), not when used as a server */
899
900                 /* Make very well sure we don't use this for a client,
901                  * it could bypass the password restrictions */
902                 entry_ex->entry.flags.client = 0;
903
904                 entry_ex->entry.valid_end = NULL;
905                 entry_ex->entry.pw_end = NULL;
906
907         } else {
908                 NTTIME must_change_time
909                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
910                                                              realm_dn, msg);
911                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
912                         entry_ex->entry.pw_end = NULL;
913                 } else {
914                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
915                         if (entry_ex->entry.pw_end == NULL) {
916                                 ret = ENOMEM;
917                                 goto out;
918                         }
919                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
920                 }
921
922                 acct_expiry = samdb_result_account_expires(msg);
923                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
924                         entry_ex->entry.valid_end = NULL;
925                 } else {
926                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
927                         if (entry_ex->entry.valid_end == NULL) {
928                                 ret = ENOMEM;
929                                 goto out;
930                         }
931                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
932                 }
933         }
934
935         entry_ex->entry.valid_start = NULL;
936
937         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
938         if (entry_ex->entry.max_life == NULL) {
939                 ret = ENOMEM;
940                 goto out;
941         }
942
943         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
944                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
945         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
946                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
947         } else {
948                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
949                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
950         }
951
952         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
953         if (entry_ex->entry.max_renew == NULL) {
954                 ret = ENOMEM;
955                 goto out;
956         }
957
958         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
959
960         /* Get keys from the db */
961         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
962                                            rid, is_rodc, userAccountControl,
963                                            ent_type, entry_ex);
964         if (ret) {
965                 /* Could be bogus data in the entry, or out of memory */
966                 goto out;
967         }
968
969         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
970         if (entry_ex->entry.etypes == NULL) {
971                 krb5_clear_error_message(context);
972                 ret = ENOMEM;
973                 goto out;
974         }
975         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
976         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
977         if (entry_ex->entry.etypes->val == NULL) {
978                 krb5_clear_error_message(context);
979                 ret = ENOMEM;
980                 goto out;
981         }
982         for (i=0; i < entry_ex->entry.etypes->len; i++) {
983                 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
984         }
985
986
987         p->msg = talloc_steal(p, msg);
988
989 out:
990         if (ret != 0) {
991                 /* This doesn't free ent itself, that is for the eventual caller to do */
992                 hdb_free_entry(context, entry_ex);
993                 ZERO_STRUCTP(entry_ex);
994         } else {
995                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
996         }
997
998         return ret;
999 }
1000
1001 /*
1002  * Construct an hdb_entry from a directory entry.
1003  * The kvno is what the remote client asked for
1004  */
1005 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1006                                                struct samba_kdc_db_context *kdc_db_ctx,
1007                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
1008                                                enum trust_direction direction,
1009                                                struct ldb_dn *realm_dn,
1010                                                unsigned flags,
1011                                                uint32_t kvno,
1012                                                struct ldb_message *msg,
1013                                                hdb_entry_ex *entry_ex)
1014 {
1015         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1016         const char *our_realm = lpcfg_realm(lp_ctx);
1017         const char *dnsdomain = NULL;
1018         char *partner_realm = NULL;
1019         const char *realm = NULL;
1020         const char *krbtgt_realm = NULL;
1021         DATA_BLOB password_utf16 = data_blob_null;
1022         DATA_BLOB password_utf8 = data_blob_null;
1023         struct samr_Password _password_hash;
1024         const struct samr_Password *password_hash = NULL;
1025         const struct ldb_val *password_val;
1026         struct trustAuthInOutBlob password_blob;
1027         struct samba_kdc_entry *p;
1028         bool use_previous = false;
1029         uint32_t current_kvno;
1030         uint32_t previous_kvno;
1031         uint32_t num_keys = 0;
1032         enum ndr_err_code ndr_err;
1033         int ret, trust_direction_flags;
1034         unsigned int i;
1035         struct AuthenticationInformationArray *auth_array;
1036         struct timeval tv;
1037         NTTIME an_hour_ago;
1038         uint32_t *auth_kvno;
1039         bool preferr_current = false;
1040         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1041
1042         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1043                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1044                                         "msDS-SupportedEncryptionTypes",
1045                                         supported_enctypes);
1046         }
1047
1048         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
1049         if (!(trust_direction_flags & direction)) {
1050                 krb5_clear_error_message(context);
1051                 ret = HDB_ERR_NOENTRY;
1052                 goto out;
1053         }
1054
1055         dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
1056         if (dnsdomain == NULL) {
1057                 krb5_clear_error_message(context);
1058                 ret = HDB_ERR_NOENTRY;
1059                 goto out;
1060         }
1061         partner_realm = strupper_talloc(mem_ctx, dnsdomain);
1062         if (partner_realm == NULL) {
1063                 krb5_clear_error_message(context);
1064                 ret = ENOMEM;
1065                 goto out;
1066         }
1067
1068         if (direction == INBOUND) {
1069                 realm = our_realm;
1070                 krbtgt_realm = partner_realm;
1071
1072                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1073         } else { /* OUTBOUND */
1074                 realm = partner_realm;
1075                 krbtgt_realm = our_realm;
1076
1077                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1078         }
1079
1080         if (password_val == NULL) {
1081                 krb5_clear_error_message(context);
1082                 ret = HDB_ERR_NOENTRY;
1083                 goto out;
1084         }
1085
1086         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1087                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1088         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1089                 krb5_clear_error_message(context);
1090                 ret = EINVAL;
1091                 goto out;
1092         }
1093
1094         p = talloc(mem_ctx, struct samba_kdc_entry);
1095         if (!p) {
1096                 ret = ENOMEM;
1097                 goto out;
1098         }
1099
1100         p->kdc_db_ctx = kdc_db_ctx;
1101         p->entry_ex = entry_ex;
1102         p->realm_dn = realm_dn;
1103
1104         talloc_set_destructor(p, samba_kdc_entry_destructor);
1105
1106         /* make sure we do not have bogus data in there */
1107         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
1108
1109         entry_ex->ctx = p;
1110         entry_ex->free_entry = samba_kdc_free_entry;
1111
1112         /* use 'whenCreated' */
1113         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1114         /* use 'kadmin' for now (needed by mit_samba) */
1115         ret = smb_krb5_make_principal(context,
1116                                       &entry_ex->entry.created_by.principal,
1117                                       realm, "kadmin", NULL);
1118         if (ret) {
1119                 krb5_clear_error_message(context);
1120                 goto out;
1121         }
1122
1123         /*
1124          * We always need to generate the canonicalized principal
1125          * with the values of our database.
1126          */
1127         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, realm,
1128                                       "krbtgt", krbtgt_realm, NULL);
1129         if (ret) {
1130                 krb5_clear_error_message(context);
1131                 goto out;
1132         }
1133         smb_krb5_principal_set_type(context, entry_ex->entry.principal,
1134                                     KRB5_NT_SRV_INST);
1135
1136         entry_ex->entry.valid_start = NULL;
1137
1138         /* we need to work out if we are going to use the current or
1139          * the previous password hash.
1140          * We base this on the kvno the client passes in. If the kvno
1141          * passed in is equal to the current kvno in our database then
1142          * we use the current structure. If it is the current kvno-1,
1143          * then we use the previous substrucure.
1144          */
1145
1146         /*
1147          * Windows preferrs the previous key for one hour.
1148          */
1149         tv = timeval_current();
1150         if (tv.tv_sec > 3600) {
1151                 tv.tv_sec -= 3600;
1152         }
1153         an_hour_ago = timeval_to_nttime(&tv);
1154
1155         /* first work out the current kvno */
1156         current_kvno = 0;
1157         for (i=0; i < password_blob.count; i++) {
1158                 struct AuthenticationInformation *a =
1159                         &password_blob.current.array[i];
1160
1161                 if (a->LastUpdateTime <= an_hour_ago) {
1162                         preferr_current = true;
1163                 }
1164
1165                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1166                         current_kvno = a->AuthInfo.version.version;
1167                 }
1168         }
1169         if (current_kvno == 0) {
1170                 previous_kvno = 255;
1171         } else {
1172                 previous_kvno = current_kvno - 1;
1173         }
1174         for (i=0; i < password_blob.count; i++) {
1175                 struct AuthenticationInformation *a =
1176                         &password_blob.previous.array[i];
1177
1178                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1179                         previous_kvno = a->AuthInfo.version.version;
1180                 }
1181         }
1182
1183         /* work out whether we will use the previous or current
1184            password */
1185         if (password_blob.previous.count == 0) {
1186                 /* there is no previous password */
1187                 use_previous = false;
1188         } else if (!(flags & HDB_F_KVNO_SPECIFIED)) {
1189                 /*
1190                  * If not specified we use the lowest kvno
1191                  * for the first hour after an update.
1192                  */
1193                 if (preferr_current) {
1194                         use_previous = false;
1195                 } else if (previous_kvno < current_kvno) {
1196                         use_previous = true;
1197                 } else {
1198                         use_previous = false;
1199                 }
1200         } else if (kvno == current_kvno) {
1201                 /*
1202                  * Exact match ...
1203                  */
1204                 use_previous = false;
1205         } else if (kvno == previous_kvno) {
1206                 /*
1207                  * Exact match ...
1208                  */
1209                 use_previous = true;
1210         } else {
1211                 /*
1212                  * Fallback to the current one for anything else
1213                  */
1214                 use_previous = false;
1215         }
1216
1217         if (use_previous) {
1218                 auth_array = &password_blob.previous;
1219                 auth_kvno = &previous_kvno;
1220         } else {
1221                 auth_array = &password_blob.current;
1222                 auth_kvno = &current_kvno;
1223         }
1224
1225         /* use the kvno the client specified, if available */
1226         if (flags & HDB_F_KVNO_SPECIFIED) {
1227                 entry_ex->entry.kvno = kvno;
1228         } else {
1229                 entry_ex->entry.kvno = *auth_kvno;
1230         }
1231
1232         for (i=0; i < auth_array->count; i++) {
1233                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1234                         bool ok;
1235
1236                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1237                                                          auth_array->array[i].AuthInfo.clear.size);
1238                         if (password_utf16.length == 0) {
1239                                 break;
1240                         }
1241
1242                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1243                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1244                                 if (password_hash == NULL) {
1245                                         num_keys += 1;
1246                                 }
1247                                 password_hash = &_password_hash;
1248                         }
1249
1250                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1251                                 break;
1252                         }
1253
1254                         ok = convert_string_talloc(mem_ctx,
1255                                                    CH_UTF16MUNGED, CH_UTF8,
1256                                                    password_utf16.data,
1257                                                    password_utf16.length,
1258                                                    (void *)&password_utf8.data,
1259                                                    &password_utf8.length);
1260                         if (!ok) {
1261                                 krb5_clear_error_message(context);
1262                                 ret = ENOMEM;
1263                                 goto out;
1264                         }
1265
1266                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1267                                 num_keys += 1;
1268                         }
1269                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1270                                 num_keys += 1;
1271                         }
1272                         break;
1273                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1274                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1275                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1276                                 num_keys += 1;
1277                         }
1278                 }
1279         }
1280
1281         /* Must have found a cleartext or MD4 password */
1282         if (num_keys == 0) {
1283                 DEBUG(1,(__location__ ": no usable key found\n"));
1284                 krb5_clear_error_message(context);
1285                 ret = HDB_ERR_NOENTRY;
1286                 goto out;
1287         }
1288
1289         entry_ex->entry.keys.val = calloc(num_keys, sizeof(Key));
1290         if (entry_ex->entry.keys.val == NULL) {
1291                 krb5_clear_error_message(context);
1292                 ret = ENOMEM;
1293                 goto out;
1294         }
1295
1296         if (password_utf8.length != 0) {
1297                 Key key = {};
1298                 krb5_const_principal salt_principal = entry_ex->entry.principal;
1299                 krb5_data salt;
1300                 krb5_data cleartext_data;
1301
1302                 cleartext_data.data = discard_const_p(char, password_utf8.data);
1303                 cleartext_data.length = password_utf8.length;
1304
1305                 ret = smb_krb5_get_pw_salt(context,
1306                                            salt_principal,
1307                                            &salt);
1308                 if (ret != 0) {
1309                         goto out;
1310                 }
1311
1312                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1313                         ret = smb_krb5_create_key_from_string(context,
1314                                                               salt_principal,
1315                                                               &salt,
1316                                                               &cleartext_data,
1317                                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1318                                                               &key.key);
1319                         if (ret != 0) {
1320                                 kerberos_free_data_contents(context, &salt);
1321                                 goto out;
1322                         }
1323
1324                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1325                         entry_ex->entry.keys.len++;
1326                 }
1327
1328                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1329                         ret = smb_krb5_create_key_from_string(context,
1330                                                               salt_principal,
1331                                                               &salt,
1332                                                               &cleartext_data,
1333                                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1334                                                               &key.key);
1335                         if (ret != 0) {
1336                                 kerberos_free_data_contents(context, &salt);
1337                                 goto out;
1338                         }
1339
1340                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1341                         entry_ex->entry.keys.len++;
1342                 }
1343
1344                 kerberos_free_data_contents(context, &salt);
1345         }
1346
1347         if (password_hash != NULL) {
1348                 Key key = {};
1349
1350                 ret = smb_krb5_keyblock_init_contents(context,
1351                                                       ENCTYPE_ARCFOUR_HMAC,
1352                                                       password_hash->hash,
1353                                                       sizeof(password_hash->hash),
1354                                                       &key.key);
1355                 if (ret != 0) {
1356                         goto out;
1357                 }
1358
1359                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1360                 entry_ex->entry.keys.len++;
1361         }
1362
1363         entry_ex->entry.flags = int2HDBFlags(0);
1364         entry_ex->entry.flags.immutable = 1;
1365         entry_ex->entry.flags.invalid = 0;
1366         entry_ex->entry.flags.server = 1;
1367         entry_ex->entry.flags.require_preauth = 1;
1368
1369         entry_ex->entry.pw_end = NULL;
1370
1371         entry_ex->entry.max_life = NULL;
1372
1373         entry_ex->entry.max_renew = NULL;
1374
1375         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
1376         if (entry_ex->entry.etypes == NULL) {
1377                 krb5_clear_error_message(context);
1378                 ret = ENOMEM;
1379                 goto out;
1380         }
1381         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
1382         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
1383         if (entry_ex->entry.etypes->val == NULL) {
1384                 krb5_clear_error_message(context);
1385                 ret = ENOMEM;
1386                 goto out;
1387         }
1388         for (i=0; i < entry_ex->entry.etypes->len; i++) {
1389                 entry_ex->entry.etypes->val[i] = KRB5_KEY_TYPE(&entry_ex->entry.keys.val[i].key);
1390         }
1391
1392         p->msg = talloc_steal(p, msg);
1393
1394 out:
1395         TALLOC_FREE(partner_realm);
1396
1397         if (ret != 0) {
1398                 /* This doesn't free ent itself, that is for the eventual caller to do */
1399                 hdb_free_entry(context, entry_ex);
1400         } else {
1401                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1402         }
1403
1404         return ret;
1405
1406 }
1407
1408 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1409                                         TALLOC_CTX *mem_ctx,
1410                                         const char *realm,
1411                                         struct ldb_dn *realm_dn,
1412                                         struct ldb_message **pmsg)
1413 {
1414         NTSTATUS status;
1415         const char * const *attrs = trust_attrs;
1416
1417         status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
1418                                        attrs, mem_ctx, pmsg);
1419         if (NT_STATUS_IS_OK(status)) {
1420                 return 0;
1421         } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1422                 return HDB_ERR_NOENTRY;
1423         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1424                 int ret = ENOMEM;
1425                 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1426                 return ret;
1427         } else {
1428                 int ret = EINVAL;
1429                 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1430                 return ret;
1431         }
1432 }
1433
1434 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1435                                                 struct samba_kdc_db_context *kdc_db_ctx,
1436                                                 TALLOC_CTX *mem_ctx,
1437                                                 krb5_const_principal principal,
1438                                                 const char **attrs,
1439                                                 struct ldb_dn **realm_dn,
1440                                                 struct ldb_message **msg)
1441 {
1442         NTSTATUS nt_status;
1443         char *principal_string = NULL;
1444
1445         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1446                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1447                                                                       principal, 0);
1448                 if (principal_string == NULL) {
1449                         return ENOMEM;
1450                 }
1451         } else {
1452                 char *principal_string_m = NULL;
1453                 krb5_error_code ret;
1454
1455                 ret = krb5_unparse_name(context, principal, &principal_string_m);
1456                 if (ret != 0) {
1457                         return ret;
1458                 }
1459
1460                 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1461                 SAFE_FREE(principal_string_m);
1462                 if (principal_string == NULL) {
1463                         return ENOMEM;
1464                 }
1465         }
1466
1467         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1468                                               mem_ctx, principal_string, attrs,
1469                                               realm_dn, msg);
1470         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1471                 krb5_principal fallback_principal = NULL;
1472                 unsigned int num_comp;
1473                 char *fallback_realm = NULL;
1474                 char *fallback_account = NULL;
1475                 krb5_error_code ret;
1476
1477                 ret = krb5_parse_name(context, principal_string,
1478                                       &fallback_principal);
1479                 TALLOC_FREE(principal_string);
1480                 if (ret != 0) {
1481                         return ret;
1482                 }
1483
1484                 num_comp = krb5_princ_size(context, fallback_principal);
1485                 fallback_realm = smb_krb5_principal_get_realm(context,
1486                                                               fallback_principal);
1487                 if (fallback_realm == NULL) {
1488                         krb5_free_principal(context, fallback_principal);
1489                         return ENOMEM;
1490                 }
1491
1492                 if (num_comp == 1) {
1493                         size_t len;
1494
1495                         fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1496                                                 context, fallback_principal, 0);
1497                         if (fallback_account == NULL) {
1498                                 krb5_free_principal(context, fallback_principal);
1499                                 SAFE_FREE(fallback_realm);
1500                                 return ENOMEM;
1501                         }
1502
1503                         len = strlen(fallback_account);
1504                         if (len >= 2 && fallback_account[len - 1] == '$') {
1505                                 TALLOC_FREE(fallback_account);
1506                         }
1507                 }
1508                 krb5_free_principal(context, fallback_principal);
1509                 fallback_principal = NULL;
1510
1511                 if (fallback_account != NULL) {
1512                         char *with_dollar;
1513
1514                         with_dollar = talloc_asprintf(mem_ctx, "%s$",
1515                                                      fallback_account);
1516                         if (with_dollar == NULL) {
1517                                 SAFE_FREE(fallback_realm);
1518                                 return ENOMEM;
1519                         }
1520                         TALLOC_FREE(fallback_account);
1521
1522                         ret = smb_krb5_make_principal(context,
1523                                                       &fallback_principal,
1524                                                       fallback_realm,
1525                                                       with_dollar, NULL);
1526                         TALLOC_FREE(with_dollar);
1527                         if (ret != 0) {
1528                                 SAFE_FREE(fallback_realm);
1529                                 return ret;
1530                         }
1531                 }
1532                 SAFE_FREE(fallback_realm);
1533
1534                 if (fallback_principal != NULL) {
1535                         char *fallback_string = NULL;
1536
1537                         ret = krb5_unparse_name(context,
1538                                                 fallback_principal,
1539                                                 &fallback_string);
1540                         if (ret != 0) {
1541                                 krb5_free_principal(context, fallback_principal);
1542                                 return ret;
1543                         }
1544
1545                         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1546                                                               mem_ctx,
1547                                                               fallback_string,
1548                                                               attrs,
1549                                                               realm_dn, msg);
1550                         SAFE_FREE(fallback_string);
1551                 }
1552                 krb5_free_principal(context, fallback_principal);
1553                 fallback_principal = NULL;
1554         }
1555         TALLOC_FREE(principal_string);
1556
1557         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1558                 return HDB_ERR_NOENTRY;
1559         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1560                 return ENOMEM;
1561         } else if (!NT_STATUS_IS_OK(nt_status)) {
1562                 return EINVAL;
1563         }
1564
1565         return 0;
1566 }
1567
1568 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1569                                                struct samba_kdc_db_context *kdc_db_ctx,
1570                                                TALLOC_CTX *mem_ctx,
1571                                                krb5_const_principal principal,
1572                                                unsigned flags,
1573                                                hdb_entry_ex *entry_ex) {
1574         struct ldb_dn *realm_dn;
1575         krb5_error_code ret;
1576         struct ldb_message *msg = NULL;
1577
1578         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1579                                       mem_ctx, principal, user_attrs,
1580                                       &realm_dn, &msg);
1581         if (ret != 0) {
1582                 return ret;
1583         }
1584
1585         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1586                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1587                                       flags,
1588                                       realm_dn, msg, entry_ex);
1589         return ret;
1590 }
1591
1592 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1593                                               struct samba_kdc_db_context *kdc_db_ctx,
1594                                               TALLOC_CTX *mem_ctx,
1595                                               krb5_const_principal principal,
1596                                               unsigned flags,
1597                                               uint32_t kvno,
1598                                               hdb_entry_ex *entry_ex)
1599 {
1600         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1601         krb5_error_code ret;
1602         struct ldb_message *msg = NULL;
1603         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1604         char *realm_from_princ, *realm_from_princ_malloc;
1605         char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1606
1607         realm_from_princ_malloc = smb_krb5_principal_get_realm(context, principal);
1608         if (realm_from_princ_malloc == NULL) {
1609                 /* can't happen */
1610                 return HDB_ERR_NOENTRY;
1611         }
1612         realm_from_princ = talloc_strdup(mem_ctx, realm_from_princ_malloc);
1613         free(realm_from_princ_malloc);
1614         if (realm_from_princ == NULL) {
1615                 return HDB_ERR_NOENTRY;
1616         }
1617
1618         if (krb5_princ_size(context, principal) != 2
1619             || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1620                 /* Not a krbtgt */
1621                 return HDB_ERR_NOENTRY;
1622         }
1623
1624         /* krbtgt case.  Either us or a trusted realm */
1625
1626         if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1627             && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1628                 /* us, or someone quite like us */
1629                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1630                  * is in our db, then direct the caller at our primary
1631                  * krbtgt */
1632
1633                 int lret;
1634                 unsigned int krbtgt_number;
1635                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1636                    trust tickets. We don't yet know what this means, but we do
1637                    seem to need to treat it as unspecified */
1638                 if (flags & HDB_F_KVNO_SPECIFIED) {
1639                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1640                         if (kdc_db_ctx->rodc) {
1641                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1642                                         return HDB_ERR_NOT_FOUND_HERE;
1643                                 }
1644                         }
1645                 } else {
1646                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1647                 }
1648
1649                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1650                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1651                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1652                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1653                                                "(objectClass=user)");
1654                 } else {
1655                         /* We need to look up an RODC krbtgt (perhaps
1656                          * ours, if we are an RODC, perhaps another
1657                          * RODC if we are a read-write DC */
1658                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1659                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1660                                                krbtgt_attrs,
1661                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1662                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1663                 }
1664
1665                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1666                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1667                                    (unsigned)(krbtgt_number));
1668                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1669                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1670                                                (unsigned)(krbtgt_number));
1671                         return HDB_ERR_NOENTRY;
1672                 } else if (lret != LDB_SUCCESS) {
1673                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1674                                    (unsigned)(krbtgt_number));
1675                         krb5_set_error_message(context, HDB_ERR_NOENTRY,
1676                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1677                                                (unsigned)(krbtgt_number));
1678                         return HDB_ERR_NOENTRY;
1679                 }
1680
1681                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1682                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1683                                               flags, realm_dn, msg, entry_ex);
1684                 if (ret != 0) {
1685                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1686                 }
1687                 return ret;
1688
1689         } else {
1690                 enum trust_direction direction = UNKNOWN;
1691                 const char *realm = NULL;
1692
1693                 /* Either an inbound or outbound trust */
1694
1695                 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1696                         /* look for inbound trust */
1697                         direction = INBOUND;
1698                         realm = realm_princ_comp;
1699                 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
1700                         /* look for outbound trust */
1701                         direction = OUTBOUND;
1702                         realm = realm_from_princ;
1703                 } else {
1704                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1705                                    realm_from_princ,
1706                                    realm_princ_comp);
1707                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1708                                                realm_from_princ,
1709                                                realm_princ_comp);
1710                         return HDB_ERR_NOENTRY;
1711                 }
1712
1713                 /* Trusted domains are under CN=system */
1714
1715                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1716                                        mem_ctx,
1717                                        realm, realm_dn, &msg);
1718
1719                 if (ret != 0) {
1720                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1721                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1722                         return ret;
1723                 }
1724
1725                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1726                                                     principal, direction,
1727                                                     realm_dn, flags, kvno, msg, entry_ex);
1728                 if (ret != 0) {
1729                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1730                                    ldb_dn_get_linearized(msg->dn));
1731                         krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1732                                                "trust_message2entry failed for %s",
1733                                                ldb_dn_get_linearized(msg->dn));
1734                 }
1735                 return ret;
1736         }
1737
1738 }
1739
1740 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1741                                                struct samba_kdc_db_context *kdc_db_ctx,
1742                                                TALLOC_CTX *mem_ctx,
1743                                                krb5_const_principal principal,
1744                                                unsigned flags,
1745                                                const char **attrs,
1746                                                struct ldb_dn **realm_dn,
1747                                                struct ldb_message **msg)
1748 {
1749         krb5_error_code ret;
1750         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1751             && krb5_princ_size(context, principal) >= 2) {
1752                 /* 'normal server' case */
1753                 int ldb_ret;
1754                 NTSTATUS nt_status;
1755                 struct ldb_dn *user_dn;
1756                 char *principal_string;
1757
1758                 ret = krb5_unparse_name_flags(context, principal,
1759                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1760                                               &principal_string);
1761                 if (ret != 0) {
1762                         return ret;
1763                 }
1764
1765                 /* At this point we may find the host is known to be
1766                  * in a different realm, so we should generate a
1767                  * referral instead */
1768                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1769                                                          mem_ctx, principal_string,
1770                                                          &user_dn, realm_dn);
1771                 free(principal_string);
1772
1773                 if (!NT_STATUS_IS_OK(nt_status)) {
1774                         return HDB_ERR_NOENTRY;
1775                 }
1776
1777                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1778                                           mem_ctx,
1779                                           msg, user_dn, LDB_SCOPE_BASE,
1780                                           attrs,
1781                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1782                                           "(objectClass=*)");
1783                 if (ldb_ret != LDB_SUCCESS) {
1784                         return HDB_ERR_NOENTRY;
1785                 }
1786                 return 0;
1787         } else if (!(flags & HDB_F_FOR_AS_REQ)
1788                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1789                 /*
1790                  * The behaviour of accepting an
1791                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1792                  * containing a UPN only applies to TGS-REQ packets,
1793                  * not AS-REQ packets.
1794                  */
1795                 return samba_kdc_lookup_client(context, kdc_db_ctx,
1796                                                mem_ctx, principal, attrs,
1797                                                realm_dn, msg);
1798         } else {
1799                 /*
1800                  * This case is for:
1801                  *  - the AS-REQ, where we only accept
1802                  *    samAccountName based lookups for the server, no
1803                  *    matter if the name is an
1804                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
1805                  *  - for the TGS-REQ when we are not given an
1806                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1807                  *    only lookup samAccountName based names.
1808                  */
1809                 int lret;
1810                 char *short_princ;
1811                 krb5_principal enterprise_principal = NULL;
1812                 krb5_const_principal used_principal = NULL;
1813                 char *name1 = NULL;
1814                 size_t len1 = 0;
1815                 char *filter = NULL;
1816
1817                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1818                         char *str = NULL;
1819                         /* Need to reparse the enterprise principal to find the real target */
1820                         if (krb5_princ_size(context, principal) != 1) {
1821                                 ret = KRB5_PARSE_MALFORMED;
1822                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
1823                                                        "enterprise principal with wrong (%d) number of components",
1824                                                        krb5_princ_size(context, principal));
1825                                 return ret;
1826                         }
1827                         str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
1828                         if (str == NULL) {
1829                                 return KRB5_PARSE_MALFORMED;
1830                         }
1831                         ret = krb5_parse_name(context, str,
1832                                               &enterprise_principal);
1833                         talloc_free(str);
1834                         if (ret) {
1835                                 return ret;
1836                         }
1837                         used_principal = enterprise_principal;
1838                 } else {
1839                         used_principal = principal;
1840                 }
1841
1842                 /* server as client principal case, but we must not lookup userPrincipalNames */
1843                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1844
1845                 /* TODO: Check if it is our realm, otherwise give referral */
1846
1847                 ret = krb5_unparse_name_flags(context, used_principal,
1848                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
1849                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
1850                                               &short_princ);
1851                 used_principal = NULL;
1852                 krb5_free_principal(context, enterprise_principal);
1853                 enterprise_principal = NULL;
1854
1855                 if (ret != 0) {
1856                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1857                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1858                         return ret;
1859                 }
1860
1861                 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
1862                 SAFE_FREE(short_princ);
1863                 if (name1 == NULL) {
1864                         return ENOMEM;
1865                 }
1866                 len1 = strlen(name1);
1867                 if (len1 >= 1 && name1[len1 - 1] != '$') {
1868                         filter = talloc_asprintf(mem_ctx,
1869                                         "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
1870                                         name1, name1);
1871                         if (filter == NULL) {
1872                                 return ENOMEM;
1873                         }
1874                 } else {
1875                         filter = talloc_asprintf(mem_ctx,
1876                                         "(&(objectClass=user)(samAccountName=%s))",
1877                                         name1);
1878                         if (filter == NULL) {
1879                                 return ENOMEM;
1880                         }
1881                 }
1882
1883                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1884                                        *realm_dn, LDB_SCOPE_SUBTREE,
1885                                        attrs,
1886                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1887                                        "%s", filter);
1888                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1889                         DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
1890                                   name1, filter));
1891                         return HDB_ERR_NOENTRY;
1892                 }
1893                 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
1894                         DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
1895                                   name1, filter));
1896                         return HDB_ERR_NOENTRY;
1897                 }
1898                 if (lret != LDB_SUCCESS) {
1899                         DEBUG(0, ("Failed single search for %s - %s\n",
1900                                   name1, ldb_errstring(kdc_db_ctx->samdb)));
1901                         return HDB_ERR_NOENTRY;
1902                 }
1903                 return 0;
1904         }
1905         return HDB_ERR_NOENTRY;
1906 }
1907
1908
1909
1910 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1911                                               struct samba_kdc_db_context *kdc_db_ctx,
1912                                               TALLOC_CTX *mem_ctx,
1913                                               krb5_const_principal principal,
1914                                               unsigned flags,
1915                                               hdb_entry_ex *entry_ex)
1916 {
1917         krb5_error_code ret;
1918         struct ldb_dn *realm_dn;
1919         struct ldb_message *msg;
1920
1921         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1922                                       flags, server_attrs, &realm_dn, &msg);
1923         if (ret != 0) {
1924                 return ret;
1925         }
1926
1927         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1928                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
1929                                       flags,
1930                                       realm_dn, msg, entry_ex);
1931         if (ret != 0) {
1932                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1933         }
1934
1935         return ret;
1936 }
1937
1938 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
1939                                               struct samba_kdc_db_context *kdc_db_ctx,
1940                                               TALLOC_CTX *mem_ctx,
1941                                               krb5_const_principal principal,
1942                                               unsigned flags,
1943                                               hdb_entry_ex *entry_ex)
1944 {
1945         TALLOC_CTX *frame = talloc_stackframe();
1946         NTSTATUS status;
1947         krb5_error_code ret;
1948         char *_realm = NULL;
1949         bool check_realm = false;
1950         const char *realm = NULL;
1951         struct dsdb_trust_routing_table *trt = NULL;
1952         const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1953         unsigned int num_comp;
1954         bool ok;
1955         char *upper = NULL;
1956
1957         num_comp = krb5_princ_size(context, principal);
1958
1959         if (flags & HDB_F_GET_CLIENT) {
1960                 if (flags & HDB_F_FOR_AS_REQ) {
1961                         check_realm = true;
1962                 }
1963         }
1964         if (flags & HDB_F_GET_SERVER) {
1965                 if (flags & HDB_F_FOR_TGS_REQ) {
1966                         check_realm = true;
1967                 }
1968         }
1969
1970         if (!check_realm) {
1971                 TALLOC_FREE(frame);
1972                 return 0;
1973         }
1974
1975         _realm = smb_krb5_principal_get_realm(context, principal);
1976         if (_realm == NULL) {
1977                 TALLOC_FREE(frame);
1978                 return ENOMEM;
1979         }
1980
1981         /*
1982          * The requested realm needs to be our own
1983          */
1984         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, _realm);
1985         if (!ok) {
1986                 /*
1987                  * The request is not for us...
1988                  */
1989                 SAFE_FREE(_realm);
1990                 TALLOC_FREE(frame);
1991                 return HDB_ERR_NOENTRY;
1992         }
1993
1994         realm = talloc_strdup(frame, _realm);
1995         SAFE_FREE(_realm);
1996         if (realm == NULL) {
1997                 TALLOC_FREE(frame);
1998                 return ENOMEM;
1999         }
2000
2001         if (krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2002                 char *principal_string = NULL;
2003                 krb5_principal enterprise_principal = NULL;
2004                 char *enterprise_realm = NULL;
2005
2006                 if (num_comp != 1) {
2007                         TALLOC_FREE(frame);
2008                         return HDB_ERR_NOENTRY;
2009                 }
2010
2011                 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2012                                                                       principal, 0);
2013                 if (principal_string == NULL) {
2014                         TALLOC_FREE(frame);
2015                         return ENOMEM;
2016                 }
2017
2018                 ret = krb5_parse_name(context, principal_string,
2019                                       &enterprise_principal);
2020                 TALLOC_FREE(principal_string);
2021                 if (ret) {
2022                         TALLOC_FREE(frame);
2023                         return ret;
2024                 }
2025
2026                 enterprise_realm = smb_krb5_principal_get_realm(context,
2027                                                         enterprise_principal);
2028                 krb5_free_principal(context, enterprise_principal);
2029                 if (enterprise_realm != NULL) {
2030                         realm = talloc_strdup(frame, enterprise_realm);
2031                         SAFE_FREE(enterprise_realm);
2032                         if (realm == NULL) {
2033                                 TALLOC_FREE(frame);
2034                                 return ENOMEM;
2035                         }
2036                 }
2037         }
2038
2039         if (flags & HDB_F_GET_SERVER) {
2040                 char *service_realm = NULL;
2041
2042                 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2043                 if (ret == 0) {
2044                         /*
2045                          * we need to search krbtgt/ locally
2046                          */
2047                         TALLOC_FREE(frame);
2048                         return 0;
2049                 }
2050
2051                 /*
2052                  * We need to check the last component against the routing table.
2053                  *
2054                  * Note this works only with 2 or 3 component principals, e.g:
2055                  *
2056                  * servicePrincipalName: ldap/W2K8R2-219.bla.base
2057                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2058                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2059                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2060                  */
2061
2062                 if (num_comp == 2 || num_comp == 3) {
2063                         service_realm = smb_krb5_principal_get_comp_string(frame,
2064                                                                            context,
2065                                                                            principal,
2066                                                                            num_comp - 1);
2067                 }
2068
2069                 if (service_realm != NULL) {
2070                         realm = service_realm;
2071                 }
2072         }
2073
2074         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2075         if (ok) {
2076                 /*
2077                  * skip the expensive routing lookup
2078                  */
2079                 TALLOC_FREE(frame);
2080                 return 0;
2081         }
2082
2083         status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2084                                                frame, &trt);
2085         if (!NT_STATUS_IS_OK(status)) {
2086                 TALLOC_FREE(frame);
2087                 return EINVAL;
2088         }
2089
2090         tdo = dsdb_trust_routing_by_name(trt, realm);
2091         if (tdo == NULL) {
2092                 /*
2093                  * This principal has to be local
2094                  */
2095                 TALLOC_FREE(frame);
2096                 return 0;
2097         }
2098
2099         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2100                 /*
2101                  * TODO: handle the routing within the forest
2102                  *
2103                  * This should likely be handled in
2104                  * samba_kdc_message2entry() in case we're
2105                  * a global catalog. We'd need to check
2106                  * if realm_dn is our own domain and derive
2107                  * the dns domain name from realm_dn and check that
2108                  * against the routing table or fallback to
2109                  * the tdo we found here.
2110                  *
2111                  * But for now we don't support multiple domains
2112                  * in our forest correctly anyway.
2113                  *
2114                  * Just search in our local database.
2115                  */
2116                 TALLOC_FREE(frame);
2117                 return 0;
2118         }
2119
2120         ZERO_STRUCT(entry_ex->entry);
2121
2122         ret = krb5_copy_principal(context, principal,
2123                                   &entry_ex->entry.principal);
2124         if (ret) {
2125                 TALLOC_FREE(frame);
2126                 return ret;
2127         }
2128
2129         upper = strupper_talloc(frame, tdo->domain_name.string);
2130         if (upper == NULL) {
2131                 TALLOC_FREE(frame);
2132                 return ENOMEM;
2133         }
2134
2135         ret = krb5_principal_set_realm(context,
2136                                        entry_ex->entry.principal,
2137                                        upper);
2138         if (ret) {
2139                 TALLOC_FREE(frame);
2140                 return ret;
2141         }
2142
2143         TALLOC_FREE(frame);
2144         return HDB_ERR_WRONG_REALM;
2145 }
2146
2147 krb5_error_code samba_kdc_fetch(krb5_context context,
2148                                 struct samba_kdc_db_context *kdc_db_ctx,
2149                                 krb5_const_principal principal,
2150                                 unsigned flags,
2151                                 krb5_kvno kvno,
2152                                 hdb_entry_ex *entry_ex)
2153 {
2154         krb5_error_code ret = HDB_ERR_NOENTRY;
2155         TALLOC_CTX *mem_ctx;
2156
2157         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2158         if (!mem_ctx) {
2159                 ret = ENOMEM;
2160                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2161                 return ret;
2162         }
2163
2164         ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2165                                      principal, flags, entry_ex);
2166         if (ret != 0) {
2167                 goto done;
2168         }
2169
2170         ret = HDB_ERR_NOENTRY;
2171
2172         if (flags & HDB_F_GET_CLIENT) {
2173                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2174                 if (ret != HDB_ERR_NOENTRY) goto done;
2175         }
2176         if (flags & HDB_F_GET_SERVER) {
2177                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2178                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2179                 if (ret != HDB_ERR_NOENTRY) goto done;
2180
2181                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2182                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2183                 if (ret != HDB_ERR_NOENTRY) goto done;
2184         }
2185         if (flags & HDB_F_GET_KRBTGT) {
2186                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2187                 if (ret != HDB_ERR_NOENTRY) goto done;
2188         }
2189
2190 done:
2191         talloc_free(mem_ctx);
2192         return ret;
2193 }
2194
2195 struct samba_kdc_seq {
2196         unsigned int index;
2197         unsigned int count;
2198         struct ldb_message **msgs;
2199         struct ldb_dn *realm_dn;
2200 };
2201
2202 static krb5_error_code samba_kdc_seq(krb5_context context,
2203                                      struct samba_kdc_db_context *kdc_db_ctx,
2204                                      hdb_entry_ex *entry)
2205 {
2206         krb5_error_code ret;
2207         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2208         const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2209         struct ldb_message *msg = NULL;
2210         const char *sAMAccountName = NULL;
2211         krb5_principal principal = NULL;
2212         TALLOC_CTX *mem_ctx;
2213
2214         if (!priv) {
2215                 return HDB_ERR_NOENTRY;
2216         }
2217
2218         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2219
2220         if (!mem_ctx) {
2221                 ret = ENOMEM;
2222                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2223                 return ret;
2224         }
2225
2226         while (priv->index < priv->count) {
2227                 msg = priv->msgs[priv->index++];
2228
2229                 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2230                 if (sAMAccountName != NULL) {
2231                         break;
2232                 }
2233         }
2234
2235         if (sAMAccountName == NULL) {
2236                 ret = HDB_ERR_NOENTRY;
2237                 goto out;
2238         }
2239
2240         ret = smb_krb5_make_principal(context, &principal,
2241                                       realm, sAMAccountName, NULL);
2242         if (ret != 0) {
2243                 goto out;
2244         }
2245
2246         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2247                                       principal, SAMBA_KDC_ENT_TYPE_ANY,
2248                                       HDB_F_ADMIN_DATA|HDB_F_GET_ANY,
2249                                       priv->realm_dn, msg, entry);
2250
2251 out:
2252         if (principal != NULL) {
2253                 krb5_free_principal(context, principal);
2254         }
2255
2256         if (ret != 0) {
2257                 TALLOC_FREE(priv);
2258                 kdc_db_ctx->seq_ctx = NULL;
2259         } else {
2260                 talloc_free(mem_ctx);
2261         }
2262
2263         return ret;
2264 }
2265
2266 krb5_error_code samba_kdc_firstkey(krb5_context context,
2267                                    struct samba_kdc_db_context *kdc_db_ctx,
2268                                    hdb_entry_ex *entry)
2269 {
2270         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2271         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2272         char *realm;
2273         struct ldb_result *res = NULL;
2274         krb5_error_code ret;
2275         TALLOC_CTX *mem_ctx;
2276         int lret;
2277
2278         if (priv) {
2279                 TALLOC_FREE(priv);
2280                 kdc_db_ctx->seq_ctx = NULL;
2281         }
2282
2283         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2284         if (!priv) {
2285                 ret = ENOMEM;
2286                 krb5_set_error_message(context, ret, "talloc: out of memory");
2287                 return ret;
2288         }
2289
2290         priv->index = 0;
2291         priv->msgs = NULL;
2292         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2293         priv->count = 0;
2294
2295         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2296
2297         if (!mem_ctx) {
2298                 ret = ENOMEM;
2299                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2300                 return ret;
2301         }
2302
2303         ret = krb5_get_default_realm(context, &realm);
2304         if (ret != 0) {
2305                 TALLOC_FREE(priv);
2306                 return ret;
2307         }
2308         krb5_free_default_realm(context, realm);
2309
2310         lret = dsdb_search(ldb_ctx, priv, &res,
2311                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2312                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
2313                            "(objectClass=user)");
2314
2315         if (lret != LDB_SUCCESS) {
2316                 TALLOC_FREE(priv);
2317                 return HDB_ERR_NOENTRY;
2318         }
2319
2320         priv->count = res->count;
2321         priv->msgs = talloc_steal(priv, res->msgs);
2322         talloc_free(res);
2323
2324         kdc_db_ctx->seq_ctx = priv;
2325
2326         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2327
2328         if (ret != 0) {
2329                 TALLOC_FREE(priv);
2330                 kdc_db_ctx->seq_ctx = NULL;
2331         } else {
2332                 talloc_free(mem_ctx);
2333         }
2334         return ret;
2335 }
2336
2337 krb5_error_code samba_kdc_nextkey(krb5_context context,
2338                                   struct samba_kdc_db_context *kdc_db_ctx,
2339                                   hdb_entry_ex *entry)
2340 {
2341         return samba_kdc_seq(context, kdc_db_ctx, entry);
2342 }
2343
2344 /* Check if a given entry may delegate or do s4u2self to this target principal
2345  *
2346  * This is currently a very nasty hack - allowing only delegation to itself.
2347  */
2348 krb5_error_code
2349 samba_kdc_check_s4u2self(krb5_context context,
2350                          struct samba_kdc_db_context *kdc_db_ctx,
2351                          struct samba_kdc_entry *skdc_entry,
2352                          krb5_const_principal target_principal)
2353 {
2354         krb5_error_code ret;
2355         struct ldb_dn *realm_dn;
2356         struct ldb_message *msg;
2357         struct dom_sid *orig_sid;
2358         struct dom_sid *target_sid;
2359         const char *delegation_check_attrs[] = {
2360                 "objectSid", NULL
2361         };
2362
2363         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
2364
2365         if (!mem_ctx) {
2366                 ret = ENOMEM;
2367                 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
2368                 return ret;
2369         }
2370
2371         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
2372                                       HDB_F_GET_CLIENT|HDB_F_GET_SERVER,
2373                                       delegation_check_attrs, &realm_dn, &msg);
2374
2375         if (ret != 0) {
2376                 talloc_free(mem_ctx);
2377                 return ret;
2378         }
2379
2380         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2381         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2382
2383         /* Allow delegation to the same principal, even if by a different
2384          * name.  The easy and safe way to prove this is by SID
2385          * comparison */
2386         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2387                 talloc_free(mem_ctx);
2388                 return KRB5KDC_ERR_BADOPTION;
2389         }
2390
2391         talloc_free(mem_ctx);
2392         return ret;
2393 }
2394
2395 /* Certificates printed by a the Certificate Authority might have a
2396  * slightly different form of the user principal name to that in the
2397  * database.  Allow a mismatch where they both refer to the same
2398  * SID */
2399
2400 krb5_error_code
2401 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2402                                     struct samba_kdc_db_context *kdc_db_ctx,
2403                                     struct samba_kdc_entry *skdc_entry,
2404                                      krb5_const_principal certificate_principal)
2405 {
2406         krb5_error_code ret;
2407         struct ldb_dn *realm_dn;
2408         struct ldb_message *msg;
2409         struct dom_sid *orig_sid;
2410         struct dom_sid *target_sid;
2411         const char *ms_upn_check_attrs[] = {
2412                 "objectSid", NULL
2413         };
2414
2415         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2416
2417         if (!mem_ctx) {
2418                 ret = ENOMEM;
2419                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2420                 return ret;
2421         }
2422
2423         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2424                                       mem_ctx, certificate_principal,
2425                                       ms_upn_check_attrs, &realm_dn, &msg);
2426
2427         if (ret != 0) {
2428                 talloc_free(mem_ctx);
2429                 return ret;
2430         }
2431
2432         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2433         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2434
2435         /* Consider these to be the same principal, even if by a different
2436          * name.  The easy and safe way to prove this is by SID
2437          * comparison */
2438         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2439                 talloc_free(mem_ctx);
2440 #ifdef KRB5_KDC_ERR_CLIENT_NAME_MISMATCH /* Heimdal */
2441                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2442 #elif defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2443                 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2444 #endif
2445         }
2446
2447         talloc_free(mem_ctx);
2448         return ret;
2449 }
2450
2451 /*
2452  * Check if a given entry may delegate to this target principal
2453  * with S4U2Proxy.
2454  */
2455 krb5_error_code
2456 samba_kdc_check_s4u2proxy(krb5_context context,
2457                           struct samba_kdc_db_context *kdc_db_ctx,
2458                           struct samba_kdc_entry *skdc_entry,
2459                           krb5_const_principal target_principal)
2460 {
2461         krb5_error_code ret;
2462         char *tmp = NULL;
2463         const char *client_dn = NULL;
2464         const char *target_principal_name = NULL;
2465         struct ldb_message_element *el;
2466         struct ldb_val val;
2467         unsigned int i;
2468         bool found = false;
2469
2470         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2471
2472         if (!mem_ctx) {
2473                 ret = ENOMEM;
2474                 krb5_set_error_message(context, ret,
2475                                        "samba_kdc_check_s4u2proxy:"
2476                                        " talloc_named() failed!");
2477                 return ret;
2478         }
2479
2480         client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2481         if (!client_dn) {
2482                 if (errno == 0) {
2483                         errno = ENOMEM;
2484                 }
2485                 ret = errno;
2486                 krb5_set_error_message(context, ret,
2487                                        "samba_kdc_check_s4u2proxy:"
2488                                        " ldb_dn_get_linearized() failed!");
2489                 return ret;
2490         }
2491
2492         /*
2493          * The main heimdal code already checked that the target_principal
2494          * belongs to the same realm as the client.
2495          *
2496          * So we just need the principal without the realm,
2497          * as that is what is configured in the "msDS-AllowedToDelegateTo"
2498          * attribute.
2499          */
2500         ret = krb5_unparse_name_flags(context, target_principal,
2501                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2502         if (ret) {
2503                 talloc_free(mem_ctx);
2504                 krb5_set_error_message(context, ret,
2505                                        "samba_kdc_check_s4u2proxy:"
2506                                        " krb5_unparse_name() failed!");
2507                 return ret;
2508         }
2509         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2510                  client_dn, tmp));
2511
2512         target_principal_name = talloc_strdup(mem_ctx, tmp);
2513         SAFE_FREE(tmp);
2514         if (target_principal_name == NULL) {
2515                 ret = ENOMEM;
2516                 krb5_set_error_message(context, ret,
2517                                        "samba_kdc_check_s4u2proxy:"
2518                                        " talloc_strdup() failed!");
2519                 return ret;
2520         }
2521
2522         el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2523         if (el == NULL) {
2524                 goto bad_option;
2525         }
2526
2527         val = data_blob_string_const(target_principal_name);
2528
2529         for (i=0; i<el->num_values; i++) {
2530                 struct ldb_val *val1 = &val;
2531                 struct ldb_val *val2 = &el->values[i];
2532                 int cmp;
2533
2534                 if (val1->length != val2->length) {
2535                         continue;
2536                 }
2537
2538                 cmp = strncasecmp((const char *)val1->data,
2539                                   (const char *)val2->data,
2540                                   val1->length);
2541                 if (cmp != 0) {
2542                         continue;
2543                 }
2544
2545                 found = true;
2546                 break;
2547         }
2548
2549         if (!found) {
2550                 goto bad_option;
2551         }
2552
2553         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2554                  client_dn, tmp));
2555         talloc_free(mem_ctx);
2556         return 0;
2557
2558 bad_option:
2559         krb5_set_error_message(context, ret,
2560                                "samba_kdc_check_s4u2proxy: client[%s] "
2561                                "not allowed for delegation to target[%s]",
2562                                client_dn,
2563                                target_principal_name);
2564         talloc_free(mem_ctx);
2565         return KRB5KDC_ERR_BADOPTION;
2566 }
2567
2568 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2569                                 struct samba_kdc_db_context **kdc_db_ctx_out)
2570 {
2571         int ldb_ret;
2572         struct ldb_message *msg;
2573         struct auth_session_info *session_info;
2574         struct samba_kdc_db_context *kdc_db_ctx;
2575         /* The idea here is very simple.  Using Kerberos to
2576          * authenticate the KDC to the LDAP server is higly likely to
2577          * be circular.
2578          *
2579          * In future we may set this up to use EXERNAL and SSL
2580          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2581         */
2582
2583         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2584         if (kdc_db_ctx == NULL) {
2585                 return NT_STATUS_NO_MEMORY;
2586         }
2587         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2588         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2589
2590         /* get default kdc policy */
2591         lpcfg_default_kdc_policy(base_ctx->lp_ctx,
2592                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
2593                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
2594                                  &kdc_db_ctx->policy.renewal_lifetime);
2595
2596         session_info = system_session(kdc_db_ctx->lp_ctx);
2597         if (session_info == NULL) {
2598                 return NT_STATUS_INTERNAL_ERROR;
2599         }
2600
2601         /* Setup the link to LDB */
2602         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
2603                                           base_ctx->lp_ctx, session_info, 0);
2604         if (kdc_db_ctx->samdb == NULL) {
2605                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2606                 talloc_free(kdc_db_ctx);
2607                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2608         }
2609
2610         /* Find out our own krbtgt kvno */
2611         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2612         if (ldb_ret != LDB_SUCCESS) {
2613                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2614                           ldb_errstring(kdc_db_ctx->samdb)));
2615                 talloc_free(kdc_db_ctx);
2616                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2617         }
2618         if (kdc_db_ctx->rodc) {
2619                 int my_krbtgt_number;
2620                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2621                 struct ldb_dn *account_dn;
2622                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2623                 if (!server_dn) {
2624                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2625                                   ldb_errstring(kdc_db_ctx->samdb)));
2626                         talloc_free(kdc_db_ctx);
2627                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2628                 }
2629
2630                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2631                                              "serverReference", &account_dn);
2632                 if (ldb_ret != LDB_SUCCESS) {
2633                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2634                                   ldb_errstring(kdc_db_ctx->samdb)));
2635                         talloc_free(kdc_db_ctx);
2636                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2637                 }
2638
2639                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2640                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2641                 talloc_free(account_dn);
2642                 if (ldb_ret != LDB_SUCCESS) {
2643                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2644                                   ldb_errstring(kdc_db_ctx->samdb)));
2645                         talloc_free(kdc_db_ctx);
2646                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2647                 }
2648
2649                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2650                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2651                                           secondary_keytab,
2652                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2653                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2654                 if (ldb_ret != LDB_SUCCESS) {
2655                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2656                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2657                                   ldb_errstring(kdc_db_ctx->samdb),
2658                                   ldb_strerror(ldb_ret)));
2659                         talloc_free(kdc_db_ctx);
2660                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2661                 }
2662                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2663                 if (my_krbtgt_number == -1) {
2664                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2665                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2666                                   my_krbtgt_number));
2667                         talloc_free(kdc_db_ctx);
2668                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2669                 }
2670                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2671
2672         } else {
2673                 kdc_db_ctx->my_krbtgt_number = 0;
2674                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2675                                           &msg,
2676                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
2677                                           LDB_SCOPE_SUBTREE,
2678                                           krbtgt_attrs,
2679                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2680                                           "(&(objectClass=user)(samAccountName=krbtgt))");
2681
2682                 if (ldb_ret != LDB_SUCCESS) {
2683                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2684                         talloc_free(kdc_db_ctx);
2685                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2686                 }
2687                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2688                 kdc_db_ctx->my_krbtgt_number = 0;
2689                 talloc_free(msg);
2690         }
2691         *kdc_db_ctx_out = kdc_db_ctx;
2692         return NT_STATUS_OK;
2693 }