summaryrefslogtreecommitdiffstats
path: root/source4/dsdb/samdb/ldb_modules/group_audit.c
blob: a6ca25eae4cd21cbd6a733d96ac79714207cfdff (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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
/*
   ldb database library

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

   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/>.
*/

/*
 * Provide an audit log of changes made to group memberships
 *
 */

#include "includes.h"
#include "ldb_module.h"
#include "lib/audit_logging/audit_logging.h"
#include "librpc/gen_ndr/windows_event_ids.h"

#include "dsdb/samdb/samdb.h"
#include "dsdb/samdb/ldb_modules/util.h"
#include "dsdb/samdb/ldb_modules/audit_util_proto.h"
#include "libcli/security/dom_sid.h"
#include "auth/common_auth.h"
#include "param/param.h"

#define AUDIT_JSON_TYPE "groupChange"
#define AUDIT_HR_TAG "Group Change"
#define AUDIT_MAJOR 1
#define AUDIT_MINOR 1
#define GROUP_LOG_LVL 5

static const char *const group_attrs[] = {"member", "groupType", NULL};
static const char *const group_type_attr[] = {"groupType", NULL};
static const char * const primary_group_attr[] = {
	"primaryGroupID",
	"objectSID",
	NULL};

struct audit_context {
	bool send_events;
	struct imessaging_context *msg_ctx;
};

struct audit_callback_context {
	struct ldb_request *request;
	struct ldb_module *module;
	struct ldb_message_element *members;
	uint32_t primary_group;
	void (*log_changes)(
		struct audit_callback_context *acc,
		const int status);
};

/*
 * @brief get the transaction id.
 *
 * Get the id of the transaction that the current request is contained in.
 *
 * @param req the request.
 *
 * @return the transaction id GUID, or NULL if it is not there.
 */
static struct GUID *get_transaction_id(
	const struct ldb_request *request)
{
	struct ldb_control *control;
	struct dsdb_control_transaction_identifier *transaction_id;

	control = ldb_request_get_control(
		discard_const(request),
		DSDB_CONTROL_TRANSACTION_IDENTIFIER_OID);
	if (control == NULL) {
		return NULL;
	}
	transaction_id = talloc_get_type(
		control->data,
		struct dsdb_control_transaction_identifier);
	if (transaction_id == NULL) {
		return NULL;
	}
	return &transaction_id->transaction_guid;
}

/*
 * @brief generate a JSON log entry for a group change.
 *
 * Generate a JSON object containing details of a users group change.
 *
 * @param module the ldb module
 * @param request the ldb_request
 * @param action the change action being performed
 * @param user the user name
 * @param group the group name
 * @param status the ldb status code for the ldb operation.
 *
 * @return A json object containing the details.
 * 	   NULL if an error was detected
 */
static struct json_object audit_group_json(const struct ldb_module *module,
					   const struct ldb_request *request,
					   const char *action,
					   const char *user,
					   const char *group,
					   const enum event_id_type event_id,
					   const int status)
{
	struct ldb_context *ldb = NULL;
	const struct dom_sid *sid = NULL;
	struct json_object wrapper = json_empty_object;
	struct json_object audit = json_empty_object;
	const struct tsocket_address *remote = NULL;
	const struct GUID *unique_session_token = NULL;
	struct GUID *transaction_id = NULL;
	int rc = 0;

	ldb = ldb_module_get_ctx(discard_const(module));

	remote = dsdb_audit_get_remote_address(ldb);
	sid = dsdb_audit_get_user_sid(module);
	unique_session_token = dsdb_audit_get_unique_session_token(module);
	transaction_id = get_transaction_id(request);

	audit = json_new_object();
	if (json_is_invalid(&audit)) {
		goto failure;
	}
	rc = json_add_version(&audit, AUDIT_MAJOR, AUDIT_MINOR);
	if (rc != 0) {
		goto failure;
	}
	if (event_id != EVT_ID_NONE) {
		rc = json_add_int(&audit, "eventId", event_id);
		if (rc != 0) {
			goto failure;
		}
	}
	rc = json_add_int(&audit, "statusCode", status);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&audit, "status", ldb_strerror(status));
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&audit, "action", action);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_address(&audit, "remoteAddress", remote);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_sid(&audit, "userSid", sid);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&audit, "group", group);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_guid(&audit, "transactionId", transaction_id);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_guid(&audit, "sessionId", unique_session_token);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_string(&audit, "user", user);
	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", AUDIT_JSON_TYPE);
	if (rc != 0) {
		goto failure;
	}
	rc = json_add_object(&wrapper, AUDIT_JSON_TYPE, &audit);
	if (rc != 0) {
		goto failure;
	}

	return wrapper;
failure:
	/*
	 * On a failure audit will not have been added to wrapper so it
	 * needs to free it to avoid a leak.
	 *
	 * wrapper is freed to invalidate it as it will have only been
	 * partially constructed and may be inconsistent.
	 *
	 * All the json manipulation routines handle a freed object correctly
	 */
	json_free(&audit);
	json_free(&wrapper);
	DBG_ERR("Failed to create group change JSON log message\n");
	return wrapper;
}

/*
 * @brief generate a human readable log entry for a group change.
 *
 * Generate a human readable log entry containing details of a users group
 * change.
 *
 * @param ctx the talloc context owning the returned log entry
 * @param module the ldb module
 * @param request the ldb_request
 * @param action the change action being performed
 * @param user the user name
 * @param group the group name
 * @param status the ldb status code for the ldb operation.
 *
 * @return A human readable log line.
 */
static char *audit_group_human_readable(
	TALLOC_CTX *mem_ctx,
	const struct ldb_module *module,
	const struct ldb_request *request,
	const char *action,
	const char *user,
	const char *group,
	const int status)
{
	struct ldb_context *ldb = NULL;
	const char *remote_host = NULL;
	const struct dom_sid *sid = NULL;
	const char *user_sid = NULL;
	const char *timestamp = NULL;
	char *log_entry = NULL;

	TALLOC_CTX *ctx = talloc_new(NULL);

	ldb = ldb_module_get_ctx(discard_const(module));

	remote_host = dsdb_audit_get_remote_host(ldb, ctx);
	sid = dsdb_audit_get_user_sid(module);
	user_sid = dom_sid_string(ctx, sid);
	timestamp = audit_get_timestamp(ctx);

	log_entry = talloc_asprintf(
		mem_ctx,
		"[%s] at [%s] status [%s] "
		"Remote host [%s] SID [%s] Group [%s] User [%s]",
		action,
		timestamp,
		ldb_strerror(status),
		remote_host,
		user_sid,
		group,
		user);
	TALLOC_FREE(ctx);
	return log_entry;
}

/*
 * @brief generate an array of parsed_dns, deferring the actual parsing.
 *
 * Get an array of 'struct parsed_dns' without the parsing.
 * The parsed_dns are parsed only when needed to avoid the expense of parsing.
 *
 * This procedure assumes that the dn's are sorted in GUID order and contains
 * no duplicates.  This should be valid as the module sits below repl_meta_data
 * which ensures this.
 *
 * @param mem_ctx The memory context that will own the generated array
 * @param el The message element used to generate the array.
 *
 * @return an array of struct parsed_dns, or NULL in the event of an error
 */
static struct parsed_dn *get_parsed_dns(
	TALLOC_CTX *mem_ctx,
	struct ldb_message_element *el)
{
	int ret;
	struct parsed_dn *pdn = NULL;

	if (el == NULL || el->num_values == 0) {
		return NULL;
	}

	ret = get_parsed_dns_trusted(mem_ctx, el, &pdn);
	if (ret == LDB_ERR_OPERATIONS_ERROR) {
		DBG_ERR("Out of memory\n");
		return NULL;
	}
	return pdn;

}

enum dn_compare_result {
	LESS_THAN,
	BINARY_EQUAL,
	EQUAL,
	GREATER_THAN
};
/*
 * @brief compare parsed_dn, using GUID ordering
 *
 * Compare two parsed_dn structures, using GUID ordering.
 * To avoid the overhead of parsing the DN's this function does a binary
 * compare first. The DN's tre only parsed if they are not equal at a binary
 * level.
 *
 * @param ctx talloc context that will own the parsed dsdb_dn
 * @param ldb ldb_context
 * @param dn1 The first dn
 * @param dn2 The second dn
 *
 * @return BINARY_EQUAL values are equal at a binary level
 *         EQUAL        DN's are equal but the meta data is different
 *         LESS_THAN    dn1's GUID is less than dn2's GUID
 *         GREATER_THAN dn1's GUID is greater than  dn2's GUID
 *
 */
static enum dn_compare_result dn_compare(
	TALLOC_CTX *mem_ctx,
	struct ldb_context *ldb,
	struct parsed_dn *dn1,
	struct parsed_dn *dn2) {

	int res = 0;

	/*
	 * Do a binary compare first to avoid unnecessary parsing
	 */
	if (data_blob_cmp(dn1->v, dn2->v) == 0) {
		/*
		 * Values are equal at a binary level so no need
		 * for further processing
		 */
		return BINARY_EQUAL;
	}
	/*
	 * Values not equal at the binary level, so lets
	 * do a GUID ordering compare. To do this we will need to ensure
	 * that the dn's have been parsed.
	 */
	if (dn1->dsdb_dn == NULL) {
		really_parse_trusted_dn(
			mem_ctx,
			ldb,
			dn1,
			LDB_SYNTAX_DN);
	}
	if (dn2->dsdb_dn == NULL) {
		really_parse_trusted_dn(
			mem_ctx,
			ldb,
			dn2,
			LDB_SYNTAX_DN);
	}

	res = ndr_guid_compare(&dn1->guid, &dn2->guid);
	if (res < 0) {
		return LESS_THAN;
	} else if (res == 0) {
		return EQUAL;
	} else {
		return GREATER_THAN;
	}
}

/*
 * @brief Get the DN of a users primary group as a printable string.
 *
 * Get the DN of a users primary group as a printable string.
 *
 * @param mem_ctx Talloc context the the returned string will be allocated on.
 * @param module The ldb module
 * @param account_sid The SID for the uses account.
 * @param primary_group_rid The RID for the users primary group.
 *
 * @return a formatted DN, or null if there is an error.
 */
static const char *get_primary_group_dn(
	TALLOC_CTX *mem_ctx,
	struct ldb_module *module,
	struct dom_sid *account_sid,
	uint32_t primary_group_rid)
{
	NTSTATUS status;

	struct ldb_context *ldb = NULL;
	struct dom_sid *domain_sid = NULL;
	struct dom_sid *primary_group_sid = NULL;
	char *sid = NULL;
	struct ldb_dn *dn = NULL;
	struct ldb_message *msg = NULL;
	int rc;

	ldb = ldb_module_get_ctx(module);

	status = dom_sid_split_rid(mem_ctx, account_sid, &domain_sid, NULL);
	if (!NT_STATUS_IS_OK(status)) {
		return NULL;
	}

	primary_group_sid = dom_sid_add_rid(
		mem_ctx,
		domain_sid,
		primary_group_rid);
	if (!primary_group_sid) {
		return NULL;
	}

	sid = dom_sid_string(mem_ctx, primary_group_sid);
	if (sid == NULL) {
		return NULL;
	}

	dn = ldb_dn_new_fmt(mem_ctx, ldb, "<SID=%s>", sid);
	if(dn == NULL) {
		return sid;
	}
	rc = dsdb_search_one(
		ldb,
		mem_ctx,
		&msg,
		dn,
		LDB_SCOPE_BASE,
		NULL,
		0,
		NULL);
	if (rc != LDB_SUCCESS) {
		return NULL;
	}

	return ldb_dn_get_linearized(msg->dn);
}

/*
 * @brief Log details of a change to a users primary group.
 *
 * Log details of a change to a users primary group.
 * There is no windows event id associated with a Primary Group change.
 * However for a new user we generate an added to group event.
 *
 * @param module The ldb module.
 * @param request The request being logged.
 * @param action Description of the action being performed.
 * @param group The linearized for of the group DN
 * @param status the LDB status code for the processing of the request.
 *
 */
static void log_primary_group_change(
	struct ldb_module *module,
	const struct ldb_request *request,
	const char *action,
	const char *group,
	const int  status)
{
	const char *user = NULL;

	struct audit_context *ac =
		talloc_get_type(
			ldb_module_get_private(module),
			struct audit_context);

	TALLOC_CTX *ctx = talloc_new(NULL);

	user = dsdb_audit_get_primary_dn(request);
	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT, GROUP_LOG_LVL)) {
		char *message = NULL;
		message = audit_group_human_readable(
			ctx,
			module,
			request,
			action,
			user,
			group,
			status);
		audit_log_human_text(
			AUDIT_HR_TAG,
			message,
			DBGC_DSDB_GROUP_AUDIT,
			GROUP_LOG_LVL);
		TALLOC_FREE(message);
	}

	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT_JSON, GROUP_LOG_LVL) ||
		(ac->msg_ctx && ac->send_events)) {

		struct json_object json;
		json = audit_group_json(
		    module, request, action, user, group, EVT_ID_NONE, status);
		audit_log_json(
			&json,
			DBGC_DSDB_GROUP_AUDIT_JSON,
			GROUP_LOG_LVL);
		if (ac->send_events) {
			audit_message_send(
				ac->msg_ctx,
				DSDB_GROUP_EVENT_NAME,
				MSG_GROUP_LOG,
				&json);
		}
		json_free(&json);
		if (request->operation == LDB_ADD) {
			/*
			 * Have just added a user, generate a groupChange
			 * message indicating the user has been added to thier
			 * new PrimaryGroup.
			 */
		}
	}
	TALLOC_FREE(ctx);
}

/*
 * @brief Log details of a single change to a users group membership.
 *
 * Log details of a change to a users group membership, except for changes
 * to their primary group which is handled by log_primary_group_change.
 *
 * @param module The ldb module.
 * @param request The request being logged.
 * @param action Description of the action being performed.
 * @param user The linearized form of the users DN
 * @param status the LDB status code for the processing of the request.
 *
 */
static void log_membership_change(struct ldb_module *module,
				  const struct ldb_request *request,
				  const char *action,
				  const char *user,
				  const enum event_id_type event_id,
				  const int status)
{
	const char *group = NULL;
	struct audit_context *ac =
		talloc_get_type(
			ldb_module_get_private(module),
			struct audit_context);

	TALLOC_CTX *ctx = talloc_new(NULL);
	group = dsdb_audit_get_primary_dn(request);
	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT, GROUP_LOG_LVL)) {
		char *message = NULL;
		message = audit_group_human_readable(
			ctx,
			module,
			request,
			action,
			user,
			group,
			status);
		audit_log_human_text(
			AUDIT_HR_TAG,
			message,
			DBGC_DSDB_GROUP_AUDIT,
			GROUP_LOG_LVL);
		TALLOC_FREE(message);
	}

	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT_JSON, GROUP_LOG_LVL) ||
		(ac->msg_ctx && ac->send_events)) {
		struct json_object json;
		json = audit_group_json(
		    module, request, action, user, group, event_id, status);
		audit_log_json(
			&json,
			DBGC_DSDB_GROUP_AUDIT_JSON,
			GROUP_LOG_LVL);
		if (ac->send_events) {
			audit_message_send(
				ac->msg_ctx,
				DSDB_GROUP_EVENT_NAME,
				MSG_GROUP_LOG,
				&json);
		}
		json_free(&json);
	}
	TALLOC_FREE(ctx);
}

/*
 * @brief Get the windows event type id for removing a user from a group type.
 *
 * @param group_type the type of the current group, see libds/common/flags.h
 *
 * @return the Windows Event Id
 *
 */
static enum event_id_type get_remove_member_event(uint32_t group_type)
{

	switch (group_type) {
	case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_LOCAL_SEC_GROUP;
	case GTYPE_SECURITY_GLOBAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_GLOBAL_SEC_GROUP;
	case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_LOCAL_SEC_GROUP;
	case GTYPE_SECURITY_UNIVERSAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_UNIVERSAL_SEC_GROUP;
	case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_GLOBAL_GROUP;
	case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_LOCAL_GROUP;
	case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
		return EVT_ID_USER_REMOVED_FROM_UNIVERSAL_GROUP;
	default:
		return EVT_ID_NONE;
	}
}

/*
 * @brief Get the windows event type id for adding a user to a group type.
 *
 * @param group_type the type of the current group, see libds/common/flags.h
 *
 * @return the Windows Event Id
 *
 */
static enum event_id_type get_add_member_event(uint32_t group_type)
{

	switch (group_type) {
	case GTYPE_SECURITY_BUILTIN_LOCAL_GROUP:
		return EVT_ID_USER_ADDED_TO_LOCAL_SEC_GROUP;
	case GTYPE_SECURITY_GLOBAL_GROUP:
		return EVT_ID_USER_ADDED_TO_GLOBAL_SEC_GROUP;
	case GTYPE_SECURITY_DOMAIN_LOCAL_GROUP:
		return EVT_ID_USER_ADDED_TO_LOCAL_SEC_GROUP;
	case GTYPE_SECURITY_UNIVERSAL_GROUP:
		return EVT_ID_USER_ADDED_TO_UNIVERSAL_SEC_GROUP;
	case GTYPE_DISTRIBUTION_GLOBAL_GROUP:
		return EVT_ID_USER_ADDED_TO_GLOBAL_GROUP;
	case GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP:
		return EVT_ID_USER_ADDED_TO_LOCAL_GROUP;
	case GTYPE_DISTRIBUTION_UNIVERSAL_GROUP:
		return EVT_ID_USER_ADDED_TO_UNIVERSAL_GROUP;
	default:
		return EVT_ID_NONE;
	}
}

/*
 * @brief Log all the changes to a users group membership.
 *
 * Log details of a change to a users group memberships, except for changes
 * to their primary group which is handled by log_primary_group_change.
 *
 * @param module The ldb module.
 * @param request The request being logged.
 * @param action Description of the action being performed.
 * @param user The linearized form of the users DN
 * @param status the LDB status code for the processing of the request.
 *
 */
static void log_membership_changes(struct ldb_module *module,
				   const struct ldb_request *request,
				   struct ldb_message_element *el,
				   struct ldb_message_element *old_el,
				   uint32_t group_type,
				   int status)
{
	unsigned int i, old_i, new_i;
	unsigned int old_num_values;
	unsigned int max_num_values;
	unsigned int new_num_values;
	struct parsed_dn *old_val = NULL;
	struct parsed_dn *new_val = NULL;
	struct parsed_dn *new_values = NULL;
	struct parsed_dn *old_values = NULL;
	struct ldb_context *ldb = NULL;

	TALLOC_CTX *ctx = talloc_new(NULL);

	old_num_values = old_el ? old_el->num_values : 0;
	new_num_values = el ? el->num_values : 0;
	max_num_values = old_num_values + new_num_values;

	if (max_num_values == 0) {
		/*
		 * There is nothing to do!
		 */
		TALLOC_FREE(ctx);
		return;
	}

	old_values = get_parsed_dns(ctx, old_el);
	new_values = get_parsed_dns(ctx, el);
	ldb = ldb_module_get_ctx(module);

	old_i = 0;
	new_i = 0;
	for (i = 0; i < max_num_values; i++) {
		enum dn_compare_result cmp;
		if (old_i < old_num_values && new_i < new_num_values) {
			/*
			 * Both list have values, so compare the values
			 */
			old_val = &old_values[old_i];
			new_val = &new_values[new_i];
			cmp = dn_compare(ctx, ldb, old_val, new_val);
		} else if (old_i < old_num_values) {
			/*
			 * the new list is empty, read the old list
			 */
			old_val = &old_values[old_i];
			new_val = NULL;
			cmp = LESS_THAN;
		} else if (new_i < new_num_values) {
			/*
			 * the old list is empty, read new list
			 */
			old_val = NULL;
			new_val = &new_values[new_i];
			cmp = GREATER_THAN;
		} else {
			break;
		}

		if (cmp == LESS_THAN) {
			/*
			 * Have an entry in the original record that is not in
			 * the new record. So it's been deleted
			 */
			const char *user = NULL;
			enum event_id_type event_id;
			if (old_val->dsdb_dn == NULL) {
				really_parse_trusted_dn(
					ctx,
					ldb,
					old_val,
					LDB_SYNTAX_DN);
			}
			user = ldb_dn_get_linearized(old_val->dsdb_dn->dn);
			event_id = get_remove_member_event(group_type);
			log_membership_change(
			    module, request, "Removed", user, event_id, status);
			old_i++;
		} else if (cmp == BINARY_EQUAL) {
			/*
			 * DN's unchanged at binary level so nothing to do.
			 */
			old_i++;
			new_i++;
		} else if (cmp == EQUAL) {
			/*
			 * DN is unchanged now need to check the flags to
			 * determine if a record has been deleted or undeleted
			 */
			uint32_t old_flags;
			uint32_t new_flags;
			if (old_val->dsdb_dn == NULL) {
				really_parse_trusted_dn(
					ctx,
					ldb,
					old_val,
					LDB_SYNTAX_DN);
			}
			if (new_val->dsdb_dn == NULL) {
				really_parse_trusted_dn(
					ctx,
					ldb,
					new_val,
					LDB_SYNTAX_DN);
			}

			dsdb_get_extended_dn_uint32(
				old_val->dsdb_dn->dn,
				&old_flags,
				"RMD_FLAGS");
			dsdb_get_extended_dn_uint32(
				new_val->dsdb_dn->dn,
				&new_flags,
				"RMD_FLAGS");
			if (new_flags == old_flags) {
				/*
				 * No changes to the Repl meta data so can
				 * no need to log the change
				 */
				old_i++;
				new_i++;
				continue;
			}
			if (new_flags & DSDB_RMD_FLAG_DELETED) {
				/*
				 * DN has been deleted.
				 */
				const char *user = NULL;
				enum event_id_type event_id;
				user = ldb_dn_get_linearized(
					old_val->dsdb_dn->dn);
				event_id = get_remove_member_event(group_type);
				log_membership_change(module,
						      request,
						      "Removed",
						      user,
						      event_id,
						      status);
			} else {
				/*
				 * DN has been re-added
				 */
				const char *user = NULL;
				enum event_id_type event_id;
				user = ldb_dn_get_linearized(
					new_val->dsdb_dn->dn);
				event_id = get_add_member_event(group_type);
				log_membership_change(module,
						      request,
						      "Added",
						      user,
						      event_id,
						      status);
			}
			old_i++;
			new_i++;
		} else {
			/*
			 * Member in the updated record that's not in the
			 * original, so it must have been added.
			 */
			const char *user = NULL;
			enum event_id_type event_id;
			if ( new_val->dsdb_dn == NULL) {
				really_parse_trusted_dn(
					ctx,
					ldb,
					new_val,
					LDB_SYNTAX_DN);
			}
			user = ldb_dn_get_linearized(new_val->dsdb_dn->dn);
			event_id = get_add_member_event(group_type);
			log_membership_change(
			    module, request, "Added", user, event_id, status);
			new_i++;
		}
	}

	TALLOC_FREE(ctx);
}

/*
 * @brief log a group change message for a newly added user.
 *
 * When a user is added we need to generate a GroupChange Add message to
 * log that the user has been added to their PrimaryGroup
 */
static void log_new_user_added_to_primary_group(
    TALLOC_CTX *ctx,
    struct audit_callback_context *acc,
    const char *group,
    const int status)
{
	uint32_t group_type;
	enum event_id_type event_id = EVT_ID_NONE;
	struct ldb_result *res = NULL;
	struct ldb_dn *group_dn = NULL;
	struct ldb_context *ldb = NULL;
	int ret;

	ldb = ldb_module_get_ctx(acc->module);
	group_dn = ldb_dn_new(ctx, ldb, group);
	ret = dsdb_module_search_dn(acc->module,
				    ctx,
				    &res,
				    group_dn,
				    group_type_attr,
				    DSDB_FLAG_NEXT_MODULE |
					DSDB_SEARCH_REVEAL_INTERNALS |
					DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT,
				    NULL);
	if (ret == LDB_SUCCESS) {
		const char *user = NULL;
		group_type =
		    ldb_msg_find_attr_as_uint(res->msgs[0], "groupType", 0);
		event_id = get_add_member_event(group_type);
		user = dsdb_audit_get_primary_dn(acc->request);
		log_membership_change(
		    acc->module, acc->request, "Added", user, event_id, status);
	}
}

/*
 * @brief Log the details of a primary group change.
 *
 * Retrieve the users primary groupo after the operation has completed
 * and call log_primary_group_change to log the actual changes.
 *
 * @param acc details of the primary group before the operation.
 * @param status The status code returned by the operation.
 *
 * @return an LDB status code.
 */
static void log_user_primary_group_change(
	struct audit_callback_context *acc,
	const int status)
{
	TALLOC_CTX *ctx = talloc_new(NULL);
	uint32_t new_rid = UINT32_MAX;
	struct dom_sid *account_sid = NULL;
	int ret;
	const struct ldb_message *msg = dsdb_audit_get_message(acc->request);

	if (status == LDB_SUCCESS && msg != NULL) {
		struct ldb_result *res = NULL;
		ret = dsdb_module_search_dn(
			acc->module,
			ctx,
			&res,
			msg->dn,
			primary_group_attr,
			DSDB_FLAG_NEXT_MODULE |
			DSDB_SEARCH_REVEAL_INTERNALS |
			DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT,
			NULL);
		if (ret == LDB_SUCCESS) {
			new_rid = ldb_msg_find_attr_as_uint(
				msg,
				"primaryGroupID",
				~0);
			account_sid = samdb_result_dom_sid(
				ctx,
				res->msgs[0],
				"objectSid");
		}
	}
	/*
	 * If we don't have a new value then the user has been deleted
	 * which we currently do not log.
	 * Otherwise only log if the primary group has actually changed.
	 */
	if (account_sid != NULL &&
	    new_rid != UINT32_MAX &&
	    acc->primary_group != new_rid) {
		const char* group = get_primary_group_dn(
			ctx,
			acc->module,
			account_sid,
			new_rid);
		log_primary_group_change(
			acc->module,
			acc->request,
			"PrimaryGroup",
			group,
			status);
		/*
		 * Are we adding a new user with the primaryGroupID
		 * set. If so and we're generating JSON audit logs, will need to
		 * generate an "Add" message with the appropriate windows
		 * event id.
		 */
		if (acc->request->operation == LDB_ADD) {
			log_new_user_added_to_primary_group(
			    ctx, acc, group, status);
		}
	}
	TALLOC_FREE(ctx);
}

/*
 * @brief log the changes to users group membership.
 *
 * Retrieve the users group memberships after the operation has completed
 * and call log_membership_changes to log the actual changes.
 *
 * @param acc details of the group memberships before the operation.
 * @param status The status code returned by the operation.
 *
 */
static void log_group_membership_changes(
	struct audit_callback_context *acc,
	const int status)
{
	TALLOC_CTX *ctx = talloc_new(NULL);
	struct ldb_message_element *new_val = NULL;
	int ret;
	uint32_t group_type = 0;
	const struct ldb_message *msg = dsdb_audit_get_message(acc->request);
	if (status == LDB_SUCCESS && msg != NULL) {
		struct ldb_result *res = NULL;
		ret = dsdb_module_search_dn(
			acc->module,
			ctx,
			&res,
			msg->dn,
			group_attrs,
			DSDB_FLAG_NEXT_MODULE |
			DSDB_SEARCH_REVEAL_INTERNALS |
			DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT,
			NULL);
		if (ret == LDB_SUCCESS) {
			new_val = ldb_msg_find_element(res->msgs[0], "member");
			group_type = ldb_msg_find_attr_as_uint(
			    res->msgs[0], "groupType", 0);
			log_membership_changes(acc->module,
					       acc->request,
					       new_val,
					       acc->members,
					       group_type,
					       status);
			TALLOC_FREE(ctx);
			return;
		}
	}
	/*
	 * If we get here either
	 *   one of the lower level modules failed and the group record did
	 *   not get updated
	 * or
	 *   the updated group record could not be read.
	 *
	 * In both cases it does not make sense to log individual membership
	 * changes so we log a group membership change "Failure" message.
	 *
	 */
	log_membership_change(acc->module,
	                      acc->request,
			      "Failure",
			      "",
			      EVT_ID_NONE,
			      status);
	TALLOC_FREE(ctx);
}

/*
 * @brief call back function to log changes to the group memberships.
 *
 * Call back function to log changes to the uses broup memberships.
 *
 * @param req the ldb request.
 * @param ares the ldb result
 *
 * @return am LDB status code.
 */
static int group_audit_callback(
	struct ldb_request *req,
	struct ldb_reply *ares)
{
	struct audit_callback_context *ac = NULL;

	ac = talloc_get_type(
		req->context,
		struct audit_callback_context);

	if (!ares) {
		return ldb_module_done(
				ac->request, NULL, NULL,
				LDB_ERR_OPERATIONS_ERROR);
	}

	/* pass on to the callback */
	switch (ares->type) {
	case LDB_REPLY_ENTRY:
		return ldb_module_send_entry(
			ac->request,
			ares->message,
			ares->controls);

	case LDB_REPLY_REFERRAL:
		return ldb_module_send_referral(
			ac->request,
			ares->referral);

	case LDB_REPLY_DONE:
		/*
		 * Log on DONE now we have a result code
		 */
		ac->log_changes(ac, ares->error);
		return ldb_module_done(
			ac->request,
			ares->controls,
			ares->response,
			ares->error);
		break;

	default:
		/* Can't happen */
		return LDB_ERR_OPERATIONS_ERROR;
	}
}

/*
 * @brief Does this request change the primary group.
 *
 * Does the request change the primary group, i.e. does it contain the
 * primaryGroupID attribute.
 *
 * @param req the request to examine.
 *
 * @return True if the request modifies the primary group.
 */
static bool has_primary_group_id(struct ldb_request *req)
{
	struct ldb_message_element *el = NULL;
	const struct ldb_message *msg = NULL;

	msg = dsdb_audit_get_message(req);
	el = ldb_msg_find_element(msg, "primaryGroupID");

	return (el != NULL);
}

/*
 * @brief Does this request change group membership.
 *
 * Does the request change the ses group memberships, i.e. does it contain the
 * member attribute.
 *
 * @param req the request to examine.
 *
 * @return True if the request modifies the users group memberships.
 */
static bool has_group_membership_changes(struct ldb_request *req)
{
	struct ldb_message_element *el = NULL;
	const struct ldb_message *msg = NULL;

	msg = dsdb_audit_get_message(req);
	el = ldb_msg_find_element(msg, "member");

	return (el != NULL);
}



/*
 * @brief Install the callback function to log an add request.
 *
 * Install the callback function to log an add request changing the users
 * group memberships. As we want to log the returned status code, we need to
 * register a callback function that will be called once the operation has
 * completed.
 *
 * This function reads the current user record so that we can log the before
 * and after state.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int set_group_membership_add_callback(
	struct ldb_module *module,
	struct ldb_request *req)
{
	struct audit_callback_context *context = NULL;
	struct ldb_request *new_req = NULL;
	struct ldb_context *ldb = NULL;
	int ret;
	/*
	 * Adding group memberships so will need to log the changes.
	 */
	ldb = ldb_module_get_ctx(module);
	context = talloc_zero(req, struct audit_callback_context);

	if (context == NULL) {
		return ldb_oom(ldb);
	}
	context->request = req;
	context->module = module;
	context->log_changes = log_group_membership_changes;
	/*
	 * We want to log the return code status, so we need to register
	 * a callback function to get the actual result.
	 * We need to take a new copy so that we don't alter the callers copy
	 */
	ret = ldb_build_add_req(
		&new_req,
		ldb,
		req,
		req->op.add.message,
		req->controls,
		context,
		group_audit_callback,
		req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	return ldb_next_request(module, new_req);
}


/*
 * @brief Install the callback function to log a modify request.
 *
 * Install the callback function to log a modify request changing the primary
 * group . As we want to log the returned status code, we need to register a
 * callback function that will be called once the operation has completed.
 *
 * This function reads the current user record so that we can log the before
 * and after state.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int set_primary_group_modify_callback(
	struct ldb_module *module,
	struct ldb_request *req)
{
	struct audit_callback_context *context = NULL;
	struct ldb_request *new_req = NULL;
	struct ldb_context *ldb = NULL;
	const struct ldb_message *msg = NULL;
	struct ldb_result *res = NULL;
	int ret;

	TALLOC_CTX *ctx = talloc_new(NULL);

	ldb = ldb_module_get_ctx(module);

	context = talloc_zero(req, struct audit_callback_context);
	if (context == NULL) {
		ret = ldb_oom(ldb);
		goto exit;
	}
	context->request = req;
	context->module = module;
	context->log_changes = log_user_primary_group_change;

	msg = dsdb_audit_get_message(req);
	ret = dsdb_module_search_dn(
		module,
		ctx,
		&res,
		msg->dn,
		primary_group_attr,
		DSDB_FLAG_NEXT_MODULE |
		DSDB_SEARCH_REVEAL_INTERNALS |
		DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT,
		NULL);
	if (ret == LDB_SUCCESS) {
		uint32_t pg;
		pg = ldb_msg_find_attr_as_uint(
			res->msgs[0],
			"primaryGroupID",
			~0);
		context->primary_group = pg;
	}
	/*
	 * We want to log the return code status, so we need to register
	 * a callback function to get the actual result.
	 * We need to take a new copy so that we don't alter the callers copy
	 */
	ret = ldb_build_mod_req(
		&new_req,
		ldb,
		req,
		req->op.add.message,
		req->controls,
		context,
		group_audit_callback,
		req);
	if (ret != LDB_SUCCESS) {
		goto exit;
	}
	ret = ldb_next_request(module, new_req);
exit:
	TALLOC_FREE(ctx);
	return ret;
}

/*
 * @brief Install the callback function to log an add request.
 *
 * Install the callback function to log an add request changing the primary
 * group . As we want to log the returned status code, we need to register a
 * callback function that will be called once the operation has completed.
 *
 * This function reads the current user record so that we can log the before
 * and after state.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int set_primary_group_add_callback(
	struct ldb_module *module,
	struct ldb_request *req)
{
	struct audit_callback_context *context = NULL;
	struct ldb_request *new_req = NULL;
	struct ldb_context *ldb = NULL;
	int ret;
	/*
	 * Adding a user with a primary group.
	 */
	ldb = ldb_module_get_ctx(module);
	context = talloc_zero(req, struct audit_callback_context);

	if (context == NULL) {
		return ldb_oom(ldb);
	}
	context->request = req;
	context->module = module;
	context->log_changes = log_user_primary_group_change;
	/*
	 * We want to log the return code status, so we need to register
	 * a callback function to get the actual result.
	 * We need to take a new copy so that we don't alter the callers copy
	 */
	ret = ldb_build_add_req(
		&new_req,
		ldb,
		req,
		req->op.add.message,
		req->controls,
		context,
		group_audit_callback,
		req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	return ldb_next_request(module, new_req);
}

/*
 * @brief Module handler for add operations.
 *
 * Inspect the current add request, and if needed log any group membership
 * changes.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int group_add(
	struct ldb_module *module,
	struct ldb_request *req)
{

	struct audit_context *ac =
		talloc_get_type(
			ldb_module_get_private(module),
			struct audit_context);
	/*
	 * Currently we don't log replicated group changes
	 */
	if (ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
		return ldb_next_request(module, req);
	}

	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT, GROUP_LOG_LVL) ||
		CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT_JSON, GROUP_LOG_LVL) ||
		(ac->msg_ctx && ac->send_events)) {
		/*
		 * Avoid the overheads of logging unless it has been
		 * enabled
		 */
		if (has_group_membership_changes(req)) {
			return set_group_membership_add_callback(module, req);
		}
		if (has_primary_group_id(req)) {
			return set_primary_group_add_callback(module, req);
		}
	}
	return ldb_next_request(module, req);
}

/*
 * @brief Module handler for delete operations.
 *
 * Currently there is no logging for delete operations.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int group_delete(
	struct ldb_module *module,
	struct ldb_request *req)
{
	return ldb_next_request(module, req);
}

/*
 * @brief Install the callback function to log a modify request.
 *
 * Install the callback function to log a modify request. As we want to log the
 * returned status code, we need to register a callback function that will be
 * called once the operation has completed.
 *
 * This function reads the current user record so that we can log the before
 * and after state.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int set_group_modify_callback(
	struct ldb_module *module,
	struct ldb_request *req)
{
	struct audit_callback_context *context = NULL;
	struct ldb_request *new_req = NULL;
	struct ldb_context *ldb = NULL;
	struct ldb_result *res = NULL;
	int ret;

	ldb = ldb_module_get_ctx(module);
	context = talloc_zero(req, struct audit_callback_context);

	if (context == NULL) {
		return ldb_oom(ldb);
	}
	context->request = req;
	context->module  = module;
	context->log_changes = log_group_membership_changes;

	/*
	 * About to change the group memberships need to read
	 * the current state from the database.
	 */
	ret = dsdb_module_search_dn(
		module,
		context,
		&res,
		req->op.add.message->dn,
		group_attrs,
		DSDB_FLAG_NEXT_MODULE |
		DSDB_SEARCH_REVEAL_INTERNALS |
		DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT,
		NULL);
	if (ret == LDB_SUCCESS) {
		context->members = ldb_msg_find_element(res->msgs[0], "member");
	}

	ret = ldb_build_mod_req(
		&new_req,
		ldb,
		req,
		req->op.mod.message,
		req->controls,
		context,
		group_audit_callback,
		req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	return ldb_next_request(module, new_req);
}

/*
 * @brief Module handler for modify operations.
 *
 * Inspect the current modify request, and if needed log any group membership
 * changes.
 *
 * @param module The ldb module.
 * @param req The modify request.
 *
 * @return and LDB status code.
 */
static int group_modify(
	struct ldb_module *module,
	struct ldb_request *req)
{

	struct audit_context *ac =
		talloc_get_type(
			ldb_module_get_private(module),
			struct audit_context);
	/*
	 * Currently we don't log replicated group changes
	 */
	if (ldb_request_get_control(req, DSDB_CONTROL_REPLICATED_UPDATE_OID)) {
		return ldb_next_request(module, req);
	}

	if (CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT, GROUP_LOG_LVL) ||
	    CHECK_DEBUGLVLC(DBGC_DSDB_GROUP_AUDIT_JSON, GROUP_LOG_LVL) ||
		(ac->msg_ctx && ac->send_events)) {
		/*
		 * Avoid the overheads of logging unless it has been
		 * enabled
		 */
		if (has_group_membership_changes(req)) {
			return set_group_modify_callback(module, req);
		}
		if (has_primary_group_id(req)) {
			return set_primary_group_modify_callback(module, req);
		}
	}
	return ldb_next_request(module, req);
}

/*
 * @brief ldb module initialisation
 *
 * Initialise the module, loading the private data etc.
 *
 * @param module The ldb module to initialise.
 *
 * @return An LDB status code.
 */
static int group_init(struct ldb_module *module)
{

	struct ldb_context *ldb = ldb_module_get_ctx(module);
	struct audit_context *context = NULL;
	struct loadparm_context *lp_ctx
		= talloc_get_type_abort(
			ldb_get_opaque(ldb, "loadparm"),
			struct loadparm_context);
	struct tevent_context *ev = ldb_get_event_context(ldb);

	context = talloc_zero(module, struct audit_context);
	if (context == NULL) {
		return ldb_module_oom(module);
	}

	if (lp_ctx && lpcfg_dsdb_group_change_notification(lp_ctx)) {
		context->send_events = true;
		context->msg_ctx = imessaging_client_init(context,
							  lp_ctx,
							  ev);
	}

	ldb_module_set_private(module, context);
	return ldb_next_init(module);
}

static const struct ldb_module_ops ldb_group_audit_log_module_ops = {
	.name              = "group_audit_log",
	.add		   = group_add,
	.modify		   = group_modify,
	.del		   = group_delete,
	.init_context	   = group_init,
};

int ldb_group_audit_log_module_init(const char *version)
{
	LDB_MODULE_CHECK_VERSION(version);
	return ldb_register_module(&ldb_group_audit_log_module_ops);
}