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