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