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