r5902: A rather large change...
[kamenim/samba.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 samr_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("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(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                         = samsync_open_domain(mem_ctx, samsync_state, samsync_state->domain_name[database_id], 
313                                               &dom_sid);
314         }
315         if (samsync_state->domain_handle[database_id]) {
316                 samsync_state->sid[database_id] = talloc_reference(samsync_state, dom_sid);
317         }
318
319         printf("\tsequence_nums[%d/%s]=%llu\n",
320                database_id, domain->domain_name.string,
321                samsync_state->seq_num[database_id]);
322
323         for (i=0;i<ARRAY_SIZE(levels);i++) {
324                 q[levels[i]].in.domain_handle = samsync_state->domain_handle[database_id];
325                 q[levels[i]].in.level = levels[i];
326
327                 nt_status = dcerpc_samr_QueryDomainInfo(samsync_state->p_samr, mem_ctx, &q[levels[i]]);
328
329                 if (!NT_STATUS_IS_OK(nt_status)) {
330                         printf("QueryDomainInfo level %u failed - %s\n", 
331                                q[levels[i]].in.level, nt_errstr(nt_status));
332                         return False;
333                 }
334         }
335
336         TEST_STRING_EQUAL(q[5].out.info->info5.domain_name, domain->domain_name);
337         
338         TEST_STRING_EQUAL(q[2].out.info->info2.comment, domain->comment);
339         TEST_STRING_EQUAL(q[4].out.info->info4.comment, domain->comment);
340         TEST_TIME_EQUAL(q[2].out.info->info2.force_logoff_time, domain->force_logoff_time);
341         TEST_TIME_EQUAL(q[3].out.info->info3.force_logoff_time, domain->force_logoff_time);
342
343         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_length, domain->min_password_length);
344         TEST_TIME_EQUAL(q[1].out.info->info1.password_history_length, domain->password_history_length);
345         TEST_TIME_EQUAL(q[1].out.info->info1.max_password_age, domain->max_password_age);
346         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_age, domain->min_password_age);
347
348         TEST_UINT64_EQUAL(q[8].out.info->info8.sequence_num, 
349                         domain->sequence_num);
350         TEST_TIME_EQUAL(q[8].out.info->info8.domain_create_time, 
351                         domain->domain_create_time);
352         TEST_TIME_EQUAL(q[13].out.info->info13.domain_create_time, 
353                         domain->domain_create_time);
354
355         TEST_SEC_DESC_EQUAL(domain->sdbuf, samr, samsync_state->domain_handle[database_id]);
356
357         return ret;
358 }
359
360 static BOOL samsync_handle_policy(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
361                            int database_id, struct netr_DELTA_ENUM *delta) 
362 {
363         struct netr_DELTA_POLICY *policy = delta->delta_union.policy;
364
365         samsync_state->seq_num[database_id] = 
366                 policy->sequence_num;
367         
368         if (!samsync_state->domain_name[SAM_DATABASE_DOMAIN]) {
369                 samsync_state->domain_name[SAM_DATABASE_DOMAIN] = 
370                         talloc_reference(samsync_state, policy->primary_domain_name.string);
371         } else {
372                 if (StrCaseCmp(samsync_state->domain_name[SAM_DATABASE_DOMAIN], policy->primary_domain_name.string) != 0) {
373                         printf("PRIMARY domain has name varies between DOMAIN and POLICY!: %s != %s\n", samsync_state->domain_name[SAM_DATABASE_DOMAIN], 
374                                policy->primary_domain_name.string);
375                         return False;
376                 }
377         }
378
379         if (!dom_sid_equal(samsync_state->sid[SAM_DATABASE_DOMAIN], policy->sid)) {
380                 printf("Domain SID from POLICY (%s) does not match domain sid from SAMR (%s)\n", 
381                        dom_sid_string(mem_ctx, policy->sid), dom_sid_string(mem_ctx, samsync_state->sid[SAM_DATABASE_DOMAIN]));
382                 return False;
383         }
384
385         printf("\tsequence_nums[%d/PRIVS]=%llu\n",
386                database_id, 
387                samsync_state->seq_num[database_id]);
388         return True;
389 }
390
391 static BOOL samsync_handle_user(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
392                                 int database_id, struct netr_DELTA_ENUM *delta) 
393 {
394         uint32_t rid = delta->delta_id_union.rid;
395         struct netr_DELTA_USER *user = delta->delta_union.user;
396         struct netr_SamInfo3 *info3;
397         struct samr_Password lm_hash;
398         struct samr_Password nt_hash;
399         struct samr_Password *lm_hash_p = NULL;
400         struct samr_Password *nt_hash_p = NULL;
401         const char *domain = samsync_state->domain_name[database_id];
402         const char *username = user->account_name.string;
403         NTSTATUS nt_status;
404         BOOL ret = True;
405
406         struct samr_OpenUser r;
407         struct samr_QueryUserInfo q;
408         struct policy_handle user_handle;
409
410         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
411                 printf("SamSync needs domain information before the users\n");
412                 return False;
413         }
414
415         r.in.domain_handle = samsync_state->domain_handle[database_id];
416         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
417         r.in.rid = rid;
418         r.out.user_handle = &user_handle;
419
420         nt_status = dcerpc_samr_OpenUser(samsync_state->p_samr, mem_ctx, &r);
421         if (!NT_STATUS_IS_OK(nt_status)) {
422                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
423                 return False;
424         }
425
426         q.in.user_handle = &user_handle;
427         q.in.level = 21;
428
429         TEST_SEC_DESC_EQUAL(user->sdbuf, samr, &user_handle);
430
431         nt_status = dcerpc_samr_QueryUserInfo(samsync_state->p_samr, mem_ctx, &q);
432         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &user_handle)) {
433                 printf("samr_handle_Close failed - %s\n", 
434                        nt_errstr(nt_status));
435                 return False;
436         }
437
438         if (!NT_STATUS_IS_OK(nt_status)) {
439                 printf("QueryUserInfo level %u failed - %s\n", 
440                        q.in.level, nt_errstr(nt_status));
441                 return False;
442         }
443
444         TEST_STRING_EQUAL(q.out.info->info21.account_name, user->account_name);
445         TEST_STRING_EQUAL(q.out.info->info21.full_name, user->full_name);
446         TEST_INT_EQUAL(q.out.info->info21.rid, user->rid);
447         TEST_INT_EQUAL(q.out.info->info21.primary_gid, user->primary_gid);
448         TEST_STRING_EQUAL(q.out.info->info21.home_directory, user->home_directory);
449         TEST_STRING_EQUAL(q.out.info->info21.home_drive, user->home_drive);
450         TEST_STRING_EQUAL(q.out.info->info21.logon_script, user->logon_script);
451         TEST_STRING_EQUAL(q.out.info->info21.description, user->description);
452         TEST_STRING_EQUAL(q.out.info->info21.workstations, user->workstations);
453
454         TEST_TIME_EQUAL(q.out.info->info21.last_logon, user->last_logon);
455         TEST_TIME_EQUAL(q.out.info->info21.last_logoff, user->last_logoff);
456
457
458         TEST_INT_EQUAL(q.out.info->info21.logon_hours.units_per_week, 
459                        user->logon_hours.units_per_week);
460         if (ret) {
461                 if (memcmp(q.out.info->info21.logon_hours.bits, user->logon_hours.bits, 
462                            q.out.info->info21.logon_hours.units_per_week/8) != 0) {
463                         printf("Logon hours mismatch\n");
464                         ret = False;
465                 }
466         }
467
468         TEST_INT_EQUAL(q.out.info->info21.bad_password_count,
469                        user->bad_password_count);
470         TEST_INT_EQUAL(q.out.info->info21.logon_count,
471                        user->logon_count);
472
473         TEST_TIME_EQUAL(q.out.info->info21.last_password_change,
474                        user->last_password_change);
475         TEST_TIME_EQUAL(q.out.info->info21.acct_expiry,
476                        user->acct_expiry);
477
478         TEST_INT_EQUAL(q.out.info->info21.acct_flags, user->acct_flags);
479         TEST_INT_EQUAL(q.out.info->info21.nt_password_set, user->nt_password_present);
480         TEST_INT_EQUAL(q.out.info->info21.lm_password_set, user->lm_password_present);
481         TEST_INT_EQUAL(q.out.info->info21.password_expired, user->password_expired);
482
483         TEST_STRING_EQUAL(q.out.info->info21.comment, user->comment);
484         TEST_STRING_EQUAL(q.out.info->info21.parameters, user->parameters);
485
486         TEST_INT_EQUAL(q.out.info->info21.country_code, user->country_code);
487         TEST_INT_EQUAL(q.out.info->info21.code_page, user->code_page);
488
489         TEST_STRING_EQUAL(q.out.info->info21.profile_path, user->profile_path);
490
491         if (user->lm_password_present) {
492                 sam_rid_crypt(rid, user->lmpassword.hash, lm_hash.hash, 0);
493                 lm_hash_p = &lm_hash;
494         }
495         if (user->nt_password_present) {
496                 sam_rid_crypt(rid, user->ntpassword.hash, nt_hash.hash, 0);
497                 nt_hash_p = &nt_hash;
498         }
499
500         if (user->user_private_info.SensitiveData) {
501                 DATA_BLOB data;
502                 struct netr_USER_KEYS keys;
503                 data.data = user->user_private_info.SensitiveData;
504                 data.length = user->user_private_info.DataLength;
505                 creds_arcfour_crypt(samsync_state->creds, data.data, data.length);
506                 nt_status = ndr_pull_struct_blob(&data, mem_ctx, &keys, (ndr_pull_flags_fn_t)ndr_pull_netr_USER_KEYS);
507                 if (NT_STATUS_IS_OK(nt_status)) {
508                         if (keys.keys.keys2.lmpassword.length == 16) {
509                                 sam_rid_crypt(rid, keys.keys.keys2.lmpassword.pwd.hash, lm_hash.hash, 0);
510                                 lm_hash_p = &lm_hash;
511                         }
512                         if (keys.keys.keys2.ntpassword.length == 16) {
513                                 sam_rid_crypt(rid, keys.keys.keys2.ntpassword.pwd.hash, nt_hash.hash, 0);
514                                 nt_hash_p = &nt_hash;
515                         }
516                 } else {
517                         printf("Failed to parse Sensitive Data for %s:\n", username);
518 #if 0
519                         dump_data(0, data.data, data.length);
520 #endif
521                         return False;
522                 }
523         }
524
525         nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, mem_ctx, samsync_state->creds_netlogon_wksta, 
526                                   domain,
527                                   username, 
528                                   TEST_WKSTA_MACHINE_NAME,
529                                   lm_hash_p,
530                                   nt_hash_p,
531                                   &info3);
532
533         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_DISABLED)) {
534                 if (user->acct_flags & ACB_DISABLED) {
535                         return True;
536                 }
537         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)) {
538                 if (user->acct_flags & ACB_WSTRUST) {
539                         return True;
540                 }
541         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT)) {
542                 if (user->acct_flags & ACB_SVRTRUST) {
543                         return True;
544                 }
545         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
546                 if (user->acct_flags & ACB_DOMTRUST) {
547                         return True;
548                 }
549         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
550                 if (user->acct_flags & ACB_DOMTRUST) {
551                         return True;
552                 }
553         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
554                 if (user->acct_flags & ACB_AUTOLOCK) {
555                         return True;
556                 }
557         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
558                 if (!lm_hash_p && !nt_hash_p) {
559                         return True;
560                 }
561         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_PASSWORD_MUST_CHANGE)) {
562                 /* We would need to know the server's current time to test this properly */
563                 return True;
564         } else if (NT_STATUS_IS_OK(nt_status)) {
565                 TEST_INT_EQUAL(user->rid, info3->base.rid);
566                 TEST_INT_EQUAL(user->primary_gid, info3->base.primary_gid);
567                 /* this is 0x0 from NT4 sp6 */
568                 if (info3->base.acct_flags) {
569                         TEST_INT_EQUAL(user->acct_flags, info3->base.acct_flags);
570                 }
571                 /* this is NULL from NT4 sp6 */
572                 if (info3->base.account_name.string) {
573                         TEST_STRING_EQUAL(user->account_name, info3->base.account_name);
574                 }
575                 TEST_STRING_EQUAL(user->full_name, info3->base.full_name);
576                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
577                 TEST_STRING_EQUAL(user->profile_path, info3->base.profile_path);
578                 TEST_STRING_EQUAL(user->home_directory, info3->base.home_directory);
579                 TEST_STRING_EQUAL(user->home_drive, info3->base.home_drive);
580                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
581
582
583                 TEST_TIME_EQUAL(user->last_logon, info3->base.last_logon);
584                 TEST_TIME_EQUAL(user->acct_expiry, info3->base.acct_expiry);
585                 TEST_TIME_EQUAL(user->last_password_change, info3->base.last_password_change);
586
587                 /* Does the concept of a logoff time ever really
588                  * exist? (not in any sensible way, according to the
589                  * doco I read -- abartlet) */
590
591                 /* This copes with the two different versions of 0 I see */
592                 /* with NT4 sp6 we have the || case */
593                 if (!((user->last_logoff == 0) 
594                       || (info3->base.last_logoff == 0x7fffffffffffffffLL))) {
595                         TEST_TIME_EQUAL(user->last_logoff, info3->base.last_logoff);
596                 }
597                 return ret;
598         } else {
599                 printf("Could not validate password for user %s\\%s: %s\n",
600                        domain, username, nt_errstr(nt_status));
601                 return False;
602         } 
603         return False;
604 }
605
606 static BOOL samsync_handle_alias(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
607                                  int database_id, struct netr_DELTA_ENUM *delta) 
608 {
609         uint32_t rid = delta->delta_id_union.rid;
610         struct netr_DELTA_ALIAS *alias = delta->delta_union.alias;
611         NTSTATUS nt_status;
612         BOOL ret = True;
613
614         struct samr_OpenAlias r;
615         struct samr_QueryAliasInfo q;
616         struct policy_handle alias_handle;
617
618         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
619                 printf("SamSync needs domain information before the users\n");
620                 return False;
621         }
622
623         r.in.domain_handle = samsync_state->domain_handle[database_id];
624         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
625         r.in.rid = rid;
626         r.out.alias_handle = &alias_handle;
627
628         nt_status = dcerpc_samr_OpenAlias(samsync_state->p_samr, mem_ctx, &r);
629         if (!NT_STATUS_IS_OK(nt_status)) {
630                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
631                 return False;
632         }
633
634         q.in.alias_handle = &alias_handle;
635         q.in.level = 1;
636
637         TEST_SEC_DESC_EQUAL(alias->sdbuf, samr, &alias_handle);
638
639         nt_status = dcerpc_samr_QueryAliasInfo(samsync_state->p_samr, mem_ctx, &q);
640         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &alias_handle)) {
641                 return False;
642         }
643
644         if (!NT_STATUS_IS_OK(nt_status)) {
645                 printf("QueryAliasInfo level %u failed - %s\n", 
646                        q.in.level, nt_errstr(nt_status));
647                 return False;
648         }
649
650         TEST_STRING_EQUAL(q.out.info->all.name, alias->alias_name);
651         TEST_STRING_EQUAL(q.out.info->all.description, alias->description);
652         return ret;
653 }
654
655 static BOOL samsync_handle_group(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
656                                  int database_id, struct netr_DELTA_ENUM *delta) 
657 {
658         uint32_t rid = delta->delta_id_union.rid;
659         struct netr_DELTA_GROUP *group = delta->delta_union.group;
660         NTSTATUS nt_status;
661         BOOL ret = True;
662
663         struct samr_OpenGroup r;
664         struct samr_QueryGroupInfo q;
665         struct policy_handle group_handle;
666
667         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
668                 printf("SamSync needs domain information before the users\n");
669                 return False;
670         }
671
672         r.in.domain_handle = samsync_state->domain_handle[database_id];
673         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
674         r.in.rid = rid;
675         r.out.group_handle = &group_handle;
676
677         nt_status = dcerpc_samr_OpenGroup(samsync_state->p_samr, mem_ctx, &r);
678         if (!NT_STATUS_IS_OK(nt_status)) {
679                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
680                 return False;
681         }
682
683         q.in.group_handle = &group_handle;
684         q.in.level = 1;
685
686         TEST_SEC_DESC_EQUAL(group->sdbuf, samr, &group_handle);
687
688         nt_status = dcerpc_samr_QueryGroupInfo(samsync_state->p_samr, mem_ctx, &q);
689         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &group_handle)) {
690                 return False;
691         }
692
693         if (!NT_STATUS_IS_OK(nt_status)) {
694                 printf("QueryGroupInfo level %u failed - %s\n", 
695                        q.in.level, nt_errstr(nt_status));
696                 return False;
697         }
698
699         TEST_STRING_EQUAL(q.out.info->all.name, group->group_name);
700         TEST_INT_EQUAL(q.out.info->all.attributes, group->attributes);
701         TEST_STRING_EQUAL(q.out.info->all.description, group->description);
702         return ret;
703 }
704
705 static BOOL samsync_handle_secret(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
706                                   int database_id, struct netr_DELTA_ENUM *delta) 
707 {
708         struct netr_DELTA_SECRET *secret = delta->delta_union.secret;
709         const char *name = delta->delta_id_union.name;
710         struct samsync_secret *new = talloc(samsync_state, struct samsync_secret);
711         struct samsync_secret *old = talloc(mem_ctx, struct samsync_secret);
712         struct lsa_QuerySecret q;
713         struct lsa_OpenSecret o;
714         struct policy_handle sec_handle;
715         struct lsa_DATA_BUF_PTR bufp1;
716         struct lsa_DATA_BUF_PTR bufp2;
717         NTTIME new_mtime;
718         NTTIME old_mtime;
719         BOOL ret = True;
720         DATA_BLOB lsa_blob1, lsa_blob_out, session_key;
721         NTSTATUS status;
722
723         creds_arcfour_crypt(samsync_state->creds, secret->current_cipher.cipher_data, 
724                             secret->current_cipher.maxlen); 
725
726         creds_arcfour_crypt(samsync_state->creds, secret->old_cipher.cipher_data, 
727                             secret->old_cipher.maxlen); 
728
729         new->name = talloc_reference(new, name);
730         new->secret = data_blob_talloc(new, secret->current_cipher.cipher_data, secret->current_cipher.maxlen);
731         new->mtime = secret->current_cipher_set_time;
732
733         DLIST_ADD(samsync_state->secrets, new);
734
735         old->name = talloc_reference(old, name);
736         old->secret = data_blob_const(secret->old_cipher.cipher_data, secret->old_cipher.maxlen);
737         old->mtime = secret->old_cipher_set_time;
738
739         o.in.handle = samsync_state->lsa_handle;
740         o.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
741         o.in.name.string = name;
742         o.out.sec_handle = &sec_handle;
743
744         status = dcerpc_lsa_OpenSecret(samsync_state->p_lsa, mem_ctx, &o);
745         if (!NT_STATUS_IS_OK(status)) {
746                 printf("OpenSecret failed - %s\n", nt_errstr(status));
747                 return False;
748         }
749
750 /*
751   We would like to do this, but it is NOT_SUPPORTED on win2k3
752   TEST_SEC_DESC_EQUAL(secret->sdbuf, lsa, &sec_handle);
753 */
754         status = dcerpc_fetch_session_key(samsync_state->p_lsa, &session_key);
755         if (!NT_STATUS_IS_OK(status)) {
756                 printf("dcerpc_fetch_session_key failed - %s\n", nt_errstr(status));
757                 return False;
758         }
759
760
761         ZERO_STRUCT(new_mtime);
762         ZERO_STRUCT(old_mtime);
763
764         /* fetch the secret back again */
765         q.in.sec_handle = &sec_handle;
766         q.in.new_val = &bufp1;
767         q.in.new_mtime = &new_mtime;
768         q.in.old_val = &bufp2;
769         q.in.old_mtime = &old_mtime;
770
771         bufp1.buf = NULL;
772         bufp2.buf = NULL;
773
774         status = dcerpc_lsa_QuerySecret(samsync_state->p_lsa, mem_ctx, &q);
775         if (NT_STATUS_EQUAL(NT_STATUS_ACCESS_DENIED, status)) {
776                 /* some things are just off limits */
777                 return True;
778         } else if (!NT_STATUS_IS_OK(status)) {
779                 printf("QuerySecret failed - %s\n", nt_errstr(status));
780                 return False;
781         }
782
783         if (q.out.old_val->buf == NULL) {
784                 /* probably just not available due to ACLs */
785         } else {
786                 lsa_blob1.data = q.out.old_val->buf->data;
787                 lsa_blob1.length = q.out.old_val->buf->length;
788
789                 status = sess_decrypt_blob(mem_ctx, &lsa_blob1, &session_key, &lsa_blob_out);
790                 if (!NT_STATUS_IS_OK(status)) {
791                         printf("Failed to decrypt secrets OLD blob: %s\n", nt_errstr(status));
792                         return False;
793                 }
794
795                 if (!q.out.old_mtime) {
796                         printf("OLD mtime not available on LSA for secret %s\n", old->name);
797                         ret = False;
798                 }
799                 if (old->mtime != *q.out.old_mtime) {
800                         printf("OLD mtime on secret %s does not match between SAMSYNC (%s) and LSA (%s)\n", 
801                                old->name, nt_time_string(mem_ctx, old->mtime), 
802                                nt_time_string(mem_ctx, *q.out.old_mtime)); 
803                         ret = False;
804                 }
805
806                 if (old->secret.length != lsa_blob_out.length) {
807                         printf("Returned secret %s doesn't match: %d != %d\n",
808                                old->name, old->secret.length, lsa_blob_out.length);
809                         ret = False;
810                 } else if (memcmp(lsa_blob_out.data, 
811                            old->secret.data, old->secret.length) != 0) {
812                         printf("Returned secret %s doesn't match: \n",
813                                old->name);
814                         DEBUG(1, ("SamSync Secret:\n"));
815                         dump_data(1, old->secret.data, old->secret.length);
816                         DEBUG(1, ("LSA Secret:\n"));
817                         dump_data(1, lsa_blob_out.data, lsa_blob_out.length);
818                         ret = False;
819                 }
820
821         }
822
823         if (q.out.new_val->buf == NULL) {
824                 /* probably just not available due to ACLs */
825         } else {
826                 lsa_blob1.data = q.out.new_val->buf->data;
827                 lsa_blob1.length = q.out.new_val->buf->length;
828
829                 status = sess_decrypt_blob(mem_ctx, &lsa_blob1, &session_key, &lsa_blob_out);
830                 if (!NT_STATUS_IS_OK(status)) {
831                         printf("Failed to decrypt secrets OLD blob\n");
832                         return False;
833                 }
834                 
835                 if (!q.out.new_mtime) {
836                         printf("NEW mtime not available on LSA for secret %s\n", new->name);
837                         ret = False;
838                 }
839                 if (new->mtime != *q.out.new_mtime) {
840                         printf("NEW mtime on secret %s does not match between SAMSYNC (%s) and LSA (%s)\n", 
841                                new->name, nt_time_string(mem_ctx, new->mtime), 
842                                nt_time_string(mem_ctx, *q.out.new_mtime)); 
843                         ret = False;
844                 }
845
846                 if (new->secret.length != lsa_blob_out.length) {
847                         printf("Returned secret %s doesn't match: %d != %d\n",
848                                new->name, new->secret.length, lsa_blob_out.length);
849                         ret = False;
850                 } else if (memcmp(lsa_blob_out.data, 
851                            new->secret.data, new->secret.length) != 0) {
852                         printf("Returned secret %s doesn't match: \n",
853                                new->name);
854                         DEBUG(1, ("SamSync Secret:\n"));
855                         dump_data(1, new->secret.data, new->secret.length);
856                         DEBUG(1, ("LSA Secret:\n"));
857                         dump_data(1, lsa_blob_out.data, lsa_blob_out.length);
858                         ret = False;
859                 }
860         }
861
862         return ret;
863 }
864
865 static BOOL samsync_handle_trusted_domain(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
866                                           int database_id, struct netr_DELTA_ENUM *delta) 
867 {
868         NTSTATUS status;
869         BOOL ret = True;
870         struct netr_DELTA_TRUSTED_DOMAIN *trusted_domain = delta->delta_union.trusted_domain;
871         struct dom_sid *dom_sid = delta->delta_id_union.sid;
872
873         struct samsync_trusted_domain *new = talloc(samsync_state, struct samsync_trusted_domain);
874         struct lsa_OpenTrustedDomain t;
875         struct policy_handle trustdom_handle;
876         struct lsa_QueryTrustedDomainInfo q;
877         union lsa_TrustedDomainInfo *info[9];
878         int levels [] = {1, 3, 8};
879         int i;
880
881         new->name = talloc_reference(new, trusted_domain->domain_name.string);
882         new->sid = talloc_reference(new, dom_sid);
883
884         t.in.handle = samsync_state->lsa_handle;
885         t.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
886         t.in.sid = dom_sid;
887         t.out.trustdom_handle = &trustdom_handle;
888
889         status = dcerpc_lsa_OpenTrustedDomain(samsync_state->p_lsa, mem_ctx, &t);
890         if (!NT_STATUS_IS_OK(status)) {
891                 printf("OpenTrustedDomain failed - %s\n", nt_errstr(status));
892                 return False;
893         }
894         
895         for (i=0; i< ARRAY_SIZE(levels); i++) {
896                 q.in.trustdom_handle = &trustdom_handle;
897                 q.in.level = levels[i];
898                 status = dcerpc_lsa_QueryTrustedDomainInfo(samsync_state->p_lsa, mem_ctx, &q);
899                 if (!NT_STATUS_IS_OK(status)) {
900                         if (q.in.level == 8 && NT_STATUS_EQUAL(status,NT_STATUS_INVALID_PARAMETER)) {
901                                 info[levels[i]] = NULL;
902                                 continue;
903                         }
904                         printf("QueryInfoTrustedDomain level %d failed - %s\n", 
905                                levels[i], nt_errstr(status));
906                         return False;
907                 }
908                 info[levels[i]]  = q.out.info;
909         }
910
911         if (info[8]) {
912                 TEST_SID_EQUAL(info[8]->full_info.info_ex.sid, dom_sid);
913                 TEST_STRING_EQUAL(info[8]->full_info.info_ex.netbios_name, trusted_domain->domain_name);
914         }
915         TEST_STRING_EQUAL(info[1]->name.netbios_name, trusted_domain->domain_name);
916         TEST_INT_EQUAL(info[3]->posix_offset.posix_offset, trusted_domain->posix_offset);
917 /*
918   We would like to do this, but it is NOT_SUPPORTED on win2k3
919         TEST_SEC_DESC_EQUAL(trusted_domain->sdbuf, lsa, &trustdom_handle);
920 */
921         DLIST_ADD(samsync_state->trusted_domains, new);
922
923         return ret;
924 }
925
926 static BOOL samsync_handle_account(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
927                                           int database_id, struct netr_DELTA_ENUM *delta) 
928 {
929         NTSTATUS status;
930         BOOL ret = True;
931         struct netr_DELTA_ACCOUNT *account = delta->delta_union.account;
932         struct dom_sid *dom_sid = delta->delta_id_union.sid;
933
934         struct lsa_OpenAccount a;
935         struct policy_handle acct_handle;
936         struct lsa_EnumPrivsAccount e;
937         struct lsa_LookupPrivName r;
938
939         int i, j;
940
941         BOOL *found_priv_in_lsa;
942
943         a.in.handle = samsync_state->lsa_handle;
944         a.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
945         a.in.sid = dom_sid;
946         a.out.acct_handle = &acct_handle;
947
948         status = dcerpc_lsa_OpenAccount(samsync_state->p_lsa, mem_ctx, &a);
949         if (!NT_STATUS_IS_OK(status)) {
950                 printf("OpenTrustedDomain failed - %s\n", nt_errstr(status));
951                 return False;
952         }
953
954         TEST_SEC_DESC_EQUAL(account->sdbuf, lsa, &acct_handle);
955
956         found_priv_in_lsa = talloc_zero_array(mem_ctx, BOOL, account->privilege_entries);
957
958         e.in.handle = &acct_handle;
959
960         status = dcerpc_lsa_EnumPrivsAccount(samsync_state->p_lsa, mem_ctx, &e);
961         if (!NT_STATUS_IS_OK(status)) {
962                 printf("EnumPrivsAccount failed - %s\n", nt_errstr(status));
963                 return False;
964         }
965
966         if ((account->privilege_entries && !e.out.privs)) {
967                 printf("Account %s has privilages in SamSync, but not LSA\n",
968                        dom_sid_string(mem_ctx, dom_sid));
969                 return False;
970         }
971
972         if (!account->privilege_entries && e.out.privs && e.out.privs->count) {
973                 printf("Account %s has privilages in LSA, but not SamSync\n",
974                        dom_sid_string(mem_ctx, dom_sid));
975                 return False;
976         }
977
978         TEST_INT_EQUAL(account->privilege_entries, e.out.privs->count);
979         
980         for (i=0;i< e.out.privs->count; i++) {
981                 r.in.handle = samsync_state->lsa_handle;
982                 r.in.luid = &e.out.privs->set[i].luid;
983                 
984                 status = dcerpc_lsa_LookupPrivName(samsync_state->p_lsa, mem_ctx, &r);
985                 if (!NT_STATUS_IS_OK(status)) {
986                         printf("\nLookupPrivName failed - %s\n", nt_errstr(status));
987                         return False;
988                 }
989                 
990                 if (!r.out.name) {
991                         printf("\nLookupPrivName failed to return a name\n");
992                         return False;
993                 }
994                 for (j=0;j<account->privilege_entries; j++) {
995                         if (strcmp(r.out.name->string, account->privilege_name[j].string) == 0) {
996                                 found_priv_in_lsa[j] = True;
997                                 break;
998                         }
999                 }
1000         }
1001         for (j=0;j<account->privilege_entries; j++) {
1002                 if (!found_priv_in_lsa[j]) {
1003                         printf("Privilage %s on account %s not found in LSA\n", account->privilege_name[j].string, 
1004                                dom_sid_string(mem_ctx, dom_sid));
1005                         ret = False;
1006                 }
1007         }
1008         return ret;
1009 }
1010
1011 /*
1012   try a netlogon DatabaseSync
1013 */
1014 static BOOL test_DatabaseSync(struct samsync_state *samsync_state,
1015                               TALLOC_CTX *mem_ctx)
1016 {
1017         NTSTATUS status;
1018         struct netr_DatabaseSync r;
1019         const uint32_t database_ids[] = {SAM_DATABASE_DOMAIN, SAM_DATABASE_BUILTIN, SAM_DATABASE_PRIVS}; 
1020         int i, d;
1021         BOOL ret = True;
1022         struct samsync_trusted_domain *t;
1023         struct samsync_secret *s;
1024         
1025         const char *domain, *username;
1026
1027         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
1028         r.in.computername = TEST_MACHINE_NAME;
1029         r.in.preferredmaximumlength = (uint32_t)-1;
1030         ZERO_STRUCT(r.in.return_authenticator);
1031
1032         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1033                 r.in.sync_context = 0;
1034                 r.in.database_id = database_ids[i];
1035
1036                 printf("Testing DatabaseSync of id %d\n", r.in.database_id);
1037
1038                 do {
1039                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
1040
1041                         status = dcerpc_netr_DatabaseSync(samsync_state->p, mem_ctx, &r);
1042                         if (!NT_STATUS_IS_OK(status) &&
1043                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
1044                                 printf("DatabaseSync - %s\n", nt_errstr(status));
1045                                 ret = False;
1046                                 break;
1047                         }
1048
1049                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
1050                                 printf("Credential chaining failed\n");
1051                         }
1052
1053                         r.in.sync_context = r.out.sync_context;
1054
1055                         for (d=0; d < r.out.delta_enum_array->num_deltas; d++) {
1056                                 switch (r.out.delta_enum_array->delta_enum[d].delta_type) {
1057                                 case NETR_DELTA_DOMAIN:
1058                                         if (!samsync_handle_domain(mem_ctx, samsync_state, 
1059                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1060                                                 printf("Failed to handle DELTA_DOMAIN\n");
1061                                                 ret = False;
1062                                         }
1063                                         break;
1064                                 case NETR_DELTA_GROUP:
1065                                         if (!samsync_handle_group(mem_ctx, samsync_state, 
1066                                                                   r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1067                                                 printf("Failed to handle DELTA_USER\n");
1068                                                 ret = False;
1069                                         }
1070                                         break;
1071                                 case NETR_DELTA_USER:
1072                                         if (!samsync_handle_user(mem_ctx, samsync_state, 
1073                                                                  r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1074                                                 printf("Failed to handle DELTA_USER\n");
1075                                                 ret = False;
1076                                         }
1077                                         break;
1078                                 case NETR_DELTA_ALIAS:
1079                                         if (!samsync_handle_alias(mem_ctx, samsync_state, 
1080                                                                   r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1081                                                 printf("Failed to handle DELTA_ALIAS\n");
1082                                                 ret = False;
1083                                         }
1084                                         break;
1085                                 case NETR_DELTA_POLICY:
1086                                         if (!samsync_handle_policy(mem_ctx, samsync_state, 
1087                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1088                                                 printf("Failed to handle DELTA_POLICY\n");
1089                                                 ret = False;
1090                                         }
1091                                         break;
1092                                 case NETR_DELTA_TRUSTED_DOMAIN:
1093                                         if (!samsync_handle_trusted_domain(mem_ctx, samsync_state, 
1094                                                                            r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1095                                                 printf("Failed to handle DELTA_TRUSTED_DOMAIN\n");
1096                                                 ret = False;
1097                                         }
1098                                         break;
1099                                 case NETR_DELTA_ACCOUNT:
1100                                         if (!samsync_handle_account(mem_ctx, samsync_state, 
1101                                                                     r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1102                                                 printf("Failed to handle DELTA_ACCOUNT\n");
1103                                                 ret = False;
1104                                         }
1105                                         break;
1106                                 case NETR_DELTA_SECRET:
1107                                         if (!samsync_handle_secret(mem_ctx, samsync_state, 
1108                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d])) {
1109                                                 printf("Failed to handle DELTA_SECRET\n");
1110                                                 ret = False;
1111                                         }
1112                                         break;
1113                                 }
1114                         }
1115                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1116                 
1117         }
1118
1119         domain = samsync_state->domain_name[SAM_DATABASE_DOMAIN];
1120         if (!domain) {
1121                 printf("Never got a DOMAIN object in samsync!\n");
1122                 return False;
1123         }
1124         
1125         username = talloc_asprintf(mem_ctx, "%s$", domain);
1126         for (t=samsync_state->trusted_domains; t; t=t->next) {
1127                 char *secret_name = talloc_asprintf(mem_ctx, "G$$%s", t->name);
1128                 for (s=samsync_state->secrets; s; s=s->next) {
1129                         if (StrCaseCmp(s->name, secret_name) == 0) {
1130                                 NTSTATUS nt_status;
1131                                 struct samr_Password nt_hash;
1132                                 mdfour(nt_hash.hash, s->secret.data, s->secret.length);
1133                                 
1134                                 printf("Checking password for %s\\%s\n", t->name, username);
1135                                 nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, mem_ctx, samsync_state->creds_netlogon_wksta, 
1136                                                           t->name,
1137                                                           username, 
1138                                                           TEST_WKSTA_MACHINE_NAME,
1139                                                           NULL, 
1140                                                           &nt_hash,
1141                                                           NULL);
1142                                 if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_LOGON_SERVERS)) {
1143                                         printf("Verifiction of trust password to %s failed: %s (the trusted domain is not available)\n", 
1144                                                t->name, nt_errstr(nt_status));
1145                                         
1146                                         break;
1147                                 }
1148                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
1149                                         printf("Verifiction of trust password to %s: should have failed (nologon interdomain trust account), instead: %s\n", 
1150                                                t->name, nt_errstr(nt_status));
1151                                         ret = False;
1152                                 }
1153                                 
1154                                 /* break it */
1155                                 nt_hash.hash[0]++;
1156                                 nt_status = test_SamLogon(samsync_state->p_netlogon_wksta, mem_ctx, samsync_state->creds_netlogon_wksta, 
1157                                                           t->name,
1158                                                           username, 
1159                                                           TEST_WKSTA_MACHINE_NAME,
1160                                                           NULL,
1161                                                           &nt_hash,
1162                                                           NULL);
1163                                 
1164                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
1165                                         printf("Verifiction of trust password to %s: should have failed (wrong password), instead: %s\n", 
1166                                                t->name, nt_errstr(nt_status));
1167                                         ret = False;
1168                                 }
1169                                 
1170                                 break;
1171                         }
1172                 }
1173         }
1174         return ret;
1175 }
1176
1177
1178 /*
1179   try a netlogon DatabaseDeltas
1180 */
1181 static BOOL test_DatabaseDeltas(struct samsync_state *samsync_state, TALLOC_CTX *mem_ctx)
1182 {
1183         NTSTATUS status;
1184         struct netr_DatabaseDeltas r;
1185         const uint32_t database_ids[] = {0, 1, 2}; 
1186         int i;
1187         BOOL ret = True;
1188
1189         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
1190         r.in.computername = TEST_MACHINE_NAME;
1191         r.in.preferredmaximumlength = (uint32_t)-1;
1192         ZERO_STRUCT(r.in.return_authenticator);
1193
1194         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1195                 r.in.database_id = database_ids[i];
1196                 r.in.sequence_num = samsync_state->seq_num[i];
1197
1198                 if (r.in.sequence_num == 0) continue;
1199
1200                 r.in.sequence_num -= 1;
1201
1202
1203                 printf("Testing DatabaseDeltas of id %d at %llu\n", 
1204                        r.in.database_id, r.in.sequence_num);
1205
1206                 do {
1207                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
1208
1209                         status = dcerpc_netr_DatabaseDeltas(samsync_state->p, mem_ctx, &r);
1210                         if (!NT_STATUS_IS_OK(status) &&
1211                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES) &&
1212                             !NT_STATUS_EQUAL(status, NT_STATUS_SYNCHRONIZATION_REQUIRED)) {
1213                                 printf("DatabaseDeltas - %s\n", nt_errstr(status));
1214                                 ret = False;
1215                                 break;
1216                         }
1217
1218                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
1219                                 printf("Credential chaining failed\n");
1220                         }
1221
1222                         r.in.sequence_num++;
1223                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1224         }
1225
1226         return ret;
1227 }
1228
1229
1230 /*
1231   try a netlogon DatabaseSync2
1232 */
1233 static BOOL test_DatabaseSync2(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, 
1234                                struct creds_CredentialState *creds)
1235 {
1236         NTSTATUS status;
1237         struct netr_DatabaseSync2 r;
1238         const uint32_t database_ids[] = {0, 1, 2}; 
1239         int i;
1240         BOOL ret = True;
1241
1242         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(p));
1243         r.in.computername = TEST_MACHINE_NAME;
1244         r.in.preferredmaximumlength = (uint32_t)-1;
1245         ZERO_STRUCT(r.in.return_authenticator);
1246
1247         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
1248                 r.in.sync_context = 0;
1249                 r.in.database_id = database_ids[i];
1250                 r.in.restart_state = 0;
1251
1252                 printf("Testing DatabaseSync2 of id %d\n", r.in.database_id);
1253
1254                 do {
1255                         creds_client_authenticator(creds, &r.in.credential);
1256
1257                         status = dcerpc_netr_DatabaseSync2(p, mem_ctx, &r);
1258                         if (!NT_STATUS_IS_OK(status) &&
1259                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
1260                                 printf("DatabaseSync2 - %s\n", nt_errstr(status));
1261                                 ret = False;
1262                                 break;
1263                         }
1264
1265                         if (!creds_client_check(creds, &r.out.return_authenticator.cred)) {
1266                                 printf("Credential chaining failed\n");
1267                         }
1268
1269                         r.in.sync_context = r.out.sync_context;
1270                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
1271         }
1272
1273         return ret;
1274 }
1275
1276
1277
1278 BOOL torture_rpc_samsync(void)
1279 {
1280         NTSTATUS status;
1281         TALLOC_CTX *mem_ctx;
1282         BOOL ret = True;
1283         struct test_join *join_ctx;
1284         struct test_join *join_ctx2;
1285         struct test_join *user_ctx;
1286         const char *machine_password;
1287         const char *wksta_machine_password;
1288         const char *binding = lp_parm_string(-1, "torture", "binding");
1289         struct dcerpc_binding *b;
1290         struct dcerpc_binding *b_netlogon_wksta;
1291         struct samr_Connect c;
1292         struct samr_SetDomainInfo s;
1293         struct policy_handle *domain_policy;
1294
1295         struct lsa_ObjectAttribute attr;
1296         struct lsa_QosInfo qos;
1297         struct lsa_OpenPolicy2 r;
1298
1299         struct samsync_state *samsync_state;
1300
1301         char *test_machine_account;
1302
1303         char *test_wksta_machine_account;
1304
1305         mem_ctx = talloc_init("torture_rpc_netlogon");
1306
1307         test_machine_account = talloc_asprintf(mem_ctx, "%s$", TEST_MACHINE_NAME);
1308         join_ctx = torture_create_testuser(test_machine_account, lp_workgroup(), ACB_SVRTRUST, 
1309                                            &machine_password);
1310         if (!join_ctx) {
1311                 printf("Failed to join as BDC\n");
1312                 return False;
1313         }
1314         
1315         test_wksta_machine_account = talloc_asprintf(mem_ctx, "%s$", TEST_WKSTA_MACHINE_NAME);
1316         join_ctx2 = torture_create_testuser(test_wksta_machine_account, lp_workgroup(), ACB_WSTRUST, 
1317                                             &wksta_machine_password);
1318         if (!join_ctx2) {
1319                 printf("Failed to join as member\n");
1320                 return False;
1321         }
1322         
1323         user_ctx = torture_create_testuser(TEST_USER_NAME,
1324                                            lp_workgroup(),
1325                                            ACB_NORMAL, NULL);
1326         if (!user_ctx) {
1327                 printf("Failed to create test account\n");
1328                 return False;
1329         }
1330
1331         samsync_state = talloc_zero(mem_ctx, struct samsync_state);
1332
1333         samsync_state->p_samr = torture_join_samr_pipe(join_ctx);
1334         samsync_state->connect_handle = talloc_zero(samsync_state, struct policy_handle);
1335         samsync_state->lsa_handle = talloc_zero(samsync_state, struct policy_handle);
1336         c.in.system_name = NULL;
1337         c.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
1338         c.out.connect_handle = samsync_state->connect_handle;
1339
1340         status = dcerpc_samr_Connect(samsync_state->p_samr, mem_ctx, &c);
1341         if (!NT_STATUS_IS_OK(status)) {
1342                 printf("samr_Connect failed\n");
1343                 ret = False;
1344                 goto failed;
1345         }
1346
1347         domain_policy = samsync_open_domain(mem_ctx, samsync_state, lp_workgroup(), NULL);
1348         if (!domain_policy) {
1349                 printf("samrsync_open_domain failed\n");
1350                 ret = False;
1351                 goto failed;
1352         }
1353         
1354         s.in.domain_handle = domain_policy;
1355         s.in.level = 4;
1356         s.in.info = talloc(mem_ctx, union samr_DomainInfo);
1357         
1358         s.in.info->info4.comment.string
1359                 = talloc_asprintf(mem_ctx, 
1360                                   "Tortured by Samba4: %s", 
1361                                   timestring(mem_ctx, time(NULL)));
1362         status = dcerpc_samr_SetDomainInfo(samsync_state->p_samr, mem_ctx, &s);
1363
1364         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, domain_policy)) {
1365                 ret = False;
1366                 goto failed;
1367         }
1368
1369         if (!NT_STATUS_IS_OK(status)) {
1370                 printf("SetDomainInfo level %u failed - %s\n", 
1371                        s.in.level, nt_errstr(status));
1372                 ret = False;
1373                 goto failed;
1374         }
1375         
1376
1377         status = torture_rpc_connection(&samsync_state->p_lsa, 
1378                                         DCERPC_LSARPC_NAME,
1379                                         DCERPC_LSARPC_UUID,
1380                                         DCERPC_LSARPC_VERSION);
1381
1382         if (!NT_STATUS_IS_OK(status)) {
1383                 ret = False;
1384                 goto failed;
1385         }
1386
1387         qos.len = 0;
1388         qos.impersonation_level = 2;
1389         qos.context_mode = 1;
1390         qos.effective_only = 0;
1391
1392         attr.len = 0;
1393         attr.root_dir = NULL;
1394         attr.object_name = NULL;
1395         attr.attributes = 0;
1396         attr.sec_desc = NULL;
1397         attr.sec_qos = &qos;
1398
1399         r.in.system_name = "\\";
1400         r.in.attr = &attr;
1401         r.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
1402         r.out.handle = samsync_state->lsa_handle;
1403
1404         status = dcerpc_lsa_OpenPolicy2(samsync_state->p_lsa, mem_ctx, &r);
1405         if (!NT_STATUS_IS_OK(status)) {
1406                 printf("OpenPolicy2 failed - %s\n", nt_errstr(status));
1407                 ret = False;
1408                 goto failed;
1409         }
1410
1411         status = dcerpc_parse_binding(mem_ctx, binding, &b);
1412         if (!NT_STATUS_IS_OK(status)) {
1413                 printf("Bad binding string %s\n", binding);
1414                 ret = False;
1415                 goto failed;
1416         }
1417
1418         b->flags &= ~DCERPC_AUTH_OPTIONS;
1419         b->flags |= DCERPC_SCHANNEL_BDC | DCERPC_SIGN;
1420
1421         status = dcerpc_pipe_connect_b(&samsync_state->p, b, 
1422                                        DCERPC_NETLOGON_UUID,
1423                                        DCERPC_NETLOGON_VERSION,
1424                                        TEST_MACHINE_NAME,
1425                                        lp_workgroup(), 
1426                                        test_machine_account,
1427                                        machine_password);
1428
1429         if (!NT_STATUS_IS_OK(status)) {
1430                 printf("Failed to connect to server as a BDC: %s\n", nt_errstr(status));
1431                 ret = False;
1432                 goto failed;
1433         }
1434
1435         status = dcerpc_schannel_creds(samsync_state->p->conn->security_state.generic_state, mem_ctx, &samsync_state->creds);
1436         if (!NT_STATUS_IS_OK(status)) {
1437                 ret = False;
1438         }
1439
1440
1441
1442         status = dcerpc_parse_binding(mem_ctx, binding, &b_netlogon_wksta);
1443         if (!NT_STATUS_IS_OK(status)) {
1444                 printf("Bad binding string %s\n", binding);
1445                 ret = False;
1446                 goto failed;
1447         }
1448
1449         b_netlogon_wksta->flags &= ~DCERPC_AUTH_OPTIONS;
1450         b_netlogon_wksta->flags |= DCERPC_SCHANNEL_WORKSTATION | DCERPC_SIGN;
1451
1452         status = dcerpc_pipe_connect_b(&samsync_state->p_netlogon_wksta, 
1453                                        b_netlogon_wksta, 
1454                                        DCERPC_NETLOGON_UUID,
1455                                        DCERPC_NETLOGON_VERSION,
1456                                        TEST_WKSTA_MACHINE_NAME,
1457                                        lp_workgroup(), 
1458                                        test_wksta_machine_account,
1459                                        wksta_machine_password);
1460
1461         if (!NT_STATUS_IS_OK(status)) {
1462                 printf("Failed to connect to server as a Workstation: %s\n", nt_errstr(status));
1463                 ret = False;
1464                 goto failed;
1465         }
1466
1467         status = dcerpc_schannel_creds(samsync_state->p_netlogon_wksta->conn->security_state.generic_state, 
1468                                        mem_ctx, &samsync_state->creds_netlogon_wksta);
1469         if (!NT_STATUS_IS_OK(status)) {
1470                 printf("Failed to obtail schanel creds!\n");
1471                 ret = False;
1472         }
1473
1474         if (!test_DatabaseSync(samsync_state, mem_ctx)) {
1475                 printf("DatabaseSync failed\n");
1476                 ret = False;
1477         }
1478
1479         if (!test_DatabaseDeltas(samsync_state, mem_ctx)) {
1480                 printf("DatabaseDeltas failed\n");
1481                 ret = False;
1482         }
1483
1484         if (!test_DatabaseSync2(samsync_state->p, mem_ctx, samsync_state->creds)) {
1485                 printf("DatabaseSync2 failed\n");
1486                 ret = False;
1487         }
1488 failed:
1489         torture_rpc_close(samsync_state->p);
1490
1491         torture_leave_domain(join_ctx);
1492         torture_leave_domain(join_ctx2);
1493         torture_leave_domain(user_ctx);
1494
1495         talloc_free(mem_ctx);
1496
1497         return ret;
1498 }