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