SQ selftest: add a one-way trust between SAMBA2000 and ADDOMAIN
[metze/samba/wip.git] / selftest / target / Samba4.pm
1 #!/usr/bin/perl
2 # Bootstrap Samba and run a number of tests against it.
3 # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
4 # Published under the GNU GPL, v3 or later.
5
6 # NOTE: Refer to the README for more details about the various testenvs,
7 # and tips about adding new testenvs.
8
9 package Samba4;
10
11 use strict;
12 use Cwd qw(abs_path);
13 use FindBin qw($RealBin);
14 use POSIX;
15 use SocketWrapper;
16 use target::Samba;
17 use target::Samba3;
18 use Archive::Tar;
19 use File::Path 'make_path';
20
21 sub new($$$$$) {
22         my ($classname, $bindir, $srcdir, $server_maxtime) = @_;
23
24         my $self = {
25                 vars => {},
26                 bindir => $bindir,
27                 srcdir => $srcdir,
28                 server_maxtime => $server_maxtime,
29                 target3 => new Samba3($bindir, $srcdir, $server_maxtime)
30         };
31         bless $self;
32         return $self;
33 }
34
35 sub scriptdir_path($$) {
36         my ($self, $path) = @_;
37         return "$self->{srcdir}/source4/scripting/$path";
38 }
39
40 sub check_or_start($$$)
41 {
42         my ($self, $env_vars, $process_model) = @_;
43         my $STDIN_READER;
44
45         my $env_ok = $self->check_env($env_vars);
46         if ($env_ok) {
47                 return $env_vars->{SAMBA_PID};
48         } elsif (defined($env_vars->{SAMBA_PID})) {
49                 warn("SAMBA PID $env_vars->{SAMBA_PID} is not running (died)");
50                 return undef;
51         }
52
53         # use a pipe for stdin in the child processes. This allows
54         # those processes to monitor the pipe for EOF to ensure they
55         # exit when the test script exits
56         pipe($STDIN_READER, $env_vars->{STDIN_PIPE});
57
58         # build up the command to run samba
59         my @preargs = ();
60         my @optargs = ();
61         if (defined($ENV{SAMBA_OPTIONS})) {
62                 @optargs = split(/ /, $ENV{SAMBA_OPTIONS});
63         }
64         if(defined($ENV{SAMBA_VALGRIND})) {
65                 @preargs = split(/ /,$ENV{SAMBA_VALGRIND});
66         }
67
68         if (defined($process_model)) {
69                 push @optargs, ("-M", $process_model);
70         }
71         my $binary = Samba::bindir_path($self, "samba");
72         my @full_cmd = (@preargs, $binary, "-i",
73                         "--no-process-group", "--maximum-runtime=$self->{server_maxtime}",
74                         $env_vars->{CONFIGURATION}, @optargs);
75
76         # the samba process takes some additional env variables (compared to s3)
77         my $samba_envs = Samba::get_env_for_process("samba", $env_vars);
78         $samba_envs->{RESOLV_CONF} = $env_vars->{RESOLV_CONF};
79         $samba_envs->{UID_WRAPPER} = "1";
80         if (defined($ENV{MITKRB5})) {
81                 $samba_envs->{KRB5_KDC_PROFILE} = $env_vars->{MITKDC_CONFIG};
82         }
83
84         # fork a child process and exec() samba
85         my $daemon_ctx = {
86                 NAME => "samba",
87                 BINARY_PATH => $binary,
88                 FULL_CMD => [ @full_cmd ],
89                 LOG_FILE => $env_vars->{SAMBA_TEST_LOG},
90                 TEE_STDOUT => 1,
91                 ENV_VARS => $samba_envs,
92         };
93         my $pid = Samba::fork_and_exec($self, $env_vars, $daemon_ctx, $STDIN_READER);
94
95         $env_vars->{SAMBA_PID} = $pid;
96
97         # close the parent's read-end of the pipe
98         close($STDIN_READER);
99
100         if ($self->wait_for_start($env_vars) != 0) {
101             warn("Samba $pid failed to start up");
102             return undef;
103         }
104
105         return $pid;
106 }
107
108 sub wait_for_start($$)
109 {
110         my ($self, $testenv_vars) = @_;
111         my $count = 0;
112         my $ret = 0;
113
114         if (not $self->check_env($testenv_vars)) {
115             warn("unable to confirm Samba $testenv_vars->{SAMBA_PID} is running");
116             return -1;
117         }
118
119         # This will return quickly when things are up, but be slow if we
120         # need to wait for (eg) SSL init
121         my $nmblookup =  Samba::bindir_path($self, "nmblookup4");
122
123         do {
124                 $ret = system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{SERVER}");
125                 if ($ret != 0) {
126                         sleep(1);
127                 } else {
128                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{SERVER}");
129                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
130                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
131                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
132                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
133                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{SERVER}");
134                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{SERVER}");
135                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
136                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
137                         system("$nmblookup $testenv_vars->{CONFIGURATION} $testenv_vars->{NETBIOSNAME}");
138                         system("$nmblookup $testenv_vars->{CONFIGURATION} -U $testenv_vars->{SERVER_IP} $testenv_vars->{NETBIOSNAME}");
139                 }
140                 $count++;
141         } while ($ret != 0 && $count < 20);
142         if ($count == 20) {
143                 teardown_env($self, $testenv_vars);
144                 warn("nbt not reachable after 20 retries\n");
145                 return -1;
146         }
147
148         # Ensure we have the first RID Set before we start tests.  This makes the tests more reliable.
149         if ($testenv_vars->{SERVER_ROLE} eq "domain controller") {
150                 print "waiting for working LDAP and a RID Set to be allocated\n";
151                 my $ldbsearch = Samba::bindir_path($self, "ldbsearch");
152                 my $count = 0;
153                 my $base_dn = "DC=".join(",DC=", split(/\./, $testenv_vars->{REALM}));
154
155                 my $search_dn = $base_dn;
156                 if ($testenv_vars->{NETBIOSNAME} ne "RODC") {
157                         # TODO currently no check for actual rIDAllocationPool
158                         $search_dn = "cn=RID Set,cn=$testenv_vars->{NETBIOSNAME},ou=domain controllers,$base_dn";
159                 }
160                 my $max_wait = 60;
161
162                 # Add hosts file for name lookups
163                 my $cmd = "NSS_WRAPPER_HOSTS='$testenv_vars->{NSS_WRAPPER_HOSTS}' ";
164                 if (defined($testenv_vars->{RESOLV_WRAPPER_CONF})) {
165                         $cmd .= "RESOLV_WRAPPER_CONF='$testenv_vars->{RESOLV_WRAPPER_CONF}' ";
166                 } else {
167                         $cmd .= "RESOLV_WRAPPER_HOSTS='$testenv_vars->{RESOLV_WRAPPER_HOSTS}' ";
168                 }
169                 $cmd .= "RESOLV_CONF='$testenv_vars->{RESOLV_CONF}' ";
170
171                 $cmd .= "$ldbsearch ";
172                 $cmd .= "$testenv_vars->{CONFIGURATION} ";
173                 $cmd .= "-H ldap://$testenv_vars->{SERVER} ";
174                 $cmd .= "-U$testenv_vars->{USERNAME}%$testenv_vars->{PASSWORD} ";
175                 $cmd .= "-s base ";
176                 $cmd .= "-b '$search_dn' ";
177                 while (system("$cmd >/dev/null") != 0) {
178                         $count++;
179                         if ($count > $max_wait) {
180                                 teardown_env($self, $testenv_vars);
181                                 warn("Timed out ($max_wait sec) waiting for working LDAP and a RID Set to be allocated by $testenv_vars->{NETBIOSNAME} PID $testenv_vars->{SAMBA_PID}");
182                                 return -1;
183                         }
184                         print "Waiting for working LDAP...\n";
185                         sleep(1);
186                 }
187         }
188
189         my $wbinfo =  Samba::bindir_path($self, "wbinfo");
190
191         $count = 0;
192         do {
193                 my $cmd = "NSS_WRAPPER_PASSWD=$testenv_vars->{NSS_WRAPPER_PASSWD} ";
194                 $cmd .= "NSS_WRAPPER_GROUP=$testenv_vars->{NSS_WRAPPER_GROUP} ";
195                 $cmd .= "SELFTEST_WINBINDD_SOCKET_DIR=$testenv_vars->{SELFTEST_WINBINDD_SOCKET_DIR} ";
196                 $cmd .= "$wbinfo -P";
197                 $ret = system($cmd);
198
199                 if ($ret != 0) {
200                         sleep(1);
201                 }
202                 $count++;
203         } while ($ret != 0 && $count < 20);
204         if ($count == 20) {
205                 teardown_env($self, $testenv_vars);
206                 warn("winbind not reachable after 20 retries\n");
207                 return -1;
208         }
209
210         # Ensure we registered all our names
211         if ($testenv_vars->{SERVER_ROLE} eq "domain controller") {
212                 my $max_wait = 120;
213                 print "Waiting for dns_update_cache to be created.\n";
214                 $count = 0;
215                 while (not -e "$testenv_vars->{PRIVATEDIR}/dns_update_cache") {
216                         $count++;
217                         if ($count > $max_wait) {
218                                 teardown_env($self, $testenv_vars);
219                                 warn("Timed out ($max_wait sec) waiting for dns_update_cache PID $testenv_vars->{SAMBA_PID}");
220                                 return -1;
221                         }
222                         print "Waiting for dns_update_cache to be created...\n";
223                         sleep(1);
224                 }
225                 print "Waiting for dns_update_cache to be filled.\n";
226                 $count = 0;
227                 while ((-s "$testenv_vars->{PRIVATEDIR}/dns_update_cache") == 0) {
228                         $count++;
229                         if ($count > $max_wait) {
230                                 teardown_env($self, $testenv_vars);
231                                 warn("Timed out ($max_wait sec) waiting for dns_update_cache PID $testenv_vars->{SAMBA_PID}");
232                                 return -1;
233                         }
234                         print "Waiting for dns_update_cache to be filled...\n";
235                         sleep(1);
236                 }
237         }
238
239         print $self->getlog_env($testenv_vars);
240
241         print "READY ($testenv_vars->{SAMBA_PID})\n";
242
243         return 0
244 }
245
246 sub write_ldb_file($$$)
247 {
248         my ($self, $file, $ldif) = @_;
249
250         my $ldbadd =  Samba::bindir_path($self, "ldbadd");
251         open(LDIF, "|$ldbadd -H $file >/dev/null");
252         print LDIF $ldif;
253         return(close(LDIF));
254 }
255
256 sub add_wins_config($$)
257 {
258         my ($self, $privatedir) = @_;
259         my $client_ip = Samba::get_ipv4_addr("client");
260
261         return $self->write_ldb_file("$privatedir/wins_config.ldb", "
262 dn: name=TORTURE_11,CN=PARTNERS
263 objectClass: wreplPartner
264 name: TORTURE_11
265 address: $client_ip
266 pullInterval: 0
267 pushChangeCount: 0
268 type: 0x3
269 ");
270 }
271
272 sub setup_dns_hub_internal($$$)
273 {
274         my ($self, $hostname, $prefix) = @_;
275         my $STDIN_READER;
276
277         unless(-d $prefix or make_path($prefix, 0777)) {
278                 warn("Unable to create $prefix");
279                 return undef;
280         }
281         my $prefix_abs = abs_path($prefix);
282
283         die ("prefix=''") if $prefix_abs eq "";
284         die ("prefix='/'") if $prefix_abs eq "/";
285
286         unless (system("rm -rf $prefix_abs/*") == 0) {
287                 warn("Unable to clean up");
288         }
289
290         my $env = undef;
291         $env->{NETBIOSNAME} = $hostname;
292
293         $env->{SERVER_IP} = Samba::get_ipv4_addr($hostname);
294         $env->{SERVER_IPV6} = Samba::get_ipv6_addr($hostname);
295         $env->{SOCKET_WRAPPER_DEFAULT_IFACE} = Samba::get_interface($hostname);
296         $env->{DNS_HUB_LOG} = "$prefix_abs/dns_hub.log";
297         $env->{RESOLV_CONF} = "$prefix_abs/resolv.conf";
298         $env->{TESTENV_DIR} = $prefix_abs;
299
300         open(RESOLV_CONF, ">$env->{RESOLV_CONF}");
301         print RESOLV_CONF "nameserver $env->{SERVER_IP}\n";
302         print RESOLV_CONF "nameserver $env->{SERVER_IPV6}\n";
303         close(RESOLV_CONF);
304
305         my @preargs = ();
306         my @args = ();
307         if (!defined($ENV{PYTHON})) {
308             push (@preargs, "env");
309             push (@preargs, "python");
310         } else {
311             push (@preargs, $ENV{PYTHON});
312         }
313         my $binary = "$self->{srcdir}/selftest/target/dns_hub.py";
314         push (@args, "$self->{server_maxtime}");
315         push (@args, "$env->{SERVER_IP}");
316         push (@args, Samba::realm_to_ip_mappings());
317         my @full_cmd = (@preargs, $binary, @args);
318
319         my $daemon_ctx = {
320                 NAME => "dnshub",
321                 BINARY_PATH => $binary,
322                 FULL_CMD => [ @full_cmd ],
323                 LOG_FILE => $env->{DNS_HUB_LOG},
324                 TEE_STDOUT => 1,
325                 PCAP_FILE => "$ENV{SOCKET_WRAPPER_PCAP_DIR}/env-$hostname$.pcap",
326                 ENV_VARS => {},
327         };
328
329         # use a pipe for stdin in the child processes. This allows
330         # those processes to monitor the pipe for EOF to ensure they
331         # exit when the test script exits
332         pipe($STDIN_READER, $env->{STDIN_PIPE});
333
334         my $pid = Samba::fork_and_exec($self, $env, $daemon_ctx, $STDIN_READER);
335
336         $env->{SAMBA_PID} = $pid;
337         $env->{KRB5_CONFIG} = "$prefix_abs/no_krb5.conf";
338
339         # close the parent's read-end of the pipe
340         close($STDIN_READER);
341
342         return $env;
343 }
344
345 sub setup_dns_hub
346 {
347         my ($self, $prefix) = @_;
348
349         my $hostname = "rootdnsforwarder";
350
351         my $env = $self->setup_dns_hub_internal("$hostname", "$prefix/$hostname");
352
353         $self->{dns_hub_env} = $env;
354
355         return $env;
356 }
357
358 sub get_dns_hub_env($)
359 {
360         my ($self, $prefix) = @_;
361
362         if (defined($self->{dns_hub_env})) {
363                 return $self->{dns_hub_env};
364         }
365
366         die("get_dns_hub_env() not setup 'dns_hub_env'");
367         return undef;
368 }
369
370 # Returns the environmental variables that we pass to samba-tool commands
371 sub get_cmd_env_vars
372 {
373         my ($self, $localenv) = @_;
374
375         my $cmd_env = "NSS_WRAPPER_HOSTS='$localenv->{NSS_WRAPPER_HOSTS}' ";
376         $cmd_env .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$localenv->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
377         if (defined($localenv->{RESOLV_WRAPPER_CONF})) {
378                 $cmd_env .= "RESOLV_WRAPPER_CONF=\"$localenv->{RESOLV_WRAPPER_CONF}\" ";
379         } else {
380                 $cmd_env .= "RESOLV_WRAPPER_HOSTS=\"$localenv->{RESOLV_WRAPPER_HOSTS}\" ";
381         }
382         $cmd_env .= " KRB5_CONFIG=\"$localenv->{KRB5_CONFIG}\" ";
383         $cmd_env .= "KRB5CCNAME=\"$localenv->{KRB5_CCACHE}\" ";
384         $cmd_env .= "RESOLV_CONF=\"$localenv->{RESOLV_CONF}\" ";
385
386         return $cmd_env;
387 }
388
389 # Sets up a forest trust namespace.
390 # (Note this is different to kernel namespaces, setup by the
391 # USE_NAMESPACES=1 option)
392 sub setup_namespaces($$:$$)
393 {
394         my ($self, $localenv, $upn_array, $spn_array) = @_;
395
396         @{$upn_array} = [] unless defined($upn_array);
397         my $upn_args = "";
398         foreach my $upn (@{$upn_array}) {
399                 $upn_args .= " --add-upn-suffix=$upn";
400         }
401
402         @{$spn_array} = [] unless defined($spn_array);
403         my $spn_args = "";
404         foreach my $spn (@{$spn_array}) {
405                 $spn_args .= " --add-spn-suffix=$spn";
406         }
407
408         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
409
410         my $cmd_env = $self->get_cmd_env_vars($localenv);
411
412         my $cmd_config = " $localenv->{CONFIGURATION}";
413
414         my $namespaces = $cmd_env;
415         $namespaces .= " $samba_tool domain trust namespaces $upn_args $spn_args";
416         $namespaces .= $cmd_config;
417         unless (system($namespaces) == 0) {
418                 warn("Failed to add namespaces \n$namespaces");
419                 return;
420         }
421
422         return;
423 }
424
425 sub setup_trust($$$$$)
426 {
427         my ($self, $localenv, $remoteenv, $type, $extra_args) = @_;
428
429         $localenv->{TRUST_SERVER} = $remoteenv->{SERVER};
430
431         $localenv->{TRUST_USERNAME} = $remoteenv->{USERNAME};
432         $localenv->{TRUST_PASSWORD} = $remoteenv->{PASSWORD};
433         $localenv->{TRUST_DOMAIN} = $remoteenv->{DOMAIN};
434         $localenv->{TRUST_REALM} = $remoteenv->{REALM};
435         $localenv->{TRUST_DOMSID} = $remoteenv->{DOMSID};
436
437         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
438
439         # setup the trust
440         my $cmd_env = $self->get_cmd_env_vars($localenv);
441
442         my $cmd_config = " $localenv->{CONFIGURATION}";
443         my $cmd_creds = $cmd_config;
444         $cmd_creds .= " -U$localenv->{TRUST_DOMAIN}\\\\$localenv->{TRUST_USERNAME}\%$localenv->{TRUST_PASSWORD}";
445
446         my $create = $cmd_env;
447         $create .= " $samba_tool domain trust create --type=${type} $localenv->{TRUST_REALM}";
448         $create .= " $extra_args";
449         $create .= $cmd_creds;
450         unless (system($create) == 0) {
451                 warn("Failed to create trust \n$create");
452                 return undef;
453         }
454
455         my $groupname = "g_$localenv->{TRUST_DOMAIN}";
456         my $groupadd = $cmd_env;
457         $groupadd .= " $samba_tool group add '$groupname' --group-scope=Domain $cmd_config";
458         unless (system($groupadd) == 0) {
459                 warn("Failed to create group \n$groupadd");
460                 return undef;
461         }
462         my $groupmem = $cmd_env;
463         $groupmem .= " $samba_tool group addmembers '$groupname' '$localenv->{TRUST_DOMSID}-513' $cmd_config";
464         unless (system($groupmem) == 0) {
465                 warn("Failed to add group member \n$groupmem");
466                 return undef;
467         }
468
469         return $localenv
470 }
471
472 sub provision_raw_prepare($$$$$$$$$$$$)
473 {
474         my ($self, $prefix, $server_role, $hostname,
475             $domain, $realm, $samsid, $functional_level,
476             $password, $kdc_ipv4, $kdc_ipv6) = @_;
477         my $ctx;
478         my $python_cmd = "";
479         if (defined $ENV{PYTHON}) {
480                 $python_cmd = $ENV{PYTHON} . " ";
481         }
482         $ctx->{python} = $python_cmd;
483         my $netbiosname = uc($hostname);
484
485         unless(-d $prefix or mkdir($prefix, 0777)) {
486                 warn("Unable to create $prefix");
487                 return undef;
488         }
489         my $prefix_abs = abs_path($prefix);
490
491         die ("prefix=''") if $prefix_abs eq "";
492         die ("prefix='/'") if $prefix_abs eq "/";
493
494         unless (system("rm -rf $prefix_abs/*") == 0) {
495                 warn("Unable to clean up");
496         }
497
498         
499         my $swiface = Samba::get_interface($hostname);
500
501         $ctx->{prefix} = $prefix;
502         $ctx->{prefix_abs} = $prefix_abs;
503
504         $ctx->{server_role} = $server_role;
505         $ctx->{hostname} = $hostname;
506         $ctx->{netbiosname} = $netbiosname;
507         $ctx->{swiface} = $swiface;
508         $ctx->{password} = $password;
509         $ctx->{kdc_ipv4} = $kdc_ipv4;
510         $ctx->{kdc_ipv6} = $kdc_ipv6;
511         $ctx->{krb5_ccname} = "$prefix_abs/krb5cc_%{uid}";
512         if ($functional_level eq "2000") {
513                 $ctx->{supported_enctypes} = "arcfour-hmac-md5 des-cbc-md5 des-cbc-crc"
514         }
515
516 #
517 # Set smbd log level here.
518 #
519         $ctx->{server_loglevel} =$ENV{SERVER_LOG_LEVEL} || 1;
520         $ctx->{username} = "Administrator";
521         $ctx->{domain} = $domain;
522         $ctx->{realm} = uc($realm);
523         $ctx->{dnsname} = lc($realm);
524         $ctx->{samsid} = $samsid;
525
526         $ctx->{functional_level} = $functional_level;
527
528         my $unix_name = ($ENV{USER} or $ENV{LOGNAME} or `whoami`);
529         chomp $unix_name;
530         $ctx->{unix_name} = $unix_name;
531         $ctx->{unix_uid} = $>;
532         my @mygid = split(" ", $();
533         $ctx->{unix_gid} = $mygid[0];
534         $ctx->{unix_gids_str} = $);
535         @{$ctx->{unix_gids}} = split(" ", $ctx->{unix_gids_str});
536
537         $ctx->{etcdir} = "$prefix_abs/etc";
538         $ctx->{piddir} = "$prefix_abs/pid";
539         $ctx->{smb_conf} = "$ctx->{etcdir}/smb.conf";
540         $ctx->{krb5_conf} = "$ctx->{etcdir}/krb5.conf";
541         $ctx->{krb5_ccache} = "$prefix_abs/krb5_ccache";
542         $ctx->{mitkdc_conf} = "$ctx->{etcdir}/mitkdc.conf";
543         $ctx->{privatedir} = "$prefix_abs/private";
544         $ctx->{binddnsdir} = "$prefix_abs/bind-dns";
545         $ctx->{ncalrpcdir} = "$prefix_abs/ncalrpc";
546         $ctx->{lockdir} = "$prefix_abs/lockdir";
547         $ctx->{logdir} = "$prefix_abs/logs";
548         $ctx->{statedir} = "$prefix_abs/statedir";
549         $ctx->{cachedir} = "$prefix_abs/cachedir";
550         $ctx->{winbindd_socket_dir} = "$prefix_abs/winbindd_socket";
551         $ctx->{ntp_signd_socket_dir} = "$prefix_abs/ntp_signd_socket";
552         $ctx->{nsswrap_passwd} = "$ctx->{etcdir}/passwd";
553         $ctx->{nsswrap_group} = "$ctx->{etcdir}/group";
554         $ctx->{nsswrap_hosts} = "$ENV{SELFTEST_PREFIX}/hosts";
555         $ctx->{nsswrap_hostname} = "$ctx->{hostname}.$ctx->{dnsname}";
556         if ($ENV{SAMBA_DNS_FAKING}) {
557                 $ctx->{dns_host_file} = "$ENV{SELFTEST_PREFIX}/dns_host_file";
558                 $ctx->{samba_dnsupdate} = "$ENV{SRCDIR_ABS}/source4/scripting/bin/samba_dnsupdate -s $ctx->{smb_conf} --all-interfaces --use-file=$ctx->{dns_host_file}";
559                 $ctx->{samba_dnsupdate} = $python_cmd .  $ctx->{samba_dnsupdate};
560         } else {
561                 $ctx->{samba_dnsupdate} = "$ENV{SRCDIR_ABS}/source4/scripting/bin/samba_dnsupdate -s $ctx->{smb_conf} --all-interfaces";
562                 $ctx->{samba_dnsupdate} = $python_cmd .  $ctx->{samba_dnsupdate};
563                 $ctx->{use_resolv_wrapper} = 1;
564         }
565
566         my $dns_hub = $self->get_dns_hub_env();
567         $ctx->{resolv_conf} = $dns_hub->{RESOLV_CONF};
568
569         $ctx->{tlsdir} = "$ctx->{privatedir}/tls";
570
571         $ctx->{ipv4} = Samba::get_ipv4_addr($hostname);
572         $ctx->{ipv6} = Samba::get_ipv6_addr($hostname);
573
574         push(@{$ctx->{directories}}, $ctx->{privatedir});
575         push(@{$ctx->{directories}}, $ctx->{binddnsdir});
576         push(@{$ctx->{directories}}, $ctx->{etcdir});
577         push(@{$ctx->{directories}}, $ctx->{piddir});
578         push(@{$ctx->{directories}}, $ctx->{lockdir});
579         push(@{$ctx->{directories}}, $ctx->{logdir});
580         push(@{$ctx->{directories}}, $ctx->{statedir});
581         push(@{$ctx->{directories}}, $ctx->{cachedir});
582
583         $ctx->{smb_conf_extra_options} = "";
584
585         my @provision_options = ();
586         push (@provision_options, "KRB5_CONFIG=\"$ctx->{krb5_conf}\"");
587         push (@provision_options, "KRB5_CCACHE=\"$ctx->{krb5_ccache}\"");
588         push (@provision_options, "NSS_WRAPPER_PASSWD=\"$ctx->{nsswrap_passwd}\"");
589         push (@provision_options, "NSS_WRAPPER_GROUP=\"$ctx->{nsswrap_group}\"");
590         push (@provision_options, "NSS_WRAPPER_HOSTS=\"$ctx->{nsswrap_hosts}\"");
591         push (@provision_options, "NSS_WRAPPER_HOSTNAME=\"$ctx->{nsswrap_hostname}\"");
592         if (defined($ctx->{use_resolv_wrapper})) {
593                 push (@provision_options, "RESOLV_WRAPPER_CONF=\"$ctx->{resolv_conf}\"");
594                 push (@provision_options, "RESOLV_CONF=\"$ctx->{resolv_conf}\"");
595         } else {
596                 push (@provision_options, "RESOLV_WRAPPER_HOSTS=\"$ctx->{dns_host_file}\"");
597         }
598         if (defined($ENV{GDB_PROVISION})) {
599                 push (@provision_options, "gdb --args");
600                 if (!defined($ENV{PYTHON})) {
601                     push (@provision_options, "env");
602                     push (@provision_options, "python");
603                 }
604         }
605         if (defined($ENV{VALGRIND_PROVISION})) {
606                 push (@provision_options, "valgrind");
607                 if (!defined($ENV{PYTHON})) {
608                     push (@provision_options, "env");
609                     push (@provision_options, "python");
610                 }
611         }
612
613         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
614
615         push (@provision_options, $samba_tool);
616         push (@provision_options, "domain");
617         push (@provision_options, "provision");
618         push (@provision_options, "--configfile=$ctx->{smb_conf}");
619         push (@provision_options, "--host-name=$ctx->{hostname}");
620         push (@provision_options, "--host-ip=$ctx->{ipv4}");
621         push (@provision_options, "--quiet");
622         push (@provision_options, "--domain=$ctx->{domain}");
623         push (@provision_options, "--realm=$ctx->{realm}");
624         if (defined($ctx->{samsid})) {
625                 push (@provision_options, "--domain-sid=$ctx->{samsid}");
626         }
627         push (@provision_options, "--adminpass=$ctx->{password}");
628         push (@provision_options, "--krbtgtpass=krbtgt$ctx->{password}");
629         push (@provision_options, "--machinepass=machine$ctx->{password}");
630         push (@provision_options, "--root=$ctx->{unix_name}");
631         push (@provision_options, "--server-role=\"$ctx->{server_role}\"");
632         push (@provision_options, "--function-level=\"$ctx->{functional_level}\"");
633
634         @{$ctx->{provision_options}} = @provision_options;
635
636         return $ctx;
637 }
638
639 sub has_option
640 {
641         my ($self, $keyword, @options_list) = @_;
642
643         # convert the options-list to a hash-map for easy keyword lookup
644         my %options_dict = map { $_ => 1 } @options_list;
645
646         return exists $options_dict{$keyword};
647 }
648
649 #
650 # Step1 creates the basic configuration
651 #
652 sub provision_raw_step1($$)
653 {
654         my ($self, $ctx) = @_;
655
656         mkdir($_, 0777) foreach (@{$ctx->{directories}});
657
658         ##
659         ## lockdir and piddir must be 0755
660         ##
661         chmod 0755, $ctx->{lockdir};
662         chmod 0755, $ctx->{piddir};
663
664         unless (open(CONFFILE, ">$ctx->{smb_conf}")) {
665                 warn("can't open $ctx->{smb_conf}$?");
666                 return undef;
667         }
668
669         Samba::prepare_keyblobs($ctx);
670         my $crlfile = "$ctx->{tlsdir}/crl.pem";
671         $crlfile = "" unless -e ${crlfile};
672
673         # work out which file server to use. Default to source3 smbd (s3fs),
674         # unless the source4 NTVFS (smb) file server has been specified
675         my $services = "-smb +s3fs";
676         if ($self->has_option("--use-ntvfs", @{$ctx->{provision_options}})) {
677                 $services = "+smb -s3fs";
678         }
679
680         my $interfaces = Samba::get_interfaces_config($ctx->{netbiosname});
681
682         print CONFFILE "
683 [global]
684         netbios name = $ctx->{netbiosname}
685         posix:eadb = $ctx->{statedir}/eadb.tdb
686         workgroup = $ctx->{domain}
687         realm = $ctx->{realm}
688         private dir = $ctx->{privatedir}
689         binddns dir = $ctx->{binddnsdir}
690         pid directory = $ctx->{piddir}
691         ncalrpc dir = $ctx->{ncalrpcdir}
692         lock dir = $ctx->{lockdir}
693         state directory = $ctx->{statedir}
694         cache directory = $ctx->{cachedir}
695         winbindd socket directory = $ctx->{winbindd_socket_dir}
696         ntp signd socket directory = $ctx->{ntp_signd_socket_dir}
697         winbind separator = /
698         interfaces = $interfaces
699         tls dh params file = $ctx->{tlsdir}/dhparms.pem
700         tls crlfile = ${crlfile}
701         tls verify peer = no_check
702         panic action = $RealBin/gdb_backtrace \%d
703         wins support = yes
704         server role = $ctx->{server_role}
705         server services = +echo $services
706         dcerpc endpoint servers = +winreg +srvsvc
707         notify:inotify = false
708         ldb:nosync = true
709         ldap server require strong auth = yes
710 #We don't want to pass our self-tests if the PAC code is wrong
711         gensec:require_pac = true
712         log file = $ctx->{logdir}/log.\%m
713         log level = $ctx->{server_loglevel}
714         lanman auth = Yes
715         ntlm auth = Yes
716         client min protocol = CORE
717         server min protocol = LANMAN1
718         mangled names = yes
719         dns update command = $ctx->{samba_dnsupdate}
720         spn update command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba_spnupdate -s $ctx->{smb_conf}
721         gpo update command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba-gpupdate -s $ctx->{smb_conf} --target=Computer
722         samba kcc command = $ctx->{python} $ENV{SRCDIR_ABS}/source4/scripting/bin/samba_kcc
723         dreplsrv:periodic_startup_interval = 0
724         dsdb:schema update allowed = yes
725
726         vfs objects = dfs_samba4 acl_xattr fake_acls xattr_tdb streams_depot
727
728         idmap_ldb:use rfc2307=yes
729         winbind enum users = yes
730         winbind enum groups = yes
731
732         rpc server port:netlogon = 1026
733         include system krb5 conf = no
734
735 ";
736
737         print CONFFILE "
738
739         # Begin extra options
740         $ctx->{smb_conf_extra_options}
741         # End extra options
742 ";
743         close(CONFFILE);
744
745         #Default the KDC IP to the server's IP
746         if (not defined($ctx->{kdc_ipv4})) {
747                 $ctx->{kdc_ipv4} = $ctx->{ipv4};
748         }
749         if (not defined($ctx->{kdc_ipv6})) {
750                 $ctx->{kdc_ipv6} = $ctx->{ipv6};
751         }
752
753         Samba::mk_krb5_conf($ctx);
754         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
755
756         open(PWD, ">$ctx->{nsswrap_passwd}");
757         if ($ctx->{unix_uid} != 0) {
758                 print PWD "root:x:0:0:root gecos:$ctx->{prefix_abs}:/bin/false\n";
759         }
760         print PWD "$ctx->{unix_name}:x:$ctx->{unix_uid}:65531:$ctx->{unix_name} gecos:$ctx->{prefix_abs}:/bin/false\n";
761         print PWD "nobody:x:65534:65533:nobody gecos:$ctx->{prefix_abs}:/bin/false
762 pdbtest:x:65533:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
763 pdbtest2:x:65532:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
764 pdbtest3:x:65531:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
765 pdbtest4:x:65530:65533:pdbtest gecos:$ctx->{prefix_abs}:/bin/false
766 ";
767         close(PWD);
768         my $uid_rfc2307test = 65533;
769
770         open(GRP, ">$ctx->{nsswrap_group}");
771         if ($ctx->{unix_gid} != 0) {
772                 print GRP "root:x:0:\n";
773         }
774         print GRP "$ctx->{unix_name}:x:$ctx->{unix_gid}:\n";
775         print GRP "wheel:x:10:
776 users:x:65531:
777 nobody:x:65533:
778 nogroup:x:65534:nobody
779 ";
780         close(GRP);
781         my $gid_rfc2307test = 65532;
782
783         my $hostname = lc($ctx->{hostname});
784         open(HOSTS, ">>$ctx->{nsswrap_hosts}");
785         if ($hostname eq "localdc") {
786                 print HOSTS "$ctx->{ipv4} ${hostname}.$ctx->{dnsname} $ctx->{dnsname} ${hostname}\n";
787                 print HOSTS "$ctx->{ipv6} ${hostname}.$ctx->{dnsname} $ctx->{dnsname} ${hostname}\n";
788         } else {
789                 print HOSTS "$ctx->{ipv4} ${hostname}.$ctx->{dnsname} ${hostname}\n";
790                 print HOSTS "$ctx->{ipv6} ${hostname}.$ctx->{dnsname} ${hostname}\n";
791         }
792         close(HOSTS);
793
794         my $configuration = "--configfile=$ctx->{smb_conf}";
795
796 #Ensure the config file is valid before we start
797         my $testparm = Samba::bindir_path($self, "samba-tool") . " testparm";
798         if (system("$testparm $configuration -v --suppress-prompt >/dev/null 2>&1") != 0) {
799                 system("$testparm -v --suppress-prompt $configuration >&2");
800                 warn("Failed to create a valid smb.conf configuration $testparm!");
801                 return undef;
802         }
803         unless (system("($testparm $configuration -v --suppress-prompt --parameter-name=\"netbios name\" --section-name=global 2> /dev/null | grep -i \"^$ctx->{netbiosname}\" ) >/dev/null 2>&1") == 0) {
804                 warn("Failed to create a valid smb.conf configuration! $testparm $configuration -v --suppress-prompt --parameter-name=\"netbios name\" --section-name=global");
805                 return undef;
806         }
807
808         # Return the environment variables for the new testenv DC.
809         # Note that we have SERVER_X and DC_SERVER_X variables (which have the same
810         # value initially). In a 2 DC setup, $DC_SERVER_X will always be the PDC.
811         my $ret = {
812                 KRB5_CONFIG => $ctx->{krb5_conf},
813                 KRB5_CCACHE => $ctx->{krb5_ccache},
814                 MITKDC_CONFIG => $ctx->{mitkdc_conf},
815                 PIDDIR => $ctx->{piddir},
816                 SERVER => $ctx->{hostname},
817                 DC_SERVER => $ctx->{hostname},
818                 SERVER_IP => $ctx->{ipv4},
819                 DC_SERVER_IP => $ctx->{ipv4},
820                 SERVER_IPV6 => $ctx->{ipv6},
821                 DC_SERVER_IPV6 => $ctx->{ipv6},
822                 NETBIOSNAME => $ctx->{netbiosname},
823                 DC_NETBIOSNAME => $ctx->{netbiosname},
824                 DOMAIN => $ctx->{domain},
825                 USERNAME => $ctx->{username},
826                 DC_USERNAME => $ctx->{username},
827                 REALM => $ctx->{realm},
828                 DNSNAME => $ctx->{dnsname},
829                 SAMSID => $ctx->{samsid},
830                 PASSWORD => $ctx->{password},
831                 DC_PASSWORD => $ctx->{password},
832                 LDAPDIR => $ctx->{ldapdir},
833                 LDAP_INSTANCE => $ctx->{ldap_instance},
834                 SELFTEST_WINBINDD_SOCKET_DIR => $ctx->{winbindd_socket_dir},
835                 NCALRPCDIR => $ctx->{ncalrpcdir},
836                 LOCKDIR => $ctx->{lockdir},
837                 STATEDIR => $ctx->{statedir},
838                 CACHEDIR => $ctx->{cachedir},
839                 PRIVATEDIR => $ctx->{privatedir},
840                 BINDDNSDIR => $ctx->{binddnsdir},
841                 SERVERCONFFILE => $ctx->{smb_conf},
842                 TESTENV_DIR => $ctx->{prefix_abs},
843                 CONFIGURATION => $configuration,
844                 SOCKET_WRAPPER_DEFAULT_IFACE => $ctx->{swiface},
845                 NSS_WRAPPER_PASSWD => $ctx->{nsswrap_passwd},
846                 NSS_WRAPPER_GROUP => $ctx->{nsswrap_group},
847                 NSS_WRAPPER_HOSTS => $ctx->{nsswrap_hosts},
848                 NSS_WRAPPER_HOSTNAME => $ctx->{nsswrap_hostname},
849                 SAMBA_TEST_FIFO => "$ctx->{prefix}/samba_test.fifo",
850                 SAMBA_TEST_LOG => "$ctx->{prefix}/samba_test.log",
851                 SAMBA_TEST_LOG_POS => 0,
852                 NSS_WRAPPER_MODULE_SO_PATH => Samba::nss_wrapper_winbind_so_path($self),
853                 NSS_WRAPPER_MODULE_FN_PREFIX => "winbind",
854                 LOCAL_PATH => $ctx->{share},
855                 UID_RFC2307TEST => $uid_rfc2307test,
856                 GID_RFC2307TEST => $gid_rfc2307test,
857                 SERVER_ROLE => $ctx->{server_role},
858                 RESOLV_CONF => $ctx->{resolv_conf}
859         };
860
861         if (defined($ctx->{use_resolv_wrapper})) {
862                 $ret->{RESOLV_WRAPPER_CONF} = $ctx->{resolv_conf};
863         } else {
864                 $ret->{RESOLV_WRAPPER_HOSTS} = $ctx->{dns_host_file};
865         }
866
867         if ($ctx->{server_role} eq "domain controller") {
868                 $ret->{DOMSID} = $ret->{SAMSID};
869         }
870
871         return $ret;
872 }
873
874 #
875 # Step2 runs the provision script
876 #
877 sub provision_raw_step2($$$)
878 {
879         my ($self, $ctx, $ret) = @_;
880
881         my $provision_cmd = join(" ", @{$ctx->{provision_options}});
882         unless (system($provision_cmd) == 0) {
883                 warn("Unable to provision: \n$provision_cmd\n");
884                 return undef;
885         }
886
887         my $testallowed_account = "testallowed";
888         my $samba_tool_cmd = "";
889         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
890         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
891         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
892             . " user create --configfile=$ctx->{smb_conf} $testallowed_account $ctx->{password}";
893         unless (system($samba_tool_cmd) == 0) {
894                 warn("Unable to add testallowed user: \n$samba_tool_cmd\n");
895                 return undef;
896         }
897
898         my $ldbmodify = "";
899         $ldbmodify .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
900         $ldbmodify .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
901         $ldbmodify .= Samba::bindir_path($self, "ldbmodify");
902         $ldbmodify .=  " --configfile=$ctx->{smb_conf}";
903         my $base_dn = "DC=".join(",DC=", split(/\./, $ctx->{realm}));
904
905         if ($ctx->{server_role} ne "domain controller") {
906                 $base_dn = "DC=$ctx->{netbiosname}";
907         }
908
909         my $user_dn = "cn=$testallowed_account,cn=users,$base_dn";
910         $testallowed_account = "testallowed account";
911         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
912         print LDIF "dn: $user_dn
913 changetype: modify
914 replace: samAccountName
915 samAccountName: $testallowed_account
916 -
917 ";
918         close(LDIF);
919
920         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
921         print LDIF "dn: $user_dn
922 changetype: modify
923 replace: userPrincipalName
924 userPrincipalName: testallowed upn\@$ctx->{realm}
925 replace: servicePrincipalName
926 servicePrincipalName: host/testallowed
927 -           
928 ";
929         close(LDIF);
930
931         $samba_tool_cmd = "";
932         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
933         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
934         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
935             . " user create --configfile=$ctx->{smb_conf} testdenied $ctx->{password}";
936         unless (system($samba_tool_cmd) == 0) {
937                 warn("Unable to add testdenied user: \n$samba_tool_cmd\n");
938                 return undef;
939         }
940
941         my $user_dn = "cn=testdenied,cn=users,$base_dn";
942         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
943         print LDIF "dn: $user_dn
944 changetype: modify
945 replace: userPrincipalName
946 userPrincipalName: testdenied_upn\@$ctx->{realm}.upn
947 -           
948 ";
949         close(LDIF);
950
951         $samba_tool_cmd = "";
952         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
953         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
954         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
955             . " user create --configfile=$ctx->{smb_conf} testupnspn $ctx->{password}";
956         unless (system($samba_tool_cmd) == 0) {
957                 warn("Unable to add testupnspn user: \n$samba_tool_cmd\n");
958                 return undef;
959         }
960
961         my $user_dn = "cn=testupnspn,cn=users,$base_dn";
962         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
963         print LDIF "dn: $user_dn
964 changetype: modify
965 replace: userPrincipalName
966 userPrincipalName: http/testupnspn.$ctx->{dnsname}\@$ctx->{realm}
967 replace: servicePrincipalName
968 servicePrincipalName: http/testupnspn.$ctx->{dnsname}
969 -
970 ";
971         close(LDIF);
972
973         $samba_tool_cmd = "";
974         $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
975         $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
976         $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
977             . " group addmembers --configfile=$ctx->{smb_conf} 'Allowed RODC Password Replication Group' '$testallowed_account'";
978         unless (system($samba_tool_cmd) == 0) {
979                 warn("Unable to add '$testallowed_account' user to 'Allowed RODC Password Replication Group': \n$samba_tool_cmd\n");
980                 return undef;
981         }
982
983         # Create to users alice and bob!
984         my $user_account_array = ["alice", "bob", "jane"];
985
986         foreach my $user_account (@{$user_account_array}) {
987                 my $samba_tool_cmd = "";
988
989                 $samba_tool_cmd .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
990                 $samba_tool_cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
991                 $samba_tool_cmd .= Samba::bindir_path($self, "samba-tool")
992                     . " user create --configfile=$ctx->{smb_conf} $user_account Secret007";
993                 unless (system($samba_tool_cmd) == 0) {
994                         warn("Unable to create user: $user_account\n$samba_tool_cmd\n");
995                         return undef;
996                 }
997         }
998
999         my $ldbmodify = "";
1000         $ldbmodify .= "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1001         $ldbmodify .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1002         $ldbmodify .= Samba::bindir_path($self, "ldbmodify");
1003         $ldbmodify .=  " --configfile=$ctx->{smb_conf}";
1004         my $base_dn = "DC=".join(",DC=", split(/\./, $ctx->{realm}));
1005         my $user_dn = "cn=jane,cn=users,$base_dn";
1006
1007         open(LDIF, "|$ldbmodify -H $ctx->{privatedir}/sam.ldb");
1008         print LDIF "dn: $user_dn
1009 changetype: modify
1010 replace: userPrincipalName
1011 userPrincipalName: jane.doe\@$ctx->{realm}
1012 -
1013 ";
1014         close(LDIF);
1015
1016         return $ret;
1017 }
1018
1019 sub provision($$$$$$$$$$)
1020 {
1021         my ($self, $prefix, $server_role, $hostname,
1022             $domain, $realm, $functional_level,
1023             $password, $kdc_ipv4, $kdc_ipv6, $extra_smbconf_options, $extra_smbconf_shares,
1024             $extra_provision_options) = @_;
1025
1026         my $samsid = Samba::random_domain_sid();
1027
1028         my $ctx = $self->provision_raw_prepare($prefix, $server_role,
1029                                                $hostname,
1030                                                $domain, $realm,
1031                                                $samsid,
1032                                                $functional_level,
1033                                                $password, $kdc_ipv4, $kdc_ipv6);
1034
1035         if (defined($extra_provision_options)) {
1036                 push (@{$ctx->{provision_options}}, @{$extra_provision_options});
1037         }
1038
1039         $ctx->{share} = "$ctx->{prefix_abs}/share";
1040         push(@{$ctx->{directories}}, "$ctx->{share}");
1041         push(@{$ctx->{directories}}, "$ctx->{share}/test1");
1042         push(@{$ctx->{directories}}, "$ctx->{share}/test2");
1043
1044         # precreate directories for printer drivers
1045         push(@{$ctx->{directories}}, "$ctx->{share}/W32X86");
1046         push(@{$ctx->{directories}}, "$ctx->{share}/x64");
1047         push(@{$ctx->{directories}}, "$ctx->{share}/WIN40");
1048
1049         my $msdfs = "no";
1050         $msdfs = "yes" if ($server_role eq "domain controller");
1051         $ctx->{smb_conf_extra_options} = "
1052
1053         max xmit = 32K
1054         server max protocol = SMB2
1055         host msdfs = $msdfs
1056         lanman auth = yes
1057
1058         # fruit:copyfile is a global option
1059         fruit:copyfile = yes
1060
1061         $extra_smbconf_options
1062
1063 [tmp]
1064         path = $ctx->{share}
1065         read only = no
1066         posix:sharedelay = 100000
1067         posix:oplocktimeout = 3
1068         posix:writetimeupdatedelay = 500000
1069
1070 [xcopy_share]
1071         path = $ctx->{share}
1072         read only = no
1073         posix:sharedelay = 100000
1074         posix:oplocktimeout = 3
1075         posix:writetimeupdatedelay = 500000
1076         create mask = 777
1077         force create mode = 777
1078
1079 [posix_share]
1080         path = $ctx->{share}
1081         read only = no
1082         create mask = 0777
1083         force create mode = 0
1084         directory mask = 0777
1085         force directory mode = 0
1086
1087 [test1]
1088         path = $ctx->{share}/test1
1089         read only = no
1090         posix:sharedelay = 100000
1091         posix:oplocktimeout = 3
1092         posix:writetimeupdatedelay = 500000
1093
1094 [test2]
1095         path = $ctx->{share}/test2
1096         read only = no
1097         posix:sharedelay = 100000
1098         posix:oplocktimeout = 3
1099         posix:writetimeupdatedelay = 500000
1100
1101 [cifs]
1102         path = $ctx->{share}/_ignore_cifs_
1103         read only = no
1104         ntvfs handler = cifs
1105         cifs:server = $ctx->{netbiosname}
1106         cifs:share = tmp
1107         cifs:use-s4u2proxy = yes
1108         # There is no username specified here, instead the client is expected
1109         # to log in with kerberos, and the serverwill use delegated credentials.
1110         # Or the server tries s4u2self/s4u2proxy to impersonate the client
1111
1112 [simple]
1113         path = $ctx->{share}
1114         read only = no
1115         ntvfs handler = simple
1116
1117 [sysvol]
1118         path = $ctx->{statedir}/sysvol
1119         read only = no
1120
1121 [netlogon]
1122         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1123         read only = no
1124
1125 [cifsposix]
1126         copy = simple
1127         ntvfs handler = cifsposix
1128
1129 [vfs_fruit]
1130         path = $ctx->{share}
1131         vfs objects = catia fruit streams_xattr acl_xattr
1132         ea support = yes
1133         fruit:resource = file
1134         fruit:metadata = netatalk
1135         fruit:locking = netatalk
1136         fruit:encoding = native
1137
1138 [xattr]
1139         path = $ctx->{share}
1140         # This can be used for testing real fs xattr stuff
1141         vfs objects = streams_xattr acl_xattr
1142
1143 $extra_smbconf_shares
1144 ";
1145
1146         my $ret = $self->provision_raw_step1($ctx);
1147         unless (defined $ret) {
1148                 return undef;
1149         }
1150
1151         return $self->provision_raw_step2($ctx, $ret);
1152 }
1153
1154 # For multi-DC testenvs, we want $DC_SERVER to always be the PDC (i.e. the
1155 # original DC) in the testenv. $SERVER is always the joined DC that we are
1156 # actually running the test against
1157 sub set_pdc_env_vars
1158 {
1159         my ($self, $env, $dcvars) = @_;
1160
1161         $env->{DC_SERVER} = $dcvars->{DC_SERVER};
1162         $env->{DC_SERVER_IP} = $dcvars->{DC_SERVER_IP};
1163         $env->{DC_SERVER_IPV6} = $dcvars->{DC_SERVER_IPV6};
1164         $env->{DC_SERVERCONFFILE} = $dcvars->{SERVERCONFFILE};
1165         $env->{DC_NETBIOSNAME} = $dcvars->{DC_NETBIOSNAME};
1166         $env->{DC_USERNAME} = $dcvars->{DC_USERNAME};
1167         $env->{DC_PASSWORD} = $dcvars->{DC_PASSWORD};
1168 }
1169
1170 sub provision_s4member($$$$$)
1171 {
1172         my ($self, $prefix, $dcvars, $hostname, $more_conf) = @_;
1173         print "PROVISIONING MEMBER...\n";
1174         my $extra_smb_conf = "
1175         passdb backend = samba_dsdb
1176 winbindd:use external pipes = true
1177
1178 # the source4 smb server doesn't allow signing by default
1179 server signing = enabled
1180 raw NTLMv2 auth = yes
1181
1182 rpc_server:default = external
1183 rpc_server:svcctl = embedded
1184 rpc_server:srvsvc = embedded
1185 rpc_server:eventlog = embedded
1186 rpc_server:ntsvcs = embedded
1187 rpc_server:winreg = embedded
1188 rpc_server:spoolss = embedded
1189 rpc_daemon:spoolssd = embedded
1190 rpc_server:tcpip = no
1191 ";
1192         if ($more_conf) {
1193                 $extra_smb_conf = $extra_smb_conf . $more_conf . "\n";
1194         }
1195         my $extra_provision_options = ["--use-ntvfs"];
1196         my $ret = $self->provision($prefix,
1197                                    "member server",
1198                                    $hostname,
1199                                    $dcvars->{DOMAIN},
1200                                    $dcvars->{REALM},
1201                                    "2008",
1202                                    "locMEMpass3",
1203                                    $dcvars->{SERVER_IP},
1204                                    $dcvars->{SERVER_IPV6},
1205                                    $extra_smb_conf, "",
1206                                    $extra_provision_options);
1207         unless ($ret) {
1208                 return undef;
1209         }
1210
1211         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1212         my $cmd = $self->get_cmd_env_vars($ret);
1213         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} member";
1214         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1215         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1216
1217         unless (system($cmd) == 0) {
1218                 warn("Join failed\n$cmd");
1219                 return undef;
1220         }
1221
1222         $ret->{DOMSID} = $dcvars->{DOMSID};
1223         $self->set_pdc_env_vars($ret, $dcvars);
1224
1225         return $ret;
1226 }
1227
1228 sub provision_rpc_proxy($$$)
1229 {
1230         my ($self, $prefix, $dcvars) = @_;
1231         print "PROVISIONING RPC PROXY...\n";
1232
1233         my $extra_smbconf_options = "
1234         passdb backend = samba_dsdb
1235
1236         # rpc_proxy
1237         dcerpc_remote:binding = ncacn_ip_tcp:$dcvars->{SERVER}
1238         dcerpc endpoint servers = epmapper, remote
1239         dcerpc_remote:interfaces = rpcecho
1240         dcerpc_remote:allow_anonymous_fallback = yes
1241
1242 [cifs_to_dc]
1243         path = /tmp/_ignore_cifs_to_dc_/_none_
1244         read only = no
1245         ntvfs handler = cifs
1246         cifs:server = $dcvars->{SERVER}
1247         cifs:share = cifs
1248         cifs:use-s4u2proxy = yes
1249         # There is no username specified here, instead the client is expected
1250         # to log in with kerberos, and the serverwill use delegated credentials.
1251         # Or the server tries s4u2self/s4u2proxy to impersonate the client
1252
1253 ";
1254
1255         my $extra_provision_options = ["--use-ntvfs"];
1256         my $ret = $self->provision($prefix,
1257                                    "member server",
1258                                    "localrpcproxy",
1259                                    $dcvars->{DOMAIN},
1260                                    $dcvars->{REALM},
1261                                    "2008",
1262                                    "locRPCproxypass4",
1263                                    $dcvars->{SERVER_IP},
1264                                    $dcvars->{SERVER_IPV6},
1265                                    $extra_smbconf_options, "",
1266                                    $extra_provision_options);
1267         unless ($ret) {
1268                 return undef;
1269         }
1270
1271         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1272
1273         # The joind runs in the context of the rpc_proxy/member for now
1274         my $cmd = $self->get_cmd_env_vars($ret);
1275         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} member";
1276         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1277         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1278
1279         unless (system($cmd) == 0) {
1280                 warn("Join failed\n$cmd");
1281                 return undef;
1282         }
1283
1284         # Setting up delegation runs in the context of the DC for now
1285         $cmd = "";
1286         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$dcvars->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
1287         $cmd .= "KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
1288         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1289         $cmd .= "RESOLV_CONF=\"$dcvars->{RESOLV_CONF}\" ";
1290         $cmd .= "$samba_tool delegation for-any-protocol '$ret->{NETBIOSNAME}\$' on";
1291         $cmd .= " $dcvars->{CONFIGURATION}";
1292         print $cmd;
1293
1294         unless (system($cmd) == 0) {
1295                 warn("Delegation failed\n$cmd");
1296                 return undef;
1297         }
1298
1299         # Setting up delegation runs in the context of the DC for now
1300         $cmd = "";
1301         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$dcvars->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
1302         $cmd .= "KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
1303         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1304         $cmd .= "RESOLV_CONF=\"$dcvars->{RESOLV_CONF}\" ";
1305         $cmd .= "$samba_tool delegation add-service '$ret->{NETBIOSNAME}\$' cifs/$dcvars->{SERVER}";
1306         $cmd .= " $dcvars->{CONFIGURATION}";
1307
1308         unless (system($cmd) == 0) {
1309                 warn("Delegation failed\n$cmd");
1310                 return undef;
1311         }
1312
1313         $ret->{DOMSID} = $dcvars->{DOMSID};
1314         $self->set_pdc_env_vars($ret, $dcvars);
1315
1316         return $ret;
1317 }
1318
1319 sub provision_promoted_dc($$$)
1320 {
1321         my ($self, $prefix, $dcvars) = @_;
1322         print "PROVISIONING PROMOTED DC...\n";
1323
1324         # We do this so that we don't run the provision.  That's the job of 'samba-tool domain dcpromo'.
1325         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1326                                                "promotedvdc",
1327                                                $dcvars->{DOMAIN},
1328                                                $dcvars->{REALM},
1329                                                $dcvars->{SAMSID},
1330                                                "2008",
1331                                                $dcvars->{PASSWORD},
1332                                                $dcvars->{SERVER_IP},
1333                                                $dcvars->{SERVER_IPV6});
1334
1335         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1336
1337         $ctx->{smb_conf_extra_options} = "
1338         max xmit = 32K
1339         server max protocol = SMB2
1340
1341         ntlm auth = ntlmv2-only
1342
1343 [sysvol]
1344         path = $ctx->{statedir}/sysvol
1345         read only = yes
1346
1347 [netlogon]
1348         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1349         read only = no
1350
1351 ";
1352
1353         my $ret = $self->provision_raw_step1($ctx);
1354         unless ($ret) {
1355                 return undef;
1356         }
1357
1358         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1359         my $cmd = $self->get_cmd_env_vars($ret);
1360         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} MEMBER --realm=$dcvars->{REALM}";
1361         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1362         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1363
1364         unless (system($cmd) == 0) {
1365                 warn("Join failed\n$cmd");
1366                 return undef;
1367         }
1368
1369         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1370         my $cmd = $self->get_cmd_env_vars($ret);
1371         $cmd .= "$samba_tool domain dcpromo $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1372         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1373         $cmd .= " --machinepass=machine$ret->{PASSWORD} --use-ntvfs --dns-backend=BIND9_DLZ";
1374
1375         unless (system($cmd) == 0) {
1376                 warn("Join failed\n$cmd");
1377                 return undef;
1378         }
1379
1380         $self->set_pdc_env_vars($ret, $dcvars);
1381
1382         return $ret;
1383 }
1384
1385 sub provision_vampire_dc($$$)
1386 {
1387         my ($self, $prefix, $dcvars, $fl) = @_;
1388         print "PROVISIONING VAMPIRE DC @ FL $fl...\n";
1389         my $name = "localvampiredc";
1390         my $extra_conf = "";
1391
1392         if ($fl == "2000") {
1393                 $name = "vampire2000dc";
1394         } else {
1395                 $extra_conf = "drs: immediate link sync = yes
1396                        drs: max link sync = 250";
1397         }
1398
1399         # We do this so that we don't run the provision.  That's the job of 'net vampire'.
1400         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1401                                                $name,
1402                                                $dcvars->{DOMAIN},
1403                                                $dcvars->{REALM},
1404                                                $dcvars->{DOMSID},
1405                                                $fl,
1406                                                $dcvars->{PASSWORD},
1407                                                $dcvars->{SERVER_IP},
1408                                                $dcvars->{SERVER_IPV6});
1409
1410         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1411
1412         $ctx->{smb_conf_extra_options} = "
1413         max xmit = 32K
1414         server max protocol = SMB2
1415
1416         ntlm auth = mschapv2-and-ntlmv2-only
1417         $extra_conf
1418
1419 [sysvol]
1420         path = $ctx->{statedir}/sysvol
1421         read only = yes
1422
1423 [netlogon]
1424         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1425         read only = no
1426
1427 ";
1428
1429         my $ret = $self->provision_raw_step1($ctx);
1430         unless ($ret) {
1431                 return undef;
1432         }
1433
1434         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1435         my $cmd = $self->get_cmd_env_vars($ret);
1436         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1437         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} --domain-critical-only";
1438         $cmd .= " --machinepass=machine$ret->{PASSWORD} --use-ntvfs";
1439         $cmd .= " --backend-store=mdb";
1440
1441         unless (system($cmd) == 0) {
1442                 warn("Join failed\n$cmd");
1443                 return undef;
1444         }
1445
1446         $self->set_pdc_env_vars($ret, $dcvars);
1447         $ret->{DC_REALM} = $dcvars->{DC_REALM};
1448
1449         return $ret;
1450 }
1451
1452 sub provision_ad_dc_ntvfs($$$)
1453 {
1454         my ($self, $prefix, $extra_provision_options) = @_;
1455
1456         # We keep the old 'winbind' name here in server services to
1457         # ensure upgrades which used that name still work with the now
1458         # alias.
1459
1460         print "PROVISIONING AD DC (NTVFS)...\n";
1461         my $extra_conf_options = "netbios aliases = localDC1-a
1462         server services = +winbind -winbindd
1463         ldap server require strong auth = allow_sasl_over_tls
1464         allow nt4 crypto = yes
1465         raw NTLMv2 auth = yes
1466         lsa over netlogon = yes
1467         rpc server port = 1027
1468         auth event notification = true
1469         dsdb event notification = true
1470         dsdb password event notification = true
1471         dsdb group change notification = true
1472         server schannel = auto
1473         ";
1474         push (@{$extra_provision_options}, "--use-ntvfs");
1475         my $ret = $self->provision($prefix,
1476                                    "domain controller",
1477                                    "localdc",
1478                                    "SAMBADOMAIN",
1479                                    "samba.example.com",
1480                                    "2008",
1481                                    "locDCpass1",
1482                                    undef,
1483                                    undef,
1484                                    $extra_conf_options,
1485                                    "",
1486                                    $extra_provision_options);
1487         unless ($ret) {
1488                 return undef;
1489         }
1490
1491         unless($self->add_wins_config("$prefix/private")) {
1492                 warn("Unable to add wins configuration");
1493                 return undef;
1494         }
1495         $ret->{NETBIOSALIAS} = "localdc1-a";
1496         $ret->{DC_REALM} = $ret->{REALM};
1497
1498         return $ret;
1499 }
1500
1501 sub provision_fl2000dc($$)
1502 {
1503         my ($self, $prefix) = @_;
1504
1505         print "PROVISIONING DC WITH FOREST LEVEL 2000...\n";
1506         my $extra_conf_options = "
1507         spnego:simulate_w2k=yes
1508         ntlmssp_client:force_old_spnego=yes
1509         ntlmssp_server:force_old_spnego=yes
1510 ";
1511         my $extra_provision_options = ["--use-ntvfs", "--base-schema=2008_R2"];
1512         # This environment uses plain text secrets
1513         # i.e. secret attributes are not encrypted on disk.
1514         # This allows testing of the --plaintext-secrets option for
1515         # provision
1516         push (@{$extra_provision_options}, "--plaintext-secrets");
1517         my $ret = $self->provision($prefix,
1518                                    "domain controller",
1519                                    "dc5",
1520                                    "SAMBA2000",
1521                                    "samba2000.example.com",
1522                                    "2000",
1523                                    "locDCpass5",
1524                                    undef,
1525                                    undef,
1526                                    $extra_conf_options,
1527                                    "",
1528                                    $extra_provision_options);
1529         unless ($ret) {
1530                 return undef;
1531         }
1532
1533         unless($self->add_wins_config("$prefix/private")) {
1534                 warn("Unable to add wins configuration");
1535                 return undef;
1536         }
1537         $ret->{DC_REALM} = $ret->{REALM};
1538
1539         return $ret;
1540 }
1541
1542 sub provision_fl2003dc($$$)
1543 {
1544         my ($self, $prefix, $dcvars) = @_;
1545         my $ip_addr1 = Samba::get_ipv4_addr("fakednsforwarder1");
1546         my $ip_addr2 = Samba::get_ipv4_addr("fakednsforwarder2");
1547
1548         print "PROVISIONING DC WITH FOREST LEVEL 2003...\n";
1549         my $extra_conf_options = "allow dns updates = nonsecure and secure
1550         dcesrv:header signing = no
1551         dcesrv:max auth states = 0
1552         dns forwarder = $ip_addr1 $ip_addr2";
1553         my $extra_provision_options = ["--use-ntvfs", "--base-schema=2008_R2"];
1554         my $ret = $self->provision($prefix,
1555                                    "domain controller",
1556                                    "dc6",
1557                                    "SAMBA2003",
1558                                    "samba2003.example.com",
1559                                    "2003",
1560                                    "locDCpass6",
1561                                    undef,
1562                                    undef,
1563                                    $extra_conf_options,
1564                                    "",
1565                                    $extra_provision_options);
1566         unless (defined $ret) {
1567                 return undef;
1568         }
1569
1570         $ret->{DNS_FORWARDER1} = $ip_addr1;
1571         $ret->{DNS_FORWARDER2} = $ip_addr2;
1572
1573         my @samba_tool_options;
1574         push (@samba_tool_options, Samba::bindir_path($self, "samba-tool"));
1575         push (@samba_tool_options, "domain");
1576         push (@samba_tool_options, "passwordsettings");
1577         push (@samba_tool_options, "set");
1578         push (@samba_tool_options, "--configfile=$ret->{SERVERCONFFILE}");
1579         push (@samba_tool_options, "--min-pwd-age=0");
1580         push (@samba_tool_options, "--history-length=1");
1581
1582         my $samba_tool_cmd = join(" ", @samba_tool_options);
1583
1584         unless (system($samba_tool_cmd) == 0) {
1585                 warn("Unable to set min password age to 0: \n$samba_tool_cmd\n");
1586                 return undef;
1587         }
1588
1589         unless($self->add_wins_config("$prefix/private")) {
1590                 warn("Unable to add wins configuration");
1591                 return undef;
1592         }
1593
1594         return $ret;
1595 }
1596
1597 sub provision_fl2008r2dc($$$)
1598 {
1599         my ($self, $prefix, $dcvars) = @_;
1600
1601         print "PROVISIONING DC WITH FOREST LEVEL 2008r2...\n";
1602         my $extra_conf_options = "ldap server require strong auth = no";
1603         my $extra_provision_options = ["--use-ntvfs", "--base-schema=2008_R2"];
1604         my $ret = $self->provision($prefix,
1605                                    "domain controller",
1606                                    "dc7",
1607                                    "SAMBA2008R2",
1608                                    "samba2008R2.example.com",
1609                                    "2008_R2",
1610                                    "locDCpass7",
1611                                    undef,
1612                                    undef,
1613                                    $extra_conf_options,
1614                                    "",
1615                                    $extra_provision_options);
1616         unless (defined $ret) {
1617                 return undef;
1618         }
1619
1620         unless ($self->add_wins_config("$prefix/private")) {
1621                 warn("Unable to add wins configuration");
1622                 return undef;
1623         }
1624         $ret->{DC_REALM} = $ret->{REALM};
1625
1626         return $ret;
1627 }
1628
1629
1630 sub provision_rodc($$$)
1631 {
1632         my ($self, $prefix, $dcvars) = @_;
1633         print "PROVISIONING RODC...\n";
1634
1635         # We do this so that we don't run the provision.  That's the job of 'net join RODC'.
1636         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1637                                                "rodc",
1638                                                $dcvars->{DOMAIN},
1639                                                $dcvars->{REALM},
1640                                                $dcvars->{DOMSID},
1641                                                "2008",
1642                                                $dcvars->{PASSWORD},
1643                                                $dcvars->{SERVER_IP},
1644                                                $dcvars->{SERVER_IPV6});
1645         unless ($ctx) {
1646                 return undef;
1647         }
1648
1649         push (@{$ctx->{provision_options}}, "--use-ntvfs");
1650
1651         $ctx->{share} = "$ctx->{prefix_abs}/share";
1652         push(@{$ctx->{directories}}, "$ctx->{share}");
1653
1654         $ctx->{smb_conf_extra_options} = "
1655         max xmit = 32K
1656         server max protocol = SMB2
1657         password server = $dcvars->{DC_SERVER}
1658
1659 [sysvol]
1660         path = $ctx->{statedir}/sysvol
1661         read only = yes
1662
1663 [netlogon]
1664         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1665         read only = yes
1666
1667 [tmp]
1668         path = $ctx->{share}
1669         read only = no
1670         posix:sharedelay = 10000
1671         posix:oplocktimeout = 3
1672         posix:writetimeupdatedelay = 50000
1673
1674 ";
1675
1676         my $ret = $self->provision_raw_step1($ctx);
1677         unless ($ret) {
1678                 return undef;
1679         }
1680
1681         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1682         my $cmd = $self->get_cmd_env_vars($ret);
1683         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} RODC";
1684         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1685         $cmd .= " --server=$dcvars->{DC_SERVER} --use-ntvfs";
1686
1687         unless (system($cmd) == 0) {
1688                 warn("RODC join failed\n$cmd");
1689                 return undef;
1690         }
1691
1692         # This ensures deterministic behaviour for tests that want to have the 'testallowed account'
1693         # user password verified on the RODC
1694         my $testallowed_account = "testallowed account";
1695         $cmd = "KRB5_CONFIG=\"$ret->{KRB5_CONFIG}\" ";
1696         $cmd .= "KRB5CCNAME=\"$ret->{KRB5_CCACHE}\" ";
1697         $cmd .= "RESOLV_CONF=\"$ret->{RESOLV_CONF}\" ";
1698         $cmd .= "$samba_tool rodc preload '$testallowed_account' $ret->{CONFIGURATION}";
1699         $cmd .= " --server=$dcvars->{DC_SERVER}";
1700
1701         unless (system($cmd) == 0) {
1702                 warn("RODC join failed\n$cmd");
1703                 return undef;
1704         }
1705
1706         # we overwrite the kdc after the RODC join
1707         # so that use the RODC as kdc and test
1708         # the proxy code
1709         $ctx->{kdc_ipv4} = $ret->{SERVER_IP};
1710         $ctx->{kdc_ipv6} = $ret->{SERVER_IPV6};
1711         Samba::mk_krb5_conf($ctx);
1712         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
1713
1714         $self->set_pdc_env_vars($ret, $dcvars);
1715
1716         return $ret;
1717 }
1718
1719 sub read_config_h($)
1720 {
1721         my ($name) = @_;
1722         my %ret = {};
1723         open(LF, "<$name") or die("unable to read $name: $!");
1724         while (<LF>) {
1725                 chomp;
1726                 next if not (/^#define /);
1727                 if (/^#define (.*?)[ \t]+(.*?)$/) {
1728                         $ret{$1} = $2;
1729                         next;
1730                 }
1731                 if (/^#define (.*?)[ \t]+$/) {
1732                         $ret{$1} = 1;;
1733                         next;
1734                 }
1735         }
1736         close(LF);
1737         return \%ret;
1738 }
1739
1740 sub provision_ad_dc($$$$$$)
1741 {
1742         my ($self, $prefix, $hostname, $domain, $realm, $smbconf_args,
1743                 $extra_provision_options) = @_;
1744
1745         my $prefix_abs = abs_path($prefix);
1746
1747         my $bindir_abs = abs_path($self->{bindir});
1748         my $lockdir="$prefix_abs/lockdir";
1749         my $conffile="$prefix_abs/etc/smb.conf";
1750
1751         my $require_mutexes = "dbwrap_tdb_require_mutexes:* = yes";
1752         $require_mutexes = "" if ($ENV{SELFTEST_DONT_REQUIRE_TDB_MUTEX_SUPPORT} eq "1");
1753
1754         my $config_h = {};
1755
1756         if (defined($ENV{CONFIG_H})) {
1757                 $config_h = read_config_h($ENV{CONFIG_H});
1758         }
1759
1760         my $password_hash_gpg_key_ids = "password hash gpg key ids = 4952E40301FAB41A";
1761         $password_hash_gpg_key_ids = "" unless defined($config_h->{HAVE_GPGME});
1762
1763         my $extra_smbconf_options = "
1764         xattr_tdb:file = $prefix_abs/statedir/xattr.tdb
1765
1766         dbwrap_tdb_mutexes:* = yes
1767         ${require_mutexes}
1768
1769         ${password_hash_gpg_key_ids}
1770
1771         kernel oplocks = no
1772         kernel change notify = no
1773         smb2 leases = no
1774
1775         logging = file
1776         printing = bsd
1777         printcap name = /dev/null
1778
1779         max protocol = SMB3
1780         read only = no
1781
1782         smbd:sharedelay = 100000
1783         smbd:writetimeupdatedelay = 500000
1784         create mask = 755
1785         dos filemode = yes
1786         check parent directory delete on close = yes
1787
1788         dcerpc endpoint servers = -winreg -srvsvc
1789
1790         printcap name = /dev/null
1791
1792         addprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -a -s $conffile --
1793         deleteprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -d -s $conffile --
1794
1795         printing = vlp
1796         print command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb print %p %s
1797         lpq command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpq %p
1798         lp rm command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lprm %p %j
1799         lp pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lppause %p %j
1800         lp resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpresume %p %j
1801         queue pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queuepause %p
1802         queue resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queueresume %p
1803         lpq cache time = 0
1804         print notify backchannel = yes
1805
1806         server schannel = auto
1807         auth event notification = true
1808         dsdb event notification = true
1809         dsdb password event notification = true
1810         dsdb group change notification = true
1811         $smbconf_args
1812 ";
1813
1814         my $extra_smbconf_shares = "
1815
1816 [tmpenc]
1817         copy = tmp
1818         smb encrypt = required
1819
1820 [tmpcase]
1821         copy = tmp
1822         case sensitive = yes
1823
1824 [tmpguest]
1825         copy = tmp
1826         guest ok = yes
1827
1828 [hideunread]
1829         copy = tmp
1830         hide unreadable = yes
1831
1832 [durable]
1833         copy = tmp
1834         kernel share modes = no
1835         kernel oplocks = no
1836         posix locking = no
1837
1838 [print\$]
1839         copy = tmp
1840
1841 [print1]
1842         copy = tmp
1843         printable = yes
1844
1845 [print2]
1846         copy = print1
1847 [print3]
1848         copy = print1
1849 [lp]
1850         copy = print1
1851 ";
1852
1853         push (@{$extra_provision_options}, "--backend-store=mdb");
1854         print "PROVISIONING AD DC...\n";
1855         my $ret = $self->provision($prefix,
1856                                    "domain controller",
1857                                    $hostname,
1858                                    $domain,
1859                                    $realm,
1860                                    "2008",
1861                                    "locDCpass1",
1862                                    undef,
1863                                    undef,
1864                                    $extra_smbconf_options,
1865                                    $extra_smbconf_shares,
1866                                    $extra_provision_options);
1867         unless (defined $ret) {
1868                 return undef;
1869         }
1870
1871         unless($self->add_wins_config("$prefix/private")) {
1872                 warn("Unable to add wins configuration");
1873                 return undef;
1874         }
1875
1876         return $ret;
1877 }
1878
1879 sub provision_chgdcpass($$)
1880 {
1881         my ($self, $prefix) = @_;
1882
1883         print "PROVISIONING CHGDCPASS...\n";
1884         # This environment disallows the use of this password
1885         # (and also removes the default AD complexity checks)
1886         my $unacceptable_password = "Paßßword-widk3Dsle32jxdBdskldsk55klASKQ";
1887         my $extra_smb_conf = "
1888         check password script = $self->{srcdir}/selftest/checkpassword_arg1.sh ${unacceptable_password}
1889         allow dcerpc auth level connect:lsarpc = yes
1890         dcesrv:max auth states = 8
1891 ";
1892         my $extra_provision_options = ["--use-ntvfs"];
1893         push (@{$extra_provision_options}, "--dns-backend=BIND9_DLZ");
1894         my $ret = $self->provision($prefix,
1895                                    "domain controller",
1896                                    "chgdcpass",
1897                                    "CHDCDOMAIN",
1898                                    "chgdcpassword.samba.example.com",
1899                                    "2008",
1900                                    "chgDCpass1",
1901                                    undef,
1902                                    undef,
1903                                    $extra_smb_conf,
1904                                    "",
1905                                    $extra_provision_options);
1906         unless (defined $ret) {
1907                 return undef;
1908         }
1909
1910         unless($self->add_wins_config("$prefix/private")) {
1911                 warn("Unable to add wins configuration");
1912                 return undef;
1913         }
1914         
1915         # Remove secrets.tdb from this environment to test that we
1916         # still start up on systems without the new matching
1917         # secrets.tdb records.
1918         unless (unlink("$ret->{PRIVATEDIR}/secrets.tdb") || unlink("$ret->{PRIVATEDIR}/secrets.ntdb")) {
1919                 warn("Unable to remove $ret->{PRIVATEDIR}/secrets.tdb added during provision");
1920                 return undef;
1921         }
1922
1923         $ret->{UNACCEPTABLE_PASSWORD} = $unacceptable_password;
1924
1925         return $ret;
1926 }
1927
1928 sub teardown_env_terminate($$)
1929 {
1930         my ($self, $envvars) = @_;
1931         my $pid;
1932
1933         # This should cause samba to terminate gracefully
1934         my $smbcontrol = Samba::bindir_path($self, "smbcontrol");
1935         my $cmd = "";
1936         $cmd .= "$smbcontrol samba shutdown $envvars->{CONFIGURATION}";
1937         my $ret = system($cmd);
1938         if ($ret != 0) {
1939                 warn "'$cmd' failed with '$ret'\n";
1940         }
1941
1942         # This should cause samba to terminate gracefully
1943         close($envvars->{STDIN_PIPE});
1944
1945         $pid = $envvars->{SAMBA_PID};
1946         my $count = 0;
1947         my $childpid;
1948
1949         # This should give it time to write out the gcov data
1950         until ($count > 15) {
1951             if (Samba::cleanup_child($pid, "samba") != 0) {
1952                 return;
1953             }
1954             sleep(1);
1955             $count++;
1956         }
1957
1958         # After 15 Seconds, work out why this thing is still alive
1959         warn "server process $pid took more than $count seconds to exit, showing backtrace:\n";
1960         system("$self->{srcdir}/selftest/gdb_backtrace $pid");
1961
1962         until ($count > 30) {
1963             if (Samba::cleanup_child($pid, "samba") != 0) {
1964                 return;
1965             }
1966             sleep(1);
1967             $count++;
1968         }
1969
1970         if (kill(0, $pid)) {
1971             warn "server process $pid took more than $count seconds to exit, sending SIGTERM\n";
1972             kill "TERM", $pid;
1973         }
1974
1975         until ($count > 40) {
1976             if (Samba::cleanup_child($pid, "samba") != 0) {
1977                 return;
1978             }
1979             sleep(1);
1980             $count++;
1981         }
1982         # If it is still around, kill it
1983         if (kill(0, $pid)) {
1984             warn "server process $pid took more than $count seconds to exit, killing\n with SIGKILL\n";
1985             kill 9, $pid;
1986         }
1987         return;
1988 }
1989
1990 sub teardown_env($$)
1991 {
1992         my ($self, $envvars) = @_;
1993         teardown_env_terminate($self, $envvars);
1994
1995         print $self->getlog_env($envvars);
1996
1997         return;
1998 }
1999
2000 sub getlog_env($$)
2001 {
2002         my ($self, $envvars) = @_;
2003         my $title = "SAMBA LOG of: $envvars->{NETBIOSNAME} pid $envvars->{SAMBA_PID}\n";
2004         my $out = $title;
2005
2006         open(LOG, "<$envvars->{SAMBA_TEST_LOG}");
2007
2008         seek(LOG, $envvars->{SAMBA_TEST_LOG_POS}, SEEK_SET);
2009         while (<LOG>) {
2010                 $out .= $_;
2011         }
2012         $envvars->{SAMBA_TEST_LOG_POS} = tell(LOG);
2013         close(LOG);
2014
2015         return "" if $out eq $title;
2016
2017         return $out;
2018 }
2019
2020 sub check_env($$)
2021 {
2022         my ($self, $envvars) = @_;
2023         my $samba_pid = $envvars->{SAMBA_PID};
2024
2025         if (not defined($samba_pid)) {
2026             return 0;
2027         } elsif ($samba_pid > 0) {
2028             my $childpid = Samba::cleanup_child($samba_pid, "samba");
2029
2030             if ($childpid == 0) {
2031                 return 1;
2032             }
2033             return 0;
2034         } else {
2035             return 1;
2036         }
2037 }
2038
2039 # Declare the environments Samba4 makes available.
2040 # To be set up, they will be called as
2041 #   samba4->setup_$envname($self, $path, $dep_1_vars, $dep_2_vars, ...)
2042 # The interdependencies between the testenvs are declared below. Some testenvs
2043 # are dependent on another testenv running first, e.g. vampire_dc is dependent
2044 # on ad_dc_ntvfs because vampire_dc joins ad_dc_ntvfs's domain. All DCs are
2045 # dependent on dns_hub, which handles resolving DNS queries for the realm.
2046 %Samba4::ENV_DEPS = (
2047         # name               => [dep_1, dep_2, ...],
2048         dns_hub              => [],
2049         ad_dc_ntvfs          => ["dns_hub"],
2050         ad_dc                => ["dns_hub"],
2051         ad_dc_no_nss         => ["dns_hub"],
2052         ad_dc_no_ntlm        => ["dns_hub"],
2053
2054         fl2008r2dc           => ["ad_dc"],
2055         fl2003dc             => ["ad_dc"],
2056         fl2000dc             => ["ad_dc"],
2057
2058         vampire_2000_dc      => ["fl2000dc"],
2059         vampire_dc           => ["ad_dc_ntvfs"],
2060         promoted_dc          => ["ad_dc_ntvfs"],
2061
2062         rodc                 => ["ad_dc_ntvfs"],
2063         rpc_proxy            => ["ad_dc_ntvfs"],
2064         chgdcpass            => ["dns_hub"],
2065
2066         s4member_dflt_domain => ["ad_dc_ntvfs"],
2067         s4member             => ["ad_dc_ntvfs"],
2068
2069         # envs that test the server process model
2070         proclimitdc          => ["dns_hub"],
2071         preforkrestartdc     => ["dns_hub"],
2072
2073         # backup/restore testenvs
2074         backupfromdc         => ["dns_hub"],
2075         customdc             => ["dns_hub"],
2076         restoredc            => ["backupfromdc"],
2077         renamedc             => ["backupfromdc"],
2078         offlinebackupdc      => ["backupfromdc"],
2079         labdc                => ["backupfromdc"],
2080
2081         # aliases in order to split autbuild tasks
2082         fl2008dc             => ["ad_dc_ntvfs"],
2083         ad_dc_default        => ["ad_dc_ntvfs"],
2084         ad_dc_slowtests      => ["ad_dc_ntvfs"],
2085         ad_dc_backup         => ["ad_dc"],
2086
2087         schema_dc      => ["dns_hub"],
2088         schema_pair_dc => ["schema_dc"],
2089
2090         none                 => [],
2091 );
2092
2093 %Samba4::ENV_DEPS_POST = (
2094         schema_dc => ["schema_pair_dc"],
2095 );
2096
2097 sub return_alias_env
2098 {
2099         my ($self, $path, $env) = @_;
2100
2101         # just an alias
2102         return $env;
2103 }
2104
2105 sub setup_fl2008dc
2106 {
2107         my ($self, $path) = @_;
2108
2109         my $extra_args = ["--base-schema=2008_R2"];
2110         my $env = $self->provision_ad_dc_ntvfs($path, $extra_args);
2111         if (defined $env) {
2112                 if (not defined($self->check_or_start($env, "standard"))) {
2113                     warn("Failed to start fl2008dc");
2114                         return undef;
2115                 }
2116         }
2117         return $env;
2118 }
2119
2120 sub setup_ad_dc_default
2121 {
2122         my ($self, $path, $dep_env) = @_;
2123         return $self->return_alias_env($path, $dep_env)
2124 }
2125
2126 sub setup_ad_dc_slowtests
2127 {
2128         my ($self, $path, $dep_env) = @_;
2129         return $self->return_alias_env($path, $dep_env)
2130 }
2131
2132 sub setup_ad_dc_backup
2133 {
2134         my ($self, $path, $dep_env) = @_;
2135         return $self->return_alias_env($path, $dep_env)
2136 }
2137
2138 sub setup_s4member
2139 {
2140         my ($self, $path, $dc_vars) = @_;
2141
2142         my $env = $self->provision_s4member($path, $dc_vars, "s4member");
2143
2144         if (defined $env) {
2145                 if (not defined($self->check_or_start($env, "standard"))) {
2146                         return undef;
2147                 }
2148         }
2149
2150         return $env;
2151 }
2152
2153 sub setup_s4member_dflt_domain
2154 {
2155         my ($self, $path, $dc_vars) = @_;
2156
2157         my $env = $self->provision_s4member($path, $dc_vars, "s4member_dflt",
2158                                             "winbind use default domain = yes");
2159
2160         if (defined $env) {
2161                 if (not defined($self->check_or_start($env, "standard"))) {
2162                         return undef;
2163                 }
2164         }
2165
2166         return $env;
2167 }
2168
2169 sub setup_rpc_proxy
2170 {
2171         my ($self, $path, $dc_vars) = @_;
2172
2173         my $env = $self->provision_rpc_proxy($path, $dc_vars);
2174
2175         if (defined $env) {
2176                 if (not defined($self->check_or_start($env, "standard"))) {
2177                         return undef;
2178                 }
2179         }
2180         return $env;
2181 }
2182
2183 sub setup_ad_dc_ntvfs
2184 {
2185         my ($self, $path) = @_;
2186
2187         my $env = $self->provision_ad_dc_ntvfs($path, undef);
2188         if (defined $env) {
2189                 if (not defined($self->check_or_start($env, "standard"))) {
2190                     warn("Failed to start ad_dc_ntvfs");
2191                         return undef;
2192                 }
2193         }
2194         return $env;
2195 }
2196
2197 sub setup_chgdcpass
2198 {
2199         my ($self, $path) = @_;
2200
2201         my $env = $self->provision_chgdcpass($path);
2202         if (defined $env) {
2203                 if (not defined($self->check_or_start($env, "standard"))) {
2204                         return undef;
2205                 }
2206         }
2207         return $env;
2208 }
2209
2210 sub setup_fl2000dc
2211 {
2212         my ($self, $path, $dc_vars) = @_;
2213
2214         my $env = $self->provision_fl2000dc($path);
2215         if (defined $env) {
2216                 if (not defined($self->check_or_start($env, "standard"))) {
2217                         return undef;
2218                 }
2219
2220                 $env = $self->setup_trust($env, $dc_vars, "external", "--no-aes-keys --direction=incoming");
2221         }
2222
2223         return $env;
2224 }
2225
2226 sub setup_fl2003dc
2227 {
2228         my ($self, $path, $dc_vars) = @_;
2229
2230         my $env = $self->provision_fl2003dc($path);
2231
2232         if (defined $env) {
2233                 if (not defined($self->check_or_start($env, "standard"))) {
2234                         return undef;
2235                 }
2236
2237                 $env = $self->setup_trust($env, $dc_vars, "external", "--no-aes-keys");
2238         }
2239         return $env;
2240 }
2241
2242 sub setup_fl2008r2dc
2243 {
2244         my ($self, $path, $dc_vars) = @_;
2245
2246         my $env = $self->provision_fl2008r2dc($path);
2247
2248         if (defined $env) {
2249                 if (not defined($self->check_or_start($env, "standard"))) {
2250                         return undef;
2251                 }
2252
2253                 my $upn_array = ["$env->{REALM}.upn"];
2254                 my $spn_array = ["$env->{REALM}.spn"];
2255
2256                 $self->setup_namespaces($env, $upn_array, $spn_array);
2257
2258                 $env = $self->setup_trust($env, $dc_vars, "forest", "");
2259         }
2260
2261         return $env;
2262 }
2263
2264 sub setup_vampire_dc
2265 {
2266         return setup_generic_vampire_dc(@_, "2008");
2267 }
2268
2269 sub setup_vampire_2000_dc
2270 {
2271         return setup_generic_vampire_dc(@_, "2000");
2272 }
2273
2274 sub setup_generic_vampire_dc
2275 {
2276         my ($self, $path, $dc_vars, $fl) = @_;
2277
2278         my $env = $self->provision_vampire_dc($path, $dc_vars, $fl);
2279
2280         if (defined $env) {
2281                 if (not defined($self->check_or_start($env, "single"))) {
2282                         return undef;
2283                 }
2284
2285                 # force replicated DC to update repsTo/repsFrom
2286                 # for vampired partitions
2287                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2288
2289                 # as 'vampired' dc may add data in its local replica
2290                 # we need to synchronize data between DCs
2291                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2292                 my $cmd = $self->get_cmd_env_vars($env);
2293                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2294                 $cmd .= " $dc_vars->{CONFIGURATION}";
2295                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2296                 # replicate Configuration NC
2297                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2298                 unless(system($cmd_repl) == 0) {
2299                         warn("Failed to replicate\n$cmd_repl");
2300                         return undef;
2301                 }
2302                 # replicate Default NC
2303                 $cmd_repl = "$cmd \"$base_dn\"";
2304                 unless(system($cmd_repl) == 0) {
2305                         warn("Failed to replicate\n$cmd_repl");
2306                         return undef;
2307                 }
2308
2309                 # Pull in a full set of changes from the main DC
2310                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2311                 $cmd = $self->get_cmd_env_vars($env);
2312                 $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2313                 $cmd .= " $dc_vars->{CONFIGURATION}";
2314                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2315                 # replicate Configuration NC
2316                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2317                 unless(system($cmd_repl) == 0) {
2318                         warn("Failed to replicate\n$cmd_repl");
2319                         return undef;
2320                 }
2321                 # replicate Default NC
2322                 $cmd_repl = "$cmd \"$base_dn\"";
2323                 unless(system($cmd_repl) == 0) {
2324                         warn("Failed to replicate\n$cmd_repl");
2325                         return undef;
2326                 }
2327         }
2328
2329         return $env;
2330 }
2331
2332 sub setup_promoted_dc
2333 {
2334         my ($self, $path, $dc_vars) = @_;
2335
2336         my $env = $self->provision_promoted_dc($path, $dc_vars);
2337
2338         if (defined $env) {
2339                 if (not defined($self->check_or_start($env, "single"))) {
2340                         return undef;
2341                 }
2342
2343                 # force source and replicated DC to update repsTo/repsFrom
2344                 # for vampired partitions
2345                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2346                 my $cmd = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2347                 # as 'vampired' dc may add data in its local replica
2348                 # we need to synchronize data between DCs
2349                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2350                 $cmd = "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\"";
2351                 $cmd .= " KRB5_CONFIG=\"$env->{KRB5_CONFIG}\"";
2352                 $cmd .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2353                 $cmd .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2354                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2355                 $cmd .= " $dc_vars->{CONFIGURATION}";
2356                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2357                 # replicate Configuration NC
2358                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2359                 unless(system($cmd_repl) == 0) {
2360                         warn("Failed to replicate\n$cmd_repl");
2361                         return undef;
2362                 }
2363                 # replicate Default NC
2364                 $cmd_repl = "$cmd \"$base_dn\"";
2365                 unless(system($cmd_repl) == 0) {
2366                         warn("Failed to replicate\n$cmd_repl");
2367                         return undef;
2368                 }
2369         }
2370
2371         return $env;
2372 }
2373
2374 sub setup_rodc
2375 {
2376         my ($self, $path, $dc_vars) = @_;
2377
2378         my $env = $self->provision_rodc($path, $dc_vars);
2379
2380         unless ($env) {
2381                 return undef;
2382         }
2383
2384         if (not defined($self->check_or_start($env, "standard"))) {
2385             return undef;
2386         }
2387
2388         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2389         my $cmd = "";
2390
2391         my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2392         $cmd .= "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2393         $cmd .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\"";
2394         $cmd .= " KRB5_CONFIG=\"$env->{KRB5_CONFIG}\"";
2395         $cmd .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2396         $cmd .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2397         $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2398         $cmd .= " $dc_vars->{CONFIGURATION}";
2399         $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2400         # replicate Configuration NC
2401         my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2402         unless(system($cmd_repl) == 0) {
2403             warn("Failed to replicate\n$cmd_repl");
2404             return undef;
2405         }
2406         # replicate Default NC
2407         $cmd_repl = "$cmd \"$base_dn\"";
2408         unless(system($cmd_repl) == 0) {
2409             warn("Failed to replicate\n$cmd_repl");
2410             return undef;
2411         }
2412
2413         return $env;
2414 }
2415
2416 sub setup_ad_dc
2417 {
2418         my ($self, $path) = @_;
2419
2420         # If we didn't build with ADS, pretend this env was never available
2421         if (not $self->{target3}->have_ads()) {
2422                return "UNKNOWN";
2423         }
2424
2425         my $env = $self->provision_ad_dc($path, "addc", "ADDOMAIN",
2426                                          "addom.samba.example.com", "", undef);
2427         unless ($env) {
2428                 return undef;
2429         }
2430
2431         if (not defined($self->check_or_start($env, "prefork"))) {
2432             return undef;
2433         }
2434
2435         my $upn_array = ["$env->{REALM}.upn"];
2436         my $spn_array = ["$env->{REALM}.spn"];
2437
2438         $self->setup_namespaces($env, $upn_array, $spn_array);
2439
2440         return $env;
2441 }
2442
2443 sub setup_ad_dc_no_nss
2444 {
2445         my ($self, $path) = @_;
2446
2447         # If we didn't build with ADS, pretend this env was never available
2448         if (not $self->{target3}->have_ads()) {
2449                return "UNKNOWN";
2450         }
2451
2452         my $env = $self->provision_ad_dc($path, "addc_no_nss", "ADNONSSDOMAIN",
2453                                          "adnonssdom.samba.example.com", "", undef);
2454         unless ($env) {
2455                 return undef;
2456         }
2457
2458         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2459         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2460
2461         if (not defined($self->check_or_start($env, "single"))) {
2462             return undef;
2463         }
2464
2465         my $upn_array = ["$env->{REALM}.upn"];
2466         my $spn_array = ["$env->{REALM}.spn"];
2467
2468         $self->setup_namespaces($env, $upn_array, $spn_array);
2469
2470         return $env;
2471 }
2472
2473 sub setup_ad_dc_no_ntlm
2474 {
2475         my ($self, $path) = @_;
2476
2477         # If we didn't build with ADS, pretend this env was never available
2478         if (not $self->{target3}->have_ads()) {
2479                return "UNKNOWN";
2480         }
2481
2482         my $env = $self->provision_ad_dc($path, "addc_no_ntlm", "ADNONTLMDOMAIN",
2483                                          "adnontlmdom.samba.example.com",
2484                                          "ntlm auth = disabled", undef);
2485         unless ($env) {
2486                 return undef;
2487         }
2488
2489         if (not defined($self->check_or_start($env, "prefork"))) {
2490             return undef;
2491         }
2492
2493         my $upn_array = ["$env->{REALM}.upn"];
2494         my $spn_array = ["$env->{REALM}.spn"];
2495
2496         $self->setup_namespaces($env, $upn_array, $spn_array);
2497
2498         return $env;
2499 }
2500
2501 #
2502 # AD DC test environment used solely to test pre-fork process restarts.
2503 # As processes get killed off and restarted it should not be used for other
2504 sub setup_preforkrestartdc
2505 {
2506         my ($self, $path) = @_;
2507
2508         # If we didn't build with ADS, pretend this env was never available
2509         if (not $self->{target3}->have_ads()) {
2510                return "UNKNOWN";
2511         }
2512
2513         # note DC name must be <= 15 chars so we use 'prockill' instead of
2514         # 'preforkrestart'
2515         my $env = $self->provision_ad_dc(
2516                 $path,
2517                 "prockilldc",
2518                 "PROCKILLDOMAIN",
2519                 "prockilldom.samba.example.com",
2520                 "prefork backoff increment = 5\nprefork maximum backoff=10");
2521         unless ($env) {
2522                 return undef;
2523         }
2524
2525         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2526         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2527
2528         if (not defined($self->check_or_start($env, "prefork"))) {
2529             return undef;
2530         }
2531
2532         my $upn_array = ["$env->{REALM}.upn"];
2533         my $spn_array = ["$env->{REALM}.spn"];
2534
2535         $self->setup_namespaces($env, $upn_array, $spn_array);
2536
2537         return $env;
2538 }
2539
2540 #
2541 # ad_dc test environment used solely to test standard process model connection
2542 # process limits. As the limit is set artificially low it should not be used
2543 # for other tests.
2544 sub setup_proclimitdc
2545 {
2546         my ($self, $path) = @_;
2547
2548         # If we didn't build with ADS, pretend this env was never available
2549         if (not $self->{target3}->have_ads()) {
2550                return "UNKNOWN";
2551         }
2552
2553         my $env = $self->provision_ad_dc(
2554                 $path,
2555                 "proclimitdc",
2556                 "PROCLIMITDOM",
2557                 "proclimit.samba.example.com",
2558                 "max smbd processes = 20");
2559         unless ($env) {
2560                 return undef;
2561         }
2562
2563         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2564         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2565
2566         if (not defined($self->check_or_start($env, "standard"))) {
2567             return undef;
2568         }
2569
2570         my $upn_array = ["$env->{REALM}.upn"];
2571         my $spn_array = ["$env->{REALM}.spn"];
2572
2573         $self->setup_namespaces($env, $upn_array, $spn_array);
2574
2575         return $env;
2576 }
2577
2578 # Used to test a live upgrade of the schema on a 2 DC network.
2579 sub setup_schema_dc
2580 {
2581         my ($self, $path) = @_;
2582
2583         # provision the PDC using an older base schema
2584         my $provision_args = ["--base-schema=2008_R2", "--backend-store=mdb"];
2585
2586         my $env = $self->provision_ad_dc($path, "liveupgrade1dc", "SCHEMADOMAIN",
2587                                          "schema.samba.example.com",
2588                                          "drs: max link sync = 2",
2589                                          $provision_args);
2590         unless ($env) {
2591                 return undef;
2592         }
2593
2594         if (not defined($self->check_or_start($env, "prefork"))) {
2595             return undef;
2596         }
2597
2598         my $upn_array = ["$env->{REALM}.upn"];
2599         my $spn_array = ["$env->{REALM}.spn"];
2600
2601         $self->setup_namespaces($env, $upn_array, $spn_array);
2602
2603         return $env;
2604 }
2605
2606 # the second DC in the live schema upgrade pair
2607 sub setup_schema_pair_dc
2608 {
2609         # note: dcvars contains the env info for the dependent testenv ('schema_dc')
2610         my ($self, $prefix, $dcvars) = @_;
2611         print "Preparing SCHEMA UPGRADE PAIR DC...\n";
2612
2613         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "liveupgrade2dc",
2614                                                     $dcvars->{DOMAIN},
2615                                                     $dcvars->{REALM},
2616                                                     $dcvars->{PASSWORD},
2617                                                     "");
2618
2619         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2620         my $cmd_vars = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2621         $cmd_vars .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
2622         if (defined($env->{RESOLV_WRAPPER_CONF})) {
2623                 $cmd_vars .= "RESOLV_WRAPPER_CONF=\"$env->{RESOLV_WRAPPER_CONF}\" ";
2624         } else {
2625                 $cmd_vars .= "RESOLV_WRAPPER_HOSTS=\"$env->{RESOLV_WRAPPER_HOSTS}\" ";
2626         }
2627         $cmd_vars .= "KRB5_CONFIG=\"$env->{KRB5_CONFIG}\" ";
2628         $cmd_vars .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2629         $cmd_vars .= "RESOLV_CONF=\"$env->{RESOLV_CONF}\" ";
2630
2631         my $join_cmd = $cmd_vars;
2632         $join_cmd .= "$samba_tool domain join $env->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
2633         $join_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} ";
2634         $join_cmd .= " --backend-store=mdb";
2635
2636         my $upgrade_cmd = $cmd_vars;
2637         $upgrade_cmd .= "$samba_tool domain schemaupgrade $dcvars->{CONFIGURATION}";
2638         $upgrade_cmd .= " -U$dcvars->{USERNAME}\%$dcvars->{PASSWORD}";
2639
2640         my $repl_cmd = $cmd_vars;
2641         $repl_cmd .= "$samba_tool drs replicate $env->{SERVER} $dcvars->{SERVER}";
2642         $repl_cmd .= " CN=Schema,CN=Configuration,DC=schema,DC=samba,DC=example,DC=com";
2643         $repl_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
2644
2645         unless (system($join_cmd) == 0) {
2646                 warn("Join failed\n$join_cmd");
2647                 return undef;
2648         }
2649
2650         $env->{DC_SERVER} = $dcvars->{SERVER};
2651         $env->{DC_SERVER_IP} = $dcvars->{SERVER_IP};
2652         $env->{DC_SERVER_IPV6} = $dcvars->{SERVER_IPV6};
2653         $env->{DC_NETBIOSNAME} = $dcvars->{NETBIOSNAME};
2654
2655         # start samba for the new DC
2656         if (not defined($self->check_or_start($env, "standard"))) {
2657             return undef;
2658         }
2659
2660         unless (system($upgrade_cmd) == 0) {
2661                 warn("Schema upgrade failed\n$upgrade_cmd");
2662                 return undef;
2663         }
2664
2665         unless (system($repl_cmd) == 0) {
2666                 warn("Post-update schema replication failed\n$repl_cmd");
2667                 return undef;
2668         }
2669
2670         return $env;
2671 }
2672
2673 # Sets up a DC that's solely used to do a domain backup from. We then use the
2674 # backupfrom-DC to create the restore-DC - this proves that the backup/restore
2675 # process will create a Samba DC that will actually start up.
2676 # We don't use the backup-DC for anything else because its domain will conflict
2677 # with the restore DC.
2678 sub setup_backupfromdc
2679 {
2680         my ($self, $path) = @_;
2681
2682         # If we didn't build with ADS, pretend this env was never available
2683         if (not $self->{target3}->have_ads()) {
2684                return "UNKNOWN";
2685         }
2686
2687         my $provision_args = ["--site=Backup-Site"];
2688
2689         my $env = $self->provision_ad_dc($path, "backupfromdc", "BACKUPDOMAIN",
2690                                          "backupdom.samba.example.com",
2691                                          "samba kcc command = /bin/true",
2692                                          $provision_args);
2693         unless ($env) {
2694                 return undef;
2695         }
2696
2697         if (not defined($self->check_or_start($env))) {
2698             return undef;
2699         }
2700
2701         my $upn_array = ["$env->{REALM}.upn"];
2702         my $spn_array = ["$env->{REALM}.spn"];
2703
2704         $self->setup_namespaces($env, $upn_array, $spn_array);
2705
2706         return $env;
2707 }
2708
2709 # returns the server/user-auth params needed to run an online backup cmd
2710 sub get_backup_server_args
2711 {
2712         # dcvars contains the env info for the backup DC testenv
2713         my ($self, $dcvars) = @_;
2714         my $server = $dcvars->{DC_SERVER_IP};
2715         my $server_args = "--server=$server ";
2716         $server_args .= "-U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
2717         $server_args .= " $dcvars->{CONFIGURATION}";
2718
2719         return $server_args;
2720 }
2721
2722 # Creates a backup of a running testenv DC
2723 sub create_backup
2724 {
2725         # note: dcvars contains the env info for the backup DC testenv
2726         my ($self, $env, $dcvars, $backupdir, $backup_cmd) = @_;
2727
2728         # get all the env variables we pass in with the samba-tool command
2729         my $cmd_env = "NSS_WRAPPER_HOSTS='$env->{NSS_WRAPPER_HOSTS}' ";
2730         $cmd_env .= "SOCKET_WRAPPER_DEFAULT_IFACE=\"$env->{SOCKET_WRAPPER_DEFAULT_IFACE}\" ";
2731         if (defined($env->{RESOLV_WRAPPER_CONF})) {
2732                 $cmd_env .= "RESOLV_WRAPPER_CONF=\"$env->{RESOLV_WRAPPER_CONF}\" ";
2733         } else {
2734                 $cmd_env .= "RESOLV_WRAPPER_HOSTS=\"$env->{RESOLV_WRAPPER_HOSTS}\" ";
2735         }
2736         # Note: use the backupfrom-DC's krb5.conf to do the backup
2737         $cmd_env .= " KRB5_CONFIG=\"$dcvars->{KRB5_CONFIG}\" ";
2738         $cmd_env .= "KRB5CCNAME=\"$env->{KRB5_CCACHE}\" ";
2739
2740         # use samba-tool to create a backup from the 'backupfromdc' DC
2741         my $cmd = "";
2742         my $samba_tool = Samba::bindir_path($self, "samba-tool");
2743
2744         $cmd .= "$cmd_env $samba_tool domain backup $backup_cmd";
2745         $cmd .= " --targetdir=$backupdir";
2746
2747         print "Executing: $cmd\n";
2748         unless(system($cmd) == 0) {
2749                 warn("Failed to create backup using: \n$cmd");
2750                 return undef;
2751         }
2752
2753         # get the name of the backup file created
2754         opendir(DIR, $backupdir);
2755         my @files = grep(/\.tar/, readdir(DIR));
2756         closedir(DIR);
2757
2758         if(scalar @files != 1) {
2759                 warn("Backup file not found in directory $backupdir\n");
2760                 return undef;
2761         }
2762         my $backup_file = "$backupdir/$files[0]";
2763         print "Using backup file $backup_file...\n";
2764
2765         return $backup_file;
2766 }
2767
2768 # Restores a backup-file to populate a testenv for a new DC
2769 sub restore_backup_file
2770 {
2771         my ($self, $backup_file, $restore_opts, $restoredir, $smbconf) = @_;
2772
2773         # pass the restore command the testenv's smb.conf that we've already
2774         # generated. But move it to a temp-dir first, so that the restore doesn't
2775         # overwrite it
2776         my $tmpdir = File::Temp->newdir();
2777         my $tmpconf = "$tmpdir/smb.conf";
2778         my $cmd = "cp $smbconf $tmpconf";
2779         unless(system($cmd) == 0) {
2780                 warn("Failed to backup smb.conf using: \n$cmd");
2781                 return -1;
2782         }
2783
2784         my $samba_tool = Samba::bindir_path($self, "samba-tool");
2785         $cmd = "$samba_tool domain backup restore --backup-file=$backup_file";
2786         $cmd .= " --targetdir=$restoredir $restore_opts --configfile=$tmpconf";
2787
2788         print "Executing: $cmd\n";
2789         unless(system($cmd) == 0) {
2790                 warn("Failed to restore backup using: \n$cmd");
2791                 return -1;
2792         }
2793
2794         print "Restore complete\n";
2795         return 0
2796 }
2797
2798 # sets up the initial directory and returns the new testenv's env info
2799 # (without actually doing a 'domain join')
2800 sub prepare_dc_testenv
2801 {
2802         my ($self, $prefix, $dcname, $domain, $realm,
2803                 $password, $conf_options) = @_;
2804
2805         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
2806                                                $dcname,
2807                                                $domain,
2808                                                $realm,
2809                                                undef,
2810                                                "2008",
2811                                                $password,
2812                                                undef,
2813                                                undef);
2814
2815         # the restore uses a slightly different state-dir location to other testenvs
2816         $ctx->{statedir} = "$ctx->{prefix_abs}/state";
2817         push(@{$ctx->{directories}}, "$ctx->{statedir}");
2818
2819         # add support for sysvol/netlogon/tmp shares
2820         $ctx->{share} = "$ctx->{prefix_abs}/share";
2821         push(@{$ctx->{directories}}, "$ctx->{share}");
2822         push(@{$ctx->{directories}}, "$ctx->{share}/test1");
2823
2824         $ctx->{smb_conf_extra_options} = "
2825         $conf_options
2826         max xmit = 32K
2827         server max protocol = SMB2
2828         samba kcc command = /bin/true
2829         xattr_tdb:file = $ctx->{statedir}/xattr.tdb
2830
2831 [sysvol]
2832         path = $ctx->{statedir}/sysvol
2833         read only = no
2834
2835 [netlogon]
2836         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
2837         read only = no
2838
2839 [tmp]
2840         path = $ctx->{share}
2841         read only = no
2842         posix:sharedelay = 10000
2843         posix:oplocktimeout = 3
2844         posix:writetimeupdatedelay = 50000
2845
2846 [test1]
2847         path = $ctx->{share}/test1
2848         read only = no
2849         posix:sharedelay = 100000
2850         posix:oplocktimeout = 3
2851         posix:writetimeupdatedelay = 500000
2852 ";
2853
2854         my $env = $self->provision_raw_step1($ctx);
2855
2856     return ($env, $ctx);
2857 }
2858
2859
2860 # Set up a DC testenv solely by using the samba-tool domain backup/restore
2861 # commands. This proves that we can backup an online DC ('backupfromdc') and
2862 # use the backup file to create a valid, working samba DC.
2863 sub setup_restoredc
2864 {
2865         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
2866         my ($self, $prefix, $dcvars) = @_;
2867         print "Preparing RESTORE DC...\n";
2868
2869         # we arbitrarily designate the restored DC as having SMBv1 disabled
2870         my $extra_conf = "
2871         server min protocol = SMB2
2872         client min protocol = SMB2
2873         prefork children = 1";
2874
2875         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "restoredc",
2876                                                     $dcvars->{DOMAIN},
2877                                                     $dcvars->{REALM},
2878                                                     $dcvars->{PASSWORD},
2879                                                     $extra_conf);
2880
2881         # create a backup of the 'backupfromdc'
2882         my $backupdir = File::Temp->newdir();
2883         my $server_args = $self->get_backup_server_args($dcvars);
2884         my $backup_args = "online $server_args";
2885         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
2886                                                $backup_args);
2887         unless($backup_file) {
2888                 return undef;
2889         }
2890
2891         # restore the backup file to populate the restore-DC testenv
2892         my $restore_dir = abs_path($prefix);
2893         my $ret = $self->restore_backup_file($backup_file,
2894                                              "--newservername=$env->{SERVER}",
2895                                              $restore_dir, $env->{SERVERCONFFILE});
2896         unless ($ret == 0) {
2897                 return undef;
2898         }
2899
2900         # start samba for the restored DC
2901         if (not defined($self->check_or_start($env))) {
2902             return undef;
2903         }
2904
2905         return $env;
2906 }
2907
2908 # Set up a DC testenv solely by using the 'samba-tool domain backup rename' and
2909 # restore commands. This proves that we can backup and rename an online DC
2910 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
2911 sub setup_renamedc
2912 {
2913         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
2914         my ($self, $prefix, $dcvars) = @_;
2915         print "Preparing RENAME DC...\n";
2916         my $extra_conf = "prefork children = 1";
2917
2918         my $realm = "renamedom.samba.example.com";
2919         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "renamedc",
2920                                                     "RENAMEDOMAIN", $realm,
2921                                                     $dcvars->{PASSWORD}, $extra_conf);
2922
2923         # create a backup of the 'backupfromdc' which renames the domain
2924         my $backupdir = File::Temp->newdir();
2925         my $server_args = $self->get_backup_server_args($dcvars);
2926         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
2927         $backup_args .= " --backend-store=tdb";
2928         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
2929                                                $backup_args);
2930         unless($backup_file) {
2931                 return undef;
2932         }
2933
2934         # restore the backup file to populate the rename-DC testenv
2935         my $restore_dir = abs_path($prefix);
2936         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
2937         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
2938                                              $restore_dir, $env->{SERVERCONFFILE});
2939         unless ($ret == 0) {
2940                 return undef;
2941         }
2942
2943         # start samba for the restored DC
2944         if (not defined($self->check_or_start($env))) {
2945             return undef;
2946         }
2947
2948         my $upn_array = ["$env->{REALM}.upn"];
2949         my $spn_array = ["$env->{REALM}.spn"];
2950
2951         $self->setup_namespaces($env, $upn_array, $spn_array);
2952
2953         return $env;
2954 }
2955
2956 # Set up a DC testenv solely by using the 'samba-tool domain backup offline' and
2957 # restore commands. This proves that we do an offline backup of a local DC
2958 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
2959 sub setup_offlinebackupdc
2960 {
2961         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
2962         my ($self, $prefix, $dcvars) = @_;
2963         print "Preparing OFFLINE BACKUP DC...\n";
2964         my $extra_conf = "prefork children = 1";
2965
2966         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "offlinebackupdc",
2967                                                     $dcvars->{DOMAIN},
2968                                                     $dcvars->{REALM},
2969                                                     $dcvars->{PASSWORD}, $extra_conf);
2970
2971         # create an offline backup of the 'backupfromdc' target
2972         my $backupdir = File::Temp->newdir();
2973         my $cmd = "offline -s $dcvars->{SERVERCONFFILE}";
2974         my $backup_file = $self->create_backup($env, $dcvars,
2975                                                $backupdir, $cmd);
2976
2977         unless($backup_file) {
2978                 return undef;
2979         }
2980
2981         # restore the backup file to populate the rename-DC testenv
2982         my $restore_dir = abs_path($prefix);
2983         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
2984         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
2985                                              $restore_dir, $env->{SERVERCONFFILE});
2986         unless ($ret == 0) {
2987                 return undef;
2988         }
2989
2990         # re-create the testenv's krb5.conf (the restore may have overwritten it)
2991         Samba::mk_krb5_conf($ctx);
2992
2993         # start samba for the restored DC
2994         if (not defined($self->check_or_start($env))) {
2995             return undef;
2996         }
2997
2998         return $env;
2999 }
3000
3001 # Set up a DC testenv solely by using the samba-tool 'domain backup rename' and
3002 # restore commands, using the --no-secrets option. This proves that we can
3003 # create a realistic lab environment from an online DC ('backupfromdc').
3004 sub setup_labdc
3005 {
3006         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3007         my ($self, $prefix, $dcvars) = @_;
3008         print "Preparing LAB-DOMAIN DC...\n";
3009         my $extra_conf = "prefork children = 1";
3010
3011         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "labdc",
3012                                                     "LABDOMAIN",
3013                                                     "labdom.samba.example.com",
3014                                                     $dcvars->{PASSWORD}, $extra_conf);
3015
3016         # create a backup of the 'backupfromdc' which renames the domain and uses
3017         # the --no-secrets option to scrub any sensitive info
3018         my $backupdir = File::Temp->newdir();
3019         my $server_args = $self->get_backup_server_args($dcvars);
3020         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
3021         $backup_args .= " --no-secrets --backend-store=mdb";
3022         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3023                                                $backup_args);
3024         unless($backup_file) {
3025                 return undef;
3026         }
3027
3028         # restore the backup file to populate the lab-DC testenv
3029         my $restore_dir = abs_path($prefix);
3030         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3031         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3032                                              $restore_dir, $env->{SERVERCONFFILE});
3033         unless ($ret == 0) {
3034                 return undef;
3035         }
3036
3037         # because we don't include any secrets in the backup, we need to reset the
3038         # admin user's password back to what the testenv expects
3039         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3040         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3041         $cmd .= "--newpassword=$env->{PASSWORD} -H $restore_dir/private/sam.ldb";
3042         $cmd .= " $env->{CONFIGURATION}";
3043
3044         unless(system($cmd) == 0) {
3045                 warn("Failed to reset admin's password: \n$cmd");
3046                 return undef;
3047         }
3048
3049         # start samba for the restored DC
3050         if (not defined($self->check_or_start($env))) {
3051             return undef;
3052         }
3053
3054         my $upn_array = ["$env->{REALM}.upn"];
3055         my $spn_array = ["$env->{REALM}.spn"];
3056
3057         $self->setup_namespaces($env, $upn_array, $spn_array);
3058
3059         return $env;
3060 }
3061
3062 # Inspects a backup *.tar.bz2 file and determines the realm/domain it contains
3063 sub get_backup_domain_realm
3064 {
3065         my ($self, $backup_file) = @_;
3066
3067         print "Determining REALM/DOMAIN values in backup...\n";
3068
3069         # The backup will have the correct domain/realm values in the smb.conf.
3070         # So we can work out the env variables the testenv should use based on
3071         # that. Let's start by extracting the smb.conf
3072         my $tar = Archive::Tar->new($backup_file);
3073         my $tmpdir = File::Temp->newdir();
3074         my $smbconf = "$tmpdir/smb.conf";
3075
3076         # note that the filepaths within the tar-file differ slightly for online
3077         # and offline backups
3078         if ($tar->contains_file("etc/smb.conf")) {
3079                 $tar->extract_file("etc/smb.conf", $smbconf);
3080         } elsif ($tar->contains_file("./etc/smb.conf")) {
3081                 $tar->extract_file("./etc/smb.conf", $smbconf);
3082         } else {
3083                 warn("Could not find smb.conf in $backup_file");
3084                 return undef, undef;
3085         }
3086
3087         # make sure we don't try to create locks/sockets in the default install
3088         # location (i.e. /usr/local/samba/)
3089         my $options = "--option=\"private dir = $tmpdir\"";
3090         $options .=  " --option=\"lock dir = $tmpdir\"";
3091
3092         # now use testparm to read the values we're interested in
3093         my $testparm = Samba::bindir_path($self, "testparm");
3094         my $domain = `$testparm $smbconf -sl --parameter-name=WORKGROUP $options`;
3095         my $realm = `$testparm $smbconf -sl --parameter-name=REALM $options`;
3096         chomp $realm;
3097         chomp $domain;
3098         print "Backup-file REALM is $realm, DOMAIN is $domain\n";
3099
3100         return ($domain, $realm);
3101 }
3102
3103 # This spins up a custom testenv that can be based on any backup-file you want.
3104 # This is just intended for manual testing (rather than automated test-cases)
3105 sub setup_customdc
3106 {
3107         my ($self, $prefix) = @_;
3108         print "Preparing CUSTOM RESTORE DC...\n";
3109         my $dc_name = "customdc";
3110         my $password = "locDCpass1";
3111         my $backup_file = $ENV{'BACKUP_FILE'};
3112
3113         # user must specify a backup file to restore via an ENV variable, i.e.
3114         # BACKUP_FILE=backup-blah.tar.bz2 SELFTEST_TESTENV=customdc make testenv
3115         if (not defined($backup_file)) {
3116                 warn("Please specify BACKUP_FILE");
3117                 return undef;
3118         }
3119
3120         # work out the correct domain/realm env values from the backup-file
3121         my ($domain, $realm) = $self->get_backup_domain_realm($backup_file);
3122         if ($domain eq '' or $realm eq '') {
3123                 warn("Could not determine domain or realm");
3124                 return undef;
3125         }
3126
3127         # create a placeholder directory and smb.conf, as well as the env vars.
3128         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, $dc_name,
3129                                                     $domain, $realm, $password, "");
3130
3131         # restore the specified backup file to populate the testenv
3132         my $restore_dir = abs_path($prefix);
3133         my $ret = $self->restore_backup_file($backup_file,
3134                                              "--newservername=$env->{SERVER}",
3135                                              $restore_dir, $env->{SERVERCONFFILE});
3136         unless ($ret == 0) {
3137                 return undef;
3138         }
3139
3140         # Change the admin password to the testenv default, just in case it's
3141         # different, or in case this was a --no-secrets backup
3142         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3143         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3144         $cmd .= "--newpassword=$password -H $restore_dir/private/sam.ldb";
3145         $cmd .= " $env->{CONFIGURATION}";
3146
3147         unless(system($cmd) == 0) {
3148                 warn("Failed to reset admin's password: \n$cmd");
3149                 return undef;
3150         }
3151
3152         # re-create the testenv's krb5.conf (the restore may have overwritten it,
3153         # if the backup-file was an offline backup)
3154         Samba::mk_krb5_conf($ctx);
3155
3156         # start samba for the restored DC
3157         if (not defined($self->check_or_start($env))) {
3158             return undef;
3159         }
3160
3161         # if this was a backup-rename, then we may need to setup namespaces
3162         my $upn_array = ["$env->{REALM}.upn"];
3163         my $spn_array = ["$env->{REALM}.spn"];
3164
3165         $self->setup_namespaces($env, $upn_array, $spn_array);
3166
3167         return $env;
3168 }
3169
3170 sub setup_none
3171 {
3172         my ($self, $path) = @_;
3173
3174         my $ret = {
3175                 KRB5_CONFIG => abs_path($path) . "/no_krb5.conf",
3176                 SAMBA_PID => -1,
3177         }
3178 }
3179
3180 1;