summaryrefslogtreecommitdiffstats
path: root/auth/auth_log.c
blob: 9a110fd0b4864ae2f97fce74b7e4940f2d09d4e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
/*

   Authentication and authorization logging

   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2017

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 * Debug log levels for authentication logging (these both map to
 * LOG_NOTICE in syslog)
 */
#define AUTH_FAILURE_LEVEL 2
#define AUTH_SUCCESS_LEVEL 3
#define AUTHZ_SUCCESS_LEVEL 4
#define KDC_AUTHZ_FAILURE_LEVEL 2
#define KDC_AUTHZ_SUCCESS_LEVEL 3

/* 5 is used for both authentication and authorization */
#define AUTH_ANONYMOUS_LEVEL 5
#define AUTHZ_ANONYMOUS_LEVEL 5

#define AUTHZ_JSON_TYPE "Authorization"
#define AUTH_JSON_TYPE  "Authentication"
#define KDC_AUTHZ_JSON_TYPE "KDC Authorization"

/*
 * JSON message version numbers
 *
 * If adding a field increment the minor version
 * If removing or changing the format/meaning of a field
 * increment the major version.
 */
#define AUTH_MAJOR 1
#define AUTH_MINOR 3
#define AUTHZ_MAJOR 1
#define AUTHZ_MINOR 2
#define KDC_AUTHZ_MAJOR 1
#define KDC_AUTHZ_MINOR 0

#include "includes.h"
#include "../lib/tsocket/tsocket.h"
#include "common_auth.h"
#include "lib/util/util_str_escape.h"
#include "libcli/security/dom_sid.h"
#include "libcli/security/security_token.h"
#include "librpc/gen_ndr/server_id.h"
#include "source4/lib/messaging/messaging.h"
#include "source4/lib/messaging/irpc.h"
#include "lib/util/server_id_db.h"
#include "lib/param/param.h"
#include "librpc/ndr/libndr.h"
#include "librpc/gen_ndr/windows_event_ids.h"
#include "lib/audit_logging/audit_logging.h"

/*
 * Determine the type of the password supplied for the
 * authorisation attempt.
 *
 */
static const char* get_password_type(const struct auth_usersupplied_info *ui);

#ifdef HAVE_JANSSON

#include <jansson.h>
#include "system/time.h"

/*
 * Write the json object to the debug logs.
 *
 */
static void log_json(struct imessaging_context *msg_ctx,
		     struct loadparm_context *lp_ctx,
		     struct json_object *object,
		     int debug_class,
		     int debug_level)
{
	audit_log_json(object, debug_class, debug_level);
	if (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx)) {
		audit_message_send(msg_ctx,
				   AUTH_EVENT_NAME,
				   MSG_AUTH_LOG,
				   object);
	}
}

/*
 * Determine the Windows logon type for the current authorisation attempt.
 *
 * Currently Samba only supports
 *
 * 2 Interactive      A user logged on to this computer.
 * 3 Network          A user or computer logged on to this computer from
 *                    the network.
 * 8 NetworkCleartext A user logged on to this computer from the network.
 *                    The user's password was passed to the authentication
 *                    package in its unhashed form.
 *
 */
static enum event_logon_type get_logon_type(
	const struct auth_usersupplied_info *ui)
{
	if ((ui->logon_parameters & MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED)
	   || (ui->password_state == AUTH_PASSWORD_PLAIN)) {
		return EVT_LOGON_NETWORK_CLEAR_TEXT;
	} else if (ui->flags & USER_INFO_INTERACTIVE_LOGON) {
		return EVT_LOGON_INTERACTIVE;
	}
	return EVT_LOGON_NETWORK;
}

/*
 * Write a machine parsable json formatted authentication log entry.
 *
 * IF removing or changing the format/meaning of a field please update the
 *    major version number AUTH_MAJOR
 *
 * IF adding a new field please update the minor version number AUTH_MINOR
 *
 *  To process the resulting log lines from the command line use jq to
 *  parse the json.
 *
 *  grep "^  {" log file |
 *  jq -rc '"\(.timestamp)\t\(.Authentication.status)\t
 *           \(.Authentication.clientDomain)\t
 *           \(.Authentication.clientAccount)
 *           \t\(.Authentication.workstation)
 *           \t\(.Authentication.remoteAddress)
 *           \t\(.Authentication.localAddress)"'
 */
static void log_authentication_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct timeval *start_time,
	const struct auth_usersupplied_info *ui,
	NTSTATUS status,
	const char *domain_name,
	const char *account_name,
	struct dom_sid *sid,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info,
	enum event_id_type event_id,
	int debug_level)
{
	struct json_object wrapper = json_empty_object;
	struct json_object authentication = json_empty_object;
	struct json_object client_policy = json_null_object();
	struct json_object server_policy = json_null_object();
	char logon_id[19];
	int rc = 0;
	const char *clientDomain = ui->orig_client.domain_name ?
				   ui->orig_client.domain_name :
				   ui->client.domain_name;
	const char *clientAccount = ui->orig_client.account_name ?
				    ui->orig_client.account_name :
				    ui->client.account_name;

	authentication = json_new_object();
	if (json_is_invalid(&authentication)) {
		goto failure;
	}
	rc = json_add_version(&authentication, AUTH_MAJOR, AUTH_MINOR);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_int(&authentication,
			  "eventId",
			  event_id);
	if (rc != 0) {
		goto failure;
	}
	snprintf(logon_id,
		 sizeof( logon_id),
		 "%"PRIx64"",
		 ui->logon_id);
	rc = json_add_string(&authentication, "logonId", logon_id);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_int(&authentication, "logonType", get_logon_type(ui));
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authentication, "status", nt_errstr(status));
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&authentication, "localAddress", ui->local_host);
	if (rc != 0) {
		goto failure;
	}
	rc =
	    json_add_address(&authentication, "remoteAddress", ui->remote_host);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "serviceDescription", ui->service_description);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "authDescription", ui->auth_description);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "clientDomain", clientDomain);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "clientAccount", clientAccount);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "workstation", ui->workstation_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authentication, "becameAccount", account_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authentication, "becameDomain", domain_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_sid(&authentication, "becameSid", sid);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "mappedAccount", ui->mapped.account_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "mappedDomain", ui->mapped.domain_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authentication,
			     "netlogonComputer",
			     ui->netlogon_trust_account.computer_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authentication,
			     "netlogonTrustAccount",
			     ui->netlogon_trust_account.account_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_flags32(
	    &authentication, "netlogonNegotiateFlags",
	    ui->netlogon_trust_account.negotiate_flags);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_int(&authentication,
			  "netlogonSecureChannelType",
			  ui->netlogon_trust_account.secure_channel_type);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_sid(&authentication,
			  "netlogonTrustAccountSid",
			  ui->netlogon_trust_account.sid);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authentication, "passwordType", get_password_type(ui));
	if (rc != 0) {
		goto failure;
	}

	if (client_audit_info != NULL) {
		client_policy = json_from_audit_info(client_audit_info);
		if (json_is_invalid(&client_policy)) {
			goto failure;
		}
	}

	rc = json_add_object(&authentication, "clientPolicyAccessCheck", &client_policy);
	if (rc != 0) {
		goto failure;
	}

	if (server_audit_info != NULL) {
		server_policy = json_from_audit_info(server_audit_info);
		if (json_is_invalid(&server_policy)) {
			goto failure;
		}
	}

	rc = json_add_object(&authentication, "serverPolicyAccessCheck", &server_policy);
	if (rc != 0) {
		goto failure;
	}

	wrapper = json_new_object();
	if (json_is_invalid(&wrapper)) {
		goto failure;
	}
	rc = json_add_timestamp(&wrapper);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&wrapper, "type", AUTH_JSON_TYPE);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_object(&wrapper, AUTH_JSON_TYPE, &authentication);
	if (rc != 0) {
		goto failure;
	}

	/*
	 * While not a general-purpose profiling solution this will
	 * assist some to determine how long NTLM and KDC
	 * authentication takes once this process can handle it.  This
	 * covers transactions elsewhere but not (eg) the delay while
	 * this is waiting unread on the input socket.
	 */
	if (start_time != NULL) {
		struct timeval current_time = timeval_current();
		uint64_t duration =  usec_time_diff(&current_time,
						    start_time);
		rc = json_add_int(&authentication, "duration", duration);
		if (rc != 0) {
			goto failure;
		}
	}

	log_json(msg_ctx,
		 lp_ctx,
		 &wrapper,
		 DBGC_AUTH_AUDIT_JSON,
		 debug_level);
	json_free(&wrapper);
	return;
failure:
	json_free(&server_policy);
	json_free(&client_policy);
	/*
	 * On a failure authentication will not have been added to wrapper so it
	 * needs to be freed to avoid a leak.
	 *
	 */
	json_free(&authentication);
	json_free(&wrapper);
	DBG_ERR("Failed to write authentication event JSON log message\n");
}

/*
 * Log details of a successful authorization to a service,
 * in a machine parsable json format
 *
 * IF removing or changing the format/meaning of a field please update the
 *    major version number AUTHZ_MAJOR
 *
 * IF adding a new field please update the minor version number AUTHZ_MINOR
 *
 *  To process the resulting log lines from the command line use jq to
 *  parse the json.
 *
 *  grep "^  {" log_file |\
 *  jq -rc '"\(.timestamp)\t
 *           \(.Authorization.domain)\t
 *           \(.Authorization.account)\t
 *           \(.Authorization.remoteAddress)"'
 *
 */
static void log_successful_authz_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const char *service_description,
	const char *auth_type,
	const char *transport_protection,
	struct auth_session_info *session_info,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info,
	int debug_level)
{
	struct json_object wrapper = json_empty_object;
	struct json_object authorization = json_empty_object;
	struct json_object client_policy = json_null_object();
	struct json_object server_policy = json_null_object();
	int rc = 0;

	authorization = json_new_object();
	if (json_is_invalid(&authorization)) {
		goto failure;
	}
	rc = json_add_version(&authorization, AUTHZ_MAJOR, AUTHZ_MINOR);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&authorization, "localAddress", local);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&authorization, "remoteAddress", remote);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "serviceDescription", service_description);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "authType", auth_type);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "domain", session_info->info->domain_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "account", session_info->info->account_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_sid(
	    &authorization, "sid", &session_info->security_token->sids[PRIMARY_USER_SID_INDEX]);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_guid(
	    &authorization, "sessionId", &session_info->unique_session_token);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "logonServer", session_info->info->logon_server);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "transportProtection", transport_protection);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_flags32(&authorization, "accountFlags", session_info->info->acct_flags);
	if (rc != 0) {
		goto failure;
	}

	if (client_audit_info != NULL) {
		client_policy = json_from_audit_info(client_audit_info);
		if (json_is_invalid(&client_policy)) {
			goto failure;
		}
	}

	rc = json_add_object(&authorization, "clientPolicyAccessCheck", &client_policy);
	if (rc != 0) {
		goto failure;
	}

	if (server_audit_info != NULL) {
		server_policy = json_from_audit_info(server_audit_info);
		if (json_is_invalid(&server_policy)) {
			goto failure;
		}
	}

	rc = json_add_object(&authorization, "serverPolicyAccessCheck", &server_policy);
	if (rc != 0) {
		goto failure;
	}

	wrapper = json_new_object();
	if (json_is_invalid(&wrapper)) {
		goto failure;
	}
	rc = json_add_timestamp(&wrapper);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&wrapper, "type", AUTHZ_JSON_TYPE);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_object(&wrapper, AUTHZ_JSON_TYPE, &authorization);
	if (rc != 0) {
		goto failure;
	}

	log_json(msg_ctx,
		 lp_ctx,
		 &wrapper,
		 DBGC_AUTH_AUDIT_JSON,
		 debug_level);
	json_free(&wrapper);
	return;
failure:
	json_free(&server_policy);
	json_free(&client_policy);
	/*
	 * On a failure authorization will not have been added to wrapper so it
	 * needs to be freed to avoid a leak.
	 *
	 */
	json_free(&authorization);
	json_free(&wrapper);
	DBG_ERR("Unable to log Authentication event JSON audit message\n");
}

/*
 * Log details of an authorization to a service, in a machine parsable json
 * format
 *
 * IF removing or changing the format/meaning of a field please update the
 *    major version number KDC_AUTHZ_MAJOR
 *
 * IF adding a new field please update the minor version number KDC_AUTHZ_MINOR
 *
 *  To process the resulting log lines from the command line use jq to
 *  parse the json.
 *
 *  grep "^  {" log_file |\
 *  jq -rc '"\(.timestamp)\t
 *           \(."KDC Authorization".domain)\t
 *           \(."KDC Authorization".account)\t
 *           \(."KDC Authorization".remoteAddress)"'
 *
 */
static void log_authz_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const struct authn_audit_info *server_audit_info,
	const char *service_description,
	const char *auth_type,
	const char *domain_name,
	const char *account_name,
	const struct dom_sid *sid,
	const char *logon_server,
	const struct timeval authtime,
	NTSTATUS status,
	int debug_level)
{
	struct json_object wrapper = json_empty_object;
	struct json_object authorization = json_empty_object;
	struct json_object server_policy = json_null_object();
	int rc = 0;

	authorization = json_new_object();
	if (json_is_invalid(&authorization)) {
		goto failure;
	}
	rc = json_add_version(&authorization, KDC_AUTHZ_MAJOR, KDC_AUTHZ_MINOR);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "status", nt_errstr(status));
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&authorization, "localAddress", local);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&authorization, "remoteAddress", remote);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(
	    &authorization, "serviceDescription", service_description);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "authType", auth_type);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "domain", domain_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "account", account_name);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_sid(&authorization, "sid", sid);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&authorization, "logonServer", logon_server);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_time(&authorization, "authTime", authtime);
	if (rc != 0) {
		goto failure;
	}

	if (server_audit_info != NULL) {
		server_policy = json_from_audit_info(server_audit_info);
		if (json_is_invalid(&server_policy)) {
			goto failure;
		}
	}

	rc = json_add_object(&authorization, "serverPolicyAccessCheck", &server_policy);
	if (rc != 0) {
		goto failure;
	}

	wrapper = json_new_object();
	if (json_is_invalid(&wrapper)) {
		goto failure;
	}
	rc = json_add_timestamp(&wrapper);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&wrapper, "type", KDC_AUTHZ_JSON_TYPE);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_object(&wrapper, KDC_AUTHZ_JSON_TYPE, &authorization);
	if (rc != 0) {
		goto failure;
	}

	log_json(msg_ctx,
		 lp_ctx,
		 &wrapper,
		 DBGC_AUTH_AUDIT_JSON,
		 debug_level);
	json_free(&wrapper);
	return;
failure:
	json_free(&server_policy);
	/*
	 * On a failure authorization will not have been added to wrapper so it
	 * needs to be freed to avoid a leak.
	 */
	json_free(&authorization);
	json_free(&wrapper);
	DBG_ERR("Unable to log KDC Authorization event JSON audit message\n");
}

#else

static void log_no_json(struct imessaging_context *msg_ctx,
                        struct loadparm_context *lp_ctx)
{
	if (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx)) {
		static bool auth_event_logged = false;
		if (auth_event_logged == false) {
			auth_event_logged = true;
			DBG_ERR("auth event notification = true but Samba was "
				"not compiled with jansson\n");
		}
	} else {
		static bool json_logged = false;
		if (json_logged == false) {
			json_logged = true;
			DBG_NOTICE("JSON auth logs not available unless "
				   "compiled with jansson\n");
		}
	}
}

static void log_authentication_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct timeval *start_time,
	const struct auth_usersupplied_info *ui,
	NTSTATUS status,
	const char *domain_name,
	const char *account_name,
	struct dom_sid *sid,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info,
	enum event_id_type event_id,
	int debug_level)
{
	log_no_json(msg_ctx, lp_ctx);
}

static void log_successful_authz_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const char *service_description,
	const char *auth_type,
	const char *transport_protection,
	struct auth_session_info *session_info,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info,
	int debug_level)
{
	log_no_json(msg_ctx, lp_ctx);
}

static void log_authz_event_json(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const struct authn_audit_info *server_audit_info,
	const char *service_description,
	const char *auth_type,
	const char *domain_name,
	const char *account_name,
	const struct dom_sid *sid,
	const char *logon_server,
	const struct timeval authtime,
	NTSTATUS status,
	int debug_level)
{
	log_no_json(msg_ctx, lp_ctx);
}

#endif

/*
 * Determine the type of the password supplied for the
 * authorisation attempt.
 *
 */
static const char* get_password_type(const struct auth_usersupplied_info *ui)
{

	const char *password_type = NULL;

	if (ui->password_type != NULL) {
		password_type = ui->password_type;
	} else if (ui->auth_description != NULL &&
		   strncmp("ServerAuthenticate", ui->auth_description, 18) == 0)
	{
		if (ui->netlogon_trust_account.negotiate_flags
		    & NETLOGON_NEG_SUPPORTS_AES) {
			password_type = "HMAC-SHA256";
		} else if (ui->netlogon_trust_account.negotiate_flags
		           & NETLOGON_NEG_STRONG_KEYS) {
			password_type = "HMAC-MD5";
		} else {
			password_type = "DES";
		}
	} else if (ui->password_state == AUTH_PASSWORD_RESPONSE &&
		   (ui->logon_parameters & MSV1_0_ALLOW_MSVCHAPV2) &&
		   ui->password.response.nt.length == 24) {
		password_type = "MSCHAPv2";
	} else if ((ui->logon_parameters & MSV1_0_CLEARTEXT_PASSWORD_SUPPLIED)
		   || (ui->password_state == AUTH_PASSWORD_PLAIN)) {
		password_type = "Plaintext";
	} else if (ui->password_state == AUTH_PASSWORD_HASH) {
		password_type = "Supplied-NT-Hash";
	} else if (ui->password_state == AUTH_PASSWORD_RESPONSE
		   && ui->password.response.nt.length > 24) {
		password_type = "NTLMv2";
	} else if (ui->password_state == AUTH_PASSWORD_RESPONSE
		   && ui->password.response.nt.length == 24) {
		password_type = "NTLMv1";
	} else if (ui->password_state == AUTH_PASSWORD_RESPONSE
		   && ui->password.response.lanman.length == 24) {
		password_type = "LANMan";
	} else if (ui->password_state == AUTH_PASSWORD_RESPONSE
		   && ui->password.response.nt.length == 0
		   && ui->password.response.lanman.length == 0) {
		password_type = "No-Password";
	}
	return password_type;
}

/*
 * Write a human readable authentication log entry.
 *
 */
static void log_authentication_event_human_readable(
	const struct auth_usersupplied_info *ui,
	NTSTATUS status,
	const char *domain_name,
	const char *account_name,
	struct dom_sid *sid,
	int debug_level)
{
	TALLOC_CTX *frame = NULL;

	const char *ts = NULL;		   /* formatted current time      */
	char *remote = NULL;		   /* formatted remote host       */
	char *local = NULL;		   /* formatted local host        */
	char *nl = NULL;		   /* NETLOGON details if present */
	char *trust_computer_name = NULL;
	char *trust_account_name = NULL;
	char *logon_line = NULL;
	const char *password_type = NULL;
	const char *clientDomain = ui->orig_client.domain_name ?
				   ui->orig_client.domain_name :
				   ui->client.domain_name;
	const char *clientAccount = ui->orig_client.account_name ?
				    ui->orig_client.account_name :
				    ui->client.account_name;

	frame = talloc_stackframe();

	password_type = get_password_type(ui);
	/* Get the current time */
        ts = audit_get_timestamp(frame);

	/* Only log the NETLOGON details if they are present */
	if (ui->netlogon_trust_account.computer_name ||
	    ui->netlogon_trust_account.account_name) {
		trust_computer_name = log_escape(frame,
			ui->netlogon_trust_account.computer_name);
		trust_account_name  = log_escape(frame,
			ui->netlogon_trust_account.account_name);
		nl = talloc_asprintf(frame,
			" NETLOGON computer [%s] trust account [%s]",
			trust_computer_name, trust_account_name);
	}

	remote = tsocket_address_string(ui->remote_host, frame);
	local = tsocket_address_string(ui->local_host, frame);

	if (NT_STATUS_IS_OK(status)) {
		struct dom_sid_buf sid_buf;

		logon_line = talloc_asprintf(frame,
					     " became [%s]\\[%s] [%s].",
					     log_escape(frame, domain_name),
					     log_escape(frame, account_name),
					     dom_sid_str_buf(sid, &sid_buf));
	} else {
		logon_line = talloc_asprintf(
				frame,
				" mapped to [%s]\\[%s].",
				log_escape(frame, ui->mapped.domain_name),
				log_escape(frame, ui->mapped.account_name));
	}

	DEBUGC(DBGC_AUTH_AUDIT, debug_level,
	       ("Auth: [%s,%s] user [%s]\\[%s]"
		" at [%s] with [%s] status [%s]"
		" workstation [%s] remote host [%s]"
		"%s local host [%s]"
		" %s\n",
		ui->service_description,
		ui->auth_description,
		log_escape(frame, clientDomain),
		log_escape(frame, clientAccount),
		ts,
		password_type,
		nt_errstr(status),
		log_escape(frame, ui->workstation_name),
		remote,
		logon_line,
		local,
		nl ? nl : ""
	));

	talloc_free(frame);
}

/*
 * Log details of an authentication attempt.
 * Successful and unsuccessful attempts are logged.
 *
 * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
 * authentication events over the message bus.
 */
void log_authentication_event(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct timeval *start_time,
	const struct auth_usersupplied_info *ui,
	NTSTATUS status,
	const char *domain_name,
	const char *account_name,
	struct dom_sid *sid,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info)
{
	/* set the log level */
	int debug_level = AUTH_FAILURE_LEVEL;
	enum event_id_type event_id = EVT_ID_UNSUCCESSFUL_LOGON;

	if (NT_STATUS_IS_OK(status)) {
		debug_level = AUTH_SUCCESS_LEVEL;
		event_id = EVT_ID_SUCCESSFUL_LOGON;
		if (dom_sid_equal(sid, &global_sid_Anonymous)) {
			debug_level = AUTH_ANONYMOUS_LEVEL;
		}
	}

	if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT, debug_level)) {
		log_authentication_event_human_readable(ui,
							status,
							domain_name,
							account_name,
							sid,
							debug_level);
	}
	if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
	    (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
		log_authentication_event_json(msg_ctx,
					      lp_ctx,
					      start_time,
					      ui,
					      status,
					      domain_name,
					      account_name,
					      sid,
					      client_audit_info,
					      server_audit_info,
					      event_id,
					      debug_level);
	}
}



/*
 * Log details of a successful authorization to a service,
 * in a human readable format.
 *
 */
static void log_successful_authz_event_human_readable(
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const char *service_description,
	const char *auth_type,
	struct auth_session_info *session_info,
	int debug_level)
{
	TALLOC_CTX *frame = NULL;

	const char *ts = NULL;       /* formatted current time      */
	char *remote_str = NULL;     /* formatted remote host       */
	char *local_str = NULL;      /* formatted local host        */
	struct dom_sid_buf sid_buf;

	frame = talloc_stackframe();

	/* Get the current time */
        ts = audit_get_timestamp(frame);

	remote_str = tsocket_address_string(remote, frame);
	local_str = tsocket_address_string(local, frame);

	DEBUGC(DBGC_AUTH_AUDIT, debug_level,
	       ("Successful AuthZ: [%s,%s] user [%s]\\[%s] [%s]"
		" at [%s]"
		" Remote host [%s]"
		" local host [%s]\n",
		service_description,
		auth_type,
		log_escape(frame, session_info->info->domain_name),
		log_escape(frame, session_info->info->account_name),
		dom_sid_str_buf(&session_info->security_token->sids[PRIMARY_USER_SID_INDEX],
				&sid_buf),
		ts,
		remote_str,
		local_str));

	talloc_free(frame);
}

/*
 * Log details of a successful authorization to a service.
 *
 * Only successful authorizations are logged.  For clarity:
 * - NTLM bad passwords will be recorded by log_authentication_event
 * - Kerberos decrypt failures need to be logged in gensec_gssapi et al
 *
 * The service may later refuse authorization due to an ACL.
 *
 * NOTE: msg_ctx and lp_ctx is optional, but when supplied allows streaming the
 * authentication events over the message bus.
 */
void log_successful_authz_event(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const char *service_description,
	const char *auth_type,
	const char *transport_protection,
	struct auth_session_info *session_info,
	const struct authn_audit_info *client_audit_info,
	const struct authn_audit_info *server_audit_info)
{
	int debug_level = AUTHZ_SUCCESS_LEVEL;

	/* set the log level */
	if (security_token_is_anonymous(session_info->security_token)) {
		debug_level = AUTH_ANONYMOUS_LEVEL;
	}

	if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT, debug_level)) {
		log_successful_authz_event_human_readable(remote,
							  local,
							  service_description,
							  auth_type,
							  session_info,
							  debug_level);
	}
	if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
	    (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
		log_successful_authz_event_json(msg_ctx, lp_ctx,
						remote,
						local,
						service_description,
						auth_type,
						transport_protection,
						session_info,
						client_audit_info,
						server_audit_info,
						debug_level);
	}
}

/*
 * Log details of an authorization to a service.
 *
 * NOTE: msg_ctx and lp_ctx are optional, but when supplied, allow streaming the
 * authorization events over the message bus.
 */
void log_authz_event(
	struct imessaging_context *msg_ctx,
	struct loadparm_context *lp_ctx,
	const struct tsocket_address *remote,
	const struct tsocket_address *local,
	const struct authn_audit_info *server_audit_info,
	const char *service_description,
	const char *auth_type,
	const char *domain_name,
	const char *account_name,
	const struct dom_sid *sid,
	const char *logon_server,
	const struct timeval authtime,
	NTSTATUS status)
{
	/* set the log level */
	int debug_level = KDC_AUTHZ_FAILURE_LEVEL;

	if (NT_STATUS_IS_OK(status)) {
		debug_level = KDC_AUTHZ_SUCCESS_LEVEL;
	}

	if (CHECK_DEBUGLVLC(DBGC_AUTH_AUDIT_JSON, debug_level) ||
	    (msg_ctx && lp_ctx && lpcfg_auth_event_notification(lp_ctx))) {
		log_authz_event_json(msg_ctx, lp_ctx,
				     remote,
				     local,
				     server_audit_info,
				     service_description,
				     auth_type,
				     domain_name,
				     account_name,
				     sid,
				     logon_server,
				     authtime,
				     status,
				     debug_level);
	}
}