]> git.samba.org - obnox/samba/samba-obnox.git/blob - source4/kdc/db-glue.c
s4:kdc Use msDS-SupportedEncTypes in our KDC
[obnox/samba/samba-obnox.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 "system/time.h"
26 #include "../libds/common/flags.h"
27 #include "lib/ldb/include/ldb.h"
28 #include "librpc/gen_ndr/netlogon.h"
29 #include "libcli/security/security.h"
30 #include "auth/auth.h"
31 #include "auth/credentials/credentials.h"
32 #include "auth/auth_sam.h"
33 #include "../lib/util/util_ldb.h"
34 #include "dsdb/samdb/samdb.h"
35 #include "dsdb/common/util.h"
36 #include "librpc/ndr/libndr.h"
37 #include "librpc/gen_ndr/ndr_drsblobs.h"
38 #include "librpc/gen_ndr/lsa.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "param/param.h"
41 #include "../lib/crypto/md4.h"
42 #include "system/kerberos.h"
43 #include <hdb.h>
44 #include "kdc/samba_kdc.h"
45 #include "kdc/db-glue.h"
46
47 enum samba_kdc_ent_type
48 { SAMBA_KDC_ENT_TYPE_CLIENT, SAMBA_KDC_ENT_TYPE_SERVER,
49   SAMBA_KDC_ENT_TYPE_KRBTGT, SAMBA_KDC_ENT_TYPE_TRUST, SAMBA_KDC_ENT_TYPE_ANY };
50
51 enum trust_direction {
52         UNKNOWN = 0,
53         INBOUND = LSA_TRUST_DIRECTION_INBOUND,
54         OUTBOUND = LSA_TRUST_DIRECTION_OUTBOUND
55 };
56
57 static const char *trust_attrs[] = {
58         "trustPartner",
59         "trustAuthIncoming",
60         "trustAuthOutgoing",
61         "whenCreated",
62         "msDS-SupportedEncryptionTypes",
63         "trustAttributes",
64         "trustDirection",
65         "trustType",
66         NULL
67 };
68
69 static KerberosTime ldb_msg_find_krb5time_ldap_time(struct ldb_message *msg, const char *attr, KerberosTime 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, int 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.invalid = 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_NOT_DELEGATED)) {
162                 flags.forwardable = 1;
163                 flags.proxiable = 1;
164         }
165
166         if (userAccountControl & UF_DONT_REQUIRE_PREAUTH) {
167                 flags.require_preauth = 0;
168         } else {
169                 flags.require_preauth = 1;
170
171         }
172         return flags;
173 }
174
175 static int samba_kdc_entry_destructor(struct samba_kdc_entry *p)
176 {
177     hdb_entry_ex *entry_ex = p->entry_ex;
178     free_hdb_entry(&entry_ex->entry);
179     return 0;
180 }
181
182 static void samba_kdc_free_entry(krb5_context context, hdb_entry_ex *entry_ex)
183 {
184         /* this function is called only from hdb_free_entry().
185          * Make sure we neutralize the destructor or we will
186          * get a double free later when hdb_free_entry() will
187          * try to call free_hdb_entry() */
188         talloc_set_destructor(entry_ex->ctx, NULL);
189
190         /* now proceed to free the talloc part */
191         talloc_free(entry_ex->ctx);
192 }
193
194 /* Determine, by translation between the encryption types allowed in
195  * the msDS-SupportedEncTypes and their Kerberos defined values, if a
196  * given encryption type is permitted for this target principal at
197  * this time. */
198 static bool allowed_enc_type(enum samba_kdc_ent_type ent_type,
199                              uint32_t supported_enc_types_bitmap, uint32_t enc_type_enum)
200 {
201         switch (ent_type) {
202         case SAMBA_KDC_ENT_TYPE_KRBTGT:
203         case SAMBA_KDC_ENT_TYPE_TRUST:
204                 /* Disallow krbtgt and trust tickets to be DES encrypted, it's just too dangerous */
205                 supported_enc_types_bitmap &= (~ENC_CRC32|ENC_RSA_MD5);
206         case SAMBA_KDC_ENT_TYPE_SERVER:
207                 switch (enc_type_enum) {
208                 case ENCTYPE_DES_CBC_CRC:
209                         return supported_enc_types_bitmap & ENC_CRC32;
210                 case ENCTYPE_DES_CBC_MD5:
211                         return supported_enc_types_bitmap & ENC_RSA_MD5;
212                 case ENCTYPE_ARCFOUR_HMAC_MD5:
213                         return supported_enc_types_bitmap & ENC_RC4_HMAC_MD5;
214                 case ENCTYPE_AES128_CTS_HMAC_SHA1_96:
215                         return supported_enc_types_bitmap & ENC_HMAC_SHA1_96_AES128;
216                 case ENCTYPE_AES256_CTS_HMAC_SHA1_96:
217                         return supported_enc_types_bitmap & ENC_HMAC_SHA1_96_AES256;
218                 default:
219                         return false;
220                 }
221         default:
222                 return true;
223                 /* Return all enc types to everyone else */
224         }
225 }
226
227 static krb5_error_code samba_kdc_message2entry_keys(krb5_context context,
228                                                     TALLOC_CTX *mem_ctx,
229                                                     struct ldb_message *msg,
230                                                     unsigned int userAccountControl,
231                                                     enum samba_kdc_ent_type ent_type,
232                                                     hdb_entry_ex *entry_ex)
233 {
234         krb5_error_code ret = 0;
235         enum ndr_err_code ndr_err;
236         struct samr_Password *hash;
237         const struct ldb_val *sc_val;
238         struct supplementalCredentialsBlob scb;
239         struct supplementalCredentialsPackage *scpk = NULL;
240         bool newer_keys = false;
241         struct package_PrimaryKerberosBlob _pkb;
242         struct package_PrimaryKerberosCtr3 *pkb3 = NULL;
243         struct package_PrimaryKerberosCtr4 *pkb4 = NULL;
244         uint16_t i;
245         uint16_t allocated_keys = 0;
246
247         /* Supported Enc Types for TGS-REQ to this target */
248         uint32_t supported_enc_types = ldb_msg_find_attr_as_uint(msg, "msDS-SupportedEncTypes",
249                                                                  ENC_CRC32|ENC_RSA_MD5|ENC_RC4_HMAC_MD5);
250
251         /* If UF_USE_DES_KEY_ONLY has been set, then don't allow use of the newer enc types */
252         if (userAccountControl & UF_USE_DES_KEY_ONLY) {
253                 /* However, don't allow use of DES, if we were told not to by msDS-SupportedEncTypes */
254                 supported_enc_types &= ENC_CRC32|ENC_RSA_MD5;
255         }
256
257         entry_ex->entry.keys.val = NULL;
258         entry_ex->entry.keys.len = 0;
259
260         entry_ex->entry.kvno = ldb_msg_find_attr_as_int(msg, "msDS-KeyVersionNumber", 0);
261
262         /* Get keys from the db */
263
264         hash = samdb_result_hash(mem_ctx, msg, "unicodePwd");
265         sc_val = ldb_msg_find_ldb_val(msg, "supplementalCredentials");
266
267         /* unicodePwd for enctype 0x17 (23) if present */
268         if (hash) {
269                 allocated_keys++;
270         }
271
272         /* supplementalCredentials if present */
273         if (sc_val) {
274                 ndr_err = ndr_pull_struct_blob_all(sc_val, mem_ctx, &scb,
275                                                    (ndr_pull_flags_fn_t)ndr_pull_supplementalCredentialsBlob);
276                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
277                         dump_data(0, sc_val->data, sc_val->length);
278                         ret = EINVAL;
279                         goto out;
280                 }
281
282                 if (scb.sub.signature != SUPPLEMENTAL_CREDENTIALS_SIGNATURE) {
283                         NDR_PRINT_DEBUG(supplementalCredentialsBlob, &scb);
284                         ret = EINVAL;
285                         goto out;
286                 }
287
288                 for (i=0; i < scb.sub.num_packages; i++) {
289                         if (strcmp("Primary:Kerberos-Newer-Keys", scb.sub.packages[i].name) == 0) {
290                                 scpk = &scb.sub.packages[i];
291                                 if (!scpk->data || !scpk->data[0]) {
292                                         scpk = NULL;
293                                         continue;
294                                 }
295                                 newer_keys = true;
296                                 break;
297                         } else if (strcmp("Primary:Kerberos", scb.sub.packages[i].name) == 0) {
298                                 scpk = &scb.sub.packages[i];
299                                 if (!scpk->data || !scpk->data[0]) {
300                                         scpk = NULL;
301                                 }
302                                 /*
303                                  * we don't break here in hope to find
304                                  * a Kerberos-Newer-Keys package
305                                  */
306                         }
307                 }
308         }
309         /*
310          * Primary:Kerberos-Newer-Keys or Primary:Kerberos element
311          * of supplementalCredentials
312          */
313         if (scpk) {
314                 DATA_BLOB blob;
315
316                 blob = strhex_to_data_blob(mem_ctx, scpk->data);
317                 if (!blob.data) {
318                         ret = ENOMEM;
319                         goto out;
320                 }
321
322                 /* we cannot use ndr_pull_struct_blob_all() here, as w2k and w2k3 add padding bytes */
323                 ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, &_pkb,
324                                                (ndr_pull_flags_fn_t)ndr_pull_package_PrimaryKerberosBlob);
325                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
326                         ret = EINVAL;
327                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
328                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse package_PrimaryKerberosBlob");
329                         goto out;
330                 }
331
332                 if (newer_keys && _pkb.version != 4) {
333                         ret = EINVAL;
334                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
335                         krb5_warnx(context, "samba_kdc_message2entry_keys: Primary:Kerberos-Newer-Keys not version 4");
336                         goto out;
337                 }
338
339                 if (!newer_keys && _pkb.version != 3) {
340                         ret = EINVAL;
341                         krb5_set_error_message(context, ret, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
342                         krb5_warnx(context, "samba_kdc_message2entry_keys: could not parse Primary:Kerberos not version 3");
343                         goto out;
344                 }
345
346                 if (_pkb.version == 4) {
347                         pkb4 = &_pkb.ctr.ctr4;
348                         allocated_keys += pkb4->num_keys;
349                 } else if (_pkb.version == 3) {
350                         pkb3 = &_pkb.ctr.ctr3;
351                         allocated_keys += pkb3->num_keys;
352                 }
353         }
354
355         if (allocated_keys == 0) {
356                 /* oh, no password.  Apparently (comment in
357                  * hdb-ldap.c) this violates the ASN.1, but this
358                  * allows an entry with no keys (yet). */
359                 return 0;
360         }
361
362         /* allocate space to decode into */
363         entry_ex->entry.keys.len = 0;
364         entry_ex->entry.keys.val = calloc(allocated_keys, sizeof(Key));
365         if (entry_ex->entry.keys.val == NULL) {
366                 ret = ENOMEM;
367                 goto out;
368         }
369
370         if (hash && supported_enc_types & ENC_RC4_HMAC_MD5) {
371                 Key key;
372
373                 key.mkvno = 0;
374                 key.salt = NULL; /* No salt for this enc type */
375
376                 ret = krb5_keyblock_init(context,
377                                          ENCTYPE_ARCFOUR_HMAC,
378                                          hash->hash, sizeof(hash->hash),
379                                          &key.key);
380                 if (ret) {
381                         goto out;
382                 }
383
384                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
385                 entry_ex->entry.keys.len++;
386         }
387
388         if (pkb4) {
389                 for (i=0; i < pkb4->num_keys; i++) {
390                         Key key;
391
392                         if (!pkb4->keys[i].value) continue;
393
394                         if (!allowed_enc_type(ent_type, supported_enc_types, pkb4->keys[i].keytype)) {
395                                 continue;
396                         }
397
398                         key.mkvno = 0;
399                         key.salt = NULL;
400
401                         if (pkb4->salt.string) {
402                                 DATA_BLOB salt;
403
404                                 salt = data_blob_string_const(pkb4->salt.string);
405
406                                 key.salt = calloc(1, sizeof(*key.salt));
407                                 if (key.salt == NULL) {
408                                         ret = ENOMEM;
409                                         goto out;
410                                 }
411
412                                 key.salt->type = hdb_pw_salt;
413
414                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
415                                 if (ret) {
416                                         free(key.salt);
417                                         key.salt = NULL;
418                                         goto out;
419                                 }
420                         }
421
422                         /* TODO: maybe pass the iteration_count somehow... */
423
424                         ret = krb5_keyblock_init(context,
425                                                  pkb4->keys[i].keytype,
426                                                  pkb4->keys[i].value->data,
427                                                  pkb4->keys[i].value->length,
428                                                  &key.key);
429                         if (ret == KRB5_PROG_ETYPE_NOSUPP) {
430                                 DEBUG(2,("Unsupported keytype ignored - type %u\n",
431                                          pkb4->keys[i].keytype));
432                                 ret = 0;
433                                 continue;
434                         }
435                         if (ret) {
436                                 if (key.salt) {
437                                         free_Salt(key.salt);
438                                         free(key.salt);
439                                         key.salt = NULL;
440                                 }
441                                 goto out;
442                         }
443
444                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
445                         entry_ex->entry.keys.len++;
446                 }
447         } else if (pkb3) {
448                 for (i=0; i < pkb3->num_keys; i++) {
449                         Key key;
450
451                         if (!pkb3->keys[i].value) continue;
452
453                         if (!allowed_enc_type(ent_type, supported_enc_types, pkb3->keys[i].keytype)) {
454                                 continue;
455                         }
456
457                         key.mkvno = 0;
458                         key.salt = NULL;
459
460                         if (pkb3->salt.string) {
461                                 DATA_BLOB salt;
462
463                                 salt = data_blob_string_const(pkb3->salt.string);
464
465                                 key.salt = calloc(1, sizeof(*key.salt));
466                                 if (key.salt == NULL) {
467                                         ret = ENOMEM;
468                                         goto out;
469                                 }
470
471                                 key.salt->type = hdb_pw_salt;
472
473                                 ret = krb5_data_copy(&key.salt->salt, salt.data, salt.length);
474                                 if (ret) {
475                                         free(key.salt);
476                                         key.salt = NULL;
477                                         goto out;
478                                 }
479                         }
480
481                         ret = krb5_keyblock_init(context,
482                                                  pkb3->keys[i].keytype,
483                                                  pkb3->keys[i].value->data,
484                                                  pkb3->keys[i].value->length,
485                                                  &key.key);
486                         if (ret) {
487                                 if (key.salt) {
488                                         free_Salt(key.salt);
489                                         free(key.salt);
490                                         key.salt = NULL;
491                                 }
492                                 goto out;
493                         }
494
495                         entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
496                         entry_ex->entry.keys.len++;
497                 }
498         }
499
500 out:
501         if (ret != 0) {
502                 entry_ex->entry.keys.len = 0;
503         }
504         if (entry_ex->entry.keys.len == 0 && entry_ex->entry.keys.val) {
505                 free(entry_ex->entry.keys.val);
506                 entry_ex->entry.keys.val = NULL;
507         }
508         return ret;
509 }
510
511 /*
512  * Construct an hdb_entry from a directory entry.
513  */
514 static krb5_error_code samba_kdc_message2entry(krb5_context context,
515                                          struct samba_kdc_db_context *kdc_db_ctx,
516                                          TALLOC_CTX *mem_ctx, krb5_const_principal principal,
517                                          enum samba_kdc_ent_type ent_type,
518                                          struct ldb_dn *realm_dn,
519                                          struct ldb_message *msg,
520                                          hdb_entry_ex *entry_ex)
521 {
522         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
523         unsigned int userAccountControl;
524         unsigned int i;
525         krb5_error_code ret = 0;
526         krb5_boolean is_computer = FALSE;
527         char *realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
528
529         struct samba_kdc_entry *p;
530         NTTIME acct_expiry;
531         NTSTATUS status;
532
533         uint32_t rid;
534         struct ldb_message_element *objectclasses;
535         struct ldb_val computer_val;
536         const char *samAccountName = ldb_msg_find_attr_as_string(msg, "samAccountName", NULL);
537         computer_val.data = discard_const_p(uint8_t,"computer");
538         computer_val.length = strlen((const char *)computer_val.data);
539
540         if (!samAccountName) {
541                 ret = ENOENT;
542                 krb5_set_error_message(context, ret, "samba_kdc_message2entry: no samAccountName present");
543                 goto out;
544         }
545
546         objectclasses = ldb_msg_find_element(msg, "objectClass");
547
548         if (objectclasses && ldb_msg_find_val(objectclasses, &computer_val)) {
549                 is_computer = TRUE;
550         }
551
552         memset(entry_ex, 0, sizeof(*entry_ex));
553
554         if (!realm) {
555                 ret = ENOMEM;
556                 krb5_set_error_message(context, ret, "talloc_strdup: out of memory");
557                 goto out;
558         }
559
560         p = talloc(mem_ctx, struct samba_kdc_entry);
561         if (!p) {
562                 ret = ENOMEM;
563                 goto out;
564         }
565
566         p->kdc_db_ctx = kdc_db_ctx;
567         p->entry_ex = entry_ex;
568         p->realm_dn = talloc_reference(p, realm_dn);
569         if (!p->realm_dn) {
570                 ret = ENOMEM;
571                 goto out;
572         }
573
574         talloc_set_destructor(p, samba_kdc_entry_destructor);
575
576         /* make sure we do not have bogus data in there */
577         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
578
579         entry_ex->ctx = p;
580         entry_ex->free_entry = samba_kdc_free_entry;
581
582         userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
583
584
585         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
586         if (ent_type == SAMBA_KDC_ENT_TYPE_ANY && principal == NULL) {
587                 krb5_make_principal(context, &entry_ex->entry.principal, realm, samAccountName, NULL);
588         } else {
589                 ret = copy_Principal(principal, entry_ex->entry.principal);
590                 if (ret) {
591                         krb5_clear_error_message(context);
592                         goto out;
593                 }
594
595                 /* While we have copied the client principal, tests
596                  * show that Win2k3 returns the 'corrected' realm, not
597                  * the client-specified realm.  This code attempts to
598                  * replace the client principal's realm with the one
599                  * we determine from our records */
600
601                 /* this has to be with malloc() */
602                 krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
603         }
604
605         /* First try and figure out the flags based on the userAccountControl */
606         entry_ex->entry.flags = uf2HDBFlags(context, userAccountControl, ent_type);
607
608         /* Windows 2008 seems to enforce this (very sensible) rule by
609          * default - don't allow offline attacks on a user's password
610          * by asking for a ticket to them as a service (encrypted with
611          * their probably patheticly insecure password) */
612
613         if (entry_ex->entry.flags.server
614             && lp_parm_bool(lp_ctx, NULL, "kdc", "require spn for service", true)) {
615                 if (!is_computer && !ldb_msg_find_attr_as_string(msg, "servicePrincipalName", NULL)) {
616                         entry_ex->entry.flags.server = 0;
617                 }
618         }
619
620         {
621                 /* These (created_by, modified_by) parts of the entry are not relevant for Samba4's use
622                  * of the Heimdal KDC.  They are stored in a the traditional
623                  * DB for audit purposes, and still form part of the structure
624                  * we must return */
625
626                 /* use 'whenCreated' */
627                 entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
628                 /* use 'kadmin' for now (needed by mit_samba) */
629                 krb5_make_principal(context,
630                                     &entry_ex->entry.created_by.principal,
631                                     realm, "kadmin", NULL);
632
633                 entry_ex->entry.modified_by = (Event *) malloc(sizeof(Event));
634                 if (entry_ex->entry.modified_by == NULL) {
635                         ret = ENOMEM;
636                         krb5_set_error_message(context, ret, "malloc: out of memory");
637                         goto out;
638                 }
639
640                 /* use 'whenChanged' */
641                 entry_ex->entry.modified_by->time = ldb_msg_find_krb5time_ldap_time(msg, "whenChanged", 0);
642                 /* use 'kadmin' for now (needed by mit_samba) */
643                 krb5_make_principal(context,
644                                     &entry_ex->entry.modified_by->principal,
645                                     realm, "kadmin", NULL);
646         }
647
648
649         /* The lack of password controls etc applies to krbtgt by
650          * virtue of being that particular RID */
651         status = dom_sid_split_rid(NULL, samdb_result_dom_sid(mem_ctx, msg, "objectSid"), NULL, &rid);
652
653         if (!NT_STATUS_IS_OK(status)) {
654                 ret = EINVAL;
655                 goto out;
656         }
657
658         if (rid == DOMAIN_RID_KRBTGT) {
659                 entry_ex->entry.valid_end = NULL;
660                 entry_ex->entry.pw_end = NULL;
661
662                 entry_ex->entry.flags.invalid = 0;
663                 entry_ex->entry.flags.server = 1;
664
665                 /* Don't mark all requests for the krbtgt/realm as
666                  * 'change password', as otherwise we could get into
667                  * trouble, and not enforce the password expirty.
668                  * Instead, only do it when request is for the kpasswd service */
669                 if (ent_type == SAMBA_KDC_ENT_TYPE_SERVER
670                     && principal->name.name_string.len == 2
671                     && (strcmp(principal->name.name_string.val[0], "kadmin") == 0)
672                     && (strcmp(principal->name.name_string.val[1], "changepw") == 0)
673                     && lp_is_my_domain_or_realm(lp_ctx, principal->realm)) {
674                         entry_ex->entry.flags.change_pw = 1;
675                 }
676                 entry_ex->entry.flags.client = 0;
677                 entry_ex->entry.flags.forwardable = 1;
678                 entry_ex->entry.flags.ok_as_delegate = 1;
679         } else if (entry_ex->entry.flags.server && ent_type == SAMBA_KDC_ENT_TYPE_SERVER) {
680                 /* The account/password expiry only applies when the account is used as a
681                  * client (ie password login), not when used as a server */
682
683                 /* Make very well sure we don't use this for a client,
684                  * it could bypass the password restrictions */
685                 entry_ex->entry.flags.client = 0;
686
687                 entry_ex->entry.valid_end = NULL;
688                 entry_ex->entry.pw_end = NULL;
689
690         } else {
691                 NTTIME must_change_time
692                         = samdb_result_force_password_change(kdc_db_ctx->samdb, mem_ctx,
693                                                              realm_dn, msg);
694                 if (must_change_time == 0x7FFFFFFFFFFFFFFFULL) {
695                         entry_ex->entry.pw_end = NULL;
696                 } else {
697                         entry_ex->entry.pw_end = malloc(sizeof(*entry_ex->entry.pw_end));
698                         if (entry_ex->entry.pw_end == NULL) {
699                                 ret = ENOMEM;
700                                 goto out;
701                         }
702                         *entry_ex->entry.pw_end = nt_time_to_unix(must_change_time);
703                 }
704
705                 acct_expiry = samdb_result_account_expires(msg);
706                 if (acct_expiry == 0x7FFFFFFFFFFFFFFFULL) {
707                         entry_ex->entry.valid_end = NULL;
708                 } else {
709                         entry_ex->entry.valid_end = malloc(sizeof(*entry_ex->entry.valid_end));
710                         if (entry_ex->entry.valid_end == NULL) {
711                                 ret = ENOMEM;
712                                 goto out;
713                         }
714                         *entry_ex->entry.valid_end = nt_time_to_unix(acct_expiry);
715                 }
716         }
717
718         entry_ex->entry.valid_start = NULL;
719
720         entry_ex->entry.max_life = NULL;
721
722         entry_ex->entry.max_renew = NULL;
723
724         entry_ex->entry.generation = NULL;
725
726         /* Get keys from the db */
727         ret = samba_kdc_message2entry_keys(context, p, msg, userAccountControl,
728                                            ent_type, entry_ex);
729         if (ret) {
730                 /* Could be bougus data in the entry, or out of memory */
731                 goto out;
732         }
733
734         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
735         if (entry_ex->entry.etypes == NULL) {
736                 krb5_clear_error_message(context);
737                 ret = ENOMEM;
738                 goto out;
739         }
740         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
741         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
742         if (entry_ex->entry.etypes->val == NULL) {
743                 krb5_clear_error_message(context);
744                 ret = ENOMEM;
745                 goto out;
746         }
747         for (i=0; i < entry_ex->entry.etypes->len; i++) {
748                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
749         }
750
751
752         p->msg = talloc_steal(p, msg);
753
754 out:
755         if (ret != 0) {
756                 /* This doesn't free ent itself, that is for the eventual caller to do */
757                 hdb_free_entry(context, entry_ex);
758         } else {
759                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
760         }
761
762         return ret;
763 }
764
765 /*
766  * Construct an hdb_entry from a directory entry.
767  */
768 static krb5_error_code samba_kdc_trust_message2entry(krb5_context context,
769                                                struct samba_kdc_db_context *kdc_db_ctx,
770                                                TALLOC_CTX *mem_ctx, krb5_const_principal principal,
771                                                enum trust_direction direction,
772                                                struct ldb_dn *realm_dn,
773                                                struct ldb_message *msg,
774                                                hdb_entry_ex *entry_ex)
775 {
776         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
777         const char *dnsdomain;
778         char *realm = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
779         DATA_BLOB password_utf16;
780         struct samr_Password password_hash;
781         const struct ldb_val *password_val;
782         struct trustAuthInOutBlob password_blob;
783         struct samba_kdc_entry *p;
784
785         enum ndr_err_code ndr_err;
786         int ret, trust_direction_flags;
787         unsigned int i;
788
789         p = talloc(mem_ctx, struct samba_kdc_entry);
790         if (!p) {
791                 ret = ENOMEM;
792                 goto out;
793         }
794
795         p->kdc_db_ctx = kdc_db_ctx;
796         p->entry_ex = entry_ex;
797         p->realm_dn = realm_dn;
798
799         talloc_set_destructor(p, samba_kdc_entry_destructor);
800
801         /* make sure we do not have bogus data in there */
802         memset(&entry_ex->entry, 0, sizeof(hdb_entry));
803
804         entry_ex->ctx = p;
805         entry_ex->free_entry = samba_kdc_free_entry;
806
807         /* use 'whenCreated' */
808         entry_ex->entry.created_by.time = ldb_msg_find_krb5time_ldap_time(msg, "whenCreated", 0);
809         /* use 'kadmin' for now (needed by mit_samba) */
810         krb5_make_principal(context,
811                             &entry_ex->entry.created_by.principal,
812                             realm, "kadmin", NULL);
813
814         entry_ex->entry.valid_start = NULL;
815
816         trust_direction_flags = ldb_msg_find_attr_as_int(msg, "trustDirection", 0);
817
818         if (direction == INBOUND) {
819                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthIncoming");
820
821         } else { /* OUTBOUND */
822                 dnsdomain = ldb_msg_find_attr_as_string(msg, "trustPartner", NULL);
823                 /* replace realm */
824                 talloc_free(realm);
825                 realm = strupper_talloc(mem_ctx, dnsdomain);
826                 password_val = ldb_msg_find_ldb_val(msg, "trustAuthOutgoing");
827         }
828
829         if (!password_val || !(trust_direction_flags & direction)) {
830                 ret = ENOENT;
831                 goto out;
832         }
833
834         ndr_err = ndr_pull_struct_blob(password_val, mem_ctx, &password_blob,
835                                            (ndr_pull_flags_fn_t)ndr_pull_trustAuthInOutBlob);
836         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
837                 ret = EINVAL;
838                 goto out;
839         }
840
841         entry_ex->entry.kvno = -1;
842         for (i=0; i < password_blob.count; i++) {
843                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_VERSION) {
844                         entry_ex->entry.kvno = password_blob.current->array[i].AuthInfo.version.version;
845                 }
846         }
847
848         for (i=0; i < password_blob.count; i++) {
849                 if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_CLEAR) {
850                         password_utf16 = data_blob_const(password_blob.current->array[i].AuthInfo.clear.password,
851                                                          password_blob.current->array[i].AuthInfo.clear.size);
852                         /* In the future, generate all sorts of
853                          * hashes, but for now we can't safely convert
854                          * the random strings windows uses into
855                          * utf8 */
856
857                         /* but as it is utf16 already, we can get the NT password/arcfour-hmac-md5 key */
858                         mdfour(password_hash.hash, password_utf16.data, password_utf16.length);
859                         break;
860                 } else if (password_blob.current->array[i].AuthType == TRUST_AUTH_TYPE_NT4OWF) {
861                         password_hash = password_blob.current->array[i].AuthInfo.nt4owf.password;
862                         break;
863                 }
864         }
865
866         if (i < password_blob.count) {
867                 Key key;
868                 /* Must have found a cleartext or MD4 password */
869                 entry_ex->entry.keys.val = calloc(1, sizeof(Key));
870
871                 key.mkvno = 0;
872                 key.salt = NULL; /* No salt for this enc type */
873
874                 if (entry_ex->entry.keys.val == NULL) {
875                         ret = ENOMEM;
876                         goto out;
877                 }
878
879                 ret = krb5_keyblock_init(context,
880                                          ENCTYPE_ARCFOUR_HMAC,
881                                          password_hash.hash, sizeof(password_hash.hash),
882                                          &key.key);
883
884                 entry_ex->entry.keys.val[entry_ex->entry.keys.len] = key;
885                 entry_ex->entry.keys.len++;
886         }
887
888         entry_ex->entry.principal = malloc(sizeof(*(entry_ex->entry.principal)));
889
890         ret = copy_Principal(principal, entry_ex->entry.principal);
891         if (ret) {
892                 krb5_clear_error_message(context);
893                 goto out;
894         }
895
896         /* While we have copied the client principal, tests
897          * show that Win2k3 returns the 'corrected' realm, not
898          * the client-specified realm.  This code attempts to
899          * replace the client principal's realm with the one
900          * we determine from our records */
901
902         krb5_principal_set_realm(context, entry_ex->entry.principal, realm);
903         entry_ex->entry.flags = int2HDBFlags(0);
904         entry_ex->entry.flags.immutable = 1;
905         entry_ex->entry.flags.invalid = 0;
906         entry_ex->entry.flags.server = 1;
907         entry_ex->entry.flags.require_preauth = 1;
908
909         entry_ex->entry.pw_end = NULL;
910
911         entry_ex->entry.max_life = NULL;
912
913         entry_ex->entry.max_renew = NULL;
914
915         entry_ex->entry.generation = NULL;
916
917         entry_ex->entry.etypes = malloc(sizeof(*(entry_ex->entry.etypes)));
918         if (entry_ex->entry.etypes == NULL) {
919                 krb5_clear_error_message(context);
920                 ret = ENOMEM;
921                 goto out;
922         }
923         entry_ex->entry.etypes->len = entry_ex->entry.keys.len;
924         entry_ex->entry.etypes->val = calloc(entry_ex->entry.etypes->len, sizeof(int));
925         if (entry_ex->entry.etypes->val == NULL) {
926                 krb5_clear_error_message(context);
927                 ret = ENOMEM;
928                 goto out;
929         }
930         for (i=0; i < entry_ex->entry.etypes->len; i++) {
931                 entry_ex->entry.etypes->val[i] = entry_ex->entry.keys.val[i].key.keytype;
932         }
933
934
935         p->msg = talloc_steal(p, msg);
936
937 out:
938         if (ret != 0) {
939                 /* This doesn't free ent itself, that is for the eventual caller to do */
940                 hdb_free_entry(context, entry_ex);
941         } else {
942                 talloc_steal(kdc_db_ctx, entry_ex->ctx);
943         }
944
945         return ret;
946
947 }
948
949 static krb5_error_code samba_kdc_lookup_trust(krb5_context context, struct ldb_context *ldb_ctx,
950                                         TALLOC_CTX *mem_ctx,
951                                         const char *realm,
952                                         struct ldb_dn *realm_dn,
953                                         struct ldb_message **pmsg)
954 {
955         int lret;
956         krb5_error_code ret;
957         char *filter = NULL;
958         const char * const *attrs = trust_attrs;
959
960         struct ldb_result *res = NULL;
961         filter = talloc_asprintf(mem_ctx, "(&(objectClass=trustedDomain)(|(flatname=%s)(trustPartner=%s)))", realm, realm);
962
963         if (!filter) {
964                 ret = ENOMEM;
965                 krb5_set_error_message(context, ret, "talloc_asprintf: out of memory");
966                 return ret;
967         }
968
969         lret = ldb_search(ldb_ctx, mem_ctx, &res,
970                           ldb_get_default_basedn(ldb_ctx),
971                           LDB_SCOPE_SUBTREE, attrs, "%s", filter);
972         if (lret != LDB_SUCCESS) {
973                 DEBUG(3, ("Failed to search for %s: %s\n", filter, ldb_errstring(ldb_ctx)));
974                 return HDB_ERR_NOENTRY;
975         } else if (res->count == 0 || res->count > 1) {
976                 DEBUG(3, ("Failed find a single entry for %s: got %d\n", filter, res->count));
977                 talloc_free(res);
978                 return HDB_ERR_NOENTRY;
979         }
980         talloc_steal(mem_ctx, res->msgs);
981         *pmsg = res->msgs[0];
982         talloc_free(res);
983         return 0;
984 }
985
986 static krb5_error_code samba_kdc_lookup_client(krb5_context context,
987                                                 struct samba_kdc_db_context *kdc_db_ctx,
988                                                 TALLOC_CTX *mem_ctx,
989                                                 krb5_const_principal principal,
990                                                 const char **attrs,
991                                                 struct ldb_dn **realm_dn,
992                                                 struct ldb_message **msg) {
993         NTSTATUS nt_status;
994         char *principal_string;
995         krb5_error_code ret;
996
997         ret = krb5_unparse_name(context, principal, &principal_string);
998
999         if (ret != 0) {
1000                 return ret;
1001         }
1002
1003         nt_status = sam_get_results_principal(kdc_db_ctx->samdb,
1004                                               mem_ctx, principal_string, attrs,
1005                                               realm_dn, msg);
1006         free(principal_string);
1007         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_SUCH_USER)) {
1008                 return HDB_ERR_NOENTRY;
1009         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) {
1010                 return ENOMEM;
1011         } else if (!NT_STATUS_IS_OK(nt_status)) {
1012                 return EINVAL;
1013         }
1014
1015         return ret;
1016 }
1017
1018 static krb5_error_code samba_kdc_fetch_client(krb5_context context,
1019                                                struct samba_kdc_db_context *kdc_db_ctx,
1020                                                TALLOC_CTX *mem_ctx,
1021                                                krb5_const_principal principal,
1022                                                hdb_entry_ex *entry_ex) {
1023         struct ldb_dn *realm_dn;
1024         krb5_error_code ret;
1025         struct ldb_message *msg = NULL;
1026
1027         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1028                                        mem_ctx, principal, user_attrs,
1029                                        &realm_dn, &msg);
1030         if (ret != 0) {
1031                 return ret;
1032         }
1033
1034         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1035                                        principal, SAMBA_KDC_ENT_TYPE_CLIENT,
1036                                        realm_dn, msg, entry_ex);
1037         return ret;
1038 }
1039
1040 static krb5_error_code samba_kdc_fetch_krbtgt(krb5_context context,
1041                                         struct samba_kdc_db_context *kdc_db_ctx,
1042                                         TALLOC_CTX *mem_ctx,
1043                                         krb5_const_principal principal,
1044                                         hdb_entry_ex *entry_ex)
1045 {
1046         struct loadparm_context *lp_ctx = kdc_db_ctx->lp_ctx;
1047         krb5_error_code ret;
1048         struct ldb_message *msg = NULL;
1049         struct ldb_dn *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1050         const char *realm;
1051
1052         krb5_principal alloc_principal = NULL;
1053         if (principal->name.name_string.len != 2
1054             || (strcmp(principal->name.name_string.val[0], KRB5_TGS_NAME) != 0)) {
1055                 /* Not a krbtgt */
1056                 return HDB_ERR_NOENTRY;
1057         }
1058
1059         /* krbtgt case.  Either us or a trusted realm */
1060
1061         if (lp_is_my_domain_or_realm(lp_ctx, principal->realm)
1062             && lp_is_my_domain_or_realm(lp_ctx, principal->name.name_string.val[1])) {
1063                 /* us */
1064                 /* Cludge, cludge cludge.  If the realm part of krbtgt/realm,
1065                  * is in our db, then direct the caller at our primary
1066                  * krbtgt */
1067
1068                 int lret;
1069                 char *realm_fixed;
1070
1071                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx,
1072                                        &msg, realm_dn, LDB_SCOPE_SUBTREE,
1073                                        krbtgt_attrs,
1074                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1075                                        "(&(objectClass=user)(samAccountName=krbtgt))");
1076                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1077                         krb5_warnx(context, "samba_kdc_fetch: could not find own KRBTGT in DB!");
1078                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: could not find own KRBTGT in DB!");
1079                         return HDB_ERR_NOENTRY;
1080                 } else if (lret != LDB_SUCCESS) {
1081                         krb5_warnx(context, "samba_kdc_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1082                         krb5_set_error_message(context, HDB_ERR_NOENTRY, "samba_kdc_fetch: could not find own KRBTGT in DB: %s", ldb_errstring(kdc_db_ctx->samdb));
1083                         return HDB_ERR_NOENTRY;
1084                 }
1085
1086                 realm_fixed = strupper_talloc(mem_ctx, lp_realm(lp_ctx));
1087                 if (!realm_fixed) {
1088                         ret = ENOMEM;
1089                         krb5_set_error_message(context, ret, "strupper_talloc: out of memory");
1090                         return ret;
1091                 }
1092
1093                 ret = krb5_copy_principal(context, principal, &alloc_principal);
1094                 if (ret) {
1095                         return ret;
1096                 }
1097
1098                 free(alloc_principal->name.name_string.val[1]);
1099                 alloc_principal->name.name_string.val[1] = strdup(realm_fixed);
1100                 talloc_free(realm_fixed);
1101                 if (!alloc_principal->name.name_string.val[1]) {
1102                         ret = ENOMEM;
1103                         krb5_set_error_message(context, ret, "samba_kdc_fetch: strdup() failed!");
1104                         return ret;
1105                 }
1106                 principal = alloc_principal;
1107
1108                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1109                                         principal, SAMBA_KDC_ENT_TYPE_KRBTGT,
1110                                         realm_dn, msg, entry_ex);
1111                 if (ret != 0) {
1112                         krb5_warnx(context, "samba_kdc_fetch: self krbtgt message2entry failed");
1113                 }
1114                 return ret;
1115
1116         } else {
1117                 enum trust_direction direction = UNKNOWN;
1118
1119                 /* Either an inbound or outbound trust */
1120
1121                 if (strcasecmp(lp_realm(lp_ctx), principal->realm) == 0) {
1122                         /* look for inbound trust */
1123                         direction = INBOUND;
1124                         realm = principal->name.name_string.val[1];
1125                 }
1126
1127                 if (strcasecmp(lp_realm(lp_ctx), principal->name.name_string.val[1]) == 0) {
1128                         /* look for outbound trust */
1129                         direction = OUTBOUND;
1130                         realm = principal->realm;
1131                 }
1132
1133                 /* Trusted domains are under CN=system */
1134
1135                 ret = samba_kdc_lookup_trust(context, kdc_db_ctx->samdb,
1136                                        mem_ctx,
1137                                        realm, realm_dn, &msg);
1138
1139                 if (ret != 0) {
1140                         krb5_warnx(context, "samba_kdc_fetch: could not find principal in DB");
1141                         krb5_set_error_message(context, ret, "samba_kdc_fetch: could not find principal in DB");
1142                         return ret;
1143                 }
1144
1145                 ret = samba_kdc_trust_message2entry(context, kdc_db_ctx, mem_ctx,
1146                                               principal, direction,
1147                                               realm_dn, msg, entry_ex);
1148                 if (ret != 0) {
1149                         krb5_warnx(context, "samba_kdc_fetch: trust_message2entry failed");
1150                 }
1151                 return ret;
1152         }
1153
1154 }
1155
1156 static krb5_error_code samba_kdc_lookup_server(krb5_context context,
1157                                                 struct samba_kdc_db_context *kdc_db_ctx,
1158                                                 TALLOC_CTX *mem_ctx,
1159                                                 krb5_const_principal principal,
1160                                                 const char **attrs,
1161                                                 struct ldb_dn **realm_dn,
1162                                                 struct ldb_message **msg)
1163 {
1164         krb5_error_code ret;
1165         const char *realm;
1166         if (principal->name.name_string.len >= 2) {
1167                 /* 'normal server' case */
1168                 int ldb_ret;
1169                 NTSTATUS nt_status;
1170                 struct ldb_dn *user_dn;
1171                 char *principal_string;
1172
1173                 ret = krb5_unparse_name_flags(context, principal,
1174                                               KRB5_PRINCIPAL_UNPARSE_NO_REALM,
1175                                               &principal_string);
1176                 if (ret != 0) {
1177                         return ret;
1178                 }
1179
1180                 /* At this point we may find the host is known to be
1181                  * in a different realm, so we should generate a
1182                  * referral instead */
1183                 nt_status = crack_service_principal_name(kdc_db_ctx->samdb,
1184                                                          mem_ctx, principal_string,
1185                                                          &user_dn, realm_dn);
1186                 free(principal_string);
1187
1188                 if (!NT_STATUS_IS_OK(nt_status)) {
1189                         return HDB_ERR_NOENTRY;
1190                 }
1191
1192                 ldb_ret = dsdb_search_one(kdc_db_ctx->samdb,
1193                                           mem_ctx,
1194                                           msg, user_dn, LDB_SCOPE_BASE,
1195                                           attrs, DSDB_SEARCH_SHOW_EXTENDED_DN, "(objectClass=*)");
1196                 if (ldb_ret != LDB_SUCCESS) {
1197                         return HDB_ERR_NOENTRY;
1198                 }
1199
1200         } else {
1201                 int lret;
1202                 char *filter = NULL;
1203                 char *short_princ;
1204                 /* server as client principal case, but we must not lookup userPrincipalNames */
1205                 *realm_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
1206                 realm = krb5_principal_get_realm(context, principal);
1207
1208                 /* TODO: Check if it is our realm, otherwise give referall */
1209
1210                 ret = krb5_unparse_name_flags(context, principal,  KRB5_PRINCIPAL_UNPARSE_NO_REALM, &short_princ);
1211
1212                 if (ret != 0) {
1213                         krb5_set_error_message(context, ret, "samba_kdc_lookup_principal: could not parse principal");
1214                         krb5_warnx(context, "samba_kdc_lookup_principal: could not parse principal");
1215                         return ret;
1216                 }
1217
1218                 lret = dsdb_search_one(kdc_db_ctx->samdb, mem_ctx, msg,
1219                                        *realm_dn, LDB_SCOPE_SUBTREE,
1220                                        attrs,
1221                                        DSDB_SEARCH_SHOW_EXTENDED_DN,
1222                                        "(&(objectClass=user)(samAccountName=%s))",
1223                                        ldb_binary_encode_string(mem_ctx, short_princ));
1224                 free(short_princ);
1225                 if (lret == LDB_ERR_NO_SUCH_OBJECT) {
1226                         DEBUG(3, ("Failed find a entry for %s\n", filter));
1227                         return HDB_ERR_NOENTRY;
1228                 }
1229                 if (lret != LDB_SUCCESS) {
1230                         DEBUG(3, ("Failed single search for for %s - %s\n",
1231                                   filter, ldb_errstring(kdc_db_ctx->samdb)));
1232                         return HDB_ERR_NOENTRY;
1233                 }
1234         }
1235
1236         return 0;
1237 }
1238
1239 static krb5_error_code samba_kdc_fetch_server(krb5_context context,
1240                                                struct samba_kdc_db_context *kdc_db_ctx,
1241                                                TALLOC_CTX *mem_ctx,
1242                                                krb5_const_principal principal,
1243                                                hdb_entry_ex *entry_ex)
1244 {
1245         krb5_error_code ret;
1246         struct ldb_dn *realm_dn;
1247         struct ldb_message *msg;
1248
1249         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, principal,
1250                                        server_attrs, &realm_dn, &msg);
1251         if (ret != 0) {
1252                 return ret;
1253         }
1254
1255         ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1256                                 principal, SAMBA_KDC_ENT_TYPE_SERVER,
1257                                 realm_dn, msg, entry_ex);
1258         if (ret != 0) {
1259                 krb5_warnx(context, "samba_kdc_fetch: message2entry failed");
1260         }
1261
1262         return ret;
1263 }
1264
1265 krb5_error_code samba_kdc_fetch(krb5_context context,
1266                                 struct samba_kdc_db_context *kdc_db_ctx,
1267                                 krb5_const_principal principal,
1268                                 unsigned flags,
1269                                 hdb_entry_ex *entry_ex)
1270 {
1271         krb5_error_code ret = HDB_ERR_NOENTRY;
1272         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
1273
1274         if (!mem_ctx) {
1275                 ret = ENOMEM;
1276                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1277                 return ret;
1278         }
1279
1280         if (flags & HDB_F_GET_CLIENT) {
1281                 ret = samba_kdc_fetch_client(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1282                 if (ret != HDB_ERR_NOENTRY) goto done;
1283         }
1284         if (flags & HDB_F_GET_SERVER) {
1285                 /* krbtgt fits into this situation for trusted realms, and for resolving different versions of our own realm name */
1286                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1287                 if (ret != HDB_ERR_NOENTRY) goto done;
1288
1289                 /* We return 'no entry' if it does not start with krbtgt/, so move to the common case quickly */
1290                 ret = samba_kdc_fetch_server(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1291                 if (ret != HDB_ERR_NOENTRY) goto done;
1292         }
1293         if (flags & HDB_F_GET_KRBTGT) {
1294                 ret = samba_kdc_fetch_krbtgt(context, kdc_db_ctx, mem_ctx, principal, entry_ex);
1295                 if (ret != HDB_ERR_NOENTRY) goto done;
1296         }
1297
1298 done:
1299         talloc_free(mem_ctx);
1300         return ret;
1301 }
1302
1303 struct samba_kdc_seq {
1304         unsigned int index;
1305         unsigned int count;
1306         struct ldb_message **msgs;
1307         struct ldb_dn *realm_dn;
1308 };
1309
1310 static krb5_error_code samba_kdc_seq(krb5_context context,
1311                                      struct samba_kdc_db_context *kdc_db_ctx,
1312                                      hdb_entry_ex *entry)
1313 {
1314         krb5_error_code ret;
1315         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1316         TALLOC_CTX *mem_ctx;
1317         hdb_entry_ex entry_ex;
1318         memset(&entry_ex, '\0', sizeof(entry_ex));
1319
1320         if (!priv) {
1321                 return HDB_ERR_NOENTRY;
1322         }
1323
1324         mem_ctx = talloc_named(priv, 0, "samba_kdc_seq context");
1325
1326         if (!mem_ctx) {
1327                 ret = ENOMEM;
1328                 krb5_set_error_message(context, ret, "samba_kdc_seq: talloc_named() failed!");
1329                 return ret;
1330         }
1331
1332         if (priv->index < priv->count) {
1333                 ret = samba_kdc_message2entry(context, kdc_db_ctx, mem_ctx,
1334                                         NULL, SAMBA_KDC_ENT_TYPE_ANY,
1335                                         priv->realm_dn, priv->msgs[priv->index++], entry);
1336         } else {
1337                 ret = HDB_ERR_NOENTRY;
1338         }
1339
1340         if (ret != 0) {
1341                 TALLOC_FREE(priv);
1342                 kdc_db_ctx->seq_ctx = NULL;
1343         } else {
1344                 talloc_free(mem_ctx);
1345         }
1346
1347         return ret;
1348 }
1349
1350 krb5_error_code samba_kdc_firstkey(krb5_context context,
1351                                    struct samba_kdc_db_context *kdc_db_ctx,
1352                                    hdb_entry_ex *entry)
1353 {
1354         struct ldb_context *ldb_ctx = kdc_db_ctx->samdb;
1355         struct samba_kdc_seq *priv = kdc_db_ctx->seq_ctx;
1356         char *realm;
1357         struct ldb_result *res = NULL;
1358         krb5_error_code ret;
1359         TALLOC_CTX *mem_ctx;
1360         int lret;
1361
1362         if (priv) {
1363                 TALLOC_FREE(priv);
1364                 kdc_db_ctx->seq_ctx = NULL;
1365         }
1366
1367         priv = (struct samba_kdc_seq *) talloc(kdc_db_ctx, struct samba_kdc_seq);
1368         if (!priv) {
1369                 ret = ENOMEM;
1370                 krb5_set_error_message(context, ret, "talloc: out of memory");
1371                 return ret;
1372         }
1373
1374         priv->index = 0;
1375         priv->msgs = NULL;
1376         priv->realm_dn = ldb_get_default_basedn(ldb_ctx);
1377         priv->count = 0;
1378
1379         mem_ctx = talloc_named(priv, 0, "samba_kdc_firstkey context");
1380
1381         if (!mem_ctx) {
1382                 ret = ENOMEM;
1383                 krb5_set_error_message(context, ret, "samba_kdc_firstkey: talloc_named() failed!");
1384                 return ret;
1385         }
1386
1387         ret = krb5_get_default_realm(context, &realm);
1388         if (ret != 0) {
1389                 TALLOC_FREE(priv);
1390                 return ret;
1391         }
1392
1393         lret = ldb_search(ldb_ctx, priv, &res,
1394                           priv->realm_dn, LDB_SCOPE_SUBTREE, user_attrs,
1395                           "(objectClass=user)");
1396
1397         if (lret != LDB_SUCCESS) {
1398                 TALLOC_FREE(priv);
1399                 return HDB_ERR_NOENTRY;
1400         }
1401
1402         priv->count = res->count;
1403         priv->msgs = talloc_steal(priv, res->msgs);
1404         talloc_free(res);
1405
1406         kdc_db_ctx->seq_ctx = priv;
1407
1408         ret = samba_kdc_seq(context, kdc_db_ctx, entry);
1409
1410         if (ret != 0) {
1411                 TALLOC_FREE(priv);
1412                 kdc_db_ctx->seq_ctx = NULL;
1413         } else {
1414                 talloc_free(mem_ctx);
1415         }
1416         return ret;
1417 }
1418
1419 krb5_error_code samba_kdc_nextkey(krb5_context context,
1420                                   struct samba_kdc_db_context *kdc_db_ctx,
1421                                   hdb_entry_ex *entry)
1422 {
1423         return samba_kdc_seq(context, kdc_db_ctx, entry);
1424 }
1425
1426 /* Check if a given entry may delegate or do s4u2self to this target principal
1427  *
1428  * This is currently a very nasty hack - allowing only delegation to itself.
1429  *
1430  * This is shared between the constrained delegation and S4U2Self code.
1431  */
1432 krb5_error_code
1433 samba_kdc_check_identical_client_and_server(krb5_context context,
1434                                             struct samba_kdc_db_context *kdc_db_ctx,
1435                                             hdb_entry_ex *entry,
1436                                             krb5_const_principal target_principal)
1437 {
1438         krb5_error_code ret;
1439         krb5_principal enterprise_prinicpal = NULL;
1440         struct ldb_dn *realm_dn;
1441         struct ldb_message *msg;
1442         struct dom_sid *orig_sid;
1443         struct dom_sid *target_sid;
1444         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1445         const char *delegation_check_attrs[] = {
1446                 "objectSid", NULL
1447         };
1448
1449         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_constrained_delegation");
1450
1451         if (!mem_ctx) {
1452                 ret = ENOMEM;
1453                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1454                 return ret;
1455         }
1456
1457         if (target_principal->name.name_type == KRB5_NT_ENTERPRISE_PRINCIPAL) {
1458                 /* Need to reparse the enterprise principal to find the real target */
1459                 if (target_principal->name.name_string.len != 1) {
1460                         ret = KRB5_PARSE_MALFORMED;
1461                         krb5_set_error_message(context, ret, "samba_kdc_check_constrained_delegation: request for delegation to enterprise principal with wrong (%d) number of components",
1462                                                target_principal->name.name_string.len);
1463                         talloc_free(mem_ctx);
1464                         return ret;
1465                 }
1466                 ret = krb5_parse_name(context, target_principal->name.name_string.val[0],
1467                                       &enterprise_prinicpal);
1468                 if (ret) {
1469                         talloc_free(mem_ctx);
1470                         return ret;
1471                 }
1472                 target_principal = enterprise_prinicpal;
1473         }
1474
1475         ret = samba_kdc_lookup_server(context, kdc_db_ctx, mem_ctx, target_principal,
1476                                        delegation_check_attrs, &realm_dn, &msg);
1477
1478         krb5_free_principal(context, enterprise_prinicpal);
1479
1480         if (ret != 0) {
1481                 talloc_free(mem_ctx);
1482                 return ret;
1483         }
1484
1485         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1486         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1487
1488         /* Allow delegation to the same principal, even if by a different
1489          * name.  The easy and safe way to prove this is by SID
1490          * comparison */
1491         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1492                 talloc_free(mem_ctx);
1493                 return KRB5KDC_ERR_BADOPTION;
1494         }
1495
1496         talloc_free(mem_ctx);
1497         return ret;
1498 }
1499
1500 /* Certificates printed by a the Certificate Authority might have a
1501  * slightly different form of the user principal name to that in the
1502  * database.  Allow a mismatch where they both refer to the same
1503  * SID */
1504
1505 krb5_error_code
1506 samba_kdc_check_pkinit_ms_upn_match(krb5_context context,
1507                                     struct samba_kdc_db_context *kdc_db_ctx,
1508                                      hdb_entry_ex *entry,
1509                                      krb5_const_principal certificate_principal)
1510 {
1511         krb5_error_code ret;
1512         struct ldb_dn *realm_dn;
1513         struct ldb_message *msg;
1514         struct dom_sid *orig_sid;
1515         struct dom_sid *target_sid;
1516         struct samba_kdc_entry *p = talloc_get_type(entry->ctx, struct samba_kdc_entry);
1517         const char *ms_upn_check_attrs[] = {
1518                 "objectSid", NULL
1519         };
1520
1521         TALLOC_CTX *mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_check_pkinit_ms_upn_match");
1522
1523         if (!mem_ctx) {
1524                 ret = ENOMEM;
1525                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
1526                 return ret;
1527         }
1528
1529         ret = samba_kdc_lookup_client(context, kdc_db_ctx,
1530                                        mem_ctx, certificate_principal,
1531                                        ms_upn_check_attrs, &realm_dn, &msg);
1532
1533         if (ret != 0) {
1534                 talloc_free(mem_ctx);
1535                 return ret;
1536         }
1537
1538         orig_sid = samdb_result_dom_sid(mem_ctx, p->msg, "objectSid");
1539         target_sid = samdb_result_dom_sid(mem_ctx, msg, "objectSid");
1540
1541         /* Consider these to be the same principal, even if by a different
1542          * name.  The easy and safe way to prove this is by SID
1543          * comparison */
1544         if (!(orig_sid && target_sid && dom_sid_equal(orig_sid, target_sid))) {
1545                 talloc_free(mem_ctx);
1546                 return KRB5_KDC_ERR_CLIENT_NAME_MISMATCH;
1547         }
1548
1549         talloc_free(mem_ctx);
1550         return ret;
1551 }
1552