s4:kdc: Use more suitable type for final_ret
[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 #undef DBGC_CLASS
52 #define DBGC_CLASS DBGC_KERBEROS
53
54 static krb5_error_code hdb_samba4_open(krb5_context context, HDB *db, int flags, mode_t mode)
55 {
56         if (db->hdb_master_key_set) {
57                 krb5_error_code ret = HDB_ERR_NOENTRY;
58                 krb5_warnx(context, "hdb_samba4_open: use of a master key incompatible with LDB\n");
59                 krb5_set_error_message(context, ret, "hdb_samba4_open: use of a master key incompatible with LDB\n");
60                 return ret;
61         }
62
63         return 0;
64 }
65
66 static krb5_error_code hdb_samba4_close(krb5_context context, HDB *db)
67 {
68         return 0;
69 }
70
71 static krb5_error_code hdb_samba4_lock(krb5_context context, HDB *db, int operation)
72 {
73         return 0;
74 }
75
76 static krb5_error_code hdb_samba4_unlock(krb5_context context, HDB *db)
77 {
78         return 0;
79 }
80
81 static krb5_error_code hdb_samba4_rename(krb5_context context, HDB *db, const char *new_name)
82 {
83         return HDB_ERR_DB_INUSE;
84 }
85
86 static krb5_error_code hdb_samba4_store(krb5_context context, HDB *db, unsigned flags, hdb_entry *entry)
87 {
88         return HDB_ERR_DB_INUSE;
89 }
90
91 /*
92  * If we ever want kadmin to work fast, we might try and reopen the
93  * ldb with LDB_NOSYNC
94  */
95 static krb5_error_code hdb_samba4_set_sync(krb5_context context, struct HDB *db, int set_sync)
96 {
97         return 0;
98 }
99
100 static void hdb_samba4_free_entry_context(krb5_context context, struct HDB *db, hdb_entry *entry)
101 {
102         /*
103          * This function is now called for every HDB entry, not just those with
104          * 'context' set, so we have to check that the context is not NULL.
105         */
106         if (entry->context != NULL) {
107                 struct samba_kdc_entry *skdc_entry =
108                         talloc_get_type_abort(entry->context,
109                         struct samba_kdc_entry);
110
111                 /* this function is called only from hdb_free_entry().
112                  * Make sure we neutralize the destructor or we will
113                  * get a double free later when hdb_free_entry() will
114                  * try to call free_hdb_entry() */
115                 entry->context = NULL;
116                 skdc_entry->kdc_entry = NULL;
117                 TALLOC_FREE(skdc_entry);
118         }
119 }
120
121 static int hdb_samba4_fill_fast_cookie(krb5_context context,
122                                        struct samba_kdc_db_context *kdc_db_ctx)
123 {
124         struct ldb_message *msg = ldb_msg_new(kdc_db_ctx);
125         int ldb_ret;
126
127         uint8_t secretbuffer[32];
128         struct ldb_val val = data_blob_const(secretbuffer,
129                                              sizeof(secretbuffer));
130
131         if (msg == NULL) {
132                 DBG_ERR("Failed to allocate msg for new fast cookie\n");
133                 return LDB_ERR_OPERATIONS_ERROR;
134         }
135
136         /* Fill in all the keys with the same secret */
137         generate_secret_buffer(secretbuffer,
138                                sizeof(secretbuffer));
139
140         msg->dn = kdc_db_ctx->fx_cookie_dn;
141
142         ldb_ret = ldb_msg_add_value(msg, "secret", &val, NULL);
143
144         if (ldb_ret != LDB_SUCCESS) {
145                 return ldb_ret;
146         }
147
148         ldb_ret = ldb_add(kdc_db_ctx->secrets_db,
149                           msg);
150         if (ldb_ret != LDB_SUCCESS) {
151                 DBG_ERR("Failed to add fast cookie to ldb: %s\n",
152                         ldb_errstring(kdc_db_ctx->secrets_db));
153         }
154         return ldb_ret;
155 }
156
157 static krb5_error_code hdb_samba4_fetch_fast_cookie(krb5_context context,
158                                                     struct samba_kdc_db_context *kdc_db_ctx,
159                                                     hdb_entry *entry)
160 {
161         krb5_error_code ret = SDB_ERR_NOENTRY;
162         TALLOC_CTX *mem_ctx;
163         struct ldb_result *res;
164         int ldb_ret;
165         struct sdb_entry sentry = {};
166         const char *attrs[] = {
167                 "secret",
168                 NULL
169         };
170         const struct ldb_val *val;
171
172         mem_ctx = talloc_named(kdc_db_ctx, 0, "hdb_samba4_fetch_fast_cookie context");
173         if (!mem_ctx) {
174                 ret = ENOMEM;
175                 krb5_set_error_message(context, ret, "hdb_samba4_fetch_fast_cookie: talloc_named() failed!");
176                 return ret;
177         }
178
179         /* search for CN=FX-COOKIE */
180         ldb_ret = ldb_search(kdc_db_ctx->secrets_db,
181                              mem_ctx,
182                              &res,
183                              kdc_db_ctx->fx_cookie_dn,
184                              LDB_SCOPE_BASE,
185                              attrs, NULL);
186
187         if (ldb_ret == LDB_ERR_NO_SUCH_OBJECT || res->count == 0) {
188
189                 ldb_ret = hdb_samba4_fill_fast_cookie(context,
190                                                       kdc_db_ctx);
191
192                 if (ldb_ret != LDB_SUCCESS) {
193                         TALLOC_FREE(mem_ctx);
194                         return HDB_ERR_NO_WRITE_SUPPORT;
195                 }
196
197                 /* search for CN=FX-COOKIE */
198                 ldb_ret = ldb_search(kdc_db_ctx->secrets_db,
199                                      mem_ctx,
200                                      &res,
201                                      kdc_db_ctx->fx_cookie_dn,
202                                      LDB_SCOPE_BASE,
203                                      attrs, NULL);
204
205                 if (ldb_ret != LDB_SUCCESS || res->count != 1) {
206                         TALLOC_FREE(mem_ctx);
207                         return HDB_ERR_NOENTRY;
208                 }
209         }
210
211         val = ldb_msg_find_ldb_val(res->msgs[0],
212                                    "secret");
213         if (val == NULL || val->length != 32) {
214                 TALLOC_FREE(mem_ctx);
215                 return HDB_ERR_NOENTRY;
216         }
217
218
219         ret = krb5_make_principal(context,
220                                   &sentry.principal,
221                                   KRB5_WELLKNOWN_ORG_H5L_REALM,
222                                   KRB5_WELLKNOWN_NAME, "org.h5l.fast-cookie",
223                                   NULL);
224         if (ret) {
225                 TALLOC_FREE(mem_ctx);
226                 return ret;
227         }
228
229         ret = samba_kdc_set_fixed_keys(context, val, ENC_ALL_TYPES,
230                                        &sentry.keys);
231         if (ret != 0) {
232                 return ret;
233         }
234
235         ret = sdb_entry_to_hdb_entry(context, &sentry, entry);
236         sdb_entry_free(&sentry);
237         TALLOC_FREE(mem_ctx);
238
239         return ret;
240 }
241
242 static krb5_error_code hdb_samba4_fetch_kvno(krb5_context context, HDB *db,
243                                              krb5_const_principal principal,
244                                              unsigned flags,
245                                              krb5_kvno kvno,
246                                              hdb_entry *entry)
247 {
248         struct samba_kdc_db_context *kdc_db_ctx;
249         struct sdb_entry sentry = {};
250         krb5_error_code code, ret;
251         uint32_t sflags;
252
253         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
254                                            struct samba_kdc_db_context);
255
256         if (flags & HDB_F_GET_FAST_COOKIE) {
257                 return hdb_samba4_fetch_fast_cookie(context,
258                                                     kdc_db_ctx,
259                                                     entry);
260         }
261
262         sflags = (flags & SDB_F_HDB_MASK);
263
264         ret = samba_kdc_fetch(context,
265                               kdc_db_ctx,
266                               principal,
267                               sflags,
268                               kvno,
269                               &sentry);
270         switch (ret) {
271         case 0:
272                 code = 0;
273                 break;
274         case SDB_ERR_WRONG_REALM:
275                 /*
276                  * If SDB_ERR_WRONG_REALM is returned we need to process the
277                  * sdb_entry to fill the principal in the HDB entry.
278                  */
279                 code = HDB_ERR_WRONG_REALM;
280                 break;
281         case SDB_ERR_NOENTRY:
282                 return HDB_ERR_NOENTRY;
283         case SDB_ERR_NOT_FOUND_HERE:
284                 return HDB_ERR_NOT_FOUND_HERE;
285         default:
286                 return ret;
287         }
288
289         ret = sdb_entry_to_hdb_entry(context, &sentry, entry);
290         sdb_entry_free(&sentry);
291
292         if (code != 0 && ret != 0) {
293                 code = ret;
294         }
295
296         return code;
297 }
298
299 static krb5_error_code hdb_samba4_kpasswd_fetch_kvno(krb5_context context, HDB *db,
300                                                      krb5_const_principal _principal,
301                                                      unsigned flags,
302                                                      krb5_kvno _kvno,
303                                                      hdb_entry *entry)
304 {
305         struct samba_kdc_db_context *kdc_db_ctx = NULL;
306         krb5_error_code ret;
307         krb5_principal kpasswd_principal = NULL;
308
309         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
310                                            struct samba_kdc_db_context);
311
312         ret = smb_krb5_make_principal(context, &kpasswd_principal,
313                                       lpcfg_realm(kdc_db_ctx->lp_ctx),
314                                       "kadmin", "changepw",
315                                       NULL);
316         if (ret) {
317                 return ret;
318         }
319         smb_krb5_principal_set_type(context, kpasswd_principal, KRB5_NT_SRV_INST);
320
321         /*
322          * For the kpasswd service, always ensure we get the latest kvno. This
323          * also means we (correctly) refuse RODC-issued tickets.
324          */
325         flags &= ~HDB_F_KVNO_SPECIFIED;
326
327         /* Don't bother looking up a client or krbtgt. */
328         flags &= ~(SDB_F_GET_CLIENT|SDB_F_GET_KRBTGT);
329
330         ret = hdb_samba4_fetch_kvno(context, db,
331                                     kpasswd_principal,
332                                     flags,
333                                     0,
334                                     entry);
335
336         krb5_free_principal(context, kpasswd_principal);
337         return ret;
338 }
339
340 static krb5_error_code hdb_samba4_firstkey(krb5_context context, HDB *db, unsigned flags,
341                                         hdb_entry *entry)
342 {
343         struct samba_kdc_db_context *kdc_db_ctx;
344         struct sdb_entry sentry = {};
345         krb5_error_code ret;
346
347         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
348                                            struct samba_kdc_db_context);
349
350         ret = samba_kdc_firstkey(context, kdc_db_ctx, &sentry);
351         switch (ret) {
352         case 0:
353                 break;
354         case SDB_ERR_WRONG_REALM:
355                 return HDB_ERR_WRONG_REALM;
356         case SDB_ERR_NOENTRY:
357                 return HDB_ERR_NOENTRY;
358         case SDB_ERR_NOT_FOUND_HERE:
359                 return HDB_ERR_NOT_FOUND_HERE;
360         default:
361                 return ret;
362         }
363
364         ret = sdb_entry_to_hdb_entry(context, &sentry, entry);
365         sdb_entry_free(&sentry);
366         return ret;
367 }
368
369 static krb5_error_code hdb_samba4_nextkey(krb5_context context, HDB *db, unsigned flags,
370                                    hdb_entry *entry)
371 {
372         struct samba_kdc_db_context *kdc_db_ctx;
373         struct sdb_entry sentry = {};
374         krb5_error_code ret;
375
376         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
377                                            struct samba_kdc_db_context);
378
379         ret = samba_kdc_nextkey(context, kdc_db_ctx, &sentry);
380         switch (ret) {
381         case 0:
382                 break;
383         case SDB_ERR_WRONG_REALM:
384                 return HDB_ERR_WRONG_REALM;
385         case SDB_ERR_NOENTRY:
386                 return HDB_ERR_NOENTRY;
387         case SDB_ERR_NOT_FOUND_HERE:
388                 return HDB_ERR_NOT_FOUND_HERE;
389         default:
390                 return ret;
391         }
392
393         ret = sdb_entry_to_hdb_entry(context, &sentry, entry);
394         sdb_entry_free(&sentry);
395         return ret;
396 }
397
398 static krb5_error_code hdb_samba4_nextkey_panic(krb5_context context, HDB *db,
399                                                 unsigned flags,
400                                                 hdb_entry *entry)
401 {
402         DBG_ERR("Attempt to iterate kpasswd keytab => PANIC\n");
403         smb_panic("hdb_samba4_nextkey_panic: Attempt to iterate kpasswd keytab");
404 }
405
406 static krb5_error_code hdb_samba4_destroy(krb5_context context, HDB *db)
407 {
408         talloc_free(db);
409         return 0;
410 }
411
412 static krb5_error_code
413 hdb_samba4_check_constrained_delegation(krb5_context context, HDB *db,
414                                         hdb_entry *entry,
415                                         krb5_const_principal target_principal)
416 {
417         struct samba_kdc_db_context *kdc_db_ctx;
418         struct samba_kdc_entry *skdc_entry;
419         krb5_error_code ret;
420
421         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
422                                            struct samba_kdc_db_context);
423         skdc_entry = talloc_get_type_abort(entry->context,
424                                            struct samba_kdc_entry);
425
426         ret = samba_kdc_check_s4u2proxy(context, kdc_db_ctx,
427                                         skdc_entry,
428                                         target_principal);
429         switch (ret) {
430         case 0:
431                 break;
432         case SDB_ERR_WRONG_REALM:
433                 ret = HDB_ERR_WRONG_REALM;
434                 break;
435         case SDB_ERR_NOENTRY:
436                 ret = HDB_ERR_NOENTRY;
437                 break;
438         case SDB_ERR_NOT_FOUND_HERE:
439                 ret = HDB_ERR_NOT_FOUND_HERE;
440                 break;
441         default:
442                 break;
443         }
444
445         return ret;
446 }
447
448 static krb5_error_code
449 hdb_samba4_check_pkinit_ms_upn_match(krb5_context context, HDB *db,
450                                      hdb_entry *entry,
451                                      krb5_const_principal certificate_principal)
452 {
453         struct samba_kdc_db_context *kdc_db_ctx;
454         struct samba_kdc_entry *skdc_entry;
455         krb5_error_code ret;
456
457         kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
458                                            struct samba_kdc_db_context);
459         skdc_entry = talloc_get_type_abort(entry->context,
460                                            struct samba_kdc_entry);
461
462         ret = samba_kdc_check_pkinit_ms_upn_match(context, kdc_db_ctx,
463                                                   skdc_entry,
464                                                   certificate_principal);
465         switch (ret) {
466         case 0:
467                 break;
468         case SDB_ERR_WRONG_REALM:
469                 ret = HDB_ERR_WRONG_REALM;
470                 break;
471         case SDB_ERR_NOENTRY:
472                 ret = HDB_ERR_NOENTRY;
473                 break;
474         case SDB_ERR_NOT_FOUND_HERE:
475                 ret = HDB_ERR_NOT_FOUND_HERE;
476                 break;
477         default:
478                 break;
479         }
480
481         return ret;
482 }
483
484 static krb5_error_code
485 hdb_samba4_check_client_matches_target_service(krb5_context context, HDB *db,
486                           hdb_entry *client_entry,
487                           hdb_entry *server_target_entry)
488 {
489         struct samba_kdc_entry *skdc_client_entry
490                 = talloc_get_type_abort(client_entry->context,
491                                         struct samba_kdc_entry);
492         struct samba_kdc_entry *skdc_server_target_entry
493                 = talloc_get_type_abort(server_target_entry->context,
494                                         struct samba_kdc_entry);
495
496         return samba_kdc_check_client_matches_target_service(context,
497                                                              skdc_client_entry,
498                                                              skdc_server_target_entry);
499 }
500
501 static void reset_bad_password_netlogon(TALLOC_CTX *mem_ctx,
502                                         struct samba_kdc_db_context *kdc_db_ctx,
503                                         struct netr_SendToSamBase *send_to_sam)
504 {
505         struct dcerpc_binding_handle *irpc_handle;
506         struct winbind_SendToSam req;
507         struct tevent_req *subreq = NULL;
508
509         irpc_handle = irpc_binding_handle_by_name(mem_ctx, kdc_db_ctx->msg_ctx,
510                                                   "winbind_server",
511                                                   &ndr_table_winbind);
512
513         if (irpc_handle == NULL) {
514                 DEBUG(0, ("No winbind_server running!\n"));
515                 return;
516         }
517
518         req.in.message = *send_to_sam;
519
520         /*
521          * This seem to rely on the current IRPC implementation,
522          * which delivers the message in the _send function.
523          *
524          * TODO: we need a ONE_WAY IRPC handle and register
525          * a callback and wait for it to be triggered!
526          */
527         subreq = dcerpc_winbind_SendToSam_r_send(mem_ctx, kdc_db_ctx->ev_ctx,
528                                                  irpc_handle, &req);
529
530         /* we aren't interested in a reply */
531         TALLOC_FREE(subreq);
532 }
533
534 static krb5_error_code hdb_samba4_audit(krb5_context context,
535                                         HDB *db,
536                                         hdb_entry *entry,
537                                         hdb_request_t r)
538 {
539         struct samba_kdc_db_context *kdc_db_ctx = talloc_get_type_abort(db->hdb_db,
540                                                                         struct samba_kdc_db_context);
541         struct ldb_dn *domain_dn = ldb_get_default_basedn(kdc_db_ctx->samdb);
542         uint64_t logon_id = generate_random_u64();
543         heim_object_t auth_details_obj = NULL;
544         const char *auth_details = NULL;
545         char *etype_str = NULL;
546         heim_object_t hdb_auth_status_obj = NULL;
547         int hdb_auth_status;
548         heim_object_t pa_type_obj = NULL;
549         const char *pa_type = NULL;
550         struct auth_usersupplied_info ui;
551         size_t sa_socklen = 0;
552         krb5_error_code final_ret = 0;
553
554         hdb_auth_status_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_AUTH_EVENT);
555         if (hdb_auth_status_obj == NULL) {
556                 /* No status code found, so just return. */
557                 return 0;
558         }
559
560         hdb_auth_status = heim_number_get_int(hdb_auth_status_obj);
561
562         pa_type_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_PA_NAME);
563         if (pa_type_obj != NULL) {
564                 pa_type = heim_string_get_utf8(pa_type_obj);
565         }
566
567         auth_details_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_PKINIT_CLIENT_CERT);
568         if (auth_details_obj != NULL) {
569                 auth_details = heim_string_get_utf8(auth_details_obj);
570         } else {
571                 auth_details_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_GSS_INITIATOR);
572                 if (auth_details_obj != NULL) {
573                         auth_details = heim_string_get_utf8(auth_details_obj);
574                 } else {
575                         heim_object_t etype_obj = heim_audit_getkv((heim_svc_req_desc)r, KDC_REQUEST_KV_PA_ETYPE);
576                         if (etype_obj != NULL) {
577                                 int etype = heim_number_get_int(etype_obj);
578
579                                 krb5_error_code ret = krb5_enctype_to_string(r->context, etype, &etype_str);
580                                 if (ret == 0) {
581                                         auth_details = etype_str;
582                                 } else {
583                                         auth_details = "unknown enctype";
584                                 }
585                         }
586                 }
587         }
588
589         /*
590          * Forcing this via the NTLM auth structure is not ideal, but
591          * it is the most practical option right now, and ensures the
592          * logs are consistent, even if some elements are always NULL.
593          */
594         ui = (struct auth_usersupplied_info) {
595                 .was_mapped = true,
596                 .client = {
597                         .account_name = r->cname,
598                         .domain_name = NULL,
599                 },
600                 .service_description = "Kerberos KDC",
601                 .auth_description = "Unknown Auth Description",
602                 .password_type = auth_details,
603                 .logon_id = logon_id
604         };
605
606         switch (r->addr->sa_family) {
607         case AF_INET:
608                 sa_socklen = sizeof(struct sockaddr_in);
609                 break;
610 #ifdef HAVE_IPV6
611         case AF_INET6:
612                 sa_socklen = sizeof(struct sockaddr_in6);
613                 break;
614 #endif
615         }
616
617         switch (hdb_auth_status) {
618         default:
619         {
620                 TALLOC_CTX *frame = talloc_stackframe();
621                 struct samba_kdc_entry *p = talloc_get_type_abort(entry->context,
622                                                                   struct samba_kdc_entry);
623                 struct dom_sid *sid
624                         = samdb_result_dom_sid(frame, p->msg, "objectSid");
625                 const char *account_name
626                         = ldb_msg_find_attr_as_string(p->msg, "sAMAccountName", NULL);
627                 const char *domain_name = lpcfg_sam_name(p->kdc_db_ctx->lp_ctx);
628                 struct tsocket_address *remote_host;
629                 const char *auth_description = NULL;
630                 NTSTATUS status;
631                 int ret;
632                 bool rwdc_fallback = false;
633
634                 ret = tsocket_address_bsd_from_sockaddr(frame, r->addr,
635                                                         sa_socklen,
636                                                         &remote_host);
637                 if (ret != 0) {
638                         ui.remote_host = NULL;
639                 } else {
640                         ui.remote_host = remote_host;
641                 }
642
643                 ui.mapped.account_name = account_name;
644                 ui.mapped.domain_name = domain_name;
645
646                 if (pa_type != NULL) {
647                         auth_description = talloc_asprintf(frame,
648                                                            "%s Pre-authentication",
649                                                            pa_type);
650                         if (auth_description == NULL) {
651                                 auth_description = pa_type;
652                         }
653                 } else {
654                         auth_description = "Unknown Pre-authentication";
655                 }
656                 ui.auth_description = auth_description;
657
658                 if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_AUTHORIZED) {
659                         struct netr_SendToSamBase *send_to_sam = NULL;
660
661                         /*
662                          * TODO: We could log the AS-REQ authorization success here as
663                          * well.  However before we do that, we need to pass
664                          * in the PAC here or re-calculate it.
665                          */
666                         status = authsam_logon_success_accounting(kdc_db_ctx->samdb, p->msg,
667                                                                   domain_dn, true, frame, &send_to_sam);
668                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
669                                 final_ret = KRB5KDC_ERR_CLIENT_REVOKED;
670                                 r->error_code = final_ret;
671                                 rwdc_fallback = kdc_db_ctx->rodc;
672                         } else if (!NT_STATUS_IS_OK(status)) {
673                                 final_ret = KRB5KRB_ERR_GENERIC;
674                                 r->error_code = final_ret;
675                                 rwdc_fallback = kdc_db_ctx->rodc;
676                         } else if (kdc_db_ctx->rodc && send_to_sam != NULL) {
677                                 reset_bad_password_netlogon(frame, kdc_db_ctx, send_to_sam);
678                         }
679
680                         /* This is the final sucess */
681                 } else if (hdb_auth_status == KDC_AUTH_EVENT_VALIDATED_LONG_TERM_KEY) {
682                         /*
683                          * This was only a pre-authentication success,
684                          * but we didn't reach the final
685                          * KDC_AUTH_EVENT_CLIENT_AUTHORIZED,
686                          * so consult the error code.
687                          */
688                         if (r->error_code == 0) {
689                                 DBG_ERR("ERROR: VALIDATED_LONG_TERM_KEY "
690                                         "with error=0 => INTERNAL_ERROR\n");
691                                 status = NT_STATUS_INTERNAL_ERROR;
692                                 final_ret = KRB5KRB_ERR_GENERIC;
693                                 r->error_code = final_ret;
694                         } else if (!NT_STATUS_IS_OK(p->reject_status)) {
695                                 status = p->reject_status;
696                         } else {
697                                 status = krb5_to_nt_status(r->error_code);
698                         }
699                 } else if (hdb_auth_status == KDC_AUTH_EVENT_PREAUTH_SUCCEEDED) {
700                         /*
701                          * This was only a pre-authentication success,
702                          * but we didn't reach the final
703                          * KDC_AUTH_EVENT_CLIENT_AUTHORIZED,
704                          * so consult the error code.
705                          */
706                         if (r->error_code == 0) {
707                                 DBG_ERR("ERROR: PREAUTH_SUCCEEDED "
708                                         "with error=0 => INTERNAL_ERROR\n");
709                                 status = NT_STATUS_INTERNAL_ERROR;
710                                 final_ret = KRB5KRB_ERR_GENERIC;
711                                 r->error_code = final_ret;
712                         } else if (!NT_STATUS_IS_OK(p->reject_status)) {
713                                 status = p->reject_status;
714                         } else {
715                                 status = krb5_to_nt_status(r->error_code);
716                         }
717                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_TIME_SKEW) {
718                         status = NT_STATUS_TIME_DIFFERENCE_AT_DC;
719                 } else if (hdb_auth_status == KDC_AUTH_EVENT_WRONG_LONG_TERM_KEY) {
720                         status = authsam_update_bad_pwd_count(kdc_db_ctx->samdb, p->msg, domain_dn);
721                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
722                                 final_ret = KRB5KDC_ERR_CLIENT_REVOKED;
723                                 r->error_code = final_ret;
724                         } else {
725                                 status = NT_STATUS_WRONG_PASSWORD;
726                         }
727                         rwdc_fallback = kdc_db_ctx->rodc;
728                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_LOCKED_OUT) {
729                         status = NT_STATUS_ACCOUNT_LOCKED_OUT;
730                         rwdc_fallback = kdc_db_ctx->rodc;
731                 } else if (hdb_auth_status == KDC_AUTH_EVENT_CLIENT_NAME_UNAUTHORIZED) {
732                         if (pa_type != NULL && strncmp(pa_type, "PK-INIT", strlen("PK-INIT")) == 0) {
733                                 status = NT_STATUS_PKINIT_NAME_MISMATCH;
734                         } else {
735                                 status = NT_STATUS_ACCOUNT_RESTRICTION;
736                         }
737                         rwdc_fallback = kdc_db_ctx->rodc;
738                 } else if (hdb_auth_status == KDC_AUTH_EVENT_PREAUTH_FAILED) {
739                         if (pa_type != NULL && strncmp(pa_type, "PK-INIT", strlen("PK-INIT")) == 0) {
740                                 status = NT_STATUS_PKINIT_FAILURE;
741                         } else {
742                                 status = NT_STATUS_GENERIC_COMMAND_FAILED;
743                         }
744                         rwdc_fallback = kdc_db_ctx->rodc;
745                 } else {
746                         DBG_ERR("Unhandled hdb_auth_status=%d => INTERNAL_ERROR\n",
747                                 hdb_auth_status);
748                         status = NT_STATUS_INTERNAL_ERROR;
749                         final_ret = KRB5KRB_ERR_GENERIC;
750                         r->error_code = final_ret;
751                 }
752
753                 if (rwdc_fallback) {
754                         /*
755                          * Forward the request to an RWDC in order
756                          * to give an authoritative answer to the client.
757                          */
758                         auth_description = talloc_asprintf(frame,
759                                                            "%s,Forward-To-RWDC",
760                                                            ui.auth_description);
761                         if (auth_description != NULL) {
762                                 ui.auth_description = auth_description;
763                         }
764                         final_ret = HDB_ERR_NOT_FOUND_HERE;
765                 }
766
767                 log_authentication_event(kdc_db_ctx->msg_ctx,
768                                          kdc_db_ctx->lp_ctx,
769                                          &r->tv_start,
770                                          &ui,
771                                          status,
772                                          domain_name,
773                                          account_name,
774                                          sid);
775                 if (final_ret == KRB5KRB_ERR_GENERIC && socket_wrapper_enabled()) {
776                         /*
777                          * If we're running under make test
778                          * just panic
779                          */
780                         DBG_ERR("Unexpected situation => PANIC\n");
781                         smb_panic("hdb_samba4_audit: Unexpected situation");
782                 }
783                 TALLOC_FREE(frame);
784                 break;
785         }
786         case KDC_AUTH_EVENT_CLIENT_UNKNOWN:
787         {
788                 struct tsocket_address *remote_host;
789                 int ret;
790                 TALLOC_CTX *frame = talloc_stackframe();
791                 ret = tsocket_address_bsd_from_sockaddr(frame, r->addr,
792                                                         sa_socklen,
793                                                         &remote_host);
794                 if (ret != 0) {
795                         ui.remote_host = NULL;
796                 } else {
797                         ui.remote_host = remote_host;
798                 }
799
800                 if (pa_type == NULL) {
801                         pa_type = "AS-REQ";
802                 }
803
804                 ui.auth_description = pa_type;
805
806                 /* Note this is not forwarded to an RWDC */
807
808                 log_authentication_event(kdc_db_ctx->msg_ctx,
809                                          kdc_db_ctx->lp_ctx,
810                                          &r->tv_start,
811                                          &ui,
812                                          NT_STATUS_NO_SUCH_USER,
813                                          NULL, NULL,
814                                          NULL);
815                 TALLOC_FREE(frame);
816                 break;
817         }
818         }
819
820         free(etype_str);
821
822         return final_ret;
823 }
824
825 /* This interface is to be called by the KDC and libnet_keytab_dump,
826  * which is expecting Samba calling conventions.
827  * It is also called by a wrapper (hdb_samba4_create) from the
828  * kpasswdd -> krb5 -> keytab_hdb -> hdb code */
829
830 NTSTATUS hdb_samba4_create_kdc(struct samba_kdc_base_context *base_ctx,
831                                krb5_context context, struct HDB **db)
832 {
833         struct samba_kdc_db_context *kdc_db_ctx;
834         NTSTATUS nt_status;
835
836         if (hdb_interface_version != HDB_INTERFACE_VERSION) {
837                 krb5_set_error_message(context, EINVAL, "Heimdal HDB interface version mismatch between build-time and run-time libraries!");
838                 return NT_STATUS_ERROR_DS_INCOMPATIBLE_VERSION;
839         }
840
841         *db = talloc_zero(base_ctx, HDB);
842         if (!*db) {
843                 krb5_set_error_message(context, ENOMEM, "malloc: out of memory");
844                 return NT_STATUS_NO_MEMORY;
845         }
846
847         (*db)->hdb_master_key_set = 0;
848         (*db)->hdb_db = NULL;
849         (*db)->hdb_capability_flags = HDB_CAP_F_HANDLE_ENTERPRISE_PRINCIPAL;
850
851         nt_status = samba_kdc_setup_db_ctx(*db, base_ctx, &kdc_db_ctx);
852         if (!NT_STATUS_IS_OK(nt_status)) {
853                 talloc_free(*db);
854                 return nt_status;
855         }
856         (*db)->hdb_db = kdc_db_ctx;
857
858         (*db)->hdb_dbc = NULL;
859         (*db)->hdb_open = hdb_samba4_open;
860         (*db)->hdb_close = hdb_samba4_close;
861         (*db)->hdb_free_entry_context = hdb_samba4_free_entry_context;
862         (*db)->hdb_fetch_kvno = hdb_samba4_fetch_kvno;
863         (*db)->hdb_store = hdb_samba4_store;
864         (*db)->hdb_firstkey = hdb_samba4_firstkey;
865         (*db)->hdb_nextkey = hdb_samba4_nextkey;
866         (*db)->hdb_lock = hdb_samba4_lock;
867         (*db)->hdb_unlock = hdb_samba4_unlock;
868         (*db)->hdb_set_sync = hdb_samba4_set_sync;
869         (*db)->hdb_rename = hdb_samba4_rename;
870         /* we don't implement these, as we are not a lockable database */
871         (*db)->hdb__get = NULL;
872         (*db)->hdb__put = NULL;
873         /* kadmin should not be used for deletes - use other tools instead */
874         (*db)->hdb__del = NULL;
875         (*db)->hdb_destroy = hdb_samba4_destroy;
876
877         (*db)->hdb_audit = hdb_samba4_audit;
878         (*db)->hdb_check_constrained_delegation = hdb_samba4_check_constrained_delegation;
879         (*db)->hdb_check_pkinit_ms_upn_match = hdb_samba4_check_pkinit_ms_upn_match;
880         (*db)->hdb_check_client_matches_target_service = hdb_samba4_check_client_matches_target_service;
881
882         return NT_STATUS_OK;
883 }
884
885 NTSTATUS hdb_samba4_kpasswd_create_kdc(struct samba_kdc_base_context *base_ctx,
886                                        krb5_context context, struct HDB **db)
887 {
888         NTSTATUS nt_status;
889
890         nt_status = hdb_samba4_create_kdc(base_ctx, context, db);
891         if (!NT_STATUS_IS_OK(nt_status)) {
892                 return nt_status;
893         }
894
895         (*db)->hdb_fetch_kvno = hdb_samba4_kpasswd_fetch_kvno;
896         (*db)->hdb_firstkey = hdb_samba4_nextkey_panic;
897         (*db)->hdb_nextkey = hdb_samba4_nextkey_panic;
898
899         return NT_STATUS_OK;
900 }