777e5f36ebd74c36a9784c86affcdd53aee645d1
[samba.git] / source4 / torture / rpc / samsync.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    test suite for netlogon rpc operations
5
6    Copyright (C) Andrew Tridgell 2003
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2003-2004
8    Copyright (C) Tim Potter      2003
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "librpc/gen_ndr/ndr_netlogon.h"
27 #include "auth/auth.h"
28 #include "dlinklist.h"
29 #include "lib/crypto/crypto.h"
30 #include "system/time.h"
31
32 #define TEST_MACHINE_NAME "samsynctest"
33
34 /*
35   try a netlogon SamLogon
36 */
37 static NTSTATUS test_SamLogon(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, 
38                               struct creds_CredentialState *creds, 
39                               const char *domain, const char *username,
40                               struct samr_Password *lm_hash, 
41                               struct samr_Password *nt_hash, 
42                               struct netr_SamInfo3 **info3)
43 {
44         NTSTATUS status;
45         struct netr_LogonSamLogon r;
46         struct netr_Authenticator auth, auth2;
47         struct netr_NetworkInfo ninfo;
48
49         ninfo.identity_info.domain_name.string = domain;
50         ninfo.identity_info.parameter_control = 0;
51         ninfo.identity_info.logon_id_low = 0;
52         ninfo.identity_info.logon_id_high = 0;
53         ninfo.identity_info.account_name.string = username;
54         ninfo.identity_info.workstation.string = TEST_MACHINE_NAME;
55         generate_random_buffer(ninfo.challenge, 
56                                sizeof(ninfo.challenge));
57         if (nt_hash) {
58                 ninfo.nt.length = 24;
59                 ninfo.nt.data = talloc(mem_ctx, 24);
60                 SMBOWFencrypt(nt_hash->hash, ninfo.challenge, ninfo.nt.data);
61         } else {
62                 ninfo.nt.length = 0;
63                 ninfo.nt.data = NULL;
64         }
65         
66         if (lm_hash) {
67                 ninfo.lm.length = 24;
68                 ninfo.lm.data = talloc(mem_ctx, 24);
69                 SMBOWFencrypt(lm_hash->hash, ninfo.challenge, ninfo.lm.data);
70         } else {
71                 ninfo.lm.length = 0;
72                 ninfo.lm.data = NULL;
73         }
74
75         r.in.server_name = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(p));
76         r.in.workstation = TEST_MACHINE_NAME;
77         r.in.credential = &auth;
78         r.in.return_authenticator = &auth2;
79         r.in.logon_level = 2;
80         r.in.logon.network = &ninfo;
81
82         ZERO_STRUCT(auth2);
83         creds_client_authenticator(creds, &auth);
84         
85         r.in.validation_level = 3;
86         
87         status = dcerpc_netr_LogonSamLogon(p, mem_ctx, &r);
88
89         if (!creds_client_check(creds, &r.out.return_authenticator->cred)) {
90                 printf("Credential chaining failed\n");
91         }
92
93         if (info3) {
94                 *info3 = r.out.validation.sam3;
95         }
96
97         return status;
98 }
99
100 struct samsync_state {
101 /* we remember the sequence numbers so we can easily do a DatabaseDelta */
102         uint64_t seq_num[3];
103         char *domain_name[2];
104         struct samsync_secret *secrets;
105         struct samsync_trusted_domain *trusted_domains;
106         struct creds_CredentialState *creds;
107         struct policy_handle *connect_handle;
108         struct policy_handle *domain_handle[2];
109         struct dom_sid *sid[2];
110         struct dcerpc_pipe *p;
111         struct dcerpc_pipe *p_samr;
112         struct dcerpc_pipe *p_lsa;
113         struct policy_handle *lsa_handle;
114 };
115
116 struct samsync_secret {
117         struct samsync_secret *prev, *next;
118         DATA_BLOB secret;
119         char *name;
120 };
121
122 struct samsync_trusted_domain {
123         struct samsync_trusted_domain *prev, *next;
124         struct dom_sid *sid;
125         char *name;
126 };
127
128 static struct policy_handle *samsync_open_domain(TALLOC_CTX *mem_ctx, 
129                                                  struct samsync_state *samsync_state, 
130                                                  const char *domain, 
131                                                  struct dom_sid **sid)
132 {
133         struct samr_String name;
134         struct samr_OpenDomain o;
135         struct samr_LookupDomain l;
136         struct policy_handle *domain_handle = talloc_p(mem_ctx, struct policy_handle);
137         NTSTATUS nt_status;
138
139         name.string = domain;
140         l.in.connect_handle = samsync_state->connect_handle;
141         l.in.domain = &name;
142
143         nt_status = dcerpc_samr_LookupDomain(samsync_state->p_samr, mem_ctx, &l);
144         if (!NT_STATUS_IS_OK(nt_status)) {
145                 printf("LookupDomain failed - %s\n", nt_errstr(nt_status));
146                 return NULL;
147         }
148
149         o.in.connect_handle = samsync_state->connect_handle;
150         o.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
151         o.in.sid = l.out.sid;
152         o.out.domain_handle = domain_handle;
153         
154         if (sid) {
155                 *sid = l.out.sid;
156         }
157
158         nt_status = dcerpc_samr_OpenDomain(samsync_state->p_samr, mem_ctx, &o);
159         if (!NT_STATUS_IS_OK(nt_status)) {
160                 printf("OpenDomain failed - %s\n", nt_errstr(nt_status));
161                 return NULL;
162         }
163
164         return domain_handle;
165 }
166
167
168 #define TEST_UINT64_EQUAL(i1, i2) do {\
169         if (i1 != i2) {\
170               printf("uint64 mismatch: " #i1 ": 0x%08x%08x (%lld) != " #i2 ": 0x%08x%08x (%lld)\n", \
171                      (uint32_t)(i1 >> 32), (uint32_t)(i1 & 0xFFFFFFFF), i1, \
172                      (uint32_t)(i2 >> 32), (uint32_t)(i2 & 0xFFFFFFFF), i2);\
173               ret = False;\
174         } \
175 } while (0)
176 #define TEST_INT_EQUAL(i1, i2) do {\
177         if (i1 != i2) {\
178               printf("integer mismatch: " #i1 ":%d != " #i2 ": %d\n", \
179                      i1, i2);\
180               ret = False;\
181         } \
182 } while (0)
183 #define TEST_TIME_EQUAL(t1, t2) do {\
184         if (t1 != t2) {\
185               printf("NTTIME mismatch: " #t1 ":%s != " #t2 ": %s\n", \
186                      nt_time_string(mem_ctx, t1),  nt_time_string(mem_ctx, t2));\
187               ret = False;\
188         } \
189 } while (0)
190 #define TEST_STRING_EQUAL(s1, s2) do {\
191         if (!((!s1.string || s1.string[0]=='\0') && (!s2.string || s2.string[0]=='\0')) \
192             && strcmp_safe(s1.string, s2.string) != 0) {\
193               printf("string mismatch: " #s1 ":%s != " #s2 ": %s\n", \
194                      s1.string, s2.string);\
195               ret = False;\
196         } \
197 } while (0)
198
199 static BOOL samsync_handle_domain(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
200                            int database_id, struct netr_DELTA_ENUM *delta) 
201 {
202         struct netr_DELTA_DOMAIN *domain = delta->delta_union.domain;
203         struct dom_sid *dom_sid;
204         struct samr_QueryDomainInfo q[14]; /* q[0] will be unused simple for clarity */
205         uint16_t levels[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13};
206         NTSTATUS nt_status;
207         int i;
208         BOOL ret = True;
209         
210         samsync_state->seq_num[database_id] = 
211                 domain->sequence_num;
212         switch (database_id) {
213         case SAM_DATABASE_DOMAIN:
214                 break;
215         case SAM_DATABASE_BUILTIN:
216                 if (StrCaseCmp("BUILTIN", domain->domain_name.string) != 0) {
217                         printf("BUILTIN domain has different name: %s\n", domain->domain_name.string);
218                 }
219                 break;
220         case SAM_DATABASE_PRIVS:
221                 printf("DOMAIN entry on privs DB!\n");
222                 return False;
223                 break;
224         }
225         
226         if (!samsync_state->domain_name[database_id]) {
227                 samsync_state->domain_name[database_id] = 
228                         talloc_reference(samsync_state, domain->domain_name.string);
229         } else {
230                 if (StrCaseCmp(samsync_state->domain_name[database_id], domain->domain_name.string) != 0) {
231                         printf("Domain has name varies!: %s != %s\n", samsync_state->domain_name[database_id], 
232                                domain->domain_name.string);
233                         return False;
234                 }
235         }
236
237         if (!samsync_state->domain_handle[database_id]) {
238                 samsync_state->domain_handle[database_id]
239                         = samsync_open_domain(mem_ctx, samsync_state, samsync_state->domain_name[database_id], 
240                                               &dom_sid);
241         }
242         if (samsync_state->domain_handle[database_id]) {
243                 samsync_state->sid[database_id] = talloc_reference(samsync_state, dom_sid);
244         }
245
246         printf("\tsequence_nums[%d/%s]=%llu\n",
247                database_id, domain->domain_name.string,
248                samsync_state->seq_num[database_id]);
249
250         for (i=0;i<ARRAY_SIZE(levels);i++) {
251                 q[levels[i]].in.domain_handle = samsync_state->domain_handle[database_id];
252                 q[levels[i]].in.level = levels[i];
253
254                 nt_status = dcerpc_samr_QueryDomainInfo(samsync_state->p_samr, mem_ctx, &q[levels[i]]);
255
256                 if (!NT_STATUS_IS_OK(nt_status)) {
257                         printf("QueryDomainInfo level %u failed - %s\n", 
258                                q[levels[i]].in.level, nt_errstr(nt_status));
259                         return False;
260                 }
261         }
262
263         TEST_STRING_EQUAL(q[5].out.info->info5.domain_name, domain->domain_name);
264         
265         TEST_STRING_EQUAL(q[2].out.info->info2.comment, domain->comment);
266         TEST_STRING_EQUAL(q[4].out.info->info4.comment, domain->comment);
267         TEST_TIME_EQUAL(q[2].out.info->info2.force_logoff_time, domain->force_logoff_time);
268         TEST_TIME_EQUAL(q[3].out.info->info3.force_logoff_time, domain->force_logoff_time);
269
270         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_length, domain->min_password_length);
271         TEST_TIME_EQUAL(q[1].out.info->info1.password_history_length, domain->password_history_length);
272         TEST_TIME_EQUAL(q[1].out.info->info1.max_password_age, domain->max_password_age);
273         TEST_TIME_EQUAL(q[1].out.info->info1.min_password_age, domain->min_password_age);
274
275         TEST_UINT64_EQUAL(q[8].out.info->info8.sequence_num, 
276                         domain->sequence_num);
277         TEST_TIME_EQUAL(q[8].out.info->info8.domain_create_time, 
278                         domain->domain_create_time);
279         TEST_TIME_EQUAL(q[13].out.info->info13.domain_create_time, 
280                         domain->domain_create_time);
281
282         return ret;
283 }
284
285 static BOOL samsync_handle_policy(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
286                            int database_id, struct netr_DELTA_ENUM *delta) 
287 {
288         struct netr_DELTA_POLICY *policy = delta->delta_union.policy;
289
290         samsync_state->seq_num[database_id] = 
291                 policy->sequence_num;
292         
293         if (!samsync_state->domain_name[SAM_DATABASE_DOMAIN]) {
294                 samsync_state->domain_name[SAM_DATABASE_DOMAIN] = 
295                         talloc_reference(samsync_state, policy->primary_domain_name.string);
296         } else {
297                 if (StrCaseCmp(samsync_state->domain_name[SAM_DATABASE_DOMAIN], policy->primary_domain_name.string) != 0) {
298                         printf("PRIMARY domain has name varies between DOMAIN and POLICY!: %s != %s\n", samsync_state->domain_name[SAM_DATABASE_DOMAIN], 
299                                policy->primary_domain_name.string);
300                         return False;
301                 }
302         }
303
304         if (!sid_equal(samsync_state->sid[SAM_DATABASE_DOMAIN], policy->sid)) {
305                 printf("Domain SID from POLICY (%s) does not match domain sid from SAMR (%s)\n", 
306                        dom_sid_string(mem_ctx, policy->sid), dom_sid_string(mem_ctx, samsync_state->sid[SAM_DATABASE_DOMAIN]));
307                 return False;
308         }
309
310         printf("\tsequence_nums[%d/PRIVS]=%llu\n",
311                database_id, 
312                samsync_state->seq_num[database_id]);
313         return True;
314 }
315
316 static BOOL samsync_handle_user(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
317                                 int database_id, struct netr_DELTA_ENUM *delta) 
318 {
319         uint32 rid = delta->delta_id_union.rid;
320         struct netr_DELTA_USER *user = delta->delta_union.user;
321         struct netr_SamInfo3 *info3;
322         struct samr_Password lm_hash;
323         struct samr_Password nt_hash;
324         struct samr_Password *lm_hash_p = NULL;
325         struct samr_Password *nt_hash_p = NULL;
326         const char *domain = samsync_state->domain_name[database_id];
327         const char *username = user->account_name.string;
328         NTSTATUS nt_status;
329         BOOL ret = True;
330
331         struct samr_OpenUser r;
332         struct samr_QueryUserInfo q;
333         struct policy_handle user_handle;
334
335         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
336                 printf("SamSync needs domain information before the users\n");
337                 return False;
338         }
339
340         r.in.domain_handle = samsync_state->domain_handle[database_id];
341         r.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
342         r.in.rid = rid;
343         r.out.user_handle = &user_handle;
344
345         nt_status = dcerpc_samr_OpenUser(samsync_state->p_samr, mem_ctx, &r);
346         if (!NT_STATUS_IS_OK(nt_status)) {
347                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
348                 return False;
349         }
350
351         q.in.user_handle = &user_handle;
352         q.in.level = 21;
353
354         nt_status = dcerpc_samr_QueryUserInfo(samsync_state->p_samr, mem_ctx, &q);
355         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &user_handle)) {
356                 return False;
357         }
358
359         if (!NT_STATUS_IS_OK(nt_status)) {
360                 printf("QueryUserInfo level %u failed - %s\n", 
361                        q.in.level, nt_errstr(nt_status));
362                 return False;
363         }
364
365         TEST_STRING_EQUAL(q.out.info->info21.account_name, user->account_name);
366         TEST_STRING_EQUAL(q.out.info->info21.full_name, user->full_name);
367         TEST_INT_EQUAL(q.out.info->info21.rid, user->rid);
368         TEST_INT_EQUAL(q.out.info->info21.primary_gid, user->primary_gid);
369         TEST_STRING_EQUAL(q.out.info->info21.home_directory, user->home_directory);
370         TEST_STRING_EQUAL(q.out.info->info21.home_drive, user->home_drive);
371         TEST_STRING_EQUAL(q.out.info->info21.logon_script, user->logon_script);
372         TEST_STRING_EQUAL(q.out.info->info21.description, user->description);
373         TEST_STRING_EQUAL(q.out.info->info21.workstations, user->workstations);
374
375         TEST_TIME_EQUAL(q.out.info->info21.last_logon, user->last_logon);
376         TEST_TIME_EQUAL(q.out.info->info21.last_logoff, user->last_logoff);
377
378
379         TEST_INT_EQUAL(q.out.info->info21.logon_hours.units_per_week, 
380                        user->logon_hours.units_per_week);
381         if (ret) {
382                 if (memcmp(q.out.info->info21.logon_hours.bitmap, user->logon_hours.bitmap, 
383                            q.out.info->info21.logon_hours.units_per_week/8) != 0) {
384                         printf("Logon hours mismatch\n");
385                         ret = False;
386                 }
387         }
388
389         TEST_INT_EQUAL(q.out.info->info21.bad_password_count,
390                        user->bad_password_count);
391         TEST_INT_EQUAL(q.out.info->info21.logon_count,
392                        user->logon_count);
393
394         TEST_TIME_EQUAL(q.out.info->info21.last_password_change,
395                        user->last_password_change);
396         TEST_TIME_EQUAL(q.out.info->info21.acct_expiry,
397                        user->acct_expiry);
398
399         TEST_INT_EQUAL(q.out.info->info21.logon_hours.units_per_week, 
400                        user->logon_hours.units_per_week);
401
402         TEST_INT_EQUAL(q.out.info->info21.acct_flags, user->acct_flags);
403         TEST_INT_EQUAL(q.out.info->info21.nt_password_set, user->nt_password_present);
404         TEST_INT_EQUAL(q.out.info->info21.lm_password_set, user->lm_password_present);
405         TEST_INT_EQUAL(q.out.info->info21.password_expired, user->password_expired);
406
407         TEST_STRING_EQUAL(q.out.info->info21.comment, user->comment);
408         TEST_STRING_EQUAL(q.out.info->info21.parameters, user->parameters);
409
410         TEST_INT_EQUAL(q.out.info->info21.country_code, user->country_code);
411         TEST_INT_EQUAL(q.out.info->info21.code_page, user->code_page);
412
413         TEST_STRING_EQUAL(q.out.info->info21.profile_path, user->profile_path);
414
415         if (user->lm_password_present) {
416                 sam_rid_crypt(rid, user->lmpassword.hash, lm_hash.hash, 0);
417                 lm_hash_p = &lm_hash;
418         }
419         if (user->nt_password_present) {
420                 sam_rid_crypt(rid, user->ntpassword.hash, nt_hash.hash, 0);
421                 nt_hash_p = &nt_hash;
422         }
423
424         if (user->user_private_info.SensitiveData) {
425                 DATA_BLOB data;
426                 struct netr_USER_KEYS keys;
427                 data.data = user->user_private_info.SensitiveData;
428                 data.length = user->user_private_info.DataLength;
429                 creds_arcfour_crypt(samsync_state->creds, data.data, data.length);
430 #if 0           
431                 printf("Sensitive Data for %s:\n", username);
432                 dump_data(0, data.data, data.length);
433 #endif
434                 nt_status = ndr_pull_struct_blob(&data, mem_ctx, &keys, (ndr_pull_flags_fn_t)ndr_pull_netr_USER_KEYS);
435                 if (NT_STATUS_IS_OK(nt_status)) {
436                         if (keys.keys.keys2.lmpassword.length == 16) {
437                                 sam_rid_crypt(rid, keys.keys.keys2.lmpassword.pwd.hash, lm_hash.hash, 0);
438                                 lm_hash_p = &lm_hash;
439                         }
440                         if (keys.keys.keys2.ntpassword.length == 16) {
441                                 sam_rid_crypt(rid, keys.keys.keys2.ntpassword.pwd.hash, nt_hash.hash, 0);
442                                 nt_hash_p = &nt_hash;
443                         }
444                 }
445                 
446         }
447
448         nt_status = test_SamLogon(samsync_state->p, mem_ctx, samsync_state->creds, 
449                                   domain,
450                                   username, 
451                                   lm_hash_p,
452                                   nt_hash_p,
453                                   &info3);
454
455         if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_DISABLED)) {
456                 if (user->acct_flags & ACB_DISABLED) {
457                         return True;
458                 }
459         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)) {
460                 if (user->acct_flags & ACB_WSTRUST) {
461                         return True;
462                 }
463         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT)) {
464                 if (user->acct_flags & ACB_SVRTRUST) {
465                         return True;
466                 }
467         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
468                 if (user->acct_flags & ACB_DOMTRUST) {
469                         return True;
470                 }
471         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
472                 if (user->acct_flags & ACB_DOMTRUST) {
473                         return True;
474                 }
475         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_ACCOUNT_LOCKED_OUT)) {
476                 if (user->acct_flags & ACB_AUTOLOCK) {
477                         return True;
478                 }
479         } else if (NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
480                 if (!lm_hash_p && !nt_hash_p) {
481                         return True;
482                 }
483         } else if (NT_STATUS_IS_OK(nt_status)) {
484                 TEST_INT_EQUAL(user->rid, info3->base.rid);
485                 TEST_INT_EQUAL(user->primary_gid, info3->base.primary_gid);
486                 TEST_INT_EQUAL(user->acct_flags, info3->base.acct_flags);
487                 TEST_STRING_EQUAL(user->account_name, info3->base.account_name);
488                 TEST_STRING_EQUAL(user->full_name, info3->base.full_name);
489                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
490                 TEST_STRING_EQUAL(user->profile_path, info3->base.profile_path);
491                 TEST_STRING_EQUAL(user->home_directory, info3->base.home_directory);
492                 TEST_STRING_EQUAL(user->home_drive, info3->base.home_drive);
493                 TEST_STRING_EQUAL(user->logon_script, info3->base.logon_script);
494
495
496                 TEST_TIME_EQUAL(user->last_logon, info3->base.last_logon);
497                 TEST_TIME_EQUAL(user->acct_expiry, info3->base.acct_expiry);
498                 TEST_TIME_EQUAL(user->last_password_change, info3->base.last_password_change);
499
500                 /* Does the concept of a logoff time ever really
501                  * exist? (not in any sensible way, according to the
502                  * doco I read -- abartlet) */
503
504                 /* This copes with the two different versions of 0 I see */
505                 if (!((user->last_logoff == 0) 
506                       && (info3->base.last_logoff == 0x7fffffffffffffffLL))) {
507                         TEST_TIME_EQUAL(user->last_logoff, info3->base.last_logoff);
508                 }
509                 return ret;
510         } else {
511                 printf("Could not validate password for user %s\\%s: %s\n",
512                        domain, username, nt_errstr(nt_status));
513                 return False;
514         } 
515         return False;
516 }
517
518 static BOOL samsync_handle_alias(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
519                                  int database_id, struct netr_DELTA_ENUM *delta) 
520 {
521         uint32 rid = delta->delta_id_union.rid;
522         struct netr_DELTA_ALIAS *alias = delta->delta_union.alias;
523         NTSTATUS nt_status;
524         BOOL ret = True;
525
526         struct samr_OpenAlias r;
527         struct samr_QueryAliasInfo q;
528         struct policy_handle alias_handle;
529
530         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
531                 printf("SamSync needs domain information before the users\n");
532                 return False;
533         }
534
535         r.in.domain_handle = samsync_state->domain_handle[database_id];
536         r.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
537         r.in.rid = rid;
538         r.out.alias_handle = &alias_handle;
539
540         nt_status = dcerpc_samr_OpenAlias(samsync_state->p_samr, mem_ctx, &r);
541         if (!NT_STATUS_IS_OK(nt_status)) {
542                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
543                 return False;
544         }
545
546         q.in.alias_handle = &alias_handle;
547         q.in.level = 1;
548
549         nt_status = dcerpc_samr_QueryAliasInfo(samsync_state->p_samr, mem_ctx, &q);
550         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &alias_handle)) {
551                 return False;
552         }
553
554         if (!NT_STATUS_IS_OK(nt_status)) {
555                 printf("QueryAliasInfo level %u failed - %s\n", 
556                        q.in.level, nt_errstr(nt_status));
557                 return False;
558         }
559
560         TEST_STRING_EQUAL(q.out.info->all.name, alias->alias_name);
561         TEST_STRING_EQUAL(q.out.info->all.description, alias->description);
562         return False;
563 }
564
565 static BOOL samsync_handle_group(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
566                                  int database_id, struct netr_DELTA_ENUM *delta) 
567 {
568         uint32 rid = delta->delta_id_union.rid;
569         struct netr_DELTA_GROUP *group = delta->delta_union.group;
570         NTSTATUS nt_status;
571         BOOL ret = True;
572
573         struct samr_OpenGroup r;
574         struct samr_QueryGroupInfo q;
575         struct policy_handle group_handle;
576
577         if (!samsync_state->domain_name || !samsync_state->domain_handle[database_id]) {
578                 printf("SamSync needs domain information before the users\n");
579                 return False;
580         }
581
582         r.in.domain_handle = samsync_state->domain_handle[database_id];
583         r.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
584         r.in.rid = rid;
585         r.out.group_handle = &group_handle;
586
587         nt_status = dcerpc_samr_OpenGroup(samsync_state->p_samr, mem_ctx, &r);
588         if (!NT_STATUS_IS_OK(nt_status)) {
589                 printf("OpenUser(%u) failed - %s\n", rid, nt_errstr(nt_status));
590                 return False;
591         }
592
593         q.in.group_handle = &group_handle;
594         q.in.level = 1;
595
596         nt_status = dcerpc_samr_QueryGroupInfo(samsync_state->p_samr, mem_ctx, &q);
597         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, &group_handle)) {
598                 return False;
599         }
600
601         if (!NT_STATUS_IS_OK(nt_status)) {
602                 printf("QueryGroupInfo level %u failed - %s\n", 
603                        q.in.level, nt_errstr(nt_status));
604                 return False;
605         }
606
607         TEST_STRING_EQUAL(q.out.info->all.name, group->group_name);
608         TEST_INT_EQUAL(q.out.info->all.attributes, group->attributes);
609         TEST_STRING_EQUAL(q.out.info->all.description, group->description);
610         return False;
611 }
612
613 static BOOL samsync_handle_secret(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
614                                   int database_id, struct netr_DELTA_ENUM *delta) 
615 {
616         struct netr_DELTA_SECRET *secret = delta->delta_union.secret;
617         const char *name = delta->delta_id_union.name;
618         struct samsync_secret *new = talloc_p(samsync_state, struct samsync_secret);
619         struct lsa_QuerySecret q;
620         struct lsa_OpenSecret o;
621         struct policy_handle sec_handle;
622         struct lsa_DATA_BUF_PTR bufp1;
623         NTTIME new_mtime;
624         BOOL ret = True;
625         DATA_BLOB lsa_blob1, lsa_blob_out, session_key;
626         NTSTATUS status;
627
628         creds_arcfour_crypt(samsync_state->creds, secret->current_cipher.cipher_data, 
629                             secret->current_cipher.maxlen); 
630
631         creds_arcfour_crypt(samsync_state->creds, secret->old_cipher.cipher_data, 
632                             secret->old_cipher.maxlen); 
633
634         new->name = talloc_reference(new, name);
635         new->secret = data_blob_talloc(new, secret->current_cipher.cipher_data, secret->current_cipher.maxlen);
636
637         DLIST_ADD(samsync_state->secrets, new);
638
639         o.in.handle = samsync_state->lsa_handle;
640         o.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
641         o.in.name.name = name;
642         o.out.sec_handle = &sec_handle;
643
644         status = dcerpc_lsa_OpenSecret(samsync_state->p_lsa, mem_ctx, &o);
645         if (!NT_STATUS_IS_OK(status)) {
646                 printf("OpenSecret failed - %s\n", nt_errstr(status));
647                 ret = False;
648         }
649
650         status = dcerpc_fetch_session_key(samsync_state->p_lsa, &session_key);
651         if (!NT_STATUS_IS_OK(status)) {
652                 printf("dcerpc_fetch_session_key failed - %s\n", nt_errstr(status));
653                 ret = False;
654         }
655
656
657         ZERO_STRUCT(new_mtime);
658
659         /* fetch the secret back again */
660         q.in.handle = &sec_handle;
661         q.in.new_val = &bufp1;
662         q.in.new_mtime = &new_mtime;
663         q.in.old_val = NULL;
664         q.in.old_mtime = NULL;
665
666         bufp1.buf = NULL;
667
668         status = dcerpc_lsa_QuerySecret(samsync_state->p_lsa, mem_ctx, &q);
669         if (!NT_STATUS_IS_OK(status)) {
670                 printf("QuerySecret failed - %s\n", nt_errstr(status));
671                 ret = False;
672         }
673
674         if (q.out.new_val->buf == NULL) {
675                 /* probably just not available due to ACLs */
676         } else {
677                 lsa_blob1.data = q.out.new_val->buf->data;
678                 lsa_blob1.length = q.out.new_val->buf->length;
679
680                 lsa_blob_out = sess_decrypt_blob(mem_ctx, &lsa_blob1, &session_key);
681                 
682                 if (new->secret.length != lsa_blob_out.length) {
683                         printf("Returned secret %s doesn't match: %d != %d\n",
684                                new->name, new->secret.length, lsa_blob_out.length);
685                         ret = False;
686                 }
687
688                 if (memcmp(lsa_blob_out.data, 
689                            new->secret.data, new->secret.length) != 0) {
690                         printf("Returned secret %s doesn't match: \n",
691                                new->name);
692                         DEBUG(1, ("SamSync Secret:\n"));
693                         dump_data(1, new->secret.data, new->secret.length);
694                         DEBUG(1, ("LSA Secret:\n"));
695                         dump_data(1, lsa_blob_out.data, lsa_blob_out.length);
696                         ret = False;
697                 }
698         }
699
700         return ret;
701 }
702
703 static BOOL samsync_handle_trusted_domain(TALLOC_CTX *mem_ctx, struct samsync_state *samsync_state,
704                                           int database_id, struct netr_DELTA_ENUM *delta) 
705 {
706         struct netr_DELTA_TRUSTED_DOMAIN *trusted_domain = delta->delta_union.trusted_domain;
707         struct dom_sid *dom_sid = delta->delta_id_union.sid;
708
709         struct samsync_trusted_domain *new = talloc_p(samsync_state, struct samsync_trusted_domain);
710         new->name = talloc_reference(new, trusted_domain->domain_name.string);
711         new->sid = talloc_reference(new, dom_sid);
712
713         DLIST_ADD(samsync_state->trusted_domains, new);
714
715         return True;
716 }
717
718 /*
719   try a netlogon DatabaseSync
720 */
721 static BOOL test_DatabaseSync(struct samsync_state *samsync_state,
722                               TALLOC_CTX *mem_ctx)
723 {
724         NTSTATUS status;
725         struct netr_DatabaseSync r;
726         const uint32_t database_ids[] = {SAM_DATABASE_DOMAIN, SAM_DATABASE_BUILTIN, SAM_DATABASE_PRIVS}; 
727         int i, d;
728         BOOL ret = True;
729         struct samsync_trusted_domain *t;
730         struct samsync_secret *s;
731         
732         const char *domain, *username;
733
734         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
735         r.in.computername = TEST_MACHINE_NAME;
736         r.in.preferredmaximumlength = (uint32_t)-1;
737         ZERO_STRUCT(r.in.return_authenticator);
738
739         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
740                 r.in.sync_context = 0;
741                 r.in.database_id = database_ids[i];
742
743                 printf("Testing DatabaseSync of id %d\n", r.in.database_id);
744
745                 do {
746                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
747
748                         status = dcerpc_netr_DatabaseSync(samsync_state->p, mem_ctx, &r);
749                         if (!NT_STATUS_IS_OK(status) &&
750                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
751                                 printf("DatabaseSync - %s\n", nt_errstr(status));
752                                 ret = False;
753                                 break;
754                         }
755
756                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
757                                 printf("Credential chaining failed\n");
758                         }
759
760                         r.in.sync_context = r.out.sync_context;
761
762                         for (d=0; d < r.out.delta_enum_array->num_deltas; d++) {
763                                 switch (r.out.delta_enum_array->delta_enum[d].delta_type) {
764                                 case NETR_DELTA_DOMAIN:
765                                         ret &= samsync_handle_domain(mem_ctx, samsync_state, 
766                                                                      r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
767                                         break;
768                                 case NETR_DELTA_USER:
769                                         ret &= samsync_handle_user(mem_ctx, samsync_state, 
770                                                                    r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
771                                         break;
772                                 case NETR_DELTA_GROUP:
773                                         ret &= samsync_handle_group(mem_ctx, samsync_state, 
774                                                                     r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
775                                         break;
776                                 case NETR_DELTA_ALIAS:
777                                         ret &= samsync_handle_alias(mem_ctx, samsync_state, 
778                                                                     r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
779                                         break;
780                                 case NETR_DELTA_TRUSTED_DOMAIN:
781                                         ret &= samsync_handle_trusted_domain(mem_ctx, samsync_state, 
782                                                                              r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
783                                         break;
784                                 case NETR_DELTA_SECRET:
785                                         ret &= samsync_handle_secret(mem_ctx, samsync_state, 
786                                                                      r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
787                                         break;
788                                 case NETR_DELTA_POLICY:
789                                         ret &= samsync_handle_policy(mem_ctx, samsync_state, 
790                                                                      r.in.database_id, &r.out.delta_enum_array->delta_enum[d]);
791                                         break;
792                                 }
793                         }
794                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
795                 
796         }
797
798         domain = samsync_state->domain_name[SAM_DATABASE_DOMAIN];
799         if (!domain) {
800                 printf("Never got a DOMAIN object in samsync!\n");
801                 return False;
802         }
803         
804         username = talloc_asprintf(mem_ctx, "%s$", domain);
805         for (t=samsync_state->trusted_domains; t; t=t->next) {
806                 char *secret_name = talloc_asprintf(mem_ctx, "G$$%s", t->name);
807                 for (s=samsync_state->secrets; s; s=s->next) {
808                         if (StrCaseCmp(s->name, secret_name) == 0) {
809                                 NTSTATUS nt_status;
810                                 struct samr_Password nt_hash;
811                                 mdfour(nt_hash.hash, s->secret.data, s->secret.length);
812                                 
813                                 printf("Checking password for %s\\%s\n", t->name, username);
814                                 nt_status = test_SamLogon(samsync_state->p, mem_ctx, samsync_state->creds, 
815                                                           t->name,
816                                                           username, 
817                                                           NULL, 
818                                                           &nt_hash,
819                                                           NULL);
820                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT)) {
821                                         printf("Verifiction of trust password to %s: should have failed (nologon interdomain trust account), instead: %s\n", 
822                                                t->name, nt_errstr(nt_status));
823                                         ret = False;
824                                 }
825                                 
826                                 /* break it */
827                                 nt_hash.hash[0]++;
828                                 nt_status = test_SamLogon(samsync_state->p, mem_ctx, samsync_state->creds, 
829                                                           t->name,
830                                                           username, 
831                                                           NULL,
832                                                           &nt_hash,
833                                                           NULL);
834                                 
835                                 if (!NT_STATUS_EQUAL(nt_status, NT_STATUS_WRONG_PASSWORD)) {
836                                         printf("Verifiction of trust password to %s: should have failed (wrong password), instead: %s\n", 
837                                                t->name, nt_errstr(nt_status));
838                                         ret = False;
839                                         ret = False;
840                                 }
841                                 
842                                 break;
843                         }
844                 }
845         }
846         return ret;
847 }
848
849
850 /*
851   try a netlogon DatabaseDeltas
852 */
853 static BOOL test_DatabaseDeltas(struct samsync_state *samsync_state, TALLOC_CTX *mem_ctx)
854 {
855         NTSTATUS status;
856         struct netr_DatabaseDeltas r;
857         const uint32_t database_ids[] = {0, 1, 2}; 
858         int i;
859         BOOL ret = True;
860
861         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(samsync_state->p));
862         r.in.computername = TEST_MACHINE_NAME;
863         r.in.preferredmaximumlength = (uint32_t)-1;
864         ZERO_STRUCT(r.in.return_authenticator);
865
866         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
867                 r.in.database_id = database_ids[i];
868                 r.in.sequence_num = samsync_state->seq_num[i];
869
870                 if (r.in.sequence_num == 0) continue;
871
872                 r.in.sequence_num -= 1;
873
874
875                 printf("Testing DatabaseDeltas of id %d at %llu\n", 
876                        r.in.database_id, r.in.sequence_num);
877
878                 do {
879                         creds_client_authenticator(samsync_state->creds, &r.in.credential);
880
881                         status = dcerpc_netr_DatabaseDeltas(samsync_state->p, mem_ctx, &r);
882                         if (!NT_STATUS_IS_OK(status) &&
883                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
884                                 printf("DatabaseDeltas - %s\n", nt_errstr(status));
885                                 ret = False;
886                                 break;
887                         }
888
889                         if (!creds_client_check(samsync_state->creds, &r.out.return_authenticator.cred)) {
890                                 printf("Credential chaining failed\n");
891                         }
892
893                         r.in.sequence_num++;
894                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
895         }
896
897         return ret;
898 }
899
900
901 /*
902   try a netlogon DatabaseSync2
903 */
904 static BOOL test_DatabaseSync2(struct dcerpc_pipe *p, TALLOC_CTX *mem_ctx, 
905                                struct creds_CredentialState *creds)
906 {
907         NTSTATUS status;
908         struct netr_DatabaseSync2 r;
909         const uint32_t database_ids[] = {0, 1, 2}; 
910         int i;
911         BOOL ret = True;
912
913         r.in.logon_server = talloc_asprintf(mem_ctx, "\\\\%s", dcerpc_server_name(p));
914         r.in.computername = TEST_MACHINE_NAME;
915         r.in.preferredmaximumlength = (uint32_t)-1;
916         ZERO_STRUCT(r.in.return_authenticator);
917
918         for (i=0;i<ARRAY_SIZE(database_ids);i++) {
919                 r.in.sync_context = 0;
920                 r.in.database_id = database_ids[i];
921                 r.in.restart_state = 0;
922
923                 printf("Testing DatabaseSync2 of id %d\n", r.in.database_id);
924
925                 do {
926                         creds_client_authenticator(creds, &r.in.credential);
927
928                         status = dcerpc_netr_DatabaseSync2(p, mem_ctx, &r);
929                         if (!NT_STATUS_IS_OK(status) &&
930                             !NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
931                                 printf("DatabaseSync2 - %s\n", nt_errstr(status));
932                                 ret = False;
933                                 break;
934                         }
935
936                         if (!creds_client_check(creds, &r.out.return_authenticator.cred)) {
937                                 printf("Credential chaining failed\n");
938                         }
939
940                         r.in.sync_context = r.out.sync_context;
941                 } while (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES));
942         }
943
944         return ret;
945 }
946
947
948
949 BOOL torture_rpc_samsync(void)
950 {
951         NTSTATUS status;
952         TALLOC_CTX *mem_ctx;
953         BOOL ret = True;
954         struct test_join *join_ctx;
955         const char *machine_password;
956         const char *binding = lp_parm_string(-1, "torture", "binding");
957         struct dcerpc_binding b;
958         struct samr_Connect c;
959         struct samr_SetDomainInfo s;
960         struct policy_handle *domain_policy;
961
962         struct lsa_ObjectAttribute attr;
963         struct lsa_QosInfo qos;
964         struct lsa_OpenPolicy2 r;
965
966         struct samsync_state *samsync_state;
967
968         mem_ctx = talloc_init("torture_rpc_netlogon");
969
970         join_ctx = torture_join_domain(TEST_MACHINE_NAME, lp_workgroup(), ACB_SVRTRUST, 
971                                        &machine_password);
972         if (!join_ctx) {
973                 printf("Failed to join as BDC\n");
974                 return False;
975         }
976         
977         samsync_state = talloc_zero_p(mem_ctx, struct samsync_state);
978
979         samsync_state->p_samr = torture_join_samr_pipe(join_ctx);
980         samsync_state->connect_handle = talloc_zero_p(samsync_state, struct policy_handle);
981         samsync_state->lsa_handle = talloc_zero_p(samsync_state, struct policy_handle);
982         c.in.system_name = NULL;
983         c.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
984         c.out.connect_handle = samsync_state->connect_handle;
985
986         status = dcerpc_samr_Connect(samsync_state->p_samr, mem_ctx, &c);
987         if (!NT_STATUS_IS_OK(status)) {
988                 printf("samr_Connect failed\n");
989                 ret = False;
990                 goto failed;
991         }
992
993         domain_policy = samsync_open_domain(mem_ctx, samsync_state, lp_workgroup(), NULL);
994         if (!domain_policy) {
995                 printf("samrsync_open_domain failed\n");
996                 ret = False;
997                 goto failed;
998         }
999         
1000         s.in.domain_handle = domain_policy;
1001         s.in.level = 4;
1002         s.in.info = talloc_p(mem_ctx, union samr_DomainInfo);
1003         
1004         s.in.info->info4.comment.string
1005                 = talloc_asprintf(mem_ctx, 
1006                                   "Tortured by Samba4: %s", 
1007                                   timestring(mem_ctx, time(NULL)));
1008         status = dcerpc_samr_SetDomainInfo(samsync_state->p_samr, mem_ctx, &s);
1009
1010         if (!test_samr_handle_Close(samsync_state->p_samr, mem_ctx, domain_policy)) {
1011                 ret = False;
1012                 goto failed;
1013         }
1014
1015         if (!NT_STATUS_IS_OK(status)) {
1016                 printf("SetDomainInfo level %u failed - %s\n", 
1017                        s.in.level, nt_errstr(status));
1018                 ret = False;
1019                 goto failed;
1020         }
1021         
1022
1023         status = dcerpc_parse_binding(mem_ctx, binding, &b);
1024         if (!NT_STATUS_IS_OK(status)) {
1025                 printf("Bad binding string %s\n", binding);
1026                 ret = False;
1027                 goto failed;
1028         }
1029
1030         status = torture_rpc_connection(&samsync_state->p_lsa, 
1031                                         DCERPC_LSARPC_NAME,
1032                                         DCERPC_LSARPC_UUID,
1033                                         DCERPC_LSARPC_VERSION);
1034
1035         if (!NT_STATUS_IS_OK(status)) {
1036                 ret = False;
1037                 goto failed;
1038         }
1039
1040         qos.len = 0;
1041         qos.impersonation_level = 2;
1042         qos.context_mode = 1;
1043         qos.effective_only = 0;
1044
1045         attr.len = 0;
1046         attr.root_dir = NULL;
1047         attr.object_name = NULL;
1048         attr.attributes = 0;
1049         attr.sec_desc = NULL;
1050         attr.sec_qos = &qos;
1051
1052         r.in.system_name = "\\";
1053         r.in.attr = &attr;
1054         r.in.access_mask = SEC_RIGHTS_MAXIMUM_ALLOWED;
1055         r.out.handle = samsync_state->lsa_handle;
1056
1057         status = dcerpc_lsa_OpenPolicy2(samsync_state->p_lsa, mem_ctx, &r);
1058         if (!NT_STATUS_IS_OK(status)) {
1059                 printf("OpenPolicy2 failed - %s\n", nt_errstr(status));
1060                 ret = False;
1061                 goto failed;
1062         }
1063
1064         b.flags &= ~DCERPC_AUTH_OPTIONS;
1065         b.flags |= DCERPC_SCHANNEL_BDC | DCERPC_SIGN | DCERPC_SCHANNEL_128;
1066
1067         status = dcerpc_pipe_connect_b(&samsync_state->p, &b, 
1068                                        DCERPC_NETLOGON_UUID,
1069                                        DCERPC_NETLOGON_VERSION,
1070                                        lp_workgroup(), 
1071                                        TEST_MACHINE_NAME,
1072                                        machine_password);
1073
1074         if (!NT_STATUS_IS_OK(status)) {
1075                 ret = False;
1076                 goto failed;
1077         }
1078
1079         status = dcerpc_schannel_creds(samsync_state->p->security_state.generic_state, mem_ctx, &samsync_state->creds);
1080         if (!NT_STATUS_IS_OK(status)) {
1081                 ret = False;
1082         }
1083
1084         if (!test_DatabaseSync(samsync_state, mem_ctx)) {
1085                 ret = False;
1086         }
1087
1088         if (!test_DatabaseDeltas(samsync_state, mem_ctx)) {
1089                 ret = False;
1090         }
1091
1092         if (!test_DatabaseSync2(samsync_state->p, mem_ctx, samsync_state->creds)) {
1093                 ret = False;
1094         }
1095 failed:
1096         torture_rpc_close(samsync_state->p);
1097
1098         torture_leave_domain(join_ctx);
1099
1100         talloc_destroy(mem_ctx);
1101
1102         return ret;
1103 }