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