s4:kdc: only support LSA_TRUST_TYPE_UPLEVEL domains in samba_kdc_trust_message2entry()
[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->kdc_db_ctx = kdc_db_ctx;
832         p->realm_dn = talloc_reference(p, realm_dn);
833         if (!p->realm_dn) {
834                 ret = ENOMEM;
835                 goto out;
836         }
837
838         talloc_set_destructor(p, samba_kdc_entry_destructor);
839
840         entry_ex->ctx = p;
841
842         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
843
844         msDS_User_Account_Control_Computed
845                 = ldb_msg_find_attr_as_uint(msg,
846                                             "msDS-User-Account-Control-Computed",
847                                             UF_ACCOUNTDISABLE);
848
849         /*
850          * This brings in the lockout flag, block the account if not
851          * found.  We need the weird UF_ACCOUNTDISABLE check because
852          * we do not want to fail open if the value is not returned,
853          * but 0 is a valid value (all OK)
854          */
855         if (msDS_User_Account_Control_Computed == UF_ACCOUNTDISABLE) {
856                 ret = EINVAL;
857                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: "
858                                 "no msDS-User-Account-Control-Computed present");
859                 goto out;
860         } else {
861                 userAccountControl |= msDS_User_Account_Control_Computed;
862         }
863
864         /* 
865          * If we are set to canonicalize, we get back the fixed UPPER
866          * case realm, and the real username (ie matching LDAP
867          * samAccountName) 
868          *
869          * Otherwise, if we are set to enterprise, we
870          * get back the whole principal as-sent 
871          *
872          * Finally, if we are not set to canonicalize, we get back the
873          * fixed UPPER case realm, but the as-sent username
874          */
875
876         if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT) {
877                 if (flags & (SDB_F_CANON)) {
878                         /*
879                          * When requested to do so, ensure that the
880                          * both realm values in the principal are set
881                          * to the upper case, canonical realm
882                          */
883                         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal,
884                                                       lpcfg_realm(lp_ctx), "krbtgt",
885                                                       lpcfg_realm(lp_ctx), NULL);
886                         if (ret) {
887                                 krb5_clear_error_message(context);
888                                 goto out;
889                         }
890                         smb_krb5_principal_set_type(context, entry_ex->entry.principal, KRB5_NT_SRV_INST);
891                 } else {
892                         ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
893                         if (ret) {
894                                 krb5_clear_error_message(context);
895                                 goto out;
896                         }
897                         /*
898                          * this appears to be required regardless of
899                          * the canonicalize flag from the client
900                          */
901                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
902                         if (ret) {
903                                 krb5_clear_error_message(context);
904                                 goto out;
905                         }
906                 }
907
908         } else if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
909                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
910                 if (ret) {
911                         krb5_clear_error_message(context);
912                         goto out;
913                 }
914         } else if (flags & SDB_F_CANON && flags & SDB_F_FOR_AS_REQ) {
915                 /*
916                  * SDB_F_CANON maps from the canonicalize flag in the
917                  * packet, and has a different meaning between AS-REQ
918                  * and TGS-REQ.  We only change the principal in the AS-REQ case
919                  */
920                 ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, lpcfg_realm(lp_ctx), samAccountName, NULL);
921                 if (ret) {
922                         krb5_clear_error_message(context);
923                         goto out;
924                 }
925         } else {
926                 ret = krb5_copy_principal(context, principal, &entry_ex->entry.principal);
927                 if (ret) {
928                         krb5_clear_error_message(context);
929                         goto out;
930                 }
931
932                 if (smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL) {
933                         /* While we have copied the client principal, tests
934                          * show that Win2k3 returns the 'corrected' realm, not
935                          * the client-specified realm.  This code attempts to
936                          * replace the client principal's realm with the one
937                          * we determine from our records */
938                         
939                         /* this has to be with malloc() */
940                         ret = smb_krb5_principal_set_realm(context, entry_ex->entry.principal, lpcfg_realm(lp_ctx));
941                         if (ret) {
942                                 krb5_clear_error_message(context);
943                                 goto out;
944                         }
945                 }
946         }
947
948         /* First try and figure out the flags based on the userAccountControl */
949         entry_ex->entry.flags = uf2SDBFlags(context, userAccountControl, ent_type);
950
951         /* Windows 2008 seems to enforce this (very sensible) rule by
952          * default - don't allow offline attacks on a user's password
953          * by asking for a ticket to them as a service (encrypted with
954          * their probably patheticly insecure password) */
955
956         if (entry_ex->entry.flags.server
957             && lpcfg_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
958                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
959                         entry_ex->entry.flags.server = 0;
960                 }
961         }
962         /*
963          * To give the correct type of error to the client, we must
964          * not just return the entry without .server set, we must
965          * pretend the principal does not exist.  Otherwise we may
966          * return ERR_POLICY instead of
967          * KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN
968          */
969         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER && entry_ex->entry.flags.server == 0) {
970                 ret = SDB_ERR_NOENTRY;
971                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no servicePrincipalName present for this server, refusing with no-such-entry");
972                 goto out;
973         }
974         if (flags & SDB_F_ADMIN_DATA) {
975                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
976                  * of the Heimdal KDC.  They are stored in a the traditional
977                  * DB for audit purposes, and still form part of the structure
978                  * we must return */
979
980                 /* use 'whenCreated' */
981                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
982                 /* use 'kadmin' for now (needed by mit_samba) */
983
984                 ret = smb_krb5_make_principal(context,
985                                               &entry_ex->entry.created_by.principal,
986                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
987                 if (ret) {
988                         krb5_clear_error_message(context);
989                         goto out;
990                 }
991
992                 entry_ex->entry.modified_by = (struct sdb_event *) malloc(sizeof(struct sdb_event));
993                 if (entry_ex->entry.modified_by == NULL) {
994                         ret = ENOMEM;
995                         krb5_set_error_message(context, ret, "malloc: out of memory");
996                         goto out;
997                 }
998
999                 /* use 'whenChanged' */
1000                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
1001                 /* use 'kadmin' for now (needed by mit_samba) */
1002                 ret = smb_krb5_make_principal(context,
1003                                               &entry_ex->entry.modified_by->principal,
1004                                               lpcfg_realm(lp_ctx), "kadmin", NULL);
1005                 if (ret) {
1006                         krb5_clear_error_message(context);
1007                         goto out;
1008                 }
1009         }
1010
1011
1012         /* The lack of password controls etc applies to krbtgt by
1013          * virtue of being that particular RID */
1014         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
1015
1016         if (!NT_STATUS_IS_OK(status)) {
1017                 ret = EINVAL;
1018                 goto out;
1019         }
1020
1021         if (rid == DOMAIN_RID_KRBTGT) {
1022                 char *realm = NULL;
1023
1024                 entry_ex->entry.valid_end = NULL;
1025                 entry_ex->entry.pw_end = NULL;
1026
1027                 entry_ex->entry.flags.invalid = 0;
1028                 entry_ex->entry.flags.server = 1;
1029
1030                 realm = smb_krb5_principal_get_realm(context, principal);
1031                 if (realm == NULL) {
1032                         ret = ENOMEM;
1033                         goto out;
1034                 }
1035
1036                 /* Don't mark all requests for the krbtgt/realm as
1037                  * 'change password', as otherwise we could get into
1038                  * trouble, and not enforce the password expirty.
1039                  * Instead, only do it when request is for the kpasswd service */
1040                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
1041                     && krb5_princ_size(context, principal) == 2
1042                     && (principal_comp_strcmp(context, principal, 0, "kadmin") == 0)
1043                     && (principal_comp_strcmp(context, principal, 1, "changepw") == 0)
1044                     && lpcfg_is_my_domain_or_realm(lp_ctx, realm)) {
1045                         entry_ex->entry.flags.change_pw = 1;
1046                 }
1047
1048                 SAFE_FREE(realm);
1049
1050                 entry_ex->entry.flags.client = 0;
1051                 entry_ex->entry.flags.forwardable = 1;
1052                 entry_ex->entry.flags.ok_as_delegate = 1;
1053         } else if (is_rodc) {
1054                 /* The RODC krbtgt account is like the main krbtgt,
1055                  * but it does not have a changepw or kadmin
1056                  * service */
1057
1058                 entry_ex->entry.valid_end = NULL;
1059                 entry_ex->entry.pw_end = NULL;
1060
1061                 /* Also don't allow the RODC krbtgt to be a client (it should not be needed) */
1062                 entry_ex->entry.flags.client = 0;
1063                 entry_ex->entry.flags.invalid = 0;
1064                 entry_ex->entry.flags.server = 1;
1065
1066                 entry_ex->entry.flags.client = 0;
1067                 entry_ex->entry.flags.forwardable = 1;
1068                 entry_ex->entry.flags.ok_as_delegate = 0;
1069         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1070                 /* The account/password expiry only applies when the account is used as a
1071                  * client (ie password login), not when used as a server */
1072
1073                 /* Make very well sure we don't use this for a client,
1074                  * it could bypass the password restrictions */
1075                 entry_ex->entry.flags.client = 0;
1076
1077                 entry_ex->entry.valid_end = NULL;
1078                 entry_ex->entry.pw_end = NULL;
1079
1080         } else {
1081                 NTTIME must_change_time
1082                         = samdb_result_nttime(msg,
1083                                         "msDS-UserPasswordExpiryTimeComputed",
1084                                         0);
1085                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
1086                         entry_ex->entry.pw_end = NULL;
1087                 } else {
1088                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
1089                         if (entry_ex->entry.pw_end == NULL) {
1090                                 ret = ENOMEM;
1091                                 goto out;
1092                         }
1093                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
1094                 }
1095
1096                 acct_expiry = samdb_result_account_expires(msg);
1097                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
1098                         entry_ex->entry.valid_end = NULL;
1099                 } else {
1100                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
1101                         if (entry_ex->entry.valid_end == NULL) {
1102                                 ret = ENOMEM;
1103                                 goto out;
1104                         }
1105                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
1106                 }
1107         }
1108
1109         entry_ex->entry.valid_start = NULL;
1110
1111         entry_ex->entry.max_life = malloc(sizeof(*entry_ex->entry.max_life));
1112         if (entry_ex->entry.max_life == NULL) {
1113                 ret = ENOMEM;
1114                 goto out;
1115         }
1116
1117         if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
1118                 *entry_ex->entry.max_life = kdc_db_ctx->policy.svc_tkt_lifetime;
1119         } else if (ent_type == SAMBA_KDC_ENT_TYPE_KRBTGT || ent_type == SAMBA_KDC_ENT_TYPE_CLIENT) {
1120                 *entry_ex->entry.max_life = kdc_db_ctx->policy.usr_tkt_lifetime;
1121         } else {
1122                 *entry_ex->entry.max_life = MIN(kdc_db_ctx->policy.svc_tkt_lifetime,
1123                                                 kdc_db_ctx->policy.usr_tkt_lifetime);
1124         }
1125
1126         entry_ex->entry.max_renew = malloc(sizeof(*entry_ex->entry.max_life));
1127         if (entry_ex->entry.max_renew == NULL) {
1128                 ret = ENOMEM;
1129                 goto out;
1130         }
1131
1132         *entry_ex->entry.max_renew = kdc_db_ctx->policy.renewal_lifetime;
1133
1134         /* Get keys from the db */
1135         ret = samba_kdc_message2entry_keys(context, kdc_db_ctx, p, msg,
1136                                            rid, is_rodc, userAccountControl,
1137                                            ent_type, entry_ex);
1138         if (ret) {
1139                 /* Could be bogus data in the entry, or out of memory */
1140                 goto out;
1141         }
1142
1143         p->msg = talloc_steal(p, msg);
1144
1145 out:
1146         if (ret != 0) {
1147                 /* This doesn't free ent itself, that is for the eventual caller to do */
1148                 sdb_free_entry(entry_ex);
1149                 ZERO_STRUCTP(entry_ex);
1150         } else {
1151                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1152         }
1153
1154         return ret;
1155 }
1156
1157 /*
1158  * Construct an hdb_entry from a directory entry.
1159  * The kvno is what the remote client asked for
1160  */
1161 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
1162                                                struct samba_kdc_db_context *kdc_db_ctx,
1163                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
1164                                                enum trust_direction direction,
1165                                                struct ldb_dn *realm_dn,
1166                                                unsigned flags,
1167                                                uint32_t kvno,
1168                                                struct ldb_message *msg,
1169                                                struct sdb_entry_ex *entry_ex)
1170 {
1171         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1172         const char *our_realm = lpcfg_realm(lp_ctx);
1173         char *partner_realm = NULL;
1174         const char *realm = NULL;
1175         const char *krbtgt_realm = NULL;
1176         DATA_BLOB password_utf16 = data_blob_null;
1177         DATA_BLOB password_utf8 = data_blob_null;
1178         struct samr_Password _password_hash;
1179         const struct samr_Password *password_hash = NULL;
1180         const struct ldb_val *password_val;
1181         struct trustAuthInOutBlob password_blob;
1182         struct samba_kdc_entry *p;
1183         bool use_previous = false;
1184         uint32_t current_kvno;
1185         uint32_t previous_kvno;
1186         uint32_t num_keys = 0;
1187         enum ndr_err_code ndr_err;
1188         int ret;
1189         unsigned int i;
1190         struct AuthenticationInformationArray *auth_array;
1191         struct timeval tv;
1192         NTTIME an_hour_ago;
1193         uint32_t *auth_kvno;
1194         bool preferr_current = false;
1195         uint32_t supported_enctypes = ENC_RC4_HMAC_MD5;
1196         struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
1197         NTSTATUS status;
1198
1199         if (dsdb_functional_level(kdc_db_ctx->samdb) >= DS_DOMAIN_FUNCTION_2008) {
1200                 supported_enctypes = ldb_msg_find_attr_as_uint(msg,
1201                                         "msDS-SupportedEncryptionTypes",
1202                                         supported_enctypes);
1203         }
1204
1205         status = dsdb_trust_parse_tdo_info(mem_ctx, msg, &tdo);
1206         if (!NT_STATUS_IS_OK(status)) {
1207                 krb5_clear_error_message(context);
1208                 ret = ENOMEM;
1209                 goto out;
1210         }
1211
1212         if (!(tdo->trust_direction & direction)) {
1213                 krb5_clear_error_message(context);
1214                 ret = SDB_ERR_NOENTRY;
1215                 goto out;
1216         }
1217
1218         if (tdo->trust_type != LSA_TRUST_TYPE_UPLEVEL) {
1219                 /*
1220                  * Only UPLEVEL domains support kerberos here,
1221                  * as we don't support LSA_TRUST_TYPE_MIT.
1222                  */
1223                 krb5_clear_error_message(context);
1224                 ret = SDB_ERR_NOENTRY;
1225                 goto out;
1226         }
1227
1228         if (tdo->domain_name.string == NULL) {
1229                 krb5_clear_error_message(context);
1230                 ret = SDB_ERR_NOENTRY;
1231                 goto out;
1232         }
1233         partner_realm = strupper_talloc(mem_ctx, tdo->domain_name.string);
1234         if (partner_realm == NULL) {
1235                 krb5_clear_error_message(context);
1236                 ret = ENOMEM;
1237                 goto out;
1238         }
1239
1240         if (direction == INBOUND) {
1241                 realm = our_realm;
1242                 krbtgt_realm = partner_realm;
1243
1244                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
1245         } else { /* OUTBOUND */
1246                 realm = partner_realm;
1247                 krbtgt_realm = our_realm;
1248
1249                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
1250         }
1251
1252         if (password_val == NULL) {
1253                 krb5_clear_error_message(context);
1254                 ret = SDB_ERR_NOENTRY;
1255                 goto out;
1256         }
1257
1258         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
1259                                        (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
1260         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1261                 krb5_clear_error_message(context);
1262                 ret = EINVAL;
1263                 goto out;
1264         }
1265
1266         p = talloc(mem_ctx, struct samba_kdc_entry);
1267         if (!p) {
1268                 ret = ENOMEM;
1269                 goto out;
1270         }
1271
1272         p->kdc_db_ctx = kdc_db_ctx;
1273         p->realm_dn = realm_dn;
1274
1275         talloc_set_destructor(p, samba_kdc_entry_destructor);
1276
1277         /* make sure we do not have bogus data in there */
1278         memset(&entry_ex->entry, 0, sizeof(struct sdb_entry));
1279
1280         entry_ex->ctx = p;
1281
1282         /* use 'whenCreated' */
1283         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
1284         /* use 'kadmin' for now (needed by mit_samba) */
1285         ret = smb_krb5_make_principal(context,
1286                                       &entry_ex->entry.created_by.principal,
1287                                       realm, "kadmin", NULL);
1288         if (ret) {
1289                 krb5_clear_error_message(context);
1290                 goto out;
1291         }
1292
1293         /*
1294          * We always need to generate the canonicalized principal
1295          * with the values of our database.
1296          */
1297         ret = smb_krb5_make_principal(context, &entry_ex->entry.principal, realm,
1298                                       "krbtgt", krbtgt_realm, NULL);
1299         if (ret) {
1300                 krb5_clear_error_message(context);
1301                 goto out;
1302         }
1303         smb_krb5_principal_set_type(context, entry_ex->entry.principal,
1304                                     KRB5_NT_SRV_INST);
1305
1306         entry_ex->entry.valid_start = NULL;
1307
1308         /* we need to work out if we are going to use the current or
1309          * the previous password hash.
1310          * We base this on the kvno the client passes in. If the kvno
1311          * passed in is equal to the current kvno in our database then
1312          * we use the current structure. If it is the current kvno-1,
1313          * then we use the previous substrucure.
1314          */
1315
1316         /*
1317          * Windows preferrs the previous key for one hour.
1318          */
1319         tv = timeval_current();
1320         if (tv.tv_sec > 3600) {
1321                 tv.tv_sec -= 3600;
1322         }
1323         an_hour_ago = timeval_to_nttime(&tv);
1324
1325         /* first work out the current kvno */
1326         current_kvno = 0;
1327         for (i=0; i < password_blob.count; i++) {
1328                 struct AuthenticationInformation *a =
1329                         &password_blob.current.array[i];
1330
1331                 if (a->LastUpdateTime <= an_hour_ago) {
1332                         preferr_current = true;
1333                 }
1334
1335                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1336                         current_kvno = a->AuthInfo.version.version;
1337                 }
1338         }
1339         if (current_kvno == 0) {
1340                 previous_kvno = 255;
1341         } else {
1342                 previous_kvno = current_kvno - 1;
1343         }
1344         for (i=0; i < password_blob.count; i++) {
1345                 struct AuthenticationInformation *a =
1346                         &password_blob.previous.array[i];
1347
1348                 if (a->AuthType == TRUST_AUTH_TYPE_VERSION) {
1349                         previous_kvno = a->AuthInfo.version.version;
1350                 }
1351         }
1352
1353         /* work out whether we will use the previous or current
1354            password */
1355         if (password_blob.previous.count == 0) {
1356                 /* there is no previous password */
1357                 use_previous = false;
1358         } else if (!(flags & SDB_F_KVNO_SPECIFIED)) {
1359                 /*
1360                  * If not specified we use the lowest kvno
1361                  * for the first hour after an update.
1362                  */
1363                 if (preferr_current) {
1364                         use_previous = false;
1365                 } else if (previous_kvno < current_kvno) {
1366                         use_previous = true;
1367                 } else {
1368                         use_previous = false;
1369                 }
1370         } else if (kvno == current_kvno) {
1371                 /*
1372                  * Exact match ...
1373                  */
1374                 use_previous = false;
1375         } else if (kvno == previous_kvno) {
1376                 /*
1377                  * Exact match ...
1378                  */
1379                 use_previous = true;
1380         } else {
1381                 /*
1382                  * Fallback to the current one for anything else
1383                  */
1384                 use_previous = false;
1385         }
1386
1387         if (use_previous) {
1388                 auth_array = &password_blob.previous;
1389                 auth_kvno = &previous_kvno;
1390         } else {
1391                 auth_array = &password_blob.current;
1392                 auth_kvno = &current_kvno;
1393         }
1394
1395         /* use the kvno the client specified, if available */
1396         if (flags & SDB_F_KVNO_SPECIFIED) {
1397                 entry_ex->entry.kvno = kvno;
1398         } else {
1399                 entry_ex->entry.kvno = *auth_kvno;
1400         }
1401
1402         for (i=0; i < auth_array->count; i++) {
1403                 if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
1404                         bool ok;
1405
1406                         password_utf16 = data_blob_const(auth_array->array[i].AuthInfo.clear.password,
1407                                                          auth_array->array[i].AuthInfo.clear.size);
1408                         if (password_utf16.length == 0) {
1409                                 break;
1410                         }
1411
1412                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1413                                 mdfour(_password_hash.hash, password_utf16.data, password_utf16.length);
1414                                 if (password_hash == NULL) {
1415                                         num_keys += 1;
1416                                 }
1417                                 password_hash = &_password_hash;
1418                         }
1419
1420                         if (!(supported_enctypes & (ENC_HMAC_SHA1_96_AES128|ENC_HMAC_SHA1_96_AES256))) {
1421                                 break;
1422                         }
1423
1424                         ok = convert_string_talloc(mem_ctx,
1425                                                    CH_UTF16MUNGED, CH_UTF8,
1426                                                    password_utf16.data,
1427                                                    password_utf16.length,
1428                                                    (void *)&password_utf8.data,
1429                                                    &password_utf8.length);
1430                         if (!ok) {
1431                                 krb5_clear_error_message(context);
1432                                 ret = ENOMEM;
1433                                 goto out;
1434                         }
1435
1436                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1437                                 num_keys += 1;
1438                         }
1439                         if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1440                                 num_keys += 1;
1441                         }
1442                         break;
1443                 } else if (auth_array->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
1444                         if (supported_enctypes & ENC_RC4_HMAC_MD5) {
1445                                 password_hash = &auth_array->array[i].AuthInfo.nt4owf.password;
1446                                 num_keys += 1;
1447                         }
1448                 }
1449         }
1450
1451         /* Must have found a cleartext or MD4 password */
1452         if (num_keys == 0) {
1453                 DEBUG(1,(__location__ ": no usable key found\n"));
1454                 krb5_clear_error_message(context);
1455                 ret = SDB_ERR_NOENTRY;
1456                 goto out;
1457         }
1458
1459         entry_ex->entry.keys.val = calloc(num_keys, sizeof(struct sdb_key));
1460         if (entry_ex->entry.keys.val == NULL) {
1461                 krb5_clear_error_message(context);
1462                 ret = ENOMEM;
1463                 goto out;
1464         }
1465
1466         if (password_utf8.length != 0) {
1467                 struct sdb_key key = {};
1468                 krb5_const_principal salt_principal = entry_ex->entry.principal;
1469                 krb5_data salt;
1470                 krb5_data cleartext_data;
1471
1472                 cleartext_data.data = discard_const_p(char, password_utf8.data);
1473                 cleartext_data.length = password_utf8.length;
1474
1475                 ret = smb_krb5_get_pw_salt(context,
1476                                            salt_principal,
1477                                            &salt);
1478                 if (ret != 0) {
1479                         goto out;
1480                 }
1481
1482                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES256) {
1483                         ret = smb_krb5_create_key_from_string(context,
1484                                                               salt_principal,
1485                                                               &salt,
1486                                                               &cleartext_data,
1487                                                               ENCTYPE_AES256_CTS_HMAC_SHA1_96,
1488                                                               &key.key);
1489                         if (ret != 0) {
1490                                 smb_krb5_free_data_contents(context, &salt);
1491                                 goto out;
1492                         }
1493
1494                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1495                         entry_ex->entry.keys.len++;
1496                 }
1497
1498                 if (supported_enctypes & ENC_HMAC_SHA1_96_AES128) {
1499                         ret = smb_krb5_create_key_from_string(context,
1500                                                               salt_principal,
1501                                                               &salt,
1502                                                               &cleartext_data,
1503                                                               ENCTYPE_AES128_CTS_HMAC_SHA1_96,
1504                                                               &key.key);
1505                         if (ret != 0) {
1506                                 smb_krb5_free_data_contents(context, &salt);
1507                                 goto out;
1508                         }
1509
1510                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1511                         entry_ex->entry.keys.len++;
1512                 }
1513
1514                 smb_krb5_free_data_contents(context, &salt);
1515         }
1516
1517         if (password_hash != NULL) {
1518                 struct sdb_key key = {};
1519
1520                 ret = smb_krb5_keyblock_init_contents(context,
1521                                                       ENCTYPE_ARCFOUR_HMAC,
1522                                                       password_hash->hash,
1523                                                       sizeof(password_hash->hash),
1524                                                       &key.key);
1525                 if (ret != 0) {
1526                         goto out;
1527                 }
1528
1529                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
1530                 entry_ex->entry.keys.len++;
1531         }
1532
1533         entry_ex->entry.flags = int2SDBFlags(0);
1534         entry_ex->entry.flags.immutable = 1;
1535         entry_ex->entry.flags.invalid = 0;
1536         entry_ex->entry.flags.server = 1;
1537         entry_ex->entry.flags.require_preauth = 1;
1538
1539         entry_ex->entry.pw_end = NULL;
1540
1541         entry_ex->entry.max_life = NULL;
1542
1543         entry_ex->entry.max_renew = NULL;
1544
1545         ret = samba_kdc_sort_encryption_keys(entry_ex);
1546         if (ret != 0) {
1547                 krb5_clear_error_message(context);
1548                 ret = ENOMEM;
1549                 goto out;
1550         }
1551
1552         p->msg = talloc_steal(p, msg);
1553
1554 out:
1555         TALLOC_FREE(partner_realm);
1556
1557         if (ret != 0) {
1558                 /* This doesn't free ent itself, that is for the eventual caller to do */
1559                 sdb_free_entry(entry_ex);
1560         } else {
1561                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
1562         }
1563
1564         return ret;
1565
1566 }
1567
1568 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
1569                                         TALLOC_CTX *mem_ctx,
1570                                         const char *realm,
1571                                         struct ldb_dn *realm_dn,
1572                                         struct ldb_message **pmsg)
1573 {
1574         NTSTATUS status;
1575         const char * const *attrs = trust_attrs;
1576
1577         status = dsdb_trust_search_tdo(ldb_ctx, realm, realm,
1578                                        attrs, mem_ctx, pmsg);
1579         if (NT_STATUS_IS_OK(status)) {
1580                 return 0;
1581         } else if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1582                 return SDB_ERR_NOENTRY;
1583         } else if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MEMORY)) {
1584                 int ret = ENOMEM;
1585                 krb5_set_error_message(context, ret, "get_sam_result_trust: out of memory");
1586                 return ret;
1587         } else {
1588                 int ret = EINVAL;
1589                 krb5_set_error_message(context, ret, "get_sam_result_trust: %s", nt_errstr(status));
1590                 return ret;
1591         }
1592 }
1593
1594 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
1595                                                 struct samba_kdc_db_context *kdc_db_ctx,
1596                                                 TALLOC_CTX *mem_ctx,
1597                                                 krb5_const_principal principal,
1598                                                 const char **attrs,
1599                                                 struct ldb_dn **realm_dn,
1600                                                 struct ldb_message **msg)
1601 {
1602         NTSTATUS nt_status;
1603         char *principal_string = NULL;
1604
1605         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1606                 principal_string = smb_krb5_principal_get_comp_string(mem_ctx, context,
1607                                                                       principal, 0);
1608                 if (principal_string == NULL) {
1609                         return ENOMEM;
1610                 }
1611         } else {
1612                 char *principal_string_m = NULL;
1613                 krb5_error_code ret;
1614
1615                 ret = krb5_unparse_name(context, principal, &principal_string_m);
1616                 if (ret != 0) {
1617                         return ret;
1618                 }
1619
1620                 principal_string = talloc_strdup(mem_ctx, principal_string_m);
1621                 SAFE_FREE(principal_string_m);
1622                 if (principal_string == NULL) {
1623                         return ENOMEM;
1624                 }
1625         }
1626
1627         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1628                                               mem_ctx, principal_string, attrs,
1629                                               realm_dn, msg);
1630         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1631                 krb5_principal fallback_principal = NULL;
1632                 unsigned int num_comp;
1633                 char *fallback_realm = NULL;
1634                 char *fallback_account = NULL;
1635                 krb5_error_code ret;
1636
1637                 ret = krb5_parse_name(context, principal_string,
1638                                       &fallback_principal);
1639                 TALLOC_FREE(principal_string);
1640                 if (ret != 0) {
1641                         return ret;
1642                 }
1643
1644                 num_comp = krb5_princ_size(context, fallback_principal);
1645                 fallback_realm = smb_krb5_principal_get_realm(context,
1646                                                               fallback_principal);
1647                 if (fallback_realm == NULL) {
1648                         krb5_free_principal(context, fallback_principal);
1649                         return ENOMEM;
1650                 }
1651
1652                 if (num_comp == 1) {
1653                         size_t len;
1654
1655                         fallback_account = smb_krb5_principal_get_comp_string(mem_ctx,
1656                                                 context, fallback_principal, 0);
1657                         if (fallback_account == NULL) {
1658                                 krb5_free_principal(context, fallback_principal);
1659                                 SAFE_FREE(fallback_realm);
1660                                 return ENOMEM;
1661                         }
1662
1663                         len = strlen(fallback_account);
1664                         if (len >= 2 && fallback_account[len - 1] == '$') {
1665                                 TALLOC_FREE(fallback_account);
1666                         }
1667                 }
1668                 krb5_free_principal(context, fallback_principal);
1669                 fallback_principal = NULL;
1670
1671                 if (fallback_account != NULL) {
1672                         char *with_dollar;
1673
1674                         with_dollar = talloc_asprintf(mem_ctx, "%s$",
1675                                                      fallback_account);
1676                         if (with_dollar == NULL) {
1677                                 SAFE_FREE(fallback_realm);
1678                                 return ENOMEM;
1679                         }
1680                         TALLOC_FREE(fallback_account);
1681
1682                         ret = smb_krb5_make_principal(context,
1683                                                       &fallback_principal,
1684                                                       fallback_realm,
1685                                                       with_dollar, NULL);
1686                         TALLOC_FREE(with_dollar);
1687                         if (ret != 0) {
1688                                 SAFE_FREE(fallback_realm);
1689                                 return ret;
1690                         }
1691                 }
1692                 SAFE_FREE(fallback_realm);
1693
1694                 if (fallback_principal != NULL) {
1695                         char *fallback_string = NULL;
1696
1697                         ret = krb5_unparse_name(context,
1698                                                 fallback_principal,
1699                                                 &fallback_string);
1700                         if (ret != 0) {
1701                                 krb5_free_principal(context, fallback_principal);
1702                                 return ret;
1703                         }
1704
1705                         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1706                                                               mem_ctx,
1707                                                               fallback_string,
1708                                                               attrs,
1709                                                               realm_dn, msg);
1710                         SAFE_FREE(fallback_string);
1711                 }
1712                 krb5_free_principal(context, fallback_principal);
1713                 fallback_principal = NULL;
1714         }
1715         TALLOC_FREE(principal_string);
1716
1717         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1718                 return SDB_ERR_NOENTRY;
1719         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1720                 return ENOMEM;
1721         } else if (!NT_STATUS_IS_OK(nt_status)) {
1722                 return EINVAL;
1723         }
1724
1725         return 0;
1726 }
1727
1728 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1729                                                struct samba_kdc_db_context *kdc_db_ctx,
1730                                                TALLOC_CTX *mem_ctx,
1731                                                krb5_const_principal principal,
1732                                                unsigned flags,
1733                                                struct sdb_entry_ex *entry_ex) {
1734         struct ldb_dn *realm_dn;
1735         krb5_error_code ret;
1736         struct ldb_message *msg = NULL;
1737
1738         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1739                                       mem_ctx, principal, user_attrs,
1740                                       &realm_dn, &msg);
1741         if (ret != 0) {
1742                 return ret;
1743         }
1744
1745         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1746                                       principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1747                                       flags,
1748                                       realm_dn, msg, entry_ex);
1749         return ret;
1750 }
1751
1752 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1753                                               struct samba_kdc_db_context *kdc_db_ctx,
1754                                               TALLOC_CTX *mem_ctx,
1755                                               krb5_const_principal principal,
1756                                               unsigned flags,
1757                                               uint32_t kvno,
1758                                               struct sdb_entry_ex *entry_ex)
1759 {
1760         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1761         krb5_error_code ret;
1762         struct ldb_message *msg = NULL;
1763         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1764         char *realm_from_princ, *realm_from_princ_malloc;
1765         char *realm_princ_comp = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 1);
1766
1767         realm_from_princ_malloc = smb_krb5_principal_get_realm(context, principal);
1768         if (realm_from_princ_malloc == NULL) {
1769                 /* can't happen */
1770                 return SDB_ERR_NOENTRY;
1771         }
1772         realm_from_princ = talloc_strdup(mem_ctx, realm_from_princ_malloc);
1773         free(realm_from_princ_malloc);
1774         if (realm_from_princ == NULL) {
1775                 return SDB_ERR_NOENTRY;
1776         }
1777
1778         if (krb5_princ_size(context, principal) != 2
1779             || (principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME) != 0)) {
1780                 /* Not a krbtgt */
1781                 return SDB_ERR_NOENTRY;
1782         }
1783
1784         /* krbtgt case.  Either us or a trusted realm */
1785
1786         if (lpcfg_is_my_domain_or_realm(lp_ctx, realm_from_princ)
1787             && lpcfg_is_my_domain_or_realm(lp_ctx, realm_princ_comp)) {
1788                 /* us, or someone quite like us */
1789                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1790                  * is in our db, then direct the caller at our primary
1791                  * krbtgt */
1792
1793                 int lret;
1794                 unsigned int krbtgt_number;
1795                 /* w2k8r2 sometimes gives us a kvno of 255 for inter-domain
1796                    trust tickets. We don't yet know what this means, but we do
1797                    seem to need to treat it as unspecified */
1798                 if (flags & SDB_F_KVNO_SPECIFIED) {
1799                         krbtgt_number = SAMBA_KVNO_GET_KRBTGT(kvno);
1800                         if (kdc_db_ctx->rodc) {
1801                                 if (krbtgt_number != kdc_db_ctx->my_krbtgt_number) {
1802                                         return SDB_ERR_NOT_FOUND_HERE;
1803                                 }
1804                         }
1805                 } else {
1806                         krbtgt_number = kdc_db_ctx->my_krbtgt_number;
1807                 }
1808
1809                 if (krbtgt_number == kdc_db_ctx->my_krbtgt_number) {
1810                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1811                                                &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
1812                                                krbtgt_attrs, DSDB_SEARCH_NO_GLOBAL_CATALOG,
1813                                                "(objectClass=user)");
1814                 } else {
1815                         /* We need to look up an RODC krbtgt (perhaps
1816                          * ours, if we are an RODC, perhaps another
1817                          * RODC if we are a read-write DC */
1818                         lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1819                                                &msg, realm_dn, LDB_SCOPE_SUBTREE,
1820                                                krbtgt_attrs,
1821                                                DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1822                                                "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=%u))", (unsigned)(krbtgt_number));
1823                 }
1824
1825                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1826                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1827                                    (unsigned)(krbtgt_number));
1828                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
1829                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1830                                                (unsigned)(krbtgt_number));
1831                         return SDB_ERR_NOENTRY;
1832                 } else if (lret != LDB_SUCCESS) {
1833                         krb5_warnx(context, "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1834                                    (unsigned)(krbtgt_number));
1835                         krb5_set_error_message(context, SDB_ERR_NOENTRY,
1836                                                "samba_kdc_fetch: could not find KRBTGT number %u in DB!",
1837                                                (unsigned)(krbtgt_number));
1838                         return SDB_ERR_NOENTRY;
1839                 }
1840
1841                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1842                                               principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1843                                               flags, realm_dn, msg, entry_ex);
1844                 if (ret != 0) {
1845                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1846                 }
1847                 return ret;
1848
1849         } else {
1850                 enum trust_direction direction = UNKNOWN;
1851                 const char *realm = NULL;
1852
1853                 /* Either an inbound or outbound trust */
1854
1855                 if (strcasecmp(lpcfg_realm(lp_ctx), realm_from_princ) == 0) {
1856                         /* look for inbound trust */
1857                         direction = INBOUND;
1858                         realm = realm_princ_comp;
1859                 } else if (principal_comp_strcasecmp(context, principal, 1, lpcfg_realm(lp_ctx)) == 0) {
1860                         /* look for outbound trust */
1861                         direction = OUTBOUND;
1862                         realm = realm_from_princ;
1863                 } else {
1864                         krb5_warnx(context, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1865                                    realm_from_princ,
1866                                    realm_princ_comp);
1867                         krb5_set_error_message(context, SDB_ERR_NOENTRY, "samba_kdc_fetch: not our realm for trusts ('%s', '%s')",
1868                                                realm_from_princ,
1869                                                realm_princ_comp);
1870                         return SDB_ERR_NOENTRY;
1871                 }
1872
1873                 /* Trusted domains are under CN=system */
1874
1875                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1876                                        mem_ctx,
1877                                        realm, realm_dn, &msg);
1878
1879                 if (ret != 0) {
1880                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1881                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1882                         return ret;
1883                 }
1884
1885                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1886                                                     principal, direction,
1887                                                     realm_dn, flags, kvno, msg, entry_ex);
1888                 if (ret != 0) {
1889                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed for %s",
1890                                    ldb_dn_get_linearized(msg->dn));
1891                         krb5_set_error_message(context, ret, "samba_kdc_fetch: "
1892                                                "trust_message2entry failed for %s",
1893                                                ldb_dn_get_linearized(msg->dn));
1894                 }
1895                 return ret;
1896         }
1897
1898 }
1899
1900 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1901                                                struct samba_kdc_db_context *kdc_db_ctx,
1902                                                TALLOC_CTX *mem_ctx,
1903                                                krb5_const_principal principal,
1904                                                unsigned flags,
1905                                                const char **attrs,
1906                                                struct ldb_dn **realm_dn,
1907                                                struct ldb_message **msg)
1908 {
1909         krb5_error_code ret;
1910         if ((smb_krb5_principal_get_type(context, principal) != KRB5_NT_ENTERPRISE_PRINCIPAL)
1911             && krb5_princ_size(context, principal) >= 2) {
1912                 /* 'normal server' case */
1913                 int ldb_ret;
1914                 NTSTATUS nt_status;
1915                 struct ldb_dn *user_dn;
1916                 char *principal_string;
1917
1918                 ret = krb5_unparse_name_flags(context, principal,
1919                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1920                                               &principal_string);
1921                 if (ret != 0) {
1922                         return ret;
1923                 }
1924
1925                 /* At this point we may find the host is known to be
1926                  * in a different realm, so we should generate a
1927                  * referral instead */
1928                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1929                                                          mem_ctx, principal_string,
1930                                                          &user_dn, realm_dn);
1931                 free(principal_string);
1932
1933                 if (!NT_STATUS_IS_OK(nt_status)) {
1934                         return SDB_ERR_NOENTRY;
1935                 }
1936
1937                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1938                                           mem_ctx,
1939                                           msg, user_dn, LDB_SCOPE_BASE,
1940                                           attrs,
1941                                           DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
1942                                           "(objectClass=*)");
1943                 if (ldb_ret != LDB_SUCCESS) {
1944                         return SDB_ERR_NOENTRY;
1945                 }
1946                 return 0;
1947         } else if (!(flags & SDB_F_FOR_AS_REQ)
1948                    && smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1949                 /*
1950                  * The behaviour of accepting an
1951                  * KRB5_NT_ENTERPRISE_PRINCIPAL server principal
1952                  * containing a UPN only applies to TGS-REQ packets,
1953                  * not AS-REQ packets.
1954                  */
1955                 return samba_kdc_lookup_client(context, kdc_db_ctx,
1956                                                mem_ctx, principal, attrs,
1957                                                realm_dn, msg);
1958         } else {
1959                 /*
1960                  * This case is for:
1961                  *  - the AS-REQ, where we only accept
1962                  *    samAccountName based lookups for the server, no
1963                  *    matter if the name is an
1964                  *    KRB5_NT_ENTERPRISE_PRINCIPAL or not
1965                  *  - for the TGS-REQ when we are not given an
1966                  *    KRB5_NT_ENTERPRISE_PRINCIPAL, which also must
1967                  *    only lookup samAccountName based names.
1968                  */
1969                 int lret;
1970                 char *short_princ;
1971                 krb5_principal enterprise_principal = NULL;
1972                 krb5_const_principal used_principal = NULL;
1973                 char *name1 = NULL;
1974                 size_t len1 = 0;
1975                 char *filter = NULL;
1976
1977                 if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1978                         char *str = NULL;
1979                         /* Need to reparse the enterprise principal to find the real target */
1980                         if (krb5_princ_size(context, principal) != 1) {
1981                                 ret = KRB5_PARSE_MALFORMED;
1982                                 krb5_set_error_message(context, ret, "samba_kdc_lookup_server: request for an "
1983                                                        "enterprise principal with wrong (%d) number of components",
1984                                                        krb5_princ_size(context, principal));
1985                                 return ret;
1986                         }
1987                         str = smb_krb5_principal_get_comp_string(mem_ctx, context, principal, 0);
1988                         if (str == NULL) {
1989                                 return KRB5_PARSE_MALFORMED;
1990                         }
1991                         ret = krb5_parse_name(context, str,
1992                                               &enterprise_principal);
1993                         talloc_free(str);
1994                         if (ret) {
1995                                 return ret;
1996                         }
1997                         used_principal = enterprise_principal;
1998                 } else {
1999                         used_principal = principal;
2000                 }
2001
2002                 /* server as client principal case, but we must not lookup userPrincipalNames */
2003                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
2004
2005                 /* TODO: Check if it is our realm, otherwise give referral */
2006
2007                 ret = krb5_unparse_name_flags(context, used_principal,
2008                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM |
2009                                               KRB5_PRINCIPAL_UNPARSE_DISPLAY,
2010                                               &short_princ);
2011                 used_principal = NULL;
2012                 krb5_free_principal(context, enterprise_principal);
2013                 enterprise_principal = NULL;
2014
2015                 if (ret != 0) {
2016                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
2017                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
2018                         return ret;
2019                 }
2020
2021                 name1 = ldb_binary_encode_string(mem_ctx, short_princ);
2022                 SAFE_FREE(short_princ);
2023                 if (name1 == NULL) {
2024                         return ENOMEM;
2025                 }
2026                 len1 = strlen(name1);
2027                 if (len1 >= 1 && name1[len1 - 1] != '$') {
2028                         filter = talloc_asprintf(mem_ctx,
2029                                         "(&(objectClass=user)(|(samAccountName=%s)(samAccountName=%s$)))",
2030                                         name1, name1);
2031                         if (filter == NULL) {
2032                                 return ENOMEM;
2033                         }
2034                 } else {
2035                         filter = talloc_asprintf(mem_ctx,
2036                                         "(&(objectClass=user)(samAccountName=%s))",
2037                                         name1);
2038                         if (filter == NULL) {
2039                                 return ENOMEM;
2040                         }
2041                 }
2042
2043                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
2044                                        *realm_dn, LDB_SCOPE_SUBTREE,
2045                                        attrs,
2046                                        DSDB_SEARCH_SHOW_EXTENDED_DN | DSDB_SEARCH_NO_GLOBAL_CATALOG,
2047                                        "%s", filter);
2048                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
2049                         DEBUG(10, ("Failed to find an entry for %s filter:%s\n",
2050                                   name1, filter));
2051                         return SDB_ERR_NOENTRY;
2052                 }
2053                 if (lret == LDB_ERR_CONSTRAINT_VIOLATION) {
2054                         DEBUG(10, ("Failed to find unique entry for %s filter:%s\n",
2055                                   name1, filter));
2056                         return SDB_ERR_NOENTRY;
2057                 }
2058                 if (lret != LDB_SUCCESS) {
2059                         DEBUG(0, ("Failed single search for %s - %s\n",
2060                                   name1, ldb_errstring(kdc_db_ctx->samdb)));
2061                         return SDB_ERR_NOENTRY;
2062                 }
2063                 return 0;
2064         }
2065         return SDB_ERR_NOENTRY;
2066 }
2067
2068
2069
2070 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
2071                                               struct samba_kdc_db_context *kdc_db_ctx,
2072                                               TALLOC_CTX *mem_ctx,
2073                                               krb5_const_principal principal,
2074                                               unsigned flags,
2075                                               struct sdb_entry_ex *entry_ex)
2076 {
2077         krb5_error_code ret;
2078         struct ldb_dn *realm_dn;
2079         struct ldb_message *msg;
2080
2081         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
2082                                       flags, server_attrs, &realm_dn, &msg);
2083         if (ret != 0) {
2084                 return ret;
2085         }
2086
2087         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2088                                       principal, SAMBA_KDC_ENT_TYPE_SERVER,
2089                                       flags,
2090                                       realm_dn, msg, entry_ex);
2091         if (ret != 0) {
2092                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
2093         }
2094
2095         return ret;
2096 }
2097
2098 static krb5_error_code samba_kdc_lookup_realm(krb5_context context,
2099                                               struct samba_kdc_db_context *kdc_db_ctx,
2100                                               TALLOC_CTX *mem_ctx,
2101                                               krb5_const_principal principal,
2102                                               unsigned flags,
2103                                               struct sdb_entry_ex *entry_ex)
2104 {
2105         TALLOC_CTX *frame = talloc_stackframe();
2106         NTSTATUS status;
2107         krb5_error_code ret;
2108         char *_realm = NULL;
2109         bool check_realm = false;
2110         const char *realm = NULL;
2111         struct dsdb_trust_routing_table *trt = NULL;
2112         const struct lsa_TrustDomainInfoInfoEx *tdo = NULL;
2113         unsigned int num_comp;
2114         bool ok;
2115         char *upper = NULL;
2116
2117         num_comp = krb5_princ_size(context, principal);
2118
2119         if (flags & SDB_F_GET_CLIENT) {
2120                 if (flags & SDB_F_FOR_AS_REQ) {
2121                         check_realm = true;
2122                 }
2123         }
2124         if (flags & SDB_F_GET_SERVER) {
2125                 if (flags & SDB_F_FOR_TGS_REQ) {
2126                         check_realm = true;
2127                 }
2128         }
2129
2130         if (!check_realm) {
2131                 TALLOC_FREE(frame);
2132                 return 0;
2133         }
2134
2135         _realm = smb_krb5_principal_get_realm(context, principal);
2136         if (_realm == NULL) {
2137                 TALLOC_FREE(frame);
2138                 return ENOMEM;
2139         }
2140
2141         /*
2142          * The requested realm needs to be our own
2143          */
2144         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, _realm);
2145         if (!ok) {
2146                 /*
2147                  * The request is not for us...
2148                  */
2149                 SAFE_FREE(_realm);
2150                 TALLOC_FREE(frame);
2151                 return SDB_ERR_NOENTRY;
2152         }
2153
2154         realm = talloc_strdup(frame, _realm);
2155         SAFE_FREE(_realm);
2156         if (realm == NULL) {
2157                 TALLOC_FREE(frame);
2158                 return ENOMEM;
2159         }
2160
2161         if (smb_krb5_principal_get_type(context, principal) == KRB5_NT_ENTERPRISE_PRINCIPAL) {
2162                 char *principal_string = NULL;
2163                 krb5_principal enterprise_principal = NULL;
2164                 char *enterprise_realm = NULL;
2165
2166                 if (num_comp != 1) {
2167                         TALLOC_FREE(frame);
2168                         return SDB_ERR_NOENTRY;
2169                 }
2170
2171                 principal_string = smb_krb5_principal_get_comp_string(frame, context,
2172                                                                       principal, 0);
2173                 if (principal_string == NULL) {
2174                         TALLOC_FREE(frame);
2175                         return ENOMEM;
2176                 }
2177
2178                 ret = krb5_parse_name(context, principal_string,
2179                                       &enterprise_principal);
2180                 TALLOC_FREE(principal_string);
2181                 if (ret) {
2182                         TALLOC_FREE(frame);
2183                         return ret;
2184                 }
2185
2186                 enterprise_realm = smb_krb5_principal_get_realm(context,
2187                                                         enterprise_principal);
2188                 krb5_free_principal(context, enterprise_principal);
2189                 if (enterprise_realm != NULL) {
2190                         realm = talloc_strdup(frame, enterprise_realm);
2191                         SAFE_FREE(enterprise_realm);
2192                         if (realm == NULL) {
2193                                 TALLOC_FREE(frame);
2194                                 return ENOMEM;
2195                         }
2196                 }
2197         }
2198
2199         if (flags & SDB_F_GET_SERVER) {
2200                 char *service_realm = NULL;
2201
2202                 ret = principal_comp_strcmp(context, principal, 0, KRB5_TGS_NAME);
2203                 if (ret == 0) {
2204                         /*
2205                          * we need to search krbtgt/ locally
2206                          */
2207                         TALLOC_FREE(frame);
2208                         return 0;
2209                 }
2210
2211                 /*
2212                  * We need to check the last component against the routing table.
2213                  *
2214                  * Note this works only with 2 or 3 component principals, e.g:
2215                  *
2216                  * servicePrincipalName: ldap/W2K8R2-219.bla.base
2217                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/bla.base
2218                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/ForestDnsZones.bla.base
2219                  * servicePrincipalName: ldap/W2K8R2-219.bla.base/DomainDnsZones.bla.base
2220                  */
2221
2222                 if (num_comp == 2 || num_comp == 3) {
2223                         service_realm = smb_krb5_principal_get_comp_string(frame,
2224                                                                            context,
2225                                                                            principal,
2226                                                                            num_comp - 1);
2227                 }
2228
2229                 if (service_realm != NULL) {
2230                         realm = service_realm;
2231                 }
2232         }
2233
2234         ok = lpcfg_is_my_domain_or_realm(kdc_db_ctx->lp_ctx, realm);
2235         if (ok) {
2236                 /*
2237                  * skip the expensive routing lookup
2238                  */
2239                 TALLOC_FREE(frame);
2240                 return 0;
2241         }
2242
2243         status = dsdb_trust_routing_table_load(kdc_db_ctx->samdb,
2244                                                frame, &trt);
2245         if (!NT_STATUS_IS_OK(status)) {
2246                 TALLOC_FREE(frame);
2247                 return EINVAL;
2248         }
2249
2250         tdo = dsdb_trust_routing_by_name(trt, realm);
2251         if (tdo == NULL) {
2252                 /*
2253                  * This principal has to be local
2254                  */
2255                 TALLOC_FREE(frame);
2256                 return 0;
2257         }
2258
2259         if (tdo->trust_attributes & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST) {
2260                 /*
2261                  * TODO: handle the routing within the forest
2262                  *
2263                  * This should likely be handled in
2264                  * samba_kdc_message2entry() in case we're
2265                  * a global catalog. We'd need to check
2266                  * if realm_dn is our own domain and derive
2267                  * the dns domain name from realm_dn and check that
2268                  * against the routing table or fallback to
2269                  * the tdo we found here.
2270                  *
2271                  * But for now we don't support multiple domains
2272                  * in our forest correctly anyway.
2273                  *
2274                  * Just search in our local database.
2275                  */
2276                 TALLOC_FREE(frame);
2277                 return 0;
2278         }
2279
2280         ZERO_STRUCT(entry_ex->entry);
2281
2282         ret = krb5_copy_principal(context, principal,
2283                                   &entry_ex->entry.principal);
2284         if (ret) {
2285                 TALLOC_FREE(frame);
2286                 return ret;
2287         }
2288
2289         upper = strupper_talloc(frame, tdo->domain_name.string);
2290         if (upper == NULL) {
2291                 TALLOC_FREE(frame);
2292                 return ENOMEM;
2293         }
2294
2295         ret = smb_krb5_principal_set_realm(context,
2296                                            entry_ex->entry.principal,
2297                                            upper);
2298         if (ret) {
2299                 TALLOC_FREE(frame);
2300                 return ret;
2301         }
2302
2303         TALLOC_FREE(frame);
2304         return SDB_ERR_WRONG_REALM;
2305 }
2306
2307 krb5_error_code samba_kdc_fetch(krb5_context context,
2308                                 struct samba_kdc_db_context *kdc_db_ctx,
2309                                 krb5_const_principal principal,
2310                                 unsigned flags,
2311                                 krb5_kvno kvno,
2312                                 struct sdb_entry_ex *entry_ex)
2313 {
2314         krb5_error_code ret = SDB_ERR_NOENTRY;
2315         TALLOC_CTX *mem_ctx;
2316
2317         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
2318         if (!mem_ctx) {
2319                 ret = ENOMEM;
2320                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2321                 return ret;
2322         }
2323
2324         ret = samba_kdc_lookup_realm(context, kdc_db_ctx, mem_ctx,
2325                                      principal, flags, entry_ex);
2326         if (ret != 0) {
2327                 goto done;
2328         }
2329
2330         ret = SDB_ERR_NOENTRY;
2331
2332         if (flags & SDB_F_GET_CLIENT) {
2333                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2334                 if (ret != SDB_ERR_NOENTRY) goto done;
2335         }
2336         if (flags & SDB_F_GET_SERVER) {
2337                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
2338                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2339                 if (ret != SDB_ERR_NOENTRY) goto done;
2340
2341                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
2342                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, flags, entry_ex);
2343                 if (ret != SDB_ERR_NOENTRY) goto done;
2344         }
2345         if (flags & SDB_F_GET_KRBTGT) {
2346                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, flags, kvno, entry_ex);
2347                 if (ret != SDB_ERR_NOENTRY) goto done;
2348         }
2349
2350 done:
2351         talloc_free(mem_ctx);
2352         return ret;
2353 }
2354
2355 struct samba_kdc_seq {
2356         unsigned int index;
2357         unsigned int count;
2358         struct ldb_message **msgs;
2359         struct ldb_dn *realm_dn;
2360 };
2361
2362 static krb5_error_code samba_kdc_seq(krb5_context context,
2363                                      struct samba_kdc_db_context *kdc_db_ctx,
2364                                      struct sdb_entry_ex *entry)
2365 {
2366         krb5_error_code ret;
2367         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2368         const char *realm = lpcfg_realm(kdc_db_ctx->lp_ctx);
2369         struct ldb_message *msg = NULL;
2370         const char *sAMAccountName = NULL;
2371         krb5_principal principal = NULL;
2372         TALLOC_CTX *mem_ctx;
2373
2374         if (!priv) {
2375                 return SDB_ERR_NOENTRY;
2376         }
2377
2378         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
2379
2380         if (!mem_ctx) {
2381                 ret = ENOMEM;
2382                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
2383                 return ret;
2384         }
2385
2386         while (priv->index < priv->count) {
2387                 msg = priv->msgs[priv->index++];
2388
2389                 sAMAccountName = ldb_msg_find_attr_as_string(msg, "sAMAccountName", NULL);
2390                 if (sAMAccountName != NULL) {
2391                         break;
2392                 }
2393         }
2394
2395         if (sAMAccountName == NULL) {
2396                 ret = SDB_ERR_NOENTRY;
2397                 goto out;
2398         }
2399
2400         ret = smb_krb5_make_principal(context, &principal,
2401                                       realm, sAMAccountName, NULL);
2402         if (ret != 0) {
2403                 goto out;
2404         }
2405
2406         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
2407                                       principal, SAMBA_KDC_ENT_TYPE_ANY,
2408                                       SDB_F_ADMIN_DATA|SDB_F_GET_ANY,
2409                                       priv->realm_dn, msg, entry);
2410
2411 out:
2412         if (principal != NULL) {
2413                 krb5_free_principal(context, principal);
2414         }
2415
2416         if (ret != 0) {
2417                 TALLOC_FREE(priv);
2418                 kdc_db_ctx->seq_ctx = NULL;
2419         } else {
2420                 talloc_free(mem_ctx);
2421         }
2422
2423         return ret;
2424 }
2425
2426 krb5_error_code samba_kdc_firstkey(krb5_context context,
2427                                    struct samba_kdc_db_context *kdc_db_ctx,
2428                                    struct sdb_entry_ex *entry)
2429 {
2430         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
2431         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
2432         char *realm;
2433         struct ldb_result *res = NULL;
2434         krb5_error_code ret;
2435         TALLOC_CTX *mem_ctx;
2436         int lret;
2437
2438         if (priv) {
2439                 TALLOC_FREE(priv);
2440                 kdc_db_ctx->seq_ctx = NULL;
2441         }
2442
2443         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
2444         if (!priv) {
2445                 ret = ENOMEM;
2446                 krb5_set_error_message(context, ret, "talloc: out of memory");
2447                 return ret;
2448         }
2449
2450         priv->index = 0;
2451         priv->msgs = NULL;
2452         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
2453         priv->count = 0;
2454
2455         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
2456
2457         if (!mem_ctx) {
2458                 ret = ENOMEM;
2459                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
2460                 return ret;
2461         }
2462
2463         ret = krb5_get_default_realm(context, &realm);
2464         if (ret != 0) {
2465                 TALLOC_FREE(priv);
2466                 return ret;
2467         }
2468         krb5_free_default_realm(context, realm);
2469
2470         lret = dsdb_search(ldb_ctx, priv, &res,
2471                            priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
2472                            DSDB_SEARCH_NO_GLOBAL_CATALOG,
2473                            "(objectClass=user)");
2474
2475         if (lret != LDB_SUCCESS) {
2476                 TALLOC_FREE(priv);
2477                 return SDB_ERR_NOENTRY;
2478         }
2479
2480         priv->count = res->count;
2481         priv->msgs = talloc_steal(priv, res->msgs);
2482         talloc_free(res);
2483
2484         kdc_db_ctx->seq_ctx = priv;
2485
2486         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
2487
2488         if (ret != 0) {
2489                 TALLOC_FREE(priv);
2490                 kdc_db_ctx->seq_ctx = NULL;
2491         } else {
2492                 talloc_free(mem_ctx);
2493         }
2494         return ret;
2495 }
2496
2497 krb5_error_code samba_kdc_nextkey(krb5_context context,
2498                                   struct samba_kdc_db_context *kdc_db_ctx,
2499                                   struct sdb_entry_ex *entry)
2500 {
2501         return samba_kdc_seq(context, kdc_db_ctx, entry);
2502 }
2503
2504 /* Check if a given entry may delegate or do s4u2self to this target principal
2505  *
2506  * This is currently a very nasty hack - allowing only delegation to itself.
2507  */
2508 krb5_error_code
2509 samba_kdc_check_s4u2self(krb5_context context,
2510                          struct samba_kdc_db_context *kdc_db_ctx,
2511                          struct samba_kdc_entry *skdc_entry,
2512                          krb5_const_principal target_principal)
2513 {
2514         krb5_error_code ret;
2515         struct ldb_dn *realm_dn;
2516         struct ldb_message *msg;
2517         struct dom_sid *orig_sid;
2518         struct dom_sid *target_sid;
2519         const char *delegation_check_attrs[] = {
2520                 "objectSid", NULL
2521         };
2522
2523         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2self");
2524
2525         if (!mem_ctx) {
2526                 ret = ENOMEM;
2527                 krb5_set_error_message(context, ret, "samba_kdc_check_s4u2self: talloc_named() failed!");
2528                 return ret;
2529         }
2530
2531         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
2532                                       SDB_F_GET_CLIENT|SDB_F_GET_SERVER,
2533                                       delegation_check_attrs, &realm_dn, &msg);
2534
2535         if (ret != 0) {
2536                 talloc_free(mem_ctx);
2537                 return ret;
2538         }
2539
2540         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2541         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2542
2543         /* Allow delegation to the same principal, even if by a different
2544          * name.  The easy and safe way to prove this is by SID
2545          * comparison */
2546         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2547                 talloc_free(mem_ctx);
2548                 return KRB5KDC_ERR_BADOPTION;
2549         }
2550
2551         talloc_free(mem_ctx);
2552         return ret;
2553 }
2554
2555 /* Certificates printed by a the Certificate Authority might have a
2556  * slightly different form of the user principal name to that in the
2557  * database.  Allow a mismatch where they both refer to the same
2558  * SID */
2559
2560 krb5_error_code
2561 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
2562                                     struct samba_kdc_db_context *kdc_db_ctx,
2563                                     struct samba_kdc_entry *skdc_entry,
2564                                      krb5_const_principal certificate_principal)
2565 {
2566         krb5_error_code ret;
2567         struct ldb_dn *realm_dn;
2568         struct ldb_message *msg;
2569         struct dom_sid *orig_sid;
2570         struct dom_sid *target_sid;
2571         const char *ms_upn_check_attrs[] = {
2572                 "objectSid", NULL
2573         };
2574
2575         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
2576
2577         if (!mem_ctx) {
2578                 ret = ENOMEM;
2579                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
2580                 return ret;
2581         }
2582
2583         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
2584                                       mem_ctx, certificate_principal,
2585                                       ms_upn_check_attrs, &realm_dn, &msg);
2586
2587         if (ret != 0) {
2588                 talloc_free(mem_ctx);
2589                 return ret;
2590         }
2591
2592         orig_sid = samdb_result_dom_sid(mem_ctx, skdc_entry->msg, "objectSid");
2593         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
2594
2595         /* Consider these to be the same principal, even if by a different
2596          * name.  The easy and safe way to prove this is by SID
2597          * comparison */
2598         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
2599                 talloc_free(mem_ctx);
2600 #ifdef KRB5_KDC_ERR_CLIENT_NAME_MISMATCH /* Heimdal */
2601                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
2602 #elif defined(KRB5KDC_ERR_CLIENT_NAME_MISMATCH) /* MIT */
2603                 return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
2604 #endif
2605         }
2606
2607         talloc_free(mem_ctx);
2608         return ret;
2609 }
2610
2611 /*
2612  * Check if a given entry may delegate to this target principal
2613  * with S4U2Proxy.
2614  */
2615 krb5_error_code
2616 samba_kdc_check_s4u2proxy(krb5_context context,
2617                           struct samba_kdc_db_context *kdc_db_ctx,
2618                           struct samba_kdc_entry *skdc_entry,
2619                           krb5_const_principal target_principal)
2620 {
2621         krb5_error_code ret;
2622         char *tmp = NULL;
2623         const char *client_dn = NULL;
2624         const char *target_principal_name = NULL;
2625         struct ldb_message_element *el;
2626         struct ldb_val val;
2627         unsigned int i;
2628         bool found = false;
2629
2630         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_s4u2proxy");
2631
2632         if (!mem_ctx) {
2633                 ret = ENOMEM;
2634                 krb5_set_error_message(context, ret,
2635                                        "samba_kdc_check_s4u2proxy:"
2636                                        " talloc_named() failed!");
2637                 return ret;
2638         }
2639
2640         client_dn = ldb_dn_get_linearized(skdc_entry->msg->dn);
2641         if (!client_dn) {
2642                 if (errno == 0) {
2643                         errno = ENOMEM;
2644                 }
2645                 ret = errno;
2646                 krb5_set_error_message(context, ret,
2647                                        "samba_kdc_check_s4u2proxy:"
2648                                        " ldb_dn_get_linearized() failed!");
2649                 return ret;
2650         }
2651
2652         /*
2653          * The main heimdal code already checked that the target_principal
2654          * belongs to the same realm as the client.
2655          *
2656          * So we just need the principal without the realm,
2657          * as that is what is configured in the "msDS-AllowedToDelegateTo"
2658          * attribute.
2659          */
2660         ret = krb5_unparse_name_flags(context, target_principal,
2661                                       KRB5_PRINCIPAL_UNPARSE_NO_REALM, &tmp);
2662         if (ret) {
2663                 talloc_free(mem_ctx);
2664                 krb5_set_error_message(context, ret,
2665                                        "samba_kdc_check_s4u2proxy:"
2666                                        " krb5_unparse_name() failed!");
2667                 return ret;
2668         }
2669         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] for target[%s]\n",
2670                  client_dn, tmp));
2671
2672         target_principal_name = talloc_strdup(mem_ctx, tmp);
2673         SAFE_FREE(tmp);
2674         if (target_principal_name == NULL) {
2675                 ret = ENOMEM;
2676                 krb5_set_error_message(context, ret,
2677                                        "samba_kdc_check_s4u2proxy:"
2678                                        " talloc_strdup() failed!");
2679                 return ret;
2680         }
2681
2682         el = ldb_msg_find_element(skdc_entry->msg, "msDS-AllowedToDelegateTo");
2683         if (el == NULL) {
2684                 goto bad_option;
2685         }
2686
2687         val = data_blob_string_const(target_principal_name);
2688
2689         for (i=0; i<el->num_values; i++) {
2690                 struct ldb_val *val1 = &val;
2691                 struct ldb_val *val2 = &el->values[i];
2692                 int cmp;
2693
2694                 if (val1->length != val2->length) {
2695                         continue;
2696                 }
2697
2698                 cmp = strncasecmp((const char *)val1->data,
2699                                   (const char *)val2->data,
2700                                   val1->length);
2701                 if (cmp != 0) {
2702                         continue;
2703                 }
2704
2705                 found = true;
2706                 break;
2707         }
2708
2709         if (!found) {
2710                 goto bad_option;
2711         }
2712
2713         DEBUG(10,("samba_kdc_check_s4u2proxy: client[%s] allowed target[%s]\n",
2714                  client_dn, tmp));
2715         talloc_free(mem_ctx);
2716         return 0;
2717
2718 bad_option:
2719         krb5_set_error_message(context, ret,
2720                                "samba_kdc_check_s4u2proxy: client[%s] "
2721                                "not allowed for delegation to target[%s]",
2722                                client_dn,
2723                                target_principal_name);
2724         talloc_free(mem_ctx);
2725         return KRB5KDC_ERR_BADOPTION;
2726 }
2727
2728 NTSTATUS samba_kdc_setup_db_ctx(TALLOC_CTX *mem_ctx, struct samba_kdc_base_context *base_ctx,
2729                                 struct samba_kdc_db_context **kdc_db_ctx_out)
2730 {
2731         int ldb_ret;
2732         struct ldb_message *msg;
2733         struct auth_session_info *session_info;
2734         struct samba_kdc_db_context *kdc_db_ctx;
2735         /* The idea here is very simple.  Using Kerberos to
2736          * authenticate the KDC to the LDAP server is higly likely to
2737          * be circular.
2738          *
2739          * In future we may set this up to use EXERNAL and SSL
2740          * certificates, for now it will almost certainly be NTLMSSP_SET_USERNAME
2741         */
2742
2743         kdc_db_ctx = talloc_zero(mem_ctx, struct samba_kdc_db_context);
2744         if (kdc_db_ctx == NULL) {
2745                 return NT_STATUS_NO_MEMORY;
2746         }
2747         kdc_db_ctx->ev_ctx = base_ctx->ev_ctx;
2748         kdc_db_ctx->lp_ctx = base_ctx->lp_ctx;
2749         kdc_db_ctx->msg_ctx = base_ctx->msg_ctx;
2750
2751         /* get default kdc policy */
2752         lpcfg_default_kdc_policy(mem_ctx,
2753                                  base_ctx->lp_ctx,
2754                                  &kdc_db_ctx->policy.svc_tkt_lifetime,
2755                                  &kdc_db_ctx->policy.usr_tkt_lifetime,
2756                                  &kdc_db_ctx->policy.renewal_lifetime);
2757
2758         session_info = system_session(kdc_db_ctx->lp_ctx);
2759         if (session_info == NULL) {
2760                 return NT_STATUS_INTERNAL_ERROR;
2761         }
2762
2763         /* Setup the link to LDB */
2764         kdc_db_ctx->samdb = samdb_connect(kdc_db_ctx, base_ctx->ev_ctx,
2765                                           base_ctx->lp_ctx, session_info, 0);
2766         if (kdc_db_ctx->samdb == NULL) {
2767                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot open samdb for KDC backend!"));
2768                 talloc_free(kdc_db_ctx);
2769                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2770         }
2771
2772         /* Find out our own krbtgt kvno */
2773         ldb_ret = samdb_rodc(kdc_db_ctx->samdb, &kdc_db_ctx->rodc);
2774         if (ldb_ret != LDB_SUCCESS) {
2775                 DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine if we are an RODC in KDC backend: %s\n",
2776                           ldb_errstring(kdc_db_ctx->samdb)));
2777                 talloc_free(kdc_db_ctx);
2778                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2779         }
2780         if (kdc_db_ctx->rodc) {
2781                 int my_krbtgt_number;
2782                 const char *secondary_keytab[] = { "msDS-SecondaryKrbTgtNumber", NULL };
2783                 struct ldb_dn *account_dn;
2784                 struct ldb_dn *server_dn = samdb_server_dn(kdc_db_ctx->samdb, kdc_db_ctx);
2785                 if (!server_dn) {
2786                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server DN in KDC backend: %s\n",
2787                                   ldb_errstring(kdc_db_ctx->samdb)));
2788                         talloc_free(kdc_db_ctx);
2789                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2790                 }
2791
2792                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, server_dn,
2793                                              "serverReference", &account_dn);
2794                 if (ldb_ret != LDB_SUCCESS) {
2795                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine server account in KDC backend: %s\n",
2796                                   ldb_errstring(kdc_db_ctx->samdb)));
2797                         talloc_free(kdc_db_ctx);
2798                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2799                 }
2800
2801                 ldb_ret = samdb_reference_dn(kdc_db_ctx->samdb, kdc_db_ctx, account_dn,
2802                                              "msDS-KrbTgtLink", &kdc_db_ctx->krbtgt_dn);
2803                 talloc_free(account_dn);
2804                 if (ldb_ret != LDB_SUCCESS) {
2805                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot determine RODC krbtgt account in KDC backend: %s\n",
2806                                   ldb_errstring(kdc_db_ctx->samdb)));
2807                         talloc_free(kdc_db_ctx);
2808                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2809                 }
2810
2811                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2812                                           &msg, kdc_db_ctx->krbtgt_dn, LDB_SCOPE_BASE,
2813                                           secondary_keytab,
2814                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2815                                           "(&(objectClass=user)(msDS-SecondaryKrbTgtNumber=*))");
2816                 if (ldb_ret != LDB_SUCCESS) {
2817                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read krbtgt account %s in KDC backend to get msDS-SecondaryKrbTgtNumber: %s: %s\n",
2818                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2819                                   ldb_errstring(kdc_db_ctx->samdb),
2820                                   ldb_strerror(ldb_ret)));
2821                         talloc_free(kdc_db_ctx);
2822                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2823                 }
2824                 my_krbtgt_number = ldb_msg_find_attr_as_int(msg, "msDS-SecondaryKrbTgtNumber", -1);
2825                 if (my_krbtgt_number == -1) {
2826                         DEBUG(1, ("samba_kdc_setup_db_ctx: Cannot read msDS-SecondaryKrbTgtNumber from krbtgt account %s in KDC backend: got %d\n",
2827                                   ldb_dn_get_linearized(kdc_db_ctx->krbtgt_dn),
2828                                   my_krbtgt_number));
2829                         talloc_free(kdc_db_ctx);
2830                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2831                 }
2832                 kdc_db_ctx->my_krbtgt_number = my_krbtgt_number;
2833
2834         } else {
2835                 kdc_db_ctx->my_krbtgt_number = 0;
2836                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb, kdc_db_ctx,
2837                                           &msg,
2838                                           ldb_get_default_basedn(kdc_db_ctx->samdb),
2839                                           LDB_SCOPE_SUBTREE,
2840                                           krbtgt_attrs,
2841                                           DSDB_SEARCH_NO_GLOBAL_CATALOG,
2842                                           "(&(objectClass=user)(samAccountName=krbtgt))");
2843
2844                 if (ldb_ret != LDB_SUCCESS) {
2845                         DEBUG(1, ("samba_kdc_fetch: could not find own KRBTGT in DB: %s\n", ldb_errstring(kdc_db_ctx->samdb)));
2846                         talloc_free(kdc_db_ctx);
2847                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2848                 }
2849                 kdc_db_ctx->krbtgt_dn = talloc_steal(kdc_db_ctx, msg->dn);
2850                 kdc_db_ctx->my_krbtgt_number = 0;
2851                 talloc_free(msg);
2852         }
2853         *kdc_db_ctx_out = kdc_db_ctx;
2854         return NT_STATUS_OK;
2855 }