summaryrefslogtreecommitdiff
path: root/source4/libnet/libnet_samsync_ldb.c
blob: 9511989e8c23eed6b78072a323dac7b5c0bf93c0 (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
/* 
   Unix SMB/CIFS implementation.
   
   Extract the user/system database from a remote SamSync server

   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-2005
   Copyright (C) Andrew Tridgell 2004
   Copyright (C) Volker Lendecke 2004
   
   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/>.
*/


#include "includes.h"
#include "libnet/libnet.h"
#include "libcli/ldap/ldap.h"
#include "dsdb/samdb/samdb.h"
#include "auth/auth.h"
#include "librpc/gen_ndr/ndr_misc.h"
#include "db_wrap.h"
#include "libcli/security/security.h"
#include "librpc/rpc/dcerpc.h"
#include "param/param.h"

struct samsync_ldb_secret {
	struct samsync_ldb_secret *prev, *next;
	DATA_BLOB secret;
	char *name;
	NTTIME mtime;
};

struct samsync_ldb_trusted_domain {
	struct samsync_ldb_trusted_domain *prev, *next;
        struct dom_sid *sid;
	char *name;
};

struct samsync_ldb_state {
	/* Values from the LSA lookup */
	const struct libnet_SamSync_state *samsync_state;

	struct dom_sid *dom_sid[3];
	struct ldb_context *sam_ldb, *remote_ldb;
	struct ldb_dn *base_dn[3];
	struct samsync_ldb_secret *secrets;
	struct samsync_ldb_trusted_domain *trusted_domains;
};

static NTSTATUS samsync_ldb_add_foreignSecurityPrincipal(TALLOC_CTX *mem_ctx,
							 struct samsync_ldb_state *state,
							 struct dom_sid *sid,
							 struct ldb_dn **fsp_dn,
							 char **error_string)
{
	const char *sidstr = dom_sid_string(mem_ctx, sid);
	/* We assume that ForeignSecurityPrincipals are under the BASEDN of the main domain */
	struct ldb_dn *basedn = samdb_search_dn(state->sam_ldb, mem_ctx,
						state->base_dn[SAM_DATABASE_DOMAIN],
						"(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
	struct ldb_message *msg;
	int ret;

	if (!sidstr) {
		return NT_STATUS_NO_MEMORY;
	}

	if (basedn == NULL) {
		*error_string = talloc_asprintf(mem_ctx, 
						"Failed to find DN for "
						"ForeignSecurityPrincipal container under %s",
						ldb_dn_get_linearized(state->base_dn[SAM_DATABASE_DOMAIN]));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}
	
	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* add core elements to the ldb_message for the alias */
	msg->dn = basedn;
	if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
		return NT_STATUS_UNSUCCESSFUL;
	
	samdb_msg_add_string(state->sam_ldb, mem_ctx, msg,
			     "objectClass",
			     "foreignSecurityPrincipal");

	*fsp_dn = msg->dn;

	/* create the alias */
	ret = samdb_add(state->sam_ldb, mem_ctx, msg);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to create foreignSecurityPrincipal "
						"record %s: %s",
						ldb_dn_get_linearized(msg->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}
	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_domain(TALLOC_CTX *mem_ctx,
					  struct samsync_ldb_state *state,
					  enum netr_SamDatabaseID database,
					  struct netr_DELTA_ENUM *delta,
					  char **error_string) 
{
	struct netr_DELTA_DOMAIN *domain = delta->delta_union.domain;
	const char *domain_name = domain->domain_name.string;
	struct ldb_message *msg;
	int ret;
	
	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	if (database == SAM_DATABASE_DOMAIN) {
		struct ldb_dn *partitions_basedn;
		const char *domain_attrs[] =  {"nETBIOSName", "nCName", NULL};
		struct ldb_message **msgs_domain;
		int ret_domain;

		partitions_basedn = samdb_partitions_dn(state->sam_ldb, mem_ctx);

		ret_domain = gendb_search(state->sam_ldb, mem_ctx, partitions_basedn, &msgs_domain, domain_attrs,
					  "(&(&(nETBIOSName=%s)(objectclass=crossRef))(ncName=*))", 
					  domain_name);
		if (ret_domain == -1) {
			*error_string = talloc_asprintf(mem_ctx, "gendb_search for domain failed: %s", ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
		
		if (ret_domain != 1) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to find existing domain record for %s: %d results", domain_name,
							ret_domain);
			return NT_STATUS_NO_SUCH_DOMAIN;		
		}

		state->base_dn[database] = samdb_result_dn(state->sam_ldb, state, msgs_domain[0], "nCName", NULL);

		if (state->dom_sid[database]) {
			/* Update the domain sid with the incoming
			 * domain (found on LSA pipe, database sid may
			 * be random) */
			samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, 
					      msg, "objectSid", state->dom_sid[database]);
		} else {
			/* Well, we will have to use the one from the database */
			state->dom_sid[database] = samdb_search_dom_sid(state->sam_ldb, state,
									state->base_dn[database], 
									"objectSid", NULL);
		}

		if (state->samsync_state->domain_guid) {
			NTSTATUS nt_status;
			struct ldb_val v;
			nt_status = ndr_push_struct_blob(&v, msg, state->samsync_state->domain_guid,
							 (ndr_push_flags_fn_t)ndr_push_GUID);
			if (!NT_STATUS_IS_OK(nt_status)) {
				*error_string = talloc_asprintf(mem_ctx, "ndr_push of domain GUID failed!");
				return nt_status;
			}
			
			ldb_msg_add_value(msg, "objectGUID", &v, NULL);
		}
	} else if (database == SAM_DATABASE_BUILTIN) {
		/* work out the builtin_dn - useful for so many calls its worth
		   fetching here */
		const char *dnstring = samdb_search_string(state->sam_ldb, mem_ctx, NULL,
							   "distinguishedName", "objectClass=builtinDomain");
		state->base_dn[database] = ldb_dn_new(state, state->sam_ldb, dnstring);
		if ( ! ldb_dn_validate(state->base_dn[database])) {
			return NT_STATUS_INTERNAL_ERROR;
		}
	} else {
		/* PRIVs DB */
		return NT_STATUS_INVALID_PARAMETER;
	}

	msg->dn = talloc_reference(mem_ctx, state->base_dn[database]);
	if (!msg->dn) {
		return NT_STATUS_NO_MEMORY;
	}

	samdb_msg_add_string(state->sam_ldb, mem_ctx, 
			     msg, "oEMInformation", domain->comment.string);

	samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
			    msg, "forceLogoff", domain->force_logoff_time);

	samdb_msg_add_uint(state->sam_ldb, mem_ctx, 
			   msg, "minPwdLen", domain->min_password_length);

	samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
			    msg, "maxPwdAge", domain->max_password_age);

	samdb_msg_add_int64(state->sam_ldb, mem_ctx, 
			    msg, "minPwdAge", domain->min_password_age);

	samdb_msg_add_uint(state->sam_ldb, mem_ctx, 
			   msg, "pwdHistoryLength", domain->password_history_length);

	samdb_msg_add_uint64(state->sam_ldb, mem_ctx, 
			     msg, "modifiedCount", 
			     domain->sequence_num);

	samdb_msg_add_uint64(state->sam_ldb, mem_ctx, 
			     msg, "creationTime", domain->domain_create_time);

	/* TODO: Account lockout, password properties */
	
	ret = samdb_replace(state->sam_ldb, mem_ctx, msg);

	if (ret) {
		return NT_STATUS_INTERNAL_ERROR;
	}
	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_user(TALLOC_CTX *mem_ctx,
					struct samsync_ldb_state *state,
					enum netr_SamDatabaseID database,
					struct netr_DELTA_ENUM *delta,
					char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct netr_DELTA_USER *user = delta->delta_union.user;
	const char *container, *obj_class;
	char *cn_name;
	int cn_name_len;
	const struct dom_sid *user_sid;
	struct ldb_message *msg;
	struct ldb_message **msgs;
	struct ldb_message **remote_msgs = NULL;
	int ret, i;
	uint32_t acb;
	BOOL add = False;
	const char *attrs[] = { NULL };
	/* we may change this to a global search, then fill in only the things not in ldap later */
	const char *remote_attrs[] = { "userPrincipalName", "servicePrincipalName", 
				       "msDS-KeyVersionNumber", "objectGUID", NULL};

	user_sid = dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid);
	if (!user_sid) {
		return NT_STATUS_NO_MEMORY;
	}

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	msg->dn = NULL;
	/* search for the user, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database],
			   &msgs, attrs, "(&(objectClass=user)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "LDB for user %s failed: %s", 
						dom_sid_string(mem_ctx, user_sid),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		add = True;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one user with SID: %s in local LDB", 
						dom_sid_string(mem_ctx, user_sid));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = msgs[0]->dn;
		talloc_steal(msg, msgs[0]->dn);
	}

	/* and do the same on the remote database */
	if (state->remote_ldb) {
		ret = gendb_search(state->remote_ldb, mem_ctx, state->base_dn[database],
				   &remote_msgs, remote_attrs, "(&(objectClass=user)(objectSid=%s))", 
				   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
		
		if (ret == -1) {
			*error_string = talloc_asprintf(mem_ctx, "remote LDAP for user %s failed: %s", 
							dom_sid_string(mem_ctx, user_sid),
							ldb_errstring(state->remote_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		} else if (ret == 0) {
			*error_string = talloc_asprintf(mem_ctx, "User exists in samsync but not in remote LDAP domain! (base: %s, SID: %s)", 
							ldb_dn_get_linearized(state->base_dn[database]),
							dom_sid_string(mem_ctx, user_sid));
			return NT_STATUS_NO_SUCH_USER;
		} else if (ret > 1) {
			*error_string = talloc_asprintf(mem_ctx, "More than one user in remote LDAP domain with SID: %s", 
							dom_sid_string(mem_ctx, user_sid));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
			
			/* Try to put things in the same location as the remote server */
		} else if (add) {
			msg->dn = remote_msgs[0]->dn;
			talloc_steal(msg, remote_msgs[0]->dn);
		}
	}

	cn_name   = talloc_strdup(mem_ctx, user->account_name.string);
	NT_STATUS_HAVE_NO_MEMORY(cn_name);
	cn_name_len = strlen(cn_name);

#define ADD_OR_DEL(type, attrib, field) do {				\
		if (user->field) {					\
			samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
					       attrib, user->field);	\
		} else if (!add) {					\
			samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
					     attrib);			\
		}							\
        } while (0);

        ADD_OR_DEL(string, "samAccountName", account_name.string);
        ADD_OR_DEL(string, "displayName", full_name.string);

	if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
				  "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
		return NT_STATUS_NO_MEMORY; 
	}

        ADD_OR_DEL(uint, "primaryGroupID", primary_gid);
        ADD_OR_DEL(string, "homeDirectory", home_directory.string);
        ADD_OR_DEL(string, "homeDrive", home_drive.string);
        ADD_OR_DEL(string, "scriptPath", logon_script.string);
	ADD_OR_DEL(string, "description", description.string);
	ADD_OR_DEL(string, "userWorkstations", workstations.string);

	ADD_OR_DEL(uint64, "lastLogon", last_logon);
	ADD_OR_DEL(uint64, "lastLogoff", last_logoff);

	if (samdb_msg_add_logon_hours(state->sam_ldb, mem_ctx, msg, "logonHours", &user->logon_hours) != 0) { 
		return NT_STATUS_NO_MEMORY; 
	}

	ADD_OR_DEL(uint, "badPwdCount", bad_password_count);
	ADD_OR_DEL(uint, "logonCount", logon_count);

	ADD_OR_DEL(uint64, "pwdLastSet", last_password_change);
	ADD_OR_DEL(uint64, "accountExpires", acct_expiry);
	
	if (samdb_msg_add_acct_flags(state->sam_ldb, mem_ctx, msg, 
				     "userAccountControl", user->acct_flags) != 0) { 
		return NT_STATUS_NO_MEMORY; 
	} 
	
	if (!add) {
		/* Passwords.  Ensure there is no plaintext stored against
		 * this entry, as we only have hashes */
		samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
				     "sambaPassword"); 
	}
	if (user->lm_password_present) {
		samdb_msg_add_hash(state->sam_ldb, mem_ctx, msg,  
				   "dBCSPwd", &user->lmpassword);
	} else if (!add) {
		samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
				     "dBCSPwd"); 
	}
	if (user->nt_password_present) {
		samdb_msg_add_hash(state->sam_ldb, mem_ctx, msg,  
				   "unicodePwd", &user->ntpassword);
	} else if (!add) {
		samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
				     "unicodePwd"); 
	}
	    
	ADD_OR_DEL(string, "comment", comment.string);
	ADD_OR_DEL(string, "userParameters", parameters.string);
	ADD_OR_DEL(uint, "countryCode", country_code);
	ADD_OR_DEL(uint, "codePage", code_page);

        ADD_OR_DEL(string, "profilePath", profile_path.string);

#undef ADD_OR_DEL

	for (i=0; remote_attrs[i]; i++) {
		struct ldb_message_element *el = ldb_msg_find_element(remote_msgs[0], remote_attrs[i]);
		if (!el) {
			samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
					     remote_attrs[i]); 
		} else {
			ldb_msg_add(msg, el, LDB_FLAG_MOD_REPLACE);
		}
	}

	acb = user->acct_flags;
	if (acb & (ACB_WSTRUST)) {
		cn_name[cn_name_len - 1] = '\0';
		container = "Computers";
		obj_class = "computer";
		
	} else if (acb & ACB_SVRTRUST) {
		if (cn_name[cn_name_len - 1] != '$') {
			return NT_STATUS_FOOBAR;		
		}
		cn_name[cn_name_len - 1] = '\0';
		container = "Domain Controllers";
		obj_class = "computer";
	} else {
		container = "Users";
		obj_class = "user";
	}
	if (add) {
		samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
				     "objectClass", obj_class);
		if (!msg->dn) {
			msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
			ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
			if (!msg->dn) {
				return NT_STATUS_NO_MEMORY;		
			}
		}

		ret = samdb_add(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			struct ldb_dn *first_try_dn = msg->dn;
			/* Try again with the default DN */
			if (!remote_msgs) {
				*error_string = talloc_asprintf(mem_ctx, "Failed to create user record.  Tried %s: %s",
								ldb_dn_get_linearized(first_try_dn),
								ldb_errstring(state->sam_ldb));
				return NT_STATUS_INTERNAL_DB_CORRUPTION;
			} else {
				msg->dn = talloc_steal(msg, remote_msgs[0]->dn);
				ret = samdb_add(state->sam_ldb, mem_ctx, msg);
				if (ret != 0) {
					*error_string = talloc_asprintf(mem_ctx, "Failed to create user record.  Tried both %s and %s: %s",
									ldb_dn_get_linearized(first_try_dn),
									ldb_dn_get_linearized(msg->dn),
									ldb_errstring(state->sam_ldb));
					return NT_STATUS_INTERNAL_DB_CORRUPTION;
				}
			}
		}
	} else {
		ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to modify user record %s: %s",
							ldb_dn_get_linearized(msg->dn),
							ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_delete_user(TALLOC_CTX *mem_ctx,
					struct samsync_ldb_state *state,
					enum netr_SamDatabaseID database,
					struct netr_DELTA_ENUM *delta,
					char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };

	/* search for the user, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database],
			   &msgs, attrs, "(&(objectClass=user)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_USER;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one user with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to delete user record %s: %s",
						ldb_dn_get_linearized(msgs[0]->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_group(TALLOC_CTX *mem_ctx,
					 struct samsync_ldb_state *state,
					 enum netr_SamDatabaseID database,
					 struct netr_DELTA_ENUM *delta,
					 char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct netr_DELTA_GROUP *group = delta->delta_union.group;
	const char *container, *obj_class;
	const char *cn_name;

	struct ldb_message *msg;
	struct ldb_message **msgs;
	int ret;
	BOOL add = False;
	const char *attrs[] = { NULL };

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the group, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		add = True;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = talloc_steal(msg, msgs[0]->dn);
	}

	cn_name   = group->group_name.string;

#define ADD_OR_DEL(type, attrib, field) do {				\
		if (group->field) {					\
			samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
					       attrib, group->field);	\
		} else if (!add) {					\
			samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
					     attrib);			\
		}							\
        } while (0);

        ADD_OR_DEL(string, "samAccountName", group_name.string);

	if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
				  "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
		return NT_STATUS_NO_MEMORY; 
	}

	ADD_OR_DEL(string, "description", description.string);

#undef ADD_OR_DEL

	container = "Users";
	obj_class = "group";

	if (add) {
		samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
				     "objectClass", obj_class);
		msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
		ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
		if (!msg->dn) {
			return NT_STATUS_NO_MEMORY;		
		}

		ret = samdb_add(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to create group record %s: %s",
							ldb_dn_get_linearized(msg->dn),
							ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
	} else {
		ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
							ldb_dn_get_linearized(msg->dn),
							ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_delete_group(TALLOC_CTX *mem_ctx,
					 struct samsync_ldb_state *state,
					 enum netr_SamDatabaseID database,
					 struct netr_DELTA_ENUM *delta,
					 char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };

	/* search for the group, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_GROUP;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}
	
	ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to delete group record %s: %s",
						ldb_dn_get_linearized(msgs[0]->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_group_member(TALLOC_CTX *mem_ctx,
						struct samsync_ldb_state *state,
						enum netr_SamDatabaseID database,
						struct netr_DELTA_ENUM *delta,
						char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct netr_DELTA_GROUP_MEMBER *group_member = delta->delta_union.group_member;
	struct ldb_message *msg;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };
	int i;

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the group, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_GROUP;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = talloc_steal(msg, msgs[0]->dn);
	}
	
	talloc_free(msgs);

	for (i=0; i<group_member->num_rids; i++) {
		/* search for the group, by rid */
		ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
				   "(&(objectClass=user)(objectSid=%s))", 
				   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], group_member->rids[i]))); 
		
		if (ret == -1) {
			*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		} else if (ret == 0) {
			return NT_STATUS_NO_SUCH_USER;
		} else if (ret > 1) {
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		} else {
			samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "member", ldb_dn_alloc_linearized(mem_ctx, msgs[0]->dn));
		}
		
		talloc_free(msgs);
	}
	
	ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
						ldb_dn_get_linearized(msg->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_alias(TALLOC_CTX *mem_ctx,
					 struct samsync_ldb_state *state,
					 enum netr_SamDatabaseID database,
					 struct netr_DELTA_ENUM *delta,
					 char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct netr_DELTA_ALIAS *alias = delta->delta_union.alias;
	const char *container, *obj_class;
	const char *cn_name;

	struct ldb_message *msg;
	struct ldb_message **msgs;
	int ret;
	BOOL add = False;
	const char *attrs[] = { NULL };

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the alias, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		add = True;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = talloc_steal(mem_ctx, msgs[0]->dn);
	}

	cn_name   = alias->alias_name.string;

#define ADD_OR_DEL(type, attrib, field) do {				\
		if (alias->field) {					\
			samdb_msg_add_ ## type(state->sam_ldb, mem_ctx, msg, \
					       attrib, alias->field);	\
		} else if (!add) {					\
			samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg, \
					     attrib);			\
		}							\
	} while (0);

	ADD_OR_DEL(string, "samAccountName", alias_name.string);

	if (samdb_msg_add_dom_sid(state->sam_ldb, mem_ctx, msg, 
				  "objectSid", dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))) {
		return NT_STATUS_NO_MEMORY; 
	}

	ADD_OR_DEL(string, "description", description.string);

#undef ADD_OR_DEL

	samdb_msg_add_uint(state->sam_ldb, mem_ctx, msg, "groupType", 0x80000004);

	container = "Users";
	obj_class = "group";

	if (add) {
		samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, 
				     "objectClass", obj_class);
		msg->dn = ldb_dn_copy(mem_ctx, state->base_dn[database]);
		ldb_dn_add_child_fmt(msg->dn, "CN=%s,CN=%s", cn_name, container);
		if (!msg->dn) {
			return NT_STATUS_NO_MEMORY;		
		}

		ret = samdb_add(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to create alias record %s: %s",
							ldb_dn_get_linearized(msg->dn),
							ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
	} else {
		ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
		if (ret != 0) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to modify alias record %s: %s",
							ldb_dn_get_linearized(msg->dn),
							ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_delete_alias(TALLOC_CTX *mem_ctx,
					 struct samsync_ldb_state *state,
					 enum netr_SamDatabaseID database,
					 struct netr_DELTA_ENUM *delta,
					 char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };

	/* search for the alias, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_ALIAS;
	} else if (ret > 1) {
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	ret = samdb_delete(state->sam_ldb, mem_ctx, msgs[0]->dn);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to delete alias record %s: %s",
						ldb_dn_get_linearized(msgs[0]->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_alias_member(TALLOC_CTX *mem_ctx,
						struct samsync_ldb_state *state,
						enum netr_SamDatabaseID database,
						struct netr_DELTA_ENUM *delta,
						char **error_string) 
{
	uint32_t rid = delta->delta_id_union.rid;
	struct netr_DELTA_ALIAS_MEMBER *alias_member = delta->delta_union.alias_member;
	struct ldb_message *msg;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };
	int i;

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the alias, by rid */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[database], &msgs, attrs,
			   "(&(objectClass=group)(objectSid=%s))", 
			   ldap_encode_ndr_dom_sid(mem_ctx, dom_sid_add_rid(mem_ctx, state->dom_sid[database], rid))); 
		
	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_GROUP;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one group/alias with SID: %s", 
						dom_sid_string(mem_ctx, 
							       dom_sid_add_rid(mem_ctx, 
									       state->dom_sid[database], 
									       rid)));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = talloc_steal(msg, msgs[0]->dn);
	}
	
	talloc_free(msgs);

	for (i=0; i<alias_member->sids.num_sids; i++) {
		struct ldb_dn *alias_member_dn;
		/* search for members, in the top basedn (normal users are builtin aliases) */
		ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
				   "(objectSid=%s)", 
				   ldap_encode_ndr_dom_sid(mem_ctx, alias_member->sids.sids[i].sid)); 

		if (ret == -1) {
			*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		} else if (ret == 0) {
			NTSTATUS nt_status;
			nt_status = samsync_ldb_add_foreignSecurityPrincipal(mem_ctx, state,
									     alias_member->sids.sids[i].sid, 
									     &alias_member_dn, 
									     error_string);
			if (!NT_STATUS_IS_OK(nt_status)) {
				return nt_status;
			}
		} else if (ret > 1) {
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		} else {
			alias_member_dn = msgs[0]->dn;
		}
		samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "member", ldb_dn_alloc_linearized(mem_ctx, alias_member_dn));
	
		talloc_free(msgs);
	}

	ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to modify group record %s: %s",
						ldb_dn_get_linearized(msg->dn),
						ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_handle_account(TALLOC_CTX *mem_ctx,
					   struct samsync_ldb_state *state,
					   enum netr_SamDatabaseID database,
					   struct netr_DELTA_ENUM *delta,
					   char **error_string) 
{
	struct dom_sid *sid = delta->delta_id_union.sid;
	struct netr_DELTA_ACCOUNT *account = delta->delta_union.account;

	struct ldb_message *msg;
	struct ldb_message **msgs;
	struct ldb_dn *privilege_dn;
	int ret;
	const char *attrs[] = { NULL };
	int i;

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the account, by sid, in the top basedn */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
			   "(objectSid=%s)", ldap_encode_ndr_dom_sid(mem_ctx, sid)); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		NTSTATUS nt_status;
		nt_status = samsync_ldb_add_foreignSecurityPrincipal(mem_ctx, state,
								     sid,
								     &privilege_dn,
								     error_string);
		privilege_dn = talloc_steal(msg, privilege_dn);
		if (!NT_STATUS_IS_OK(nt_status)) {
			return nt_status;
		}
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one account with SID: %s", 
						dom_sid_string(mem_ctx, sid));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		privilege_dn = talloc_steal(msg, msgs[0]->dn);
	}

	msg->dn = privilege_dn;

	for (i=0; i< account->privilege_entries; i++) {
		samdb_msg_add_string(state->sam_ldb, mem_ctx, msg, "privilege",
				     account->privilege_name[i].string);
	}

	ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to modify privilege record %s",
						ldb_dn_get_linearized(msg->dn));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS samsync_ldb_delete_account(TALLOC_CTX *mem_ctx,
					   struct samsync_ldb_state *state,
					   enum netr_SamDatabaseID database,
					   struct netr_DELTA_ENUM *delta,
					   char **error_string) 
{
	struct dom_sid *sid = delta->delta_id_union.sid;

	struct ldb_message *msg;
	struct ldb_message **msgs;
	int ret;
	const char *attrs[] = { NULL };

	msg = ldb_msg_new(mem_ctx);
	if (msg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	/* search for the account, by sid, in the top basedn */
	ret = gendb_search(state->sam_ldb, mem_ctx, state->base_dn[SAM_DATABASE_DOMAIN], &msgs, attrs,
			   "(objectSid=%s)", 
			   ldap_encode_ndr_dom_sid(mem_ctx, sid)); 

	if (ret == -1) {
		*error_string = talloc_asprintf(mem_ctx, "gendb_search failed: %s", ldb_errstring(state->sam_ldb));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else if (ret == 0) {
		return NT_STATUS_NO_SUCH_USER;
	} else if (ret > 1) {
		*error_string = talloc_asprintf(mem_ctx, "More than one account with SID: %s", 
						dom_sid_string(mem_ctx, sid));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	} else {
		msg->dn = talloc_steal(msg, msgs[0]->dn);
	}

	samdb_msg_add_delete(state->sam_ldb, mem_ctx, msg,  
			     "privilage"); 

	ret = samdb_replace(state->sam_ldb, mem_ctx, msg);
	if (ret != 0) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to modify privilege record %s",
						ldb_dn_get_linearized(msg->dn));
		return NT_STATUS_INTERNAL_DB_CORRUPTION;
	}

	return NT_STATUS_OK;
}

static NTSTATUS libnet_samsync_ldb_fn(TALLOC_CTX *mem_ctx, 		
				      void *private, 			
				      enum netr_SamDatabaseID database,
				      struct netr_DELTA_ENUM *delta,
				      char **error_string)
{
	NTSTATUS nt_status = NT_STATUS_OK;
	struct samsync_ldb_state *state = talloc_get_type(private, struct samsync_ldb_state);

	*error_string = NULL;
	switch (delta->delta_type) {
	case NETR_DELTA_DOMAIN:
	{
		nt_status = samsync_ldb_handle_domain(mem_ctx, 
						      state,
						      database,
						      delta,
						      error_string);
		break;
	}
	case NETR_DELTA_USER:
	{
		nt_status = samsync_ldb_handle_user(mem_ctx, 
						    state,
						    database,
						    delta,
						    error_string);
		break;
	}
	case NETR_DELTA_DELETE_USER:
	{
		nt_status = samsync_ldb_delete_user(mem_ctx, 
						    state,
						    database,
						    delta,
						    error_string);
		break;
	}
	case NETR_DELTA_GROUP:
	{
		nt_status = samsync_ldb_handle_group(mem_ctx, 
						     state,
						     database,
						     delta,
						     error_string);
		break;
	}
	case NETR_DELTA_DELETE_GROUP:
	{
		nt_status = samsync_ldb_delete_group(mem_ctx, 
						     state,
						     database,
						     delta,
						     error_string);
		break;
	}
	case NETR_DELTA_GROUP_MEMBER:
	{
		nt_status = samsync_ldb_handle_group_member(mem_ctx, 
							    state,
							    database,
							    delta,
							    error_string);
		break;
	}
	case NETR_DELTA_ALIAS:
	{
		nt_status = samsync_ldb_handle_alias(mem_ctx, 
						     state,
						     database,
						     delta,
						     error_string);
		break;
	}
	case NETR_DELTA_DELETE_ALIAS:
	{
		nt_status = samsync_ldb_delete_alias(mem_ctx, 
						     state,
						     database,
						     delta,
						     error_string);
		break;
	}
	case NETR_DELTA_ALIAS_MEMBER:
	{
		nt_status = samsync_ldb_handle_alias_member(mem_ctx, 
							    state,
							    database,
							    delta,
							    error_string);
		break;
	}
	case NETR_DELTA_ACCOUNT:
	{
		nt_status = samsync_ldb_handle_account(mem_ctx, 
						       state,
						       database,
						       delta,
						       error_string);
		break;
	}
	case NETR_DELTA_DELETE_ACCOUNT:
	{
		nt_status = samsync_ldb_delete_account(mem_ctx, 
						       state,
						       database,
						       delta,
						       error_string);
		break;
	}
	default:
		/* Can't dump them all right now */
		break;
	}
	if (!NT_STATUS_IS_OK(nt_status) && !*error_string) {
		*error_string = talloc_asprintf(mem_ctx, "Failed to handle samsync delta: %s", nt_errstr(nt_status));
	}
	return nt_status;
}

static NTSTATUS libnet_samsync_ldb_init(TALLOC_CTX *mem_ctx, 		
					void *private,
					struct libnet_SamSync_state *samsync_state,
					char **error_string)
{
	struct samsync_ldb_state *state = talloc_get_type(private, struct samsync_ldb_state);
	const char *server = dcerpc_server_name(samsync_state->netlogon_pipe);
	char *ldap_url;

	state->samsync_state = samsync_state;

	ZERO_STRUCT(state->dom_sid);
	if (state->samsync_state->domain_sid) {
		state->dom_sid[SAM_DATABASE_DOMAIN] = dom_sid_dup(state, state->samsync_state->domain_sid);
	}

	state->dom_sid[SAM_DATABASE_BUILTIN] = dom_sid_parse_talloc(state, SID_BUILTIN);

	if (state->samsync_state->realm) {
		if (!server || !*server) {
			/* huh?  how do we not have a server name?  */
			*error_string = talloc_strdup(mem_ctx, "No DCE/RPC server name available.  How did we connect?");
			return NT_STATUS_INVALID_PARAMETER;
		}
		ldap_url = talloc_asprintf(state, "ldap://%s", server);
		
		state->remote_ldb = ldb_wrap_connect(mem_ctx, ldap_url, 
						     NULL, state->samsync_state->machine_net_ctx->cred,
						     0, NULL);
		if (!state->remote_ldb) {
			*error_string = talloc_asprintf(mem_ctx, "Failed to connect to remote LDAP server at %s (used to extract additional data in SamSync replication)", ldap_url);
			return NT_STATUS_NO_LOGON_SERVERS;
		}
	} else {
		state->remote_ldb = NULL;
	}
	return NT_STATUS_OK;
}

NTSTATUS libnet_samsync_ldb(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_samsync_ldb *r)
{
	NTSTATUS nt_status;
	struct libnet_SamSync r2;
	struct samsync_ldb_state *state = talloc(mem_ctx, struct samsync_ldb_state);

	if (!state) {
		return NT_STATUS_NO_MEMORY;
	}

	state->secrets         = NULL;
	state->trusted_domains = NULL;

	state->sam_ldb         = ldb_wrap_connect(mem_ctx, lp_sam_url(global_loadparm), 
						  r->in.session_info,
						  ctx->cred, 0, NULL);

	r2.out.error_string    = NULL;
	r2.in.binding_string   = r->in.binding_string;
	r2.in.rid_crypt	       = true;
	r2.in.init_fn          = libnet_samsync_ldb_init;
	r2.in.delta_fn         = libnet_samsync_ldb_fn;
	r2.in.fn_ctx           = state;
	r2.in.machine_account  = NULL; /* TODO:  Create a machine account, fill this in, and the delete it */
	nt_status              = libnet_SamSync_netlogon(ctx, state, &r2);
	r->out.error_string    = r2.out.error_string;
	talloc_steal(mem_ctx, r->out.error_string);

	if (!NT_STATUS_IS_OK(nt_status)) {
		talloc_free(state);
		return nt_status;
	}
	talloc_free(state);
	return nt_status;
}