r9792: Rename StrCaseCmp -> strcasecmp_m. All these years I was thinking
[sfrench/samba-autobuild/.git] / source4 / torture / rpc / samsync.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    test suite for netlogon rpc operations
5
6    Copyright (C) Andrew Tridgell 2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Tim Potter      2003
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "librpc/gen_ndr/ndr_netlogon.h"
27 #include "auth/auth.h"
28 #include "dlinklist.h"
29 #include "lib/crypto/crypto.h"
30 #include "system/time.h"
31
32 #define TEST_MACHINE_NAME "samsynctest"
33 #define TEST_WKSTA_MACHINE_NAME "samsynctest2"
34 #define TEST_USER_NAME "samsynctestuser"
35
36 /*
37   try a netlogon SamLogon
38 */
39 static NTSTATUS test_SamLogon(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, 
40                               struct creds_CredentialState *creds, 
41                               const char *domain, const char *account_name,
42                               const char *workstation, 
43                               struct samr_Password *lm_hash, 
44                               struct samr_Password *nt_hash, 
45                               struct netr_SamInfo3 **info3)
46 {
47         NTSTATUS status;
48         struct netr_LogonSamLogon r;
49         struct netr_Authenticator auth, auth2;
50         struct netr_NetworkInfo ninfo;
51
52         ninfo.identity_info.domain_name.string = domain;
53         ninfo.identity_info.parameter_control = 0;
54         ninfo.identity_info.logon_id_low = 0;
55         ninfo.identity_info.logon_id_high = 0;
56         ninfo.identity_info.account_name.string = account_name;
57         ninfo.identity_info.workstation.string = workstation;
58         generate_random_buffer(ninfo.challenge, 
59                                sizeof(ninfo.challenge));
60         if (nt_hash) {
61                 ninfo.nt.length = 24;
62                 ninfo.nt.data = talloc_size(mem_ctx, 24);
63                 SMBOWFencrypt(nt_hash->hash, ninfo.challenge, ninfo.nt.data);
64         } else {
65                 ninfo.nt.length = 0;
66                 ninfo.nt.data = NULL;
67         }
68         
69         if (lm_hash) {
70                 ninfo.lm.length = 24;
71                 ninfo.lm.data = talloc_size(mem_ctx, 24);
72                 SMBOWFencrypt(lm_hash->hash, ninfo.challenge, ninfo.lm.data);
73         } else {
74                 ninfo.lm.length = 0;
75                 ninfo.lm.data = NULL;
76         }
77
78         r.in.server_name = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(p));
79         r.in.workstation = workstation;
80         r.in.credential = &auth;
81         r.in.return_authenticator = &auth2;
82         r.in.logon_level = 2;
83         r.in.logon.network = &ninfo;
84
85         ZERO_STRUCT(auth2);
86         creds_client_authenticator(creds, &auth);
87         
88         r.in.validation_level = 3;
89         
90         status = dcerpc_netr_LogonSamLogon(p, mem_ctx, &r);
91
92         if (!creds_client_check(creds, &r.out.return_authenticator->cred)) {
93                 printf("Credential chaining failed\n");
94         }
95
96         if (info3) {
97                 *info3 = r.out.validation.sam3;
98         }
99
100         return status;
101 }
102
103 struct samsync_state {
104 /* we remember the sequence numbers so we can easily do a DatabaseDelta */
105         uint64_t seq_num[3];
106         char *domain_name[2];
107         struct samsync_secret *secrets;
108         struct samsync_trusted_domain *trusted_domains;
109         struct creds_CredentialState *creds;
110         struct creds_CredentialState *creds_netlogon_wksta;
111         struct policy_handle *connect_handle;
112         struct policy_handle *domain_handle[2];
113         struct dom_sid *sid[2];
114         struct dcerpc_pipe *p;
115         struct dcerpc_pipe *p_netlogon_wksta;
116         struct dcerpc_pipe *p_samr;
117         struct dcerpc_pipe *p_lsa;
118         struct policy_handle *lsa_handle;
119 };
120
121 struct samsync_secret {
122         struct samsync_secret *prev, *next;
123         DATA_BLOB secret;
124         char *name;
125         NTTIME mtime;
126 };
127
128 struct samsync_trusted_domain {
129         struct samsync_trusted_domain *prev, *next;
130         struct dom_sid *sid;
131         char *name;
132 };
133
134 static struct policy_handle *samsync_open_domain(TALLOC_CTX *mem_ctx, 
135                                                  struct samsync_state *samsync_state, 
136                                                  const char *domain, 
137                                                  struct dom_sid **sid)
138 {
139         struct lsa_String name;
140         struct samr_OpenDomain o;
141         struct samr_LookupDomain l;
142         struct policy_handle *domain_handle = talloc(mem_ctx, struct policy_handle);
143         NTSTATUS nt_status;
144
145         name.string = domain;
146         l.in.connect_handle = samsync_state->connect_handle;
147         l.in.domain_name = &name;
148
149         nt_status = dcerpc_samr_LookupDomain(samsync_state->p_samr, mem_ctx, &l);
150         if (!NT_STATUS_IS_OK(nt_status)) {
151                 printf("LookupDomain failed - %s\n", nt_errstr(nt_status));
152                 return NULL;
153         }
154
155         o.in.connect_handle = samsync_state->connect_handle;
156         o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
157         o.in.sid = l.out.sid;
158         o.out.domain_handle = domain_handle;
159         
160         if (sid) {
161                 *sid = l.out.sid;
162         }
163
164         nt_status = dcerpc_samr_OpenDomain(samsync_state->p_samr, mem_ctx, &o);
165         if (!NT_STATUS_IS_OK(nt_status)) {
166                 printf("OpenDomain failed - %s\n", nt_errstr(nt_status));
167                 return NULL;
168         }
169
170         return domain_handle;
171 }
172
173 static struct sec_desc_buf *samsync_query_samr_sec_desc(TALLOC_CTX *mem_ctx, 
174                                                         struct samsync_state *samsync_state, 
175                                                         struct policy_handle *handle) 
176 {
177         struct samr_QuerySecurity r;
178         NTSTATUS status;
179
180         r.in.handle = handle;
181         r.in.sec_info = 0x7;
182
183         status = dcerpc_samr_QuerySecurity(samsync_state->p_samr, mem_ctx, &r);
184         if (!NT_STATUS_IS_OK(status)) {
185                 printf("SAMR QuerySecurity failed - %s\n", nt_errstr(status));
186                 return NULL;
187         }
188
189         return r.out.sdbuf;
190 }
191
192 static struct sec_desc_buf *samsync_query_lsa_sec_desc(TALLOC_CTX *mem_ctx, 
193                                                        struct samsync_state *samsync_state, 
194                                                        struct policy_handle *handle) 
195 {
196         struct lsa_QuerySecurity r;
197         NTSTATUS status;
198
199         r.in.handle = handle;
200         r.in.sec_info = 0x7;
201
202         status = dcerpc_lsa_QuerySecurity(samsync_state->p_lsa, mem_ctx, &r);
203         if (!NT_STATUS_IS_OK(status)) {
204                 printf("LSA QuerySecurity failed - %s\n", nt_errstr(status));
205                 return NULL;
206         }
207
208         return r.out.sdbuf;
209 }
210
211 #define TEST_UINT64_EQUAL(i1, i2) do {\
212         if (i1 != i2) {\
213               printf("%s: uint64 mismatch: " #i1 ": 0x%08x%08x (%lld) != " #i2 ": 0x%08x%08x (%lld)\n", \
214                      __location__, \
215                      (uint32_t)(i1 >> 32), (uint32_t)(i1 & 0xFFFFFFFF), i1, \
216                      (uint32_t)(i2 >> 32), (uint32_t)(i2 & 0xFFFFFFFF), i2);\
217               ret = False;\
218         } \
219 } while (0)
220 #define TEST_INT_EQUAL(i1, i2) do {\
221         if (i1 != i2) {\
222               printf("%s: integer mismatch: " #i1 ":%d != " #i2 ": %d\n", \
223                      __location__, i1, i2);\
224               ret = False;\
225         } \
226 } while (0)
227 #define TEST_TIME_EQUAL(t1, t2) do {\
228         if (t1 != t2) {\
229               printf("%s: NTTIME mismatch: " #t1 ":%s != " #t2 ": %s\n", \
230                      __location__, nt_time_string(mem_ctx, t1),  nt_time_string(mem_ctx, t2));\
231               ret = False;\
232         } \
233 } while (0)
234
235 #define TEST_STRING_EQUAL(s1, s2) do {\
236         if (!((!s1.string || s1.string[0]=='\0') && (!s2.string || s2.string[0]=='\0')) \
237             && strcmp_safe(s1.string, s2.string) != 0) {\
238               printf("%s: string mismatch: " #s1 ":%s != " #s2 ": %s\n", \
239                      __location__, s1.string, s2.string);\
240               ret = False;\
241         } \
242 } while (0)
243
244 #define TEST_SID_EQUAL(s1, s2) do {\
245         if (!dom_sid_equal(s1, s2)) {\
246               printf("%s: dom_sid mismatch: " #s1 ":%s != " #s2 ": %s\n", \
247                      __location__, dom_sid_string(mem_ctx, s1), dom_sid_string(mem_ctx, s2));\
248               ret = False;\
249         } \
250 } while (0)
251
252 /* The ~SEC_DESC_SACL_PRESENT is because we don't, as administrator,
253  * get back the SACL part of the SD when we ask over SAMR */
254
255 #define TEST_SEC_DESC_EQUAL(sd1, pipe, handle) do {\
256         struct sec_desc_buf *sdbuf = samsync_query_ ##pipe## _sec_desc(mem_ctx, samsync_state, \
257                                                             handle); \
258         if (!sdbuf || !sdbuf->sd) { \
259                 printf("Could not obtain security descriptor to match " #sd1 "\n");\
260                 ret = False; \
261         } else {\
262                 if (!security_descriptor_mask_equal(sd1.sd, sdbuf->sd, \
263                             ~SEC_DESC_SACL_PRESENT)) {\
264                         printf("Security Descriptor Mismatch for %s:\n", #sd1);\
265                         ndr_print_debug((ndr_print_fn_t)ndr_print_security_descriptor, "SamSync", sd1.sd);\
266                         ndr_print_debug((ndr_print_fn_t)ndr_print_security_descriptor, "SamR", sdbuf->sd);\
267                         ret = False;\
268                 }\
269         }\
270 } while (0)
271
272 static BOOL samsync_handle_domain(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
273                            int database_id, struct netr_DELTA_ENUM *delta) 
274 {
275         struct netr_DELTA_DOMAIN *domain = delta->delta_union.domain;
276         struct dom_sid *dom_sid;
277         struct samr_QueryDomainInfo q[14]; /* q[0] will be unused simple for clarity */
278         uint16_t levels[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13};
279         NTSTATUS nt_status;
280         int i;
281         BOOL ret = True;
282         
283         samsync_state->seq_num[database_id] = 
284                 domain->sequence_num;
285         switch (database_id) {
286         case SAM_DATABASE_DOMAIN:
287                 break;
288         case SAM_DATABASE_BUILTIN:
289                 if (strcasecmp_m("BUILTIN", domain->domain_name.string) != 0) {
290                         printf("BUILTIN domain has different name: %s\n", domain->domain_name.string);
291                 }
292                 break;
293         case SAM_DATABASE_PRIVS:
294                 printf("DOMAIN entry on privs DB!\n");
295                 return False;
296                 break;
297         }
298         
299         if (!samsync_state->domain_name[database_id]) {
300                 samsync_state->domain_name[database_id] = 
301                         talloc_reference(samsync_state, domain->domain_name.string);
302         } else {
303                 if (strcasecmp_m(samsync_state->domain_name[database_id], domain->domain_name.string) != 0) {
304                         printf("Domain has name varies!: %s != %s\n", samsync_state->domain_name[database_id], 
305                                domain->domain_name.string);
306                         return False;
307                 }
308         }
309
310         if (!samsync_state->domain_handle[database_id]) {
311                 samsync_state->domain_handle[database_id]
312                         = talloc_reference(samsync_state, 
313                                            samsync_open_domain(mem_ctx, samsync_state, samsync_state->domain_name[database_id], 
314                                                                &dom_sid));
315         }
316         if (samsync_state->domain_handle[database_id]) {
317                 samsync_state->sid[database_id] = talloc_reference(samsync_state, dom_sid);
318                 talloc_reference(dom_sid, dom_sid->sub_auths);
319         }
320
321         printf("\tsequence_nums[%d/%s]=%llu\n",
322                database_id, domain->domain_name.string,
323                samsync_state->seq_num[database_id]);
324
325         for (i=0;i<ARRAY_SIZE(levels);i++) {
326                 q[levels[i]].in.domain_handle = samsync_state->domain_handle[database_id];
327                 q[levels[i]].in.level = levels[i];
328
329                 nt_status = dcerpc_samr_QueryDomainInfo(samsync_state->p_samr, mem_ctx, &q[levels[i]]);
330
331                 if (!NT_STATUS_IS_OK(nt_status)) {
332                         printf("QueryDomainInfo level %u failed - %s\n", 
333                                q[levels[i]].in.level, nt_errstr(nt_status));
334                         return False;
335                 }
336         }
337
338         TEST_STRING_EQUAL(q[5].out.info->info5.domain_name, domain->domain_name);
339         
340         TEST_STRING_EQUAL(q[2].out.info->info2.comment, domain->comment);
341         TEST_STRING_EQUAL(q[4].out.info->info4.comment, domain->comment);
342         TEST_TIME_EQUAL(q[2].out.info->info2.force_logoff_time, domain->force_logoff_time);
343         TEST_TIME_EQUAL(q[3].out.info->info3.force_logoff_time, domain->force_logoff_time);
344
345         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_length, domain->min_password_length);
346         TEST_TIME_EQUAL(q[1].out.info->info1.password_history_length, domain->password_history_length);
347         TEST_TIME_EQUAL(q[1].out.info->info1.max_password_age, domain->max_password_age);
348         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_age, domain->min_password_age);
349
350         TEST_UINT64_EQUAL(q[8].out.info->info8.sequence_num, 
351                         domain->sequence_num);
352         TEST_TIME_EQUAL(q[8].out.info->info8.domain_create_time, 
353                         domain->domain_create_time);
354         TEST_TIME_EQUAL(q[13].out.info->info13.domain_create_time, 
355                         domain->domain_create_time);
356
357         TEST_SEC_DESC_EQUAL(domain->sdbuf, samr, samsync_state->domain_handle[database_id]);
358
359         return ret;
360 }
361
362 static BOOL samsync_handle_policy(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
363                            int database_id, struct netr_DELTA_ENUM *delta) 
364 {
365         struct netr_DELTA_POLICY *policy = delta->delta_union.policy;
366
367         samsync_state->seq_num[database_id] = 
368                 policy->sequence_num;
369         
370         if (!samsync_state->domain_name[SAM_DATABASE_DOMAIN]) {
371                 samsync_state->domain_name[SAM_DATABASE_DOMAIN] = 
372                         talloc_reference(samsync_state, policy->primary_domain_name.string);
373         } else {
374                 if (strcasecmp_m(samsync_state->domain_name[SAM_DATABASE_DOMAIN], policy->primary_domain_name.string) != 0) {
375                         printf("PRIMARY domain has name varies between DOMAIN and POLICY!: %s != %s\n", samsync_state->domain_name[SAM_DATABASE_DOMAIN], 
376                                policy->primary_domain_name.string);
377                         return False;
378                 }
379         }
380
381         if (!dom_sid_equal(samsync_state->sid[SAM_DATABASE_DOMAIN], policy->sid)) {
382                 printf("Domain SID from POLICY (%s) does not match domain sid from SAMR (%s)\n", 
383                        dom_sid_string(mem_ctx, policy->sid), dom_sid_string(mem_ctx, samsync_state->sid[SAM_DATABASE_DOMAIN]));
384                 return False;
385         }
386
387         printf("\tsequence_nums[%d/PRIVS]=%llu\n",
388                database_id, 
389                samsync_state->seq_num[database_id]);
390         return True;
391 }
392
393 static BOOL samsync_handle_user(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
394                                 int database_id, struct netr_DELTA_ENUM *delta) 
395 {
396         uint32_t rid = delta->delta_id_union.rid;
397         struct netr_DELTA_USER *user = delta->delta_union.user;
398         struct netr_SamInfo3 *info3;
399         struct samr_Password lm_hash;
400         struct samr_Password nt_hash;
401         struct samr_Password *lm_hash_p = NULL;
402         struct samr_Password *nt_hash_p = NULL;
403         const char *domain = samsync_state->domain_name[database_id];
404         const char *username = user->account_name.string;
405         NTSTATUS nt_status;
406         BOOL ret = True;
407
408         struct samr_OpenUser r;
409         struct samr_QueryUserInfo q;
410         struct policy_handle user_handle;
411
412         struct samr_GetGroupsForUser getgroups;
413         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
414                 printf("SamSync needs domain information before the users\n");
415                 return False;
416         }
417
418         r.in.domain_handle = samsync_state->domain_handle[database_id];
419         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
420         r.in.rid = rid;
421         r.out.user_handle = &user_handle;
422
423         nt_status = dcerpc_samr_OpenUser(samsync_state->p_samr, mem_ctx, &r);
424         if (!NT_STATUS_IS_OK(nt_status)) {
425                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
426                 return False;
427         }
428
429         q.in.user_handle = &user_handle;
430         q.in.level = 21;
431
432         TEST_SEC_DESC_EQUAL(user->sdbuf, samr, &user_handle);
433
434         nt_status = dcerpc_samr_QueryUserInfo(samsync_state->p_samr, mem_ctx, &q);
435         if (!NT_STATUS_IS_OK(nt_status)) {
436                 printf("QueryUserInfo level %u failed - %s\n", 
437                        q.in.level, nt_errstr(nt_status));
438                 ret = False;
439         }
440
441         getgroups.in.user_handle = &user_handle;
442         
443         nt_status = dcerpc_samr_GetGroupsForUser(samsync_state->p_samr, mem_ctx, &getgroups);
444         if (!NT_STATUS_IS_OK(nt_status)) {
445                 printf("GetGroupsForUser failed - %s\n",
446                        nt_errstr(nt_status));
447                 ret = False;
448         }
449
450         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &user_handle)) {
451                 printf("samr_handle_Close failed - %s\n", 
452                        nt_errstr(nt_status));
453                 ret = False;
454         }
455         if (!ret) {
456                 return False;
457         }
458
459         if (!NT_STATUS_IS_OK(nt_status)) {
460                 printf("QueryUserInfo level %u failed - %s\n", 
461                        q.in.level, nt_errstr(nt_status));
462                 return False;
463         }
464
465         TEST_STRING_EQUAL(q.out.info->info21.account_name, user->account_name);
466         TEST_STRING_EQUAL(q.out.info->info21.full_name, user->full_name);
467         TEST_INT_EQUAL(q.out.info->info21.rid, user->rid);
468         TEST_INT_EQUAL(q.out.info->info21.primary_gid, user->primary_gid);
469         TEST_STRING_EQUAL(q.out.info->info21.home_directory, user->home_directory);
470         TEST_STRING_EQUAL(q.out.info->info21.home_drive, user->home_drive);
471         TEST_STRING_EQUAL(q.out.info->info21.logon_script, user->logon_script);
472         TEST_STRING_EQUAL(q.out.info->info21.description, user->description);
473         TEST_STRING_EQUAL(q.out.info->info21.workstations, user->workstations);
474
475         TEST_TIME_EQUAL(q.out.info->info21.last_logon, user->last_logon);
476         TEST_TIME_EQUAL(q.out.info->info21.last_logoff, user->last_logoff);
477
478
479         TEST_INT_EQUAL(q.out.info->info21.logon_hours.units_per_week, 
480                        user->logon_hours.units_per_week);
481         if (ret) {
482                 if (memcmp(q.out.info->info21.logon_hours.bits, user->logon_hours.bits, 
483                            q.out.info->info21.logon_hours.units_per_week/8) != 0) {
484                         printf("Logon hours mismatch\n");
485                         ret = False;
486                 }
487         }
488
489         TEST_INT_EQUAL(q.out.info->info21.bad_password_count,
490                        user->bad_password_count);
491         TEST_INT_EQUAL(q.out.info->info21.logon_count,
492                        user->logon_count);
493
494         TEST_TIME_EQUAL(q.out.info->info21.last_password_change,
495                        user->last_password_change);
496         TEST_TIME_EQUAL(q.out.info->info21.acct_expiry,
497                        user->acct_expiry);
498
499         TEST_INT_EQUAL(q.out.info->info21.acct_flags, user->acct_flags);
500         TEST_INT_EQUAL(q.out.info->info21.nt_password_set, user->nt_password_present);
501         TEST_INT_EQUAL(q.out.info->info21.lm_password_set, user->lm_password_present);
502         TEST_INT_EQUAL(q.out.info->info21.password_expired, user->password_expired);
503
504         TEST_STRING_EQUAL(q.out.info->info21.comment, user->comment);
505         TEST_STRING_EQUAL(q.out.info->info21.parameters, user->parameters);
506
507         TEST_INT_EQUAL(q.out.info->info21.country_code, user->country_code);
508         TEST_INT_EQUAL(q.out.info->info21.code_page, user->code_page);
509
510         TEST_STRING_EQUAL(q.out.info->info21.profile_path, user->profile_path);
511
512         if (user->lm_password_present) {
513                 sam_rid_crypt(rid, user->lmpassword.hash, lm_hash.hash, 0);
514                 lm_hash_p = &lm_hash;
515         }
516         if (user->nt_password_present) {
517                 sam_rid_crypt(rid, user->ntpassword.hash, nt_hash.hash, 0);
518                 nt_hash_p = &nt_hash;
519         }
520
521         if (user->user_private_info.SensitiveData) {
522                 DATA_BLOB data;
523                 struct netr_USER_KEYS keys;
524                 data.data = user->user_private_info.SensitiveData;
525                 data.length = user->user_private_info.DataLength;
526                 creds_arcfour_crypt(samsync_state->creds, data.data, data.length);
527                 nt_status = ndr_pull_struct_blob(&data, mem_ctx, &keys, (ndr_pull_flags_fn_t)ndr_pull_netr_USER_KEYS);
528                 if (NT_STATUS_IS_OK(nt_status)) {
529                         if (keys.keys.keys2.lmpassword.length == 16) {
530                                 sam_rid_crypt(rid, keys.keys.keys2.lmpassword.pwd.hash, lm_hash.hash, 0);
531                                 lm_hash_p = &lm_hash;
532                         }
533                         if (keys.keys.keys2.ntpassword.length == 16) {
534                                 sam_rid_crypt(rid, keys.keys.keys2.ntpassword.pwd.hash, nt_hash.hash, 0);
535                                 nt_hash_p = &nt_hash;
536                         }
537                 } else {
538                         printf("Failed to parse Sensitive Data for %s:\n", username);
539 #if 0
540                         dump_data(0, data.data, data.length);
541 #endif
542                         return False;
543                 }
544         }
545
546         if (nt_hash_p) {
547                 DATA_BLOB nt_hash_blob = data_blob_const(nt_hash_p, 16);
548                 DEBUG(100,("ACCOUNT [%s\\%-25s] NTHASH %s\n", samsync_state->domain_name[0], username, data_blob_hex_string(mem_ctx, &nt_hash_blob)));
549         }
550         if (lm_hash_p) {
551                 DATA_BLOB lm_hash_blob = data_blob_const(lm_hash_p, 16);
552                 DEBUG(100,("ACCOUNT [%s\\%-25s] LMHASH %s\n", samsync_state->domain_name[0], username, data_blob_hex_string(mem_ctx, &lm_hash_blob)));
553         }
554
555         nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, mem_ctx, samsync_state->creds_netlogon_wksta, 
556                                   domain,
557                                   username, 
558                                   TEST_WKSTA_MACHINE_NAME,
559                                   lm_hash_p,
560                                   nt_hash_p,
561                                   &info3);
562
563         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_DISABLED)) {
564                 if (user->acct_flags & ACB_DISABLED) {
565                         return True;
566                 }
567         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)) {
568                 if (user->acct_flags & ACB_WSTRUST) {
569                         return True;
570                 }
571         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT)) {
572                 if (user->acct_flags & ACB_SVRTRUST) {
573                         return True;
574                 }
575         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
576                 if (user->acct_flags & ACB_DOMTRUST) {
577                         return True;
578                 }
579         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
580                 if (user->acct_flags & ACB_DOMTRUST) {
581                         return True;
582                 }
583         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
584                 if (user->acct_flags & ACB_AUTOLOCK) {
585                         return True;
586                 }
587         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
588                 if (!lm_hash_p && !nt_hash_p) {
589                         return True;
590                 }
591         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_PASSWORD_MUST_CHANGE)) {
592                 /* We would need to know the server's current time to test this properly */
593                 return True;
594         } else if (NT_STATUS_IS_OK(nt_status)) {
595                 TEST_INT_EQUAL(user->rid, info3->base.rid);
596                 TEST_INT_EQUAL(user->primary_gid, info3->base.primary_gid);
597                 /* this is 0x0 from NT4 sp6 */
598                 if (info3->base.acct_flags) {
599                         TEST_INT_EQUAL(user->acct_flags, info3->base.acct_flags);
600                 }
601                 /* this is NULL from NT4 sp6 */
602                 if (info3->base.account_name.string) {
603                         TEST_STRING_EQUAL(user->account_name, info3->base.account_name);
604                 }
605                 /* this is NULL from Win2k3 */
606                 if (info3->base.full_name.string) {
607                         TEST_STRING_EQUAL(user->full_name, info3->base.full_name);
608                 }
609                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
610                 TEST_STRING_EQUAL(user->profile_path, info3->base.profile_path);
611                 TEST_STRING_EQUAL(user->home_directory, info3->base.home_directory);
612                 TEST_STRING_EQUAL(user->home_drive, info3->base.home_drive);
613                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
614
615
616                 TEST_TIME_EQUAL(user->last_logon, info3->base.last_logon);
617                 TEST_TIME_EQUAL(user->acct_expiry, info3->base.acct_expiry);
618                 TEST_TIME_EQUAL(user->last_password_change, info3->base.last_password_change);
619
620                 /* Does the concept of a logoff time ever really
621                  * exist? (not in any sensible way, according to the
622                  * doco I read -- abartlet) */
623
624                 /* This copes with the two different versions of 0 I see */
625                 /* with NT4 sp6 we have the || case */
626                 if (!((user->last_logoff == 0) 
627                       || (info3->base.last_logoff == 0x7fffffffffffffffLL))) {
628                         TEST_TIME_EQUAL(user->last_logoff, info3->base.last_logoff);
629                 }
630
631                 TEST_INT_EQUAL(getgroups.out.rids->count, info3->base.groups.count);
632                 if (getgroups.out.rids->count == info3->base.groups.count) {
633                         int i, j;
634                         int count = getgroups.out.rids->count;
635                         BOOL *matched = talloc_zero_array(mem_ctx, BOOL, getgroups.out.rids->count);
636                                 
637                         for (i = 0; i < count; i++) {
638                                 for (j = 0; j < count; j++) {
639                                         if ((getgroups.out.rids->rids[i].rid == 
640                                              info3->base.groups.rids[j].rid)
641                                             && (getgroups.out.rids->rids[i].attributes == 
642                                                 info3->base.groups.rids[j].attributes)) {
643                                                         matched[i] = True;
644                                                 }
645                                 }
646                         }
647
648                         for (i = 0; i < getgroups.out.rids->count; i++) {
649                                 if (matched[i] == False) {
650                                         ret = False;
651                                         printf("Could not find group RID %u found in getgroups in NETLOGON reply\n",
652                                                getgroups.out.rids->rids[i].rid); 
653                                 }
654                         }
655                 }
656                 return ret;
657         } else {
658                 printf("Could not validate password for user %s\\%s: %s\n",
659                        domain, username, nt_errstr(nt_status));
660                 return False;
661         } 
662         return False;
663 }
664
665 static BOOL samsync_handle_alias(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
666                                  int database_id, struct netr_DELTA_ENUM *delta) 
667 {
668         uint32_t rid = delta->delta_id_union.rid;
669         struct netr_DELTA_ALIAS *alias = delta->delta_union.alias;
670         NTSTATUS nt_status;
671         BOOL ret = True;
672
673         struct samr_OpenAlias r;
674         struct samr_QueryAliasInfo q;
675         struct policy_handle alias_handle;
676
677         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
678                 printf("SamSync needs domain information before the users\n");
679                 return False;
680         }
681
682         r.in.domain_handle = samsync_state->domain_handle[database_id];
683         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
684         r.in.rid = rid;
685         r.out.alias_handle = &alias_handle;
686
687         nt_status = dcerpc_samr_OpenAlias(samsync_state->p_samr, mem_ctx, &r);
688         if (!NT_STATUS_IS_OK(nt_status)) {
689                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
690                 return False;
691         }
692
693         q.in.alias_handle = &alias_handle;
694         q.in.level = 1;
695
696         TEST_SEC_DESC_EQUAL(alias->sdbuf, samr, &alias_handle);
697
698         nt_status = dcerpc_samr_QueryAliasInfo(samsync_state->p_samr, mem_ctx, &q);
699         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &alias_handle)) {
700                 return False;
701         }
702
703         if (!NT_STATUS_IS_OK(nt_status)) {
704                 printf("QueryAliasInfo level %u failed - %s\n", 
705                        q.in.level, nt_errstr(nt_status));
706                 return False;
707         }
708
709         TEST_STRING_EQUAL(q.out.info->all.name, alias->alias_name);
710         TEST_STRING_EQUAL(q.out.info->all.description, alias->description);
711         return ret;
712 }
713
714 static BOOL samsync_handle_group(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
715                                  int database_id, struct netr_DELTA_ENUM *delta) 
716 {
717         uint32_t rid = delta->delta_id_union.rid;
718         struct netr_DELTA_GROUP *group = delta->delta_union.group;
719         NTSTATUS nt_status;
720         BOOL ret = True;
721
722         struct samr_OpenGroup r;
723         struct samr_QueryGroupInfo q;
724         struct policy_handle group_handle;
725
726         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
727                 printf("SamSync needs domain information before the users\n");
728                 return False;
729         }
730
731         r.in.domain_handle = samsync_state->domain_handle[database_id];
732         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
733         r.in.rid = rid;
734         r.out.group_handle = &group_handle;
735
736         nt_status = dcerpc_samr_OpenGroup(samsync_state->p_samr, mem_ctx, &r);
737         if (!NT_STATUS_IS_OK(nt_status)) {
738                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
739                 return False;
740         }
741
742         q.in.group_handle = &group_handle;
743         q.in.level = 1;
744
745         TEST_SEC_DESC_EQUAL(group->sdbuf, samr, &group_handle);
746
747         nt_status = dcerpc_samr_QueryGroupInfo(samsync_state->p_samr, mem_ctx, &q);
748         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &group_handle)) {
749                 return False;
750         }
751
752         if (!NT_STATUS_IS_OK(nt_status)) {
753                 printf("QueryGroupInfo level %u failed - %s\n", 
754                        q.in.level, nt_errstr(nt_status));
755                 return False;
756         }
757
758         TEST_STRING_EQUAL(q.out.info->all.name, group->group_name);
759         TEST_INT_EQUAL(q.out.info->all.attributes, group->attributes);
760         TEST_STRING_EQUAL(q.out.info->all.description, group->description);
761         return ret;
762 }
763
764 static BOOL samsync_handle_secret(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
765                                   int database_id, struct netr_DELTA_ENUM *delta) 
766 {
767         struct netr_DELTA_SECRET *secret = delta->delta_union.secret;
768         const char *name = delta->delta_id_union.name;
769         struct samsync_secret *new = talloc(samsync_state, struct samsync_secret);
770         struct samsync_secret *old = talloc(mem_ctx, struct samsync_secret);
771         struct lsa_QuerySecret q;
772         struct lsa_OpenSecret o;
773         struct policy_handle sec_handle;
774         struct lsa_DATA_BUF_PTR bufp1;
775         struct lsa_DATA_BUF_PTR bufp2;
776         NTTIME new_mtime;
777         NTTIME old_mtime;
778         BOOL ret = True;
779         DATA_BLOB lsa_blob1, lsa_blob_out, session_key;
780         NTSTATUS status;
781
782         creds_arcfour_crypt(samsync_state->creds, secret->current_cipher.cipher_data, 
783                             secret->current_cipher.maxlen); 
784
785         creds_arcfour_crypt(samsync_state->creds, secret->old_cipher.cipher_data, 
786                             secret->old_cipher.maxlen); 
787
788         new->name = talloc_reference(new, name);
789         new->secret = data_blob_talloc(new, secret->current_cipher.cipher_data, secret->current_cipher.maxlen);
790         new->mtime = secret->current_cipher_set_time;
791
792         new = talloc_reference(samsync_state, new);
793         DLIST_ADD(samsync_state->secrets, new);
794
795         old->name = talloc_reference(old, name);
796         old->secret = data_blob_const(secret->old_cipher.cipher_data, secret->old_cipher.maxlen);
797         old->mtime = secret->old_cipher_set_time;
798
799         o.in.handle = samsync_state->lsa_handle;
800         o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
801         o.in.name.string = name;
802         o.out.sec_handle = &sec_handle;
803
804         status = dcerpc_lsa_OpenSecret(samsync_state->p_lsa, mem_ctx, &o);
805         if (!NT_STATUS_IS_OK(status)) {
806                 printf("OpenSecret failed - %s\n", nt_errstr(status));
807                 return False;
808         }
809
810 /*
811   We would like to do this, but it is NOT_SUPPORTED on win2k3
812   TEST_SEC_DESC_EQUAL(secret->sdbuf, lsa, &sec_handle);
813 */
814         status = dcerpc_fetch_session_key(samsync_state->p_lsa, &session_key);
815         if (!NT_STATUS_IS_OK(status)) {
816                 printf("dcerpc_fetch_session_key failed - %s\n", nt_errstr(status));
817                 return False;
818         }
819
820
821         ZERO_STRUCT(new_mtime);
822         ZERO_STRUCT(old_mtime);
823
824         /* fetch the secret back again */
825         q.in.sec_handle = &sec_handle;
826         q.in.new_val = &bufp1;
827         q.in.new_mtime = &new_mtime;
828         q.in.old_val = &bufp2;
829         q.in.old_mtime = &old_mtime;
830
831         bufp1.buf = NULL;
832         bufp2.buf = NULL;
833
834         status = dcerpc_lsa_QuerySecret(samsync_state->p_lsa, mem_ctx, &q);
835         if (NT_STATUS_EQUAL(NT_STATUS_ACCESS_DENIED, status)) {
836                 /* some things are just off limits */
837                 return True;
838         } else if (!NT_STATUS_IS_OK(status)) {
839                 printf("QuerySecret failed - %s\n", nt_errstr(status));
840                 return False;
841         }
842
843         if (q.out.old_val->buf == NULL) {
844                 /* probably just not available due to ACLs */
845         } else {
846                 lsa_blob1.data = q.out.old_val->buf->data;
847                 lsa_blob1.length = q.out.old_val->buf->length;
848
849                 status = sess_decrypt_blob(mem_ctx, &lsa_blob1, &session_key, &lsa_blob_out);
850                 if (!NT_STATUS_IS_OK(status)) {
851                         printf("Failed to decrypt secrets OLD blob: %s\n", nt_errstr(status));
852                         return False;
853                 }
854
855                 if (!q.out.old_mtime) {
856                         printf("OLD mtime not available on LSA for secret %s\n", old->name);
857                         ret = False;
858                 }
859                 if (old->mtime != *q.out.old_mtime) {
860                         printf("OLD mtime on secret %s does not match between SAMSYNC (%s) and LSA (%s)\n", 
861                                old->name, nt_time_string(mem_ctx, old->mtime), 
862                                nt_time_string(mem_ctx, *q.out.old_mtime)); 
863                         ret = False;
864                 }
865
866                 if (old->secret.length != lsa_blob_out.length) {
867                         printf("Returned secret %s doesn't match: %d != %d\n",
868                                old->name, (int)old->secret.length, (int)lsa_blob_out.length);
869                         ret = False;
870                 } else if (memcmp(lsa_blob_out.data, 
871                            old->secret.data, old->secret.length) != 0) {
872                         printf("Returned secret %s doesn't match: \n",
873                                old->name);
874                         DEBUG(1, ("SamSync Secret:\n"));
875                         dump_data(1, old->secret.data, old->secret.length);
876                         DEBUG(1, ("LSA Secret:\n"));
877                         dump_data(1, lsa_blob_out.data, lsa_blob_out.length);
878                         ret = False;
879                 }
880
881         }
882
883         if (q.out.new_val->buf == NULL) {
884                 /* probably just not available due to ACLs */
885         } else {
886                 lsa_blob1.data = q.out.new_val->buf->data;
887                 lsa_blob1.length = q.out.new_val->buf->length;
888
889                 status = sess_decrypt_blob(mem_ctx, &lsa_blob1, &session_key, &lsa_blob_out);
890                 if (!NT_STATUS_IS_OK(status)) {
891                         printf("Failed to decrypt secrets OLD blob\n");
892                         return False;
893                 }
894                 
895                 if (!q.out.new_mtime) {
896                         printf("NEW mtime not available on LSA for secret %s\n", new->name);
897                         ret = False;
898                 }
899                 if (new->mtime != *q.out.new_mtime) {
900                         printf("NEW mtime on secret %s does not match between SAMSYNC (%s) and LSA (%s)\n", 
901                                new->name, nt_time_string(mem_ctx, new->mtime), 
902                                nt_time_string(mem_ctx, *q.out.new_mtime)); 
903                         ret = False;
904                 }
905
906                 if (new->secret.length != lsa_blob_out.length) {
907                         printf("Returned secret %s doesn't match: %d != %d\n",
908                                new->name, (int)new->secret.length, (int)lsa_blob_out.length);
909                         ret = False;
910                 } else if (memcmp(lsa_blob_out.data, 
911                            new->secret.data, new->secret.length) != 0) {
912                         printf("Returned secret %s doesn't match: \n",
913                                new->name);
914                         DEBUG(1, ("SamSync Secret:\n"));
915                         dump_data(1, new->secret.data, new->secret.length);
916                         DEBUG(1, ("LSA Secret:\n"));
917                         dump_data(1, lsa_blob_out.data, lsa_blob_out.length);
918                         ret = False;
919                 }
920         }
921
922         return ret;
923 }
924
925 static BOOL samsync_handle_trusted_domain(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
926                                           int database_id, struct netr_DELTA_ENUM *delta) 
927 {
928         NTSTATUS status;
929         BOOL ret = True;
930         struct netr_DELTA_TRUSTED_DOMAIN *trusted_domain = delta->delta_union.trusted_domain;
931         struct dom_sid *dom_sid = delta->delta_id_union.sid;
932
933         struct samsync_trusted_domain *new = talloc(samsync_state, struct samsync_trusted_domain);
934         struct lsa_OpenTrustedDomain t;
935         struct policy_handle trustdom_handle;
936         struct lsa_QueryTrustedDomainInfo q;
937         union lsa_TrustedDomainInfo *info[9];
938         int levels [] = {1, 3, 8};
939         int i;
940
941         new->name = talloc_reference(new, trusted_domain->domain_name.string);
942         new->sid = talloc_reference(new, dom_sid);
943
944         t.in.handle = samsync_state->lsa_handle;
945         t.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
946         t.in.sid = dom_sid;
947         t.out.trustdom_handle = &trustdom_handle;
948
949         status = dcerpc_lsa_OpenTrustedDomain(samsync_state->p_lsa, mem_ctx, &t);
950         if (!NT_STATUS_IS_OK(status)) {
951                 printf("OpenTrustedDomain failed - %s\n", nt_errstr(status));
952                 return False;
953         }
954         
955         for (i=0; i< ARRAY_SIZE(levels); i++) {
956                 q.in.trustdom_handle = &trustdom_handle;
957                 q.in.level = levels[i];
958                 status = dcerpc_lsa_QueryTrustedDomainInfo(samsync_state->p_lsa, mem_ctx, &q);
959                 if (!NT_STATUS_IS_OK(status)) {
960                         if (q.in.level == 8 && NT_STATUS_EQUAL(status,NT_STATUS_INVALID_PARAMETER)) {
961                                 info[levels[i]] = NULL;
962                                 continue;
963                         }
964                         printf("QueryInfoTrustedDomain level %d failed - %s\n", 
965                                levels[i], nt_errstr(status));
966                         return False;
967                 }
968                 info[levels[i]]  = q.out.info;
969         }
970
971         if (info[8]) {
972                 TEST_SID_EQUAL(info[8]->full_info.info_ex.sid, dom_sid);
973                 TEST_STRING_EQUAL(info[8]->full_info.info_ex.netbios_name, trusted_domain->domain_name);
974         }
975         TEST_STRING_EQUAL(info[1]->name.netbios_name, trusted_domain->domain_name);
976         TEST_INT_EQUAL(info[3]->posix_offset.posix_offset, trusted_domain->posix_offset);
977 /*
978   We would like to do this, but it is NOT_SUPPORTED on win2k3
979         TEST_SEC_DESC_EQUAL(trusted_domain->sdbuf, lsa, &trustdom_handle);
980 */
981         new = talloc_reference(samsync_state, new);
982         DLIST_ADD(samsync_state->trusted_domains, new);
983
984         return ret;
985 }
986
987 static BOOL samsync_handle_account(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
988                                           int database_id, struct netr_DELTA_ENUM *delta) 
989 {
990         NTSTATUS status;
991         BOOL ret = True;
992         struct netr_DELTA_ACCOUNT *account = delta->delta_union.account;
993         struct dom_sid *dom_sid = delta->delta_id_union.sid;
994
995         struct lsa_OpenAccount a;
996         struct policy_handle acct_handle;
997         struct lsa_EnumPrivsAccount e;
998         struct lsa_LookupPrivName r;
999
1000         int i, j;
1001
1002         BOOL *found_priv_in_lsa;
1003
1004         a.in.handle = samsync_state->lsa_handle;
1005         a.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
1006         a.in.sid = dom_sid;
1007         a.out.acct_handle = &acct_handle;
1008
1009         status = dcerpc_lsa_OpenAccount(samsync_state->p_lsa, mem_ctx, &a);
1010         if (!NT_STATUS_IS_OK(status)) {
1011                 printf("OpenTrustedDomain failed - %s\n", nt_errstr(status));
1012                 return False;
1013         }
1014
1015         TEST_SEC_DESC_EQUAL(account->sdbuf, lsa, &acct_handle);
1016
1017         found_priv_in_lsa = talloc_zero_array(mem_ctx, BOOL, account->privilege_entries);
1018
1019         e.in.handle = &acct_handle;
1020
1021         status = dcerpc_lsa_EnumPrivsAccount(samsync_state->p_lsa, mem_ctx, &e);
1022         if (!NT_STATUS_IS_OK(status)) {
1023                 printf("EnumPrivsAccount failed - %s\n", nt_errstr(status));
1024                 return False;
1025         }
1026
1027         if ((account->privilege_entries && !e.out.privs)) {
1028                 printf("Account %s has privileges in SamSync, but not LSA\n",
1029                        dom_sid_string(mem_ctx, dom_sid));
1030                 return False;
1031         }
1032
1033         if (!account->privilege_entries && e.out.privs && e.out.privs->count) {
1034                 printf("Account %s has privileges in LSA, but not SamSync\n",
1035                        dom_sid_string(mem_ctx, dom_sid));
1036                 return False;
1037         }
1038
1039         TEST_INT_EQUAL(account->privilege_entries, e.out.privs->count);
1040         
1041         for (i=0;i< e.out.privs->count; i++) {
1042                 r.in.handle = samsync_state->lsa_handle;
1043                 r.in.luid = &e.out.privs->set[i].luid;
1044                 
1045                 status = dcerpc_lsa_LookupPrivName(samsync_state->p_lsa, mem_ctx, &r);
1046                 if (!NT_STATUS_IS_OK(status)) {
1047                         printf("\nLookupPrivName failed - %s\n", nt_errstr(status));
1048                         return False;
1049                 }
1050                 
1051                 if (!r.out.name) {
1052                         printf("\nLookupPrivName failed to return a name\n");
1053                         return False;
1054                 }
1055                 for (j=0;j<account->privilege_entries; j++) {
1056                         if (strcmp(r.out.name->string, account->privilege_name[j].string) == 0) {
1057                                 found_priv_in_lsa[j] = True;
1058                                 break;
1059                         }
1060                 }
1061         }
1062         for (j=0;j<account->privilege_entries; j++) {
1063                 if (!found_priv_in_lsa[j]) {
1064                         printf("Privilage %s on account %s not found in LSA\n", account->privilege_name[j].string, 
1065                                dom_sid_string(mem_ctx, dom_sid));
1066                         ret = False;
1067                 }
1068         }
1069         return ret;
1070 }
1071
1072 /*
1073   try a netlogon DatabaseSync
1074 */
1075 static BOOL test_DatabaseSync(struct samsync_state *samsync_state,
1076                               TALLOC_CTX *mem_ctx)
1077 {
1078         NTSTATUS status;
1079         TALLOC_CTX *loop_ctx, *delta_ctx, *trustdom_ctx;
1080         struct netr_DatabaseSync r;
1081         const enum netr_SamDatabaseID database_ids[] = {SAM_DATABASE_DOMAIN, SAM_DATABASE_BUILTIN, SAM_DATABASE_PRIVS}; 
1082         int i, d;
1083         BOOL ret = True;
1084         struct samsync_trusted_domain *t;
1085         struct samsync_secret *s;
1086         
1087         const char *domain, *username;
1088
1089         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
1090         r.in.computername = TEST_MACHINE_NAME;
1091         r.in.preferredmaximumlength = (uint32_t)-1;
1092         ZERO_STRUCT(r.in.return_authenticator);
1093
1094         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1095                 r.in.sync_context = 0;
1096                 r.in.database_id = database_ids[i];
1097
1098                 printf("Testing DatabaseSync of id %d\n", r.in.database_id);
1099
1100                 do {
1101                         loop_ctx = talloc_named(mem_ctx, 0, "DatabaseSync loop context");
1102                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
1103
1104                         status = dcerpc_netr_DatabaseSync(samsync_state->p, loop_ctx, &r);
1105                         if (!NT_STATUS_IS_OK(status) &&
1106                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
1107                                 printf("DatabaseSync - %s\n", nt_errstr(status));
1108                                 ret = False;
1109                                 break;
1110                         }
1111
1112                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
1113                                 printf("Credential chaining failed\n");
1114                         }
1115
1116                         r.in.sync_context = r.out.sync_context;
1117
1118                         for (d=0; d < r.out.delta_enum_array->num_deltas; d++) {
1119                                 delta_ctx = talloc_named(loop_ctx, 0, "DatabaseSync delta context");
1120                                 switch (r.out.delta_enum_array->delta_enum[d].delta_type) {
1121                                 case NETR_DELTA_DOMAIN:
1122                                         if (!samsync_handle_domain(delta_ctx, samsync_state, 
1123                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1124                                                 printf("Failed to handle DELTA_DOMAIN\n");
1125                                                 ret = False;
1126                                         }
1127                                         break;
1128                                 case NETR_DELTA_GROUP:
1129                                         if (!samsync_handle_group(delta_ctx, samsync_state, 
1130                                                                   r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1131                                                 printf("Failed to handle DELTA_USER\n");
1132                                                 ret = False;
1133                                         }
1134                                         break;
1135                                 case NETR_DELTA_USER:
1136                                         if (!samsync_handle_user(delta_ctx, samsync_state, 
1137                                                                  r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1138                                                 printf("Failed to handle DELTA_USER\n");
1139                                                 ret = False;
1140                                         }
1141                                         break;
1142                                 case NETR_DELTA_ALIAS:
1143                                         if (!samsync_handle_alias(delta_ctx, samsync_state, 
1144                                                                   r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1145                                                 printf("Failed to handle DELTA_ALIAS\n");
1146                                                 ret = False;
1147                                         }
1148                                         break;
1149                                 case NETR_DELTA_POLICY:
1150                                         if (!samsync_handle_policy(delta_ctx, samsync_state, 
1151                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1152                                                 printf("Failed to handle DELTA_POLICY\n");
1153                                                 ret = False;
1154                                         }
1155                                         break;
1156                                 case NETR_DELTA_TRUSTED_DOMAIN:
1157                                         if (!samsync_handle_trusted_domain(delta_ctx, samsync_state, 
1158                                                                            r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1159                                                 printf("Failed to handle DELTA_TRUSTED_DOMAIN\n");
1160                                                 ret = False;
1161                                         }
1162                                         break;
1163                                 case NETR_DELTA_ACCOUNT:
1164                                         if (!samsync_handle_account(delta_ctx, samsync_state, 
1165                                                                     r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1166                                                 printf("Failed to handle DELTA_ACCOUNT\n");
1167                                                 ret = False;
1168                                         }
1169                                         break;
1170                                 case NETR_DELTA_SECRET:
1171                                         if (!samsync_handle_secret(delta_ctx, samsync_state, 
1172                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1173                                                 printf("Failed to handle DELTA_SECRET\n");
1174                                                 ret = False;
1175                                         }
1176                                         break;
1177                                 }
1178                                 talloc_free(delta_ctx);
1179                         }
1180                         talloc_free(loop_ctx);
1181                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1182                 
1183         }
1184
1185         domain = samsync_state->domain_name[SAM_DATABASE_DOMAIN];
1186         if (!domain) {
1187                 printf("Never got a DOMAIN object in samsync!\n");
1188                 return False;
1189         }
1190
1191         trustdom_ctx = talloc_named(mem_ctx, 0, "test_DatabaseSync Trusted domains context");
1192         
1193         username = talloc_asprintf(trustdom_ctx, "%s$", domain);
1194         for (t=samsync_state->trusted_domains; t; t=t->next) {
1195                 char *secret_name = talloc_asprintf(trustdom_ctx, "G$$%s", t->name);
1196                 for (s=samsync_state->secrets; s; s=s->next) {
1197                         if (strcasecmp_m(s->name, secret_name) == 0) {
1198                                 NTSTATUS nt_status;
1199                                 struct samr_Password nt_hash;
1200                                 mdfour(nt_hash.hash, s->secret.data, s->secret.length);
1201                                 
1202                                 printf("Checking password for %s\\%s\n", t->name, username);
1203                                 nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, trustdom_ctx, samsync_state->creds_netlogon_wksta, 
1204                                                           t->name,
1205                                                           username, 
1206                                                           TEST_WKSTA_MACHINE_NAME,
1207                                                           NULL, 
1208                                                           &nt_hash,
1209                                                           NULL);
1210                                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_LOGON_SERVERS)) {
1211                                         printf("Verifiction of trust password to %s failed: %s (the trusted domain is not available)\n", 
1212                                                t->name, nt_errstr(nt_status));
1213                                         
1214                                         break;
1215                                 }
1216                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
1217                                         printf("Verifiction of trust password to %s: should have failed (nologon interdomain trust account), instead: %s\n", 
1218                                                t->name, nt_errstr(nt_status));
1219                                         ret = False;
1220                                 }
1221                                 
1222                                 /* break it */
1223                                 nt_hash.hash[0]++;
1224                                 nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, trustdom_ctx, samsync_state->creds_netlogon_wksta, 
1225                                                           t->name,
1226                                                           username, 
1227                                                           TEST_WKSTA_MACHINE_NAME,
1228                                                           NULL,
1229                                                           &nt_hash,
1230                                                           NULL);
1231                                 
1232                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
1233                                         printf("Verifiction of trust password to %s: should have failed (wrong password), instead: %s\n", 
1234                                                t->name, nt_errstr(nt_status));
1235                                         ret = False;
1236                                 }
1237                                 
1238                                 break;
1239                         }
1240                 }
1241         }
1242         talloc_free(trustdom_ctx);
1243         return ret;
1244 }
1245
1246
1247 /*
1248   try a netlogon DatabaseDeltas
1249 */
1250 static BOOL test_DatabaseDeltas(struct samsync_state *samsync_state, TALLOC_CTX *mem_ctx)
1251 {
1252         NTSTATUS status;
1253         TALLOC_CTX *loop_ctx;
1254         struct netr_DatabaseDeltas r;
1255         const uint32_t database_ids[] = {0, 1, 2}; 
1256         int i;
1257         BOOL ret = True;
1258
1259         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
1260         r.in.computername = TEST_MACHINE_NAME;
1261         r.in.preferredmaximumlength = (uint32_t)-1;
1262         ZERO_STRUCT(r.in.return_authenticator);
1263
1264         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1265                 r.in.database_id = database_ids[i];
1266                 r.in.sequence_num = samsync_state->seq_num[i];
1267
1268                 if (r.in.sequence_num == 0) continue;
1269
1270                 /* this shows that the bdc doesn't need to do a single call for
1271                  * each seqnumber, and the pdc doesn't need to know about old values
1272                  * -- metze
1273                  */
1274                 r.in.sequence_num -= 10;
1275
1276
1277                 printf("Testing DatabaseDeltas of id %d at %llu\n", 
1278                        r.in.database_id, r.in.sequence_num);
1279
1280                 do {
1281                         loop_ctx = talloc_named(mem_ctx, 0, "test_DatabaseDeltas loop context");
1282                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
1283
1284                         status = dcerpc_netr_DatabaseDeltas(samsync_state->p, loop_ctx, &r);
1285                         if (!NT_STATUS_IS_OK(status) &&
1286                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES) &&
1287                             !NT_STATUS_EQUAL(status, NT_STATUS_SYNCHRONIZATION_REQUIRED)) {
1288                                 printf("DatabaseDeltas - %s\n", nt_errstr(status));
1289                                 ret = False;
1290                         }
1291
1292                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
1293                                 printf("Credential chaining failed\n");
1294                         }
1295
1296                         r.in.sequence_num++;
1297                         talloc_free(loop_ctx);
1298                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1299         }
1300
1301         return ret;
1302 }
1303
1304
1305 /*
1306   try a netlogon DatabaseSync2
1307 */
1308 static BOOL test_DatabaseSync2(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, 
1309                                struct creds_CredentialState *creds)
1310 {
1311         NTSTATUS status;
1312         TALLOC_CTX *loop_ctx;
1313         struct netr_DatabaseSync2 r;
1314         const uint32_t database_ids[] = {0, 1, 2}; 
1315         int i;
1316         BOOL ret = True;
1317
1318         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(p));
1319         r.in.computername = TEST_MACHINE_NAME;
1320         r.in.preferredmaximumlength = (uint32_t)-1;
1321         ZERO_STRUCT(r.in.return_authenticator);
1322
1323         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1324                 r.in.sync_context = 0;
1325                 r.in.database_id = database_ids[i];
1326                 r.in.restart_state = 0;
1327
1328                 printf("Testing DatabaseSync2 of id %d\n", r.in.database_id);
1329
1330                 do {
1331                         loop_ctx = talloc_named(mem_ctx, 0, "test_DatabaseSync2 loop context");
1332                         creds_client_authenticator(creds, &r.in.credential);
1333
1334                         status = dcerpc_netr_DatabaseSync2(p, loop_ctx, &r);
1335                         if (!NT_STATUS_IS_OK(status) &&
1336                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
1337                                 printf("DatabaseSync2 - %s\n", nt_errstr(status));
1338                                 ret = False;
1339                         }
1340
1341                         if (!creds_client_check(creds, &r.out.return_authenticator.cred)) {
1342                                 printf("Credential chaining failed\n");
1343                         }
1344
1345                         r.in.sync_context = r.out.sync_context;
1346                         talloc_free(loop_ctx);
1347                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1348         }
1349
1350         return ret;
1351 }
1352
1353
1354
1355 BOOL torture_rpc_samsync(void)
1356 {
1357         NTSTATUS status;
1358         TALLOC_CTX *mem_ctx;
1359         BOOL ret = True;
1360         struct test_join *join_ctx;
1361         struct test_join *join_ctx2;
1362         struct test_join *user_ctx;
1363         const char *machine_password;
1364         const char *wksta_machine_password;
1365         const char *binding = lp_parm_string(-1, "torture", "binding");
1366         struct dcerpc_binding *b;
1367         struct dcerpc_binding *b_netlogon_wksta;
1368         struct samr_Connect c;
1369         struct samr_SetDomainInfo s;
1370         struct policy_handle *domain_policy;
1371
1372         struct lsa_ObjectAttribute attr;
1373         struct lsa_QosInfo qos;
1374         struct lsa_OpenPolicy2 r;
1375         struct cli_credentials *credentials;
1376         struct cli_credentials *credentials_wksta;
1377
1378         struct samsync_state *samsync_state;
1379
1380         char *test_machine_account;
1381
1382         char *test_wksta_machine_account;
1383
1384         mem_ctx = talloc_init("torture_rpc_netlogon");
1385         
1386         test_machine_account = talloc_asprintf(mem_ctx, "%s$", TEST_MACHINE_NAME);
1387         join_ctx = torture_create_testuser(test_machine_account, lp_workgroup(), ACB_SVRTRUST, 
1388                                            &machine_password);
1389         if (!join_ctx) {
1390                 talloc_free(mem_ctx);
1391                 printf("Failed to join as BDC\n");
1392                 return False;
1393         }
1394         
1395         test_wksta_machine_account = talloc_asprintf(mem_ctx, "%s$", TEST_WKSTA_MACHINE_NAME);
1396         join_ctx2 = torture_create_testuser(test_wksta_machine_account, lp_workgroup(), ACB_WSTRUST, 
1397                                             &wksta_machine_password);
1398         if (!join_ctx2) {
1399                 talloc_free(mem_ctx);
1400                 printf("Failed to join as member\n");
1401                 return False;
1402         }
1403         
1404         user_ctx = torture_create_testuser(TEST_USER_NAME,
1405                                            lp_workgroup(),
1406                                            ACB_NORMAL, NULL);
1407         if (!user_ctx) {
1408                 talloc_free(mem_ctx);
1409                 printf("Failed to create test account\n");
1410                 return False;
1411         }
1412
1413         samsync_state = talloc_zero(mem_ctx, struct samsync_state);
1414
1415         samsync_state->p_samr = torture_join_samr_pipe(join_ctx);
1416         samsync_state->connect_handle = talloc_zero(samsync_state, struct policy_handle);
1417         samsync_state->lsa_handle = talloc_zero(samsync_state, struct policy_handle);
1418         c.in.system_name = NULL;
1419         c.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
1420         c.out.connect_handle = samsync_state->connect_handle;
1421
1422         status = dcerpc_samr_Connect(samsync_state->p_samr, mem_ctx, &c);
1423         if (!NT_STATUS_IS_OK(status)) {
1424                 printf("samr_Connect failed\n");
1425                 ret = False;
1426                 goto failed;
1427         }
1428
1429         domain_policy = samsync_open_domain(mem_ctx, samsync_state, lp_workgroup(), NULL);
1430         if (!domain_policy) {
1431                 printf("samrsync_open_domain failed\n");
1432                 ret = False;
1433                 goto failed;
1434         }
1435         
1436         s.in.domain_handle = domain_policy;
1437         s.in.level = 4;
1438         s.in.info = talloc(mem_ctx, union samr_DomainInfo);
1439         
1440         s.in.info->info4.comment.string
1441                 = talloc_asprintf(mem_ctx, 
1442                                   "Tortured by Samba4: %s", 
1443                                   timestring(mem_ctx, time(NULL)));
1444         status = dcerpc_samr_SetDomainInfo(samsync_state->p_samr, mem_ctx, &s);
1445
1446         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, domain_policy)) {
1447                 ret = False;
1448                 goto failed;
1449         }
1450
1451         if (!NT_STATUS_IS_OK(status)) {
1452                 printf("SetDomainInfo level %u failed - %s\n", 
1453                        s.in.level, nt_errstr(status));
1454                 ret = False;
1455                 goto failed;
1456         }
1457         
1458
1459         status = torture_rpc_connection(samsync_state,
1460                                         &samsync_state->p_lsa, 
1461                                         DCERPC_LSARPC_NAME,
1462                                         DCERPC_LSARPC_UUID,
1463                                         DCERPC_LSARPC_VERSION);
1464
1465         if (!NT_STATUS_IS_OK(status)) {
1466                 ret = False;
1467                 goto failed;
1468         }
1469
1470         qos.len = 0;
1471         qos.impersonation_level = 2;
1472         qos.context_mode = 1;
1473         qos.effective_only = 0;
1474
1475         attr.len = 0;
1476         attr.root_dir = NULL;
1477         attr.object_name = NULL;
1478         attr.attributes = 0;
1479         attr.sec_desc = NULL;
1480         attr.sec_qos = &qos;
1481
1482         r.in.system_name = "\\";
1483         r.in.attr = &attr;
1484         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
1485         r.out.handle = samsync_state->lsa_handle;
1486
1487         status = dcerpc_lsa_OpenPolicy2(samsync_state->p_lsa, mem_ctx, &r);
1488         if (!NT_STATUS_IS_OK(status)) {
1489                 printf("OpenPolicy2 failed - %s\n", nt_errstr(status));
1490                 ret = False;
1491                 goto failed;
1492         }
1493
1494         status = dcerpc_parse_binding(mem_ctx, binding, &b);
1495         if (!NT_STATUS_IS_OK(status)) {
1496                 printf("Bad binding string %s\n", binding);
1497                 ret = False;
1498                 goto failed;
1499         }
1500
1501         b->flags &= ~DCERPC_AUTH_OPTIONS;
1502         b->flags |= DCERPC_SCHANNEL | DCERPC_SIGN;
1503
1504         credentials = cli_credentials_init(mem_ctx);
1505
1506         cli_credentials_set_workstation(credentials, TEST_MACHINE_NAME, CRED_SPECIFIED);
1507         cli_credentials_set_domain(credentials, lp_workgroup(), CRED_SPECIFIED);
1508         cli_credentials_set_username(credentials, test_machine_account, CRED_SPECIFIED);
1509         cli_credentials_set_password(credentials, machine_password, CRED_SPECIFIED);
1510         cli_credentials_set_secure_channel_type(credentials,
1511                                                 SEC_CHAN_BDC);
1512
1513         status = dcerpc_pipe_connect_b(samsync_state,
1514                                        &samsync_state->p, b, 
1515                                        DCERPC_NETLOGON_UUID,
1516                                        DCERPC_NETLOGON_VERSION,
1517                                        credentials, NULL);
1518         
1519         if (!NT_STATUS_IS_OK(status)) {
1520                 printf("Failed to connect to server as a BDC: %s\n", nt_errstr(status));
1521                 ret = False;
1522                 goto failed;
1523         }
1524
1525         status = dcerpc_schannel_creds(samsync_state->p->conn->security_state.generic_state, 
1526                                        samsync_state, &samsync_state->creds);
1527         if (!NT_STATUS_IS_OK(status)) {
1528                 ret = False;
1529         }
1530
1531
1532
1533         status = dcerpc_parse_binding(mem_ctx, binding, &b_netlogon_wksta);
1534         if (!NT_STATUS_IS_OK(status)) {
1535                 printf("Bad binding string %s\n", binding);
1536                 ret = False;
1537                 goto failed;
1538         }
1539
1540         b_netlogon_wksta->flags &= ~DCERPC_AUTH_OPTIONS;
1541         b_netlogon_wksta->flags |= DCERPC_SCHANNEL | DCERPC_SIGN;
1542
1543         credentials_wksta = cli_credentials_init(mem_ctx);
1544
1545         cli_credentials_set_workstation(credentials_wksta, TEST_WKSTA_MACHINE_NAME, CRED_SPECIFIED);
1546         cli_credentials_set_domain(credentials_wksta, lp_workgroup(), CRED_SPECIFIED);
1547         cli_credentials_set_username(credentials_wksta, test_wksta_machine_account, CRED_SPECIFIED);
1548         cli_credentials_set_password(credentials_wksta, wksta_machine_password, CRED_SPECIFIED);
1549         cli_credentials_set_secure_channel_type(credentials_wksta,
1550                                                 SEC_CHAN_WKSTA);
1551
1552         status = dcerpc_pipe_connect_b(samsync_state, 
1553                                        &samsync_state->p_netlogon_wksta, 
1554                                        b_netlogon_wksta, 
1555                                        DCERPC_NETLOGON_UUID,
1556                                        DCERPC_NETLOGON_VERSION,
1557                                        credentials_wksta, NULL);
1558
1559         if (!NT_STATUS_IS_OK(status)) {
1560                 printf("Failed to connect to server as a Workstation: %s\n", nt_errstr(status));
1561                 ret = False;
1562                 goto failed;
1563         }
1564
1565         status = dcerpc_schannel_creds(samsync_state->p_netlogon_wksta->conn->security_state.generic_state, 
1566                                        samsync_state, &samsync_state->creds_netlogon_wksta);
1567         if (!NT_STATUS_IS_OK(status)) {
1568                 printf("Failed to obtail schanel creds!\n");
1569                 ret = False;
1570         }
1571
1572         if (!test_DatabaseSync(samsync_state, mem_ctx)) {
1573                 printf("DatabaseSync failed\n");
1574                 ret = False;
1575         }
1576
1577         if (!test_DatabaseDeltas(samsync_state, mem_ctx)) {
1578                 printf("DatabaseDeltas failed\n");
1579                 ret = False;
1580         }
1581
1582         if (!test_DatabaseSync2(samsync_state->p, mem_ctx, samsync_state->creds)) {
1583                 printf("DatabaseSync2 failed\n");
1584                 ret = False;
1585         }
1586 failed:
1587
1588         torture_leave_domain(join_ctx);
1589         torture_leave_domain(join_ctx2);
1590         torture_leave_domain(user_ctx);
1591
1592         talloc_free(mem_ctx);
1593
1594         return ret;
1595 }