s4:kdc: let samba_kdc_entry take references to sdb_entry and kdc_entry
[samba.git] / source4 / kdc / hdb-samba4.c
1 /*
2  * Copyright (c) 1999-2001, 2003, PADL Software Pty Ltd.
3  * Copyright (c) 2004-2009, Andrew Bartlett <abartlet@samba.org>.
4  * Copyright (c) 2004, Stefan Metzmacher <metze@samba.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * 3. Neither the name of PADL Software  nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY PADL SOFTWARE AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL PADL SOFTWARE OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 #include "includes.h"
36 #include "kdc/kdc-glue.h"
37 #include "kdc/db-glue.h"
38 #include "auth/auth_sam.h"
39 #include "auth/common_auth.h"
40 #include <ldb.h>
41 #include "sdb.h"
42 #include "sdb_hdb.h"
43 #include "dsdb/samdb/samdb.h"
44 #include "param/param.h"
45 #include "../lib/tsocket/tsocket.h"
46 #include "librpc/gen_ndr/ndr_winbind_c.h"
47 #include "lib/messaging/irpc.h"
48 #include "hdb.h"
49 #include <kdc-audit.h>
50
51 static krb5_error_code hdb_samba4_open(krb5_context context, HDB *db, int flags, mode_t mode)
52 {
53         if (db->hdb_master_key_set) {
54                 krb5_error_code ret = HDB_ERR_NOENTRY;
55                 krb5_warnx(context, "hdb_samba4_open: use of a master key incompatible with LDB\n");
56                 krb5_set_error_message(context, ret, "hdb_samba4_open: use of a master key incompatible with LDB\n");
57                 return ret;
58         }
59
60         return 0;
61 }
62
63 static krb5_error_code hdb_samba4_close(krb5_context context, HDB *db)
64 {
65         return 0;
66 }
67
68 static krb5_error_code hdb_samba4_lock(krb5_context context, HDB *db, int operation)
69 {
70         return 0;
71 }
72
73 static krb5_error_code hdb_samba4_unlock(krb5_context context, HDB *db)
74 {
75         return 0;
76 }
77
78 static krb5_error_code hdb_samba4_rename(krb5_context context, HDB *db, const char *new_name)
79 {
80         return HDB_ERR_DB_INUSE;
81 }
82
83 static krb5_error_code hdb_samba4_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
84 {
85         return HDB_ERR_DB_INUSE;
86 }
87
88 /*
89  * If we ever want kadmin to work fast, we might try and reopen the
90  * ldb with LDB_NOSYNC
91  */
92 static krb5_error_code hdb_samba4_set_sync(krb5_context context, struct HDB *db, int set_sync)
93 {
94         return 0;
95 }
96
97 static void hdb_samba4_free_entry_context(krb5_context context, struct HDB *db, hdb_entry *entry)
98 {
99         /*
100          * This function is now called for every HDB entry, not just those with
101          * 'context' set, so we have to check that the context is not NULL.
102         */
103         if (entry->context != NULL) {
104                 struct samba_kdc_entry *skdc_entry =
105                         talloc_get_type_abort(entry->context,
106                         struct samba_kdc_entry);
107
108                 /* this function is called only from hdb_free_entry().
109                  * Make sure we neutralize the destructor or we will
110                  * get a double free later when hdb_free_entry() will
111                  * try to call free_hdb_entry() */
112                 entry->context = NULL;
113                 skdc_entry->kdc_entry = NULL;
114                 TALLOC_FREE(skdc_entry);
115         }
116 }
117
118 static int hdb_samba4_fill_fast_cookie(krb5_context context,
119                                        struct samba_kdc_db_context *kdc_db_ctx)
120 {
121         struct ldb_message *msg = ldb_msg_new(kdc_db_ctx);
122         int ldb_ret;
123
124         uint8_t secretbuffer[32];
125         struct ldb_val val = data_blob_const(secretbuffer,
126                                              sizeof(secretbuffer));
127
128         if (msg == NULL) {
129                 DBG_ERR("Failed to allocate msg for new fast cookie\n");
130                 return LDB_ERR_OPERATIONS_ERROR;
131         }
132
133         /* Fill in all the keys with the same secret */
134         generate_secret_buffer(secretbuffer,
135                                sizeof(secretbuffer));
136
137         msg->dn = kdc_db_ctx->fx_cookie_dn;
138
139         ldb_ret = ldb_msg_add_value(msg, "secret", &val, NULL);
140
141         if (ldb_ret != LDB_SUCCESS) {
142                 return ldb_ret;
143         }
144
145         ldb_ret = ldb_add(kdc_db_ctx->secrets_db,
146                           msg);
147         if (ldb_ret != LDB_SUCCESS) {
148                 DBG_ERR("Failed to add fast cookie to ldb: %s\n",
149                         ldb_errstring(kdc_db_ctx->secrets_db));
150         }
151         return ldb_ret;
152 }
153
154 static krb5_error_code hdb_samba4_fetch_fast_cookie(krb5_context context,
155                                                     struct samba_kdc_db_context *kdc_db_ctx,
156                                                     hdb_entry *entry_ex)
157 {
158         krb5_error_code ret = SDB_ERR_NOENTRY;
159         TALLOC_CTX *mem_ctx;
160         struct ldb_result *res;
161         int ldb_ret;
162         struct sdb_entry_ex sdb_entry_ex = {};
163         const char *attrs[] = {
164                 "secret",
165                 NULL
166         };
167         const struct ldb_val *val;
168
169         mem_ctx = talloc_named(kdc_db_ctx, 0, "samba_kdc_fetch context");
170         if (!mem_ctx) {
171                 ret = ENOMEM;
172                 krb5_set_error_message(context, ret, "samba_kdc_fetch: talloc_named() failed!");
173                 return ret;
174         }
175
176         /* search for CN=FX-COOKIE */
177         ldb_ret = ldb_search(kdc_db_ctx->secrets_db,
178                              mem_ctx,
179                              &res,
180                              kdc_db_ctx->fx_cookie_dn,
181                              LDB_SCOPE_BASE,
182                              attrs, NULL);
183
184         if (ldb_ret == LDB_ERR_NO_SUCH_OBJECT || res->count == 0) {
185
186                 ldb_ret = hdb_samba4_fill_fast_cookie(context,
187                                                       kdc_db_ctx);
188
189                 if (ldb_ret != LDB_SUCCESS) {
190                         TALLOC_FREE(mem_ctx);
191                         return HDB_ERR_NO_WRITE_SUPPORT;
192                 }
193
194                 /* search for CN=FX-COOKIE */
195                 ldb_ret = ldb_search(kdc_db_ctx->secrets_db,
196                                      mem_ctx,
197                                      &res,
198                                      kdc_db_ctx->fx_cookie_dn,
199                                      LDB_SCOPE_BASE,
200                                      attrs, NULL);
201
202                 if (ldb_ret != LDB_SUCCESS || res->count != 1) {
203                         TALLOC_FREE(mem_ctx);
204                         return HDB_ERR_NOENTRY;
205                 }
206         }
207
208         val = ldb_msg_find_ldb_val(res->msgs[0],
209                                    "secret");
210         if (val == NULL || val->length != 32) {
211                 TALLOC_FREE(mem_ctx);
212                 return HDB_ERR_NOENTRY;
213         }
214
215
216         ret = krb5_make_principal(context,
217                                   &sdb_entry_ex.entry.principal,
218                                   KRB5_WELLKNOWN_ORG_H5L_REALM,
219                                   KRB5_WELLKNOWN_NAME, "org.h5l.fast-cookie",
220                                   NULL);
221         if (ret) {
222                 TALLOC_FREE(mem_ctx);
223                 return ret;
224         }
225
226         ret = samba_kdc_set_fixed_keys(context, kdc_db_ctx,
227                                        val, false, &sdb_entry_ex);
228         if (ret != 0) {
229                 return ret;
230         }
231
232         ret = sdb_entry_ex_to_hdb_entry_ex(context,
233                                            &sdb_entry_ex,
234                                            entry_ex);
235         sdb_free_entry(&sdb_entry_ex);
236         TALLOC_FREE(mem_ctx);
237
238         return ret;
239 }
240
241 static krb5_error_code hdb_samba4_fetch_kvno(krb5_context context, HDB *db,
242                                              krb5_const_principal principal,
243                                              unsigned flags,
244                                              krb5_kvno kvno,
245                                              hdb_entry *entry_ex)
246 {
247         struct samba_kdc_db_context *kdc_db_ctx;
248         struct sdb_entry_ex sdb_entry_ex = {};
249         krb5_error_code code, ret;
250         uint32_t sflags;
251
252         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
253                                            struct samba_kdc_db_context);
254
255         if (flags & HDB_F_GET_FAST_COOKIE) {
256                 return hdb_samba4_fetch_fast_cookie(context,
257                                                     kdc_db_ctx,
258                                                     entry_ex);
259         }
260
261         sflags = (flags & SDB_F_HDB_MASK);
262
263         ret = samba_kdc_fetch(context,
264                               kdc_db_ctx,
265                               principal,
266                               sflags,
267                               kvno,
268                               &sdb_entry_ex);
269         switch (ret) {
270         case 0:
271                 code = 0;
272                 break;
273         case SDB_ERR_WRONG_REALM:
274                 /*
275                  * If SDB_ERR_WRONG_REALM is returned we need to process the
276                  * sdb_entry to fill the principal in the HDB entry.
277                  */
278                 code = HDB_ERR_WRONG_REALM;
279                 break;
280         case SDB_ERR_NOENTRY:
281                 return HDB_ERR_NOENTRY;
282         case SDB_ERR_NOT_FOUND_HERE:
283                 return HDB_ERR_NOT_FOUND_HERE;
284         default:
285                 return ret;
286         }
287
288         ret = sdb_entry_ex_to_hdb_entry_ex(context, &sdb_entry_ex, entry_ex);
289         sdb_free_entry(&sdb_entry_ex);
290
291         if (code != 0 && ret != 0) {
292                 code = ret;
293         }
294
295         return code;
296 }
297
298 static krb5_error_code hdb_samba4_firstkey(krb5_context context, HDB *db, unsigned flags,
299                                         hdb_entry *entry)
300 {
301         struct samba_kdc_db_context *kdc_db_ctx;
302         struct sdb_entry_ex sdb_entry_ex = {};
303         krb5_error_code ret;
304
305         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
306                                            struct samba_kdc_db_context);
307
308         ret = samba_kdc_firstkey(context, kdc_db_ctx, &sdb_entry_ex);
309         switch (ret) {
310         case 0:
311                 break;
312         case SDB_ERR_WRONG_REALM:
313                 return HDB_ERR_WRONG_REALM;
314         case SDB_ERR_NOENTRY:
315                 return HDB_ERR_NOENTRY;
316         case SDB_ERR_NOT_FOUND_HERE:
317                 return HDB_ERR_NOT_FOUND_HERE;
318         default:
319                 return ret;
320         }
321
322         ret = sdb_entry_ex_to_hdb_entry_ex(context, &sdb_entry_ex, entry);
323         sdb_free_entry(&sdb_entry_ex);
324         return ret;
325 }
326
327 static krb5_error_code hdb_samba4_nextkey(krb5_context context, HDB *db, unsigned flags,
328                                    hdb_entry *entry)
329 {
330         struct samba_kdc_db_context *kdc_db_ctx;
331         struct sdb_entry_ex sdb_entry_ex = {};
332         krb5_error_code ret;
333
334         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
335                                            struct samba_kdc_db_context);
336
337         ret = samba_kdc_nextkey(context, kdc_db_ctx, &sdb_entry_ex);
338         switch (ret) {
339         case 0:
340                 break;
341         case SDB_ERR_WRONG_REALM:
342                 return HDB_ERR_WRONG_REALM;
343         case SDB_ERR_NOENTRY:
344                 return HDB_ERR_NOENTRY;
345         case SDB_ERR_NOT_FOUND_HERE:
346                 return HDB_ERR_NOT_FOUND_HERE;
347         default:
348                 return ret;
349         }
350
351         ret = sdb_entry_ex_to_hdb_entry_ex(context, &sdb_entry_ex, entry);
352         sdb_free_entry(&sdb_entry_ex);
353         return ret;
354 }
355
356 static krb5_error_code hdb_samba4_destroy(krb5_context context, HDB *db)
357 {
358         talloc_free(db);
359         return 0;
360 }
361
362 static krb5_error_code
363 hdb_samba4_check_constrained_delegation(krb5_context context, HDB *db,
364                                         hdb_entry *entry,
365                                         krb5_const_principal target_principal)
366 {
367         struct samba_kdc_db_context *kdc_db_ctx;
368         struct samba_kdc_entry *skdc_entry;
369         krb5_error_code ret;
370
371         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
372                                            struct samba_kdc_db_context);
373         skdc_entry = talloc_get_type_abort(entry->context,
374                                            struct samba_kdc_entry);
375
376         ret = samba_kdc_check_s4u2proxy(context, kdc_db_ctx,
377                                         skdc_entry,
378                                         target_principal);
379         switch (ret) {
380         case 0:
381                 break;
382         case SDB_ERR_WRONG_REALM:
383                 ret = HDB_ERR_WRONG_REALM;
384                 break;
385         case SDB_ERR_NOENTRY:
386                 ret = HDB_ERR_NOENTRY;
387                 break;
388         case SDB_ERR_NOT_FOUND_HERE:
389                 ret = HDB_ERR_NOT_FOUND_HERE;
390                 break;
391         default:
392                 break;
393         }
394
395         return ret;
396 }
397
398 static krb5_error_code
399 hdb_samba4_check_pkinit_ms_upn_match(krb5_context context, HDB *db,
400                                      hdb_entry *entry,
401                                      krb5_const_principal certificate_principal)
402 {
403         struct samba_kdc_db_context *kdc_db_ctx;
404         struct samba_kdc_entry *skdc_entry;
405         krb5_error_code ret;
406
407         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
408                                            struct samba_kdc_db_context);
409         skdc_entry = talloc_get_type_abort(entry->context,
410                                            struct samba_kdc_entry);
411
412         ret = samba_kdc_check_pkinit_ms_upn_match(context, kdc_db_ctx,
413                                                   skdc_entry,
414                                                   certificate_principal);
415         switch (ret) {
416         case 0:
417                 break;
418         case SDB_ERR_WRONG_REALM:
419                 ret = HDB_ERR_WRONG_REALM;
420                 break;
421         case SDB_ERR_NOENTRY:
422                 ret = HDB_ERR_NOENTRY;
423                 break;
424         case SDB_ERR_NOT_FOUND_HERE:
425                 ret = HDB_ERR_NOT_FOUND_HERE;
426                 break;
427         default:
428                 break;
429         }
430
431         return ret;
432 }
433
434 static krb5_error_code
435 hdb_samba4_check_client_matches_target_service(krb5_context context, HDB *db,
436                           hdb_entry *client_entry,
437                           hdb_entry *server_target_entry)
438 {
439         struct samba_kdc_entry *skdc_client_entry
440                 = talloc_get_type_abort(client_entry->context,
441                                         struct samba_kdc_entry);
442         struct samba_kdc_entry *skdc_server_target_entry
443                 = talloc_get_type_abort(server_target_entry->context,
444                                         struct samba_kdc_entry);
445
446         return samba_kdc_check_client_matches_target_service(context,
447                                                              skdc_client_entry,
448                                                              skdc_server_target_entry);
449 }
450
451 static void reset_bad_password_netlogon(TALLOC_CTX *mem_ctx,
452                                         struct samba_kdc_db_context *kdc_db_ctx,
453                                         struct netr_SendToSamBase *send_to_sam)
454 {
455         struct dcerpc_binding_handle *irpc_handle;
456         struct winbind_SendToSam req;
457
458         irpc_handle = irpc_binding_handle_by_name(mem_ctx, kdc_db_ctx->msg_ctx,
459                                                   "winbind_server",
460                                                   &ndr_table_winbind);
461
462         if (irpc_handle == NULL) {
463                 DEBUG(0, ("No winbind_server running!\n"));
464                 return;
465         }
466
467         req.in.message = *send_to_sam;
468
469         dcerpc_winbind_SendToSam_r_send(mem_ctx, kdc_db_ctx->ev_ctx,
470                                         irpc_handle, &req);
471 }
472
473 static krb5_error_code hdb_samba4_audit(krb5_context context,
474                                         HDB *db,
475                                         hdb_entry *entry,
476                                         hdb_request_t r)
477 {
478         struct samba_kdc_db_context *kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
479                                                                         struct samba_kdc_db_context);
480         struct ldb_dn *domain_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
481         uint64_t logon_id = generate_random_u64();
482         heim_object_t auth_details_obj = NULL;
483         const char *auth_details = NULL;
484         char *etype_str = NULL;
485         heim_object_t hdb_auth_status_obj = NULL;
486         int hdb_auth_status;
487         heim_object_t pa_type_obj = NULL;
488         const char *pa_type = NULL;
489         struct auth_usersupplied_info ui;
490         size_t sa_socklen = 0;
491         int final_ret = 0;
492
493         hdb_auth_status_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_AUTH_EVENT);
494         if (hdb_auth_status_obj == NULL) {
495                 /* No status code found, so just return. */
496                 return 0;
497         }
498
499         hdb_auth_status = heim_number_get_int(hdb_auth_status_obj);
500
501         pa_type_obj = heim_audit_getkv((heim_svc_req_desc)r, "pa");
502         if (pa_type_obj != NULL) {
503                 pa_type = heim_string_get_utf8(pa_type_obj);
504         }
505
506         auth_details_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_PKINIT_CLIENT_CERT);
507         if (auth_details_obj != NULL) {
508                 auth_details = heim_string_get_utf8(auth_details_obj);
509         } else {
510                 auth_details_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_GSS_INITIATOR);
511                 if (auth_details_obj != NULL) {
512                         auth_details = heim_string_get_utf8(auth_details_obj);
513                 } else {
514                         heim_object_t etype_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_PA_ETYPE);
515                         if (etype_obj != NULL) {
516                                 int etype = heim_number_get_int(etype_obj);
517
518                                 krb5_error_code ret = krb5_enctype_to_string(r->context, etype, &etype_str);
519                                 if (ret == 0) {
520                                         auth_details = etype_str;
521                                 } else {
522                                         auth_details = "unknown enctype";
523                                 }
524                         }
525                 }
526         }
527
528         /*
529          * Forcing this via the NTLM auth structure is not ideal, but
530          * it is the most practical option right now, and ensures the
531          * logs are consistent, even if some elements are always NULL.
532          */
533         ui = (struct auth_usersupplied_info) {
534                 .was_mapped = true,
535                 .client = {
536                         .account_name = r->cname,
537                         .domain_name = NULL,
538                 },
539                 .service_description = "Kerberos KDC",
540                 .auth_description = "Unknown Auth Description",
541                 .password_type = auth_details,
542                 .logon_id = logon_id
543         };
544
545         switch (r->addr->sa_family) {
546         case AF_INET:
547                 sa_socklen = sizeof(struct sockaddr_in);
548                 break;
549 #ifdef HAVE_IPV6
550         case AF_INET6:
551                 sa_socklen = sizeof(struct sockaddr_in6);
552                 break;
553 #endif
554         }
555
556         switch (hdb_auth_status) {
557         case KDC_AUTH_EVENT_CLIENT_AUTHORIZED:
558         {
559                 TALLOC_CTX *frame = talloc_stackframe();
560                 struct samba_kdc_entry *p = talloc_get_type(entry->context,
561                                                             struct samba_kdc_entry);
562                 struct netr_SendToSamBase *send_to_sam = NULL;
563
564                 /*
565                  * TODO: We could log the AS-REQ authorization success here as
566                  * well.  However before we do that, we need to pass
567                  * in the PAC here or re-calculate it.
568                  */
569                 authsam_logon_success_accounting(kdc_db_ctx->samdb, p->msg,
570                                                  domain_dn, true, &send_to_sam);
571                 if (kdc_db_ctx->rodc && send_to_sam != NULL) {
572                         reset_bad_password_netlogon(frame, kdc_db_ctx, send_to_sam);
573                 }
574                 talloc_free(frame);
575         }
576         FALL_THROUGH;
577         default:
578         {
579                 TALLOC_CTX *frame = talloc_stackframe();
580                 struct samba_kdc_entry *p = talloc_get_type(entry->context,
581                                                             struct samba_kdc_entry);
582                 struct dom_sid *sid
583                         = samdb_result_dom_sid(frame, p->msg, "objectSid");
584                 const char *account_name
585                         = ldb_msg_find_attr_as_string(p->msg, "sAMAccountName", NULL);
586                 const char *domain_name = lpcfg_sam_name(p->kdc_db_ctx->lp_ctx);
587                 struct tsocket_address *remote_host;
588                 const char *auth_description = NULL;
589                 NTSTATUS status;
590                 int ret;
591                 bool rwdc_fallback = false;
592
593                 ret = tsocket_address_bsd_from_sockaddr(frame, r->addr,
594                                                         sa_socklen,
595                                                         &remote_host);
596                 if (ret != 0) {
597                         ui.remote_host = NULL;
598                 } else {
599                         ui.remote_host = remote_host;
600                 }
601
602                 ui.mapped.account_name = account_name;
603                 ui.mapped.domain_name = domain_name;
604
605                 if (pa_type != NULL) {
606                         auth_description = talloc_asprintf(frame,
607                                                            "%s Pre-authentication",
608                                                            pa_type);
609                         if (auth_description == NULL) {
610                                 auth_description = pa_type;
611                         }
612                 } else {
613                         auth_description = "Unknown Pre-authentication";
614                 }
615                 ui.auth_description = auth_description;
616
617                 if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_AUTHORIZED) {
618                         /* This is the final sucess */
619                         status = NT_STATUS_OK;
620                 } else if (hdb_auth_status == KDC_AUTH_EVENT_VALIDATED_LONG_TERM_KEY) {
621                         /*
622                          * This was only a pre-authentication success,
623                          * but we didn't reach the final
624                          * KDC_AUTH_EVENT_CLIENT_AUTHORIZED,
625                          * so consult the error code.
626                          */
627                         if (r->error_code == 0) {
628                                 DBG_ERR("ERROR: VALIDATED_LONG_TERM_KEY "
629                                         "with error=0 => INTERNAL_ERROR\n");
630                                 status = NT_STATUS_INTERNAL_ERROR;
631                                 final_ret = KRB5KRB_ERR_GENERIC;
632                                 r->error_code = final_ret;
633                         } else if (!NT_STATUS_IS_OK(p->reject_status)) {
634                                 status = p->reject_status;
635                         } else {
636                                 status = krb5_to_nt_status(r->error_code);
637                         }
638                 } else if (hdb_auth_status == KDC_AUTH_EVENT_PREAUTH_SUCCEEDED) {
639                         /*
640                          * This was only a pre-authentication success,
641                          * but we didn't reach the final
642                          * KDC_AUTH_EVENT_CLIENT_AUTHORIZED,
643                          * so consult the error code.
644                          */
645                         if (r->error_code == 0) {
646                                 DBG_ERR("ERROR: PREAUTH_SUCCEEDED "
647                                         "with error=0 => INTERNAL_ERROR\n");
648                                 status = NT_STATUS_INTERNAL_ERROR;
649                                 final_ret = KRB5KRB_ERR_GENERIC;
650                                 r->error_code = final_ret;
651                         } else if (!NT_STATUS_IS_OK(p->reject_status)) {
652                                 status = p->reject_status;
653                         } else {
654                                 status = krb5_to_nt_status(r->error_code);
655                         }
656                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_TIME_SKEW) {
657                         status = NT_STATUS_TIME_DIFFERENCE_AT_DC;
658                 } else if (hdb_auth_status == KDC_AUTH_EVENT_WRONG_LONG_TERM_KEY) {
659                         authsam_update_bad_pwd_count(kdc_db_ctx->samdb, p->msg, domain_dn);
660                         status = NT_STATUS_WRONG_PASSWORD;
661                         rwdc_fallback = kdc_db_ctx->rodc;
662                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_LOCKED_OUT) {
663                         status = NT_STATUS_ACCOUNT_LOCKED_OUT;
664                         rwdc_fallback = kdc_db_ctx->rodc;
665                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_NAME_UNAUTHORIZED) {
666                         if (pa_type != NULL && strncmp(pa_type, "PK-INIT", strlen("PK-INIT")) == 0) {
667                                 status = NT_STATUS_PKINIT_NAME_MISMATCH;
668                         } else {
669                                 status = NT_STATUS_ACCOUNT_RESTRICTION;
670                         }
671                         rwdc_fallback = kdc_db_ctx->rodc;
672                 } else if (hdb_auth_status == KDC_AUTH_EVENT_PREAUTH_FAILED) {
673                         if (pa_type != NULL && strncmp(pa_type, "PK-INIT", strlen("PK-INIT")) == 0) {
674                                 status = NT_STATUS_PKINIT_FAILURE;
675                         } else {
676                                 status = NT_STATUS_GENERIC_COMMAND_FAILED;
677                         }
678                         rwdc_fallback = kdc_db_ctx->rodc;
679                 } else {
680                         DBG_ERR("Unhandled hdb_auth_status=%d => INTERNAL_ERROR\n",
681                                 hdb_auth_status);
682                         status = NT_STATUS_INTERNAL_ERROR;
683                         final_ret = KRB5KRB_ERR_GENERIC;
684                         r->error_code = final_ret;
685                 }
686
687                 if (rwdc_fallback) {
688                         /*
689                          * Forward the request to an RWDC in order
690                          * to give an authoritative answer to the client.
691                          */
692                         auth_description = talloc_asprintf(frame,
693                                                            "%s,Forward-To-RWDC",
694                                                            ui.auth_description);
695                         if (auth_description != NULL) {
696                                 ui.auth_description = auth_description;
697                         }
698                         final_ret = HDB_ERR_NOT_FOUND_HERE;
699                 }
700
701                 log_authentication_event(kdc_db_ctx->msg_ctx,
702                                          kdc_db_ctx->lp_ctx,
703                                          &r->tv_start,
704                                          &ui,
705                                          status,
706                                          domain_name,
707                                          account_name,
708                                          sid);
709                 if (final_ret == KRB5KRB_ERR_GENERIC && socket_wrapper_enabled()) {
710                         /*
711                          * If we're running under make test
712                          * just panic
713                          */
714                         DBG_ERR("Unexpected situation => PANIC\n");
715                         smb_panic("hdb_samba4_audit: Unexpected situation");
716                 }
717                 TALLOC_FREE(frame);
718                 break;
719         }
720         case KDC_AUTH_EVENT_CLIENT_UNKNOWN:
721         {
722                 struct tsocket_address *remote_host;
723                 int ret;
724                 TALLOC_CTX *frame = talloc_stackframe();
725                 ret = tsocket_address_bsd_from_sockaddr(frame, r->addr,
726                                                         sa_socklen,
727                                                         &remote_host);
728                 if (ret != 0) {
729                         ui.remote_host = NULL;
730                 } else {
731                         ui.remote_host = remote_host;
732                 }
733
734                 if (pa_type == NULL) {
735                         pa_type = "AS-REQ";
736                 }
737
738                 ui.auth_description = pa_type;
739
740                 /* Note this is not forwarded to an RWDC */
741
742                 log_authentication_event(kdc_db_ctx->msg_ctx,
743                                          kdc_db_ctx->lp_ctx,
744                                          &r->tv_start,
745                                          &ui,
746                                          NT_STATUS_NO_SUCH_USER,
747                                          NULL, NULL,
748                                          NULL);
749                 TALLOC_FREE(frame);
750                 break;
751         }
752         }
753
754         free(etype_str);
755
756         return final_ret;
757 }
758
759 /* This interface is to be called by the KDC and libnet_keytab_dump,
760  * which is expecting Samba calling conventions.
761  * It is also called by a wrapper (hdb_samba4_create) from the
762  * kpasswdd -> krb5 -> keytab_hdb -> hdb code */
763
764 NTSTATUS hdb_samba4_create_kdc(struct samba_kdc_base_context *base_ctx,
765                                krb5_context context, struct HDB **db)
766 {
767         struct samba_kdc_db_context *kdc_db_ctx;
768         NTSTATUS nt_status;
769
770         if (hdb_interface_version != HDB_INTERFACE_VERSION) {
771                 krb5_set_error_message(context, EINVAL, "Heimdal HDB interface version mismatch between build-time and run-time libraries!");
772                 return NT_STATUS_ERROR_DS_INCOMPATIBLE_VERSION;
773         }
774
775         *db = talloc_zero(base_ctx, HDB);
776         if (!*db) {
777                 krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
778                 return NT_STATUS_NO_MEMORY;
779         }
780
781         (*db)->hdb_master_key_set = 0;
782         (*db)->hdb_db = NULL;
783         (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
784
785         nt_status = samba_kdc_setup_db_ctx(*db, base_ctx, &kdc_db_ctx);
786         if (!NT_STATUS_IS_OK(nt_status)) {
787                 talloc_free(*db);
788                 return nt_status;
789         }
790         (*db)->hdb_db = kdc_db_ctx;
791
792         (*db)->hdb_dbc = NULL;
793         (*db)->hdb_open = hdb_samba4_open;
794         (*db)->hdb_close = hdb_samba4_close;
795         (*db)->hdb_free_entry_context = hdb_samba4_free_entry_context;
796         (*db)->hdb_fetch_kvno = hdb_samba4_fetch_kvno;
797         (*db)->hdb_store = hdb_samba4_store;
798         (*db)->hdb_firstkey = hdb_samba4_firstkey;
799         (*db)->hdb_nextkey = hdb_samba4_nextkey;
800         (*db)->hdb_lock = hdb_samba4_lock;
801         (*db)->hdb_unlock = hdb_samba4_unlock;
802         (*db)->hdb_set_sync = hdb_samba4_set_sync;
803         (*db)->hdb_rename = hdb_samba4_rename;
804         /* we don't implement these, as we are not a lockable database */
805         (*db)->hdb__get = NULL;
806         (*db)->hdb__put = NULL;
807         /* kadmin should not be used for deletes - use other tools instead */
808         (*db)->hdb__del = NULL;
809         (*db)->hdb_destroy = hdb_samba4_destroy;
810
811         (*db)->hdb_audit = hdb_samba4_audit;
812         (*db)->hdb_check_constrained_delegation = hdb_samba4_check_constrained_delegation;
813         (*db)->hdb_check_pkinit_ms_upn_match = hdb_samba4_check_pkinit_ms_upn_match;
814         (*db)->hdb_check_client_matches_target_service = hdb_samba4_check_client_matches_target_service;
815
816         return NT_STATUS_OK;
817 }