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