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