d15156a538b25f73767c5de022d0308f7010a155
[samba.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         kdc force enable rc4 weak session keys = yes
1495
1496 [sysvol]
1497         path = $ctx->{statedir}/sysvol
1498         read only = yes
1499
1500 [netlogon]
1501         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1502         read only = no
1503
1504 ";
1505
1506         my $ret = $self->provision_raw_step1($ctx);
1507         unless ($ret) {
1508                 return undef;
1509         }
1510
1511         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1512         my $cmd = $self->get_cmd_env_vars($ret);
1513         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} --experimental-s4-member MEMBER --realm=$dcvars->{REALM}";
1514         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1515         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1516
1517         unless (system($cmd) == 0) {
1518                 warn("Join failed\n$cmd");
1519                 return undef;
1520         }
1521
1522         $samba_tool =  Samba::bindir_path($self, "samba-tool");
1523         $cmd = $self->get_cmd_env_vars($ret);
1524         $cmd .= "$samba_tool domain dcpromo $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1525         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1526         $cmd .= " --machinepass=machine$ret->{PASSWORD} --dns-backend=BIND9_DLZ";
1527
1528         unless (system($cmd) == 0) {
1529                 warn("Join failed\n$cmd");
1530                 return undef;
1531         }
1532
1533         $self->set_pdc_env_vars($ret, $dcvars);
1534
1535         return $ret;
1536 }
1537
1538 sub provision_vampire_dc($$$)
1539 {
1540         my ($self, $prefix, $dcvars, $fl) = @_;
1541         print "PROVISIONING VAMPIRE DC @ FL $fl...\n";
1542         my $name = "localvampiredc";
1543         my $extra_conf = "";
1544
1545         if ($fl == "2000") {
1546                 $name = "vampire2000dc";
1547         } else {
1548                 $extra_conf = "drs: immediate link sync = yes
1549                        drs: max link sync = 250";
1550         }
1551
1552         # We do this so that we don't run the provision.  That's the job of 'net vampire'.
1553         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1554                                                $name,
1555                                                $dcvars->{DOMAIN},
1556                                                $dcvars->{REALM},
1557                                                $dcvars->{DOMSID},
1558                                                $fl,
1559                                                $dcvars->{PASSWORD},
1560                                                $dcvars->{SERVER_IP},
1561                                                $dcvars->{SERVER_IPV6});
1562
1563         $ctx->{smb_conf_extra_options} = "
1564         max xmit = 32K
1565         server max protocol = SMB2
1566
1567         ntlm auth = mschapv2-and-ntlmv2-only
1568         $extra_conf
1569
1570 [sysvol]
1571         path = $ctx->{statedir}/sysvol
1572         read only = yes
1573
1574 [netlogon]
1575         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1576         read only = no
1577
1578 ";
1579
1580         my $ret = $self->provision_raw_step1($ctx);
1581         unless ($ret) {
1582                 return undef;
1583         }
1584
1585         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1586         my $cmd = $self->get_cmd_env_vars($ret);
1587         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
1588         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} --domain-critical-only";
1589         $cmd .= " --machinepass=machine$ret->{PASSWORD}";
1590         $cmd .= " --backend-store=$self->{default_ldb_backend}";
1591
1592         unless (system($cmd) == 0) {
1593                 warn("Join failed\n$cmd");
1594                 return undef;
1595         }
1596
1597         $self->set_pdc_env_vars($ret, $dcvars);
1598         $ret->{DC_REALM} = $dcvars->{DC_REALM};
1599
1600         return $ret;
1601 }
1602
1603 sub provision_ad_dc_ntvfs($$$)
1604 {
1605         my ($self, $prefix, $extra_provision_options) = @_;
1606
1607         # We keep the old 'winbind' name here in server services to
1608         # ensure upgrades which used that name still work with the now
1609         # alias.
1610
1611         print "PROVISIONING AD DC (NTVFS)...\n";
1612         my $extra_conf_options = "netbios aliases = localDC1-a
1613         server services = +winbind -winbindd
1614         ldap server require strong auth = allow_sasl_over_tls
1615         raw NTLMv2 auth = yes
1616         lsa over netlogon = yes
1617         rpc server port = 1027
1618         auth event notification = true
1619         dsdb event notification = true
1620         dsdb password event notification = true
1621         dsdb group change notification = true
1622         # override the new SMB2 only default
1623         client min protocol = CORE
1624         server min protocol = LANMAN1
1625
1626         CVE_2020_1472:warn_about_unused_debug_level = 3
1627         CVE_2022_38023:warn_about_unused_debug_level = 3
1628         allow nt4 crypto:torturetest\$ = yes
1629         server reject md5 schannel:schannel2\$ = no
1630         server reject md5 schannel:schannel3\$ = no
1631         server reject md5 schannel:schannel8\$ = no
1632         server reject md5 schannel:schannel9\$ = no
1633         server reject md5 schannel:torturetest\$ = no
1634         server reject md5 schannel:tests4u2proxywk\$ = no
1635         server reject md5 schannel:tests4u2selfbdc\$ = no
1636         server reject md5 schannel:tests4u2selfwk\$ = no
1637         server reject md5 schannel:torturepacbdc\$ = no
1638         server reject md5 schannel:torturepacwksta\$ = no
1639         server require schannel:schannel0\$ = no
1640         server require schannel:schannel1\$ = no
1641         server require schannel:schannel2\$ = no
1642         server require schannel:schannel3\$ = no
1643         server require schannel:schannel4\$ = no
1644         server require schannel:schannel5\$ = no
1645         server require schannel:schannel6\$ = no
1646         server require schannel:schannel7\$ = no
1647         server require schannel:schannel8\$ = no
1648         server require schannel:schannel9\$ = no
1649         server require schannel:schannel10\$ = no
1650         server require schannel:schannel11\$ = no
1651         server require schannel:torturetest\$ = no
1652         server schannel require seal:schannel0\$ = no
1653         server schannel require seal:schannel1\$ = no
1654         server schannel require seal:schannel2\$ = no
1655         server schannel require seal:schannel3\$ = no
1656         server schannel require seal:schannel4\$ = no
1657         server schannel require seal:schannel5\$ = no
1658         server schannel require seal:schannel6\$ = no
1659         server schannel require seal:schannel7\$ = no
1660         server schannel require seal:schannel8\$ = no
1661         server schannel require seal:schannel9\$ = no
1662         server schannel require seal:schannel10\$ = no
1663         server schannel require seal:schannel11\$ = no
1664         server schannel require seal:torturetest\$ = no
1665
1666         # needed for 'samba.tests.auth_log' tests
1667         server require schannel:LOCALDC\$ = no
1668         server schannel require seal:LOCALDC\$ = no
1669         ";
1670         push (@{$extra_provision_options}, "--use-ntvfs");
1671         my $ret = $self->provision($prefix,
1672                                    "domain controller",
1673                                    "localdc",
1674                                    "SAMBADOMAIN",
1675                                    "samba.example.com",
1676                                    "2008",
1677                                    "locDCpass1",
1678                                    undef,
1679                                    undef,
1680                                    undef,
1681                                    $extra_conf_options,
1682                                    "",
1683                                    $extra_provision_options);
1684         unless ($ret) {
1685                 return undef;
1686         }
1687
1688         unless($self->add_wins_config("$prefix/private")) {
1689                 warn("Unable to add wins configuration");
1690                 return undef;
1691         }
1692         $ret->{NETBIOSALIAS} = "localdc1-a";
1693         $ret->{DC_REALM} = $ret->{REALM};
1694
1695         return $ret;
1696 }
1697
1698 sub provision_fl2000dc($$)
1699 {
1700         my ($self, $prefix) = @_;
1701
1702         print "PROVISIONING DC WITH FOREST LEVEL 2000...\n";
1703         my $extra_conf_options = "
1704         kdc enable fast = no
1705         spnego:simulate_w2k=yes
1706         ntlmssp_server:force_old_spnego=yes
1707
1708         CVE_2022_38023:warn_about_unused_debug_level = 3
1709         server reject md5 schannel:tests4u2proxywk\$ = no
1710         server reject md5 schannel:tests4u2selfbdc\$ = no
1711         server reject md5 schannel:tests4u2selfwk\$ = no
1712         server reject md5 schannel:torturepacbdc\$ = no
1713         server reject md5 schannel:torturepacwksta\$ = no
1714 ";
1715         my $extra_provision_options = ["--base-schema=2008_R2"];
1716         # This environment uses plain text secrets
1717         # i.e. secret attributes are not encrypted on disk.
1718         # This allows testing of the --plaintext-secrets option for
1719         # provision
1720         push (@{$extra_provision_options}, "--plaintext-secrets");
1721         my $ret = $self->provision($prefix,
1722                                    "domain controller",
1723                                    "dc5",
1724                                    "SAMBA2000",
1725                                    "samba2000.example.com",
1726                                    "2000",
1727                                    "locDCpass5",
1728                                    undef,
1729                                    undef,
1730                                    undef,
1731                                    $extra_conf_options,
1732                                    "",
1733                                    $extra_provision_options);
1734         unless ($ret) {
1735                 return undef;
1736         }
1737
1738         unless($self->add_wins_config("$prefix/private")) {
1739                 warn("Unable to add wins configuration");
1740                 return undef;
1741         }
1742         $ret->{DC_REALM} = $ret->{REALM};
1743
1744         return $ret;
1745 }
1746
1747 sub provision_fl2003dc($$$)
1748 {
1749         my ($self, $prefix, $dcvars) = @_;
1750         my $ip_addr1 = Samba::get_ipv4_addr("fakednsforwarder1");
1751         my $ip_addr2 = Samba::get_ipv6_addr("fakednsforwarder2");
1752
1753         print "PROVISIONING DC WITH FOREST LEVEL 2003...\n";
1754         my $extra_conf_options = "
1755         allow dns updates = nonsecure and secure
1756
1757         kdc enable fast = no
1758         dcesrv:header signing = no
1759         dcesrv:max auth states = 0
1760
1761         dns forwarder = $ip_addr1 [$ip_addr2]:54
1762
1763         CVE_2022_38023:warn_about_unused_debug_level = 3
1764         server reject md5 schannel:tests4u2proxywk\$ = no
1765         server reject md5 schannel:tests4u2selfbdc\$ = no
1766         server reject md5 schannel:tests4u2selfwk\$ = no
1767         server reject md5 schannel:torturepacbdc\$ = no
1768         server reject md5 schannel:torturepacwksta\$ = no
1769 ";
1770
1771         my $extra_provision_options = ["--base-schema=2008_R2"];
1772         my $ret = $self->provision($prefix,
1773                                    "domain controller",
1774                                    "dc6",
1775                                    "SAMBA2003",
1776                                    "samba2003.example.com",
1777                                    "2003",
1778                                    "locDCpass6",
1779                                    undef,
1780                                    undef,
1781                                    undef,
1782                                    $extra_conf_options,
1783                                    "",
1784                                    $extra_provision_options);
1785         unless (defined $ret) {
1786                 return undef;
1787         }
1788
1789         $ret->{DNS_FORWARDER1} = $ip_addr1;
1790         $ret->{DNS_FORWARDER2} = $ip_addr2;
1791
1792         my @samba_tool_options;
1793         push (@samba_tool_options, Samba::bindir_path($self, "samba-tool"));
1794         push (@samba_tool_options, "domain");
1795         push (@samba_tool_options, "passwordsettings");
1796         push (@samba_tool_options, "set");
1797         push (@samba_tool_options, "--configfile=$ret->{SERVERCONFFILE}");
1798         push (@samba_tool_options, "--min-pwd-age=0");
1799         push (@samba_tool_options, "--history-length=1");
1800
1801         my $samba_tool_cmd = join(" ", @samba_tool_options);
1802
1803         unless (system($samba_tool_cmd) == 0) {
1804                 warn("Unable to set min password age to 0: \n$samba_tool_cmd\n");
1805                 return undef;
1806         }
1807
1808         unless($self->add_wins_config("$prefix/private")) {
1809                 warn("Unable to add wins configuration");
1810                 return undef;
1811         }
1812
1813         return $ret;
1814 }
1815
1816 sub provision_fl2008r2dc($$$)
1817 {
1818         my ($self, $prefix, $dcvars) = @_;
1819
1820         print "PROVISIONING DC WITH FOREST LEVEL 2008r2...\n";
1821         my $extra_conf_options = "
1822         ldap server require strong auth = no
1823         # delay by 10 seconds, 10^7 usecs
1824         ldap_server:delay_expire_disconnect = 10000
1825
1826         CVE_2022_38023:warn_about_unused_debug_level = 3
1827         server reject md5 schannel:tests4u2proxywk\$ = no
1828         server reject md5 schannel:tests4u2selfbdc\$ = no
1829         server reject md5 schannel:tests4u2selfwk\$ = no
1830         server reject md5 schannel:torturepacbdc\$ = no
1831         server reject md5 schannel:torturepacwksta\$ = no
1832 ";
1833         my $extra_provision_options = ["--base-schema=2008_R2"];
1834         my $ret = $self->provision($prefix,
1835                                    "domain controller",
1836                                    "dc7",
1837                                    "SAMBA2008R2",
1838                                    "samba2008R2.example.com",
1839                                    "2008_R2",
1840                                    "locDCpass7",
1841                                    undef,
1842                                    undef,
1843                                    undef,
1844                                    $extra_conf_options,
1845                                    "",
1846                                    $extra_provision_options);
1847         unless (defined $ret) {
1848                 return undef;
1849         }
1850
1851         unless ($self->add_wins_config("$prefix/private")) {
1852                 warn("Unable to add wins configuration");
1853                 return undef;
1854         }
1855         $ret->{DC_REALM} = $ret->{REALM};
1856
1857         return $ret;
1858 }
1859
1860
1861 sub provision_rodc($$$)
1862 {
1863         my ($self, $prefix, $dcvars) = @_;
1864         print "PROVISIONING RODC...\n";
1865
1866         # We do this so that we don't run the provision.  That's the job of 'net join RODC'.
1867         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
1868                                                "rodc",
1869                                                $dcvars->{DOMAIN},
1870                                                $dcvars->{REALM},
1871                                                $dcvars->{DOMSID},
1872                                                "2008",
1873                                                $dcvars->{PASSWORD},
1874                                                $dcvars->{SERVER_IP},
1875                                                $dcvars->{SERVER_IPV6});
1876         unless ($ctx) {
1877                 return undef;
1878         }
1879
1880         $ctx->{share} = "$ctx->{prefix_abs}/share";
1881         push(@{$ctx->{directories}}, "$ctx->{share}");
1882
1883         $ctx->{smb_conf_extra_options} = "
1884         max xmit = 32K
1885         server max protocol = SMB2
1886         password server = $dcvars->{DC_SERVER}
1887
1888 [sysvol]
1889         path = $ctx->{statedir}/sysvol
1890         read only = yes
1891
1892 [netlogon]
1893         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
1894         read only = yes
1895
1896 [tmp]
1897         path = $ctx->{share}
1898         read only = no
1899         posix:sharedelay = 10000
1900         posix:oplocktimeout = 3
1901         posix:writetimeupdatedelay = 50000
1902
1903 ";
1904
1905         my $ret = $self->provision_raw_step1($ctx);
1906         unless ($ret) {
1907                 return undef;
1908         }
1909
1910         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
1911         my $cmd = $self->get_cmd_env_vars($ret);
1912         $cmd .= "$samba_tool domain join $ret->{CONFIGURATION} $dcvars->{REALM} RODC";
1913         $cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
1914         $cmd .= " --server=$dcvars->{DC_SERVER}";
1915
1916         unless (system($cmd) == 0) {
1917                 warn("RODC join failed\n$cmd");
1918                 return undef;
1919         }
1920
1921         # This ensures deterministic behaviour for tests that want to have the 'testallowed account'
1922         # user password verified on the RODC
1923         my $testallowed_account = "testallowed account";
1924         $cmd = $self->get_cmd_env_vars($ret);
1925         $cmd .= "$samba_tool rodc preload '$testallowed_account' $ret->{CONFIGURATION}";
1926         $cmd .= " --server=$dcvars->{DC_SERVER}";
1927
1928         unless (system($cmd) == 0) {
1929                 warn("RODC join failed\n$cmd");
1930                 return undef;
1931         }
1932
1933         # we overwrite the kdc after the RODC join
1934         # so that use the RODC as kdc and test
1935         # the proxy code
1936         $ctx->{kdc_ipv4} = $ret->{SERVER_IP};
1937         $ctx->{kdc_ipv6} = $ret->{SERVER_IPV6};
1938         Samba::mk_krb5_conf($ctx);
1939         Samba::mk_mitkdc_conf($ctx, abs_path(Samba::bindir_path($self, "shared")));
1940
1941         $self->set_pdc_env_vars($ret, $dcvars);
1942
1943         return $ret;
1944 }
1945
1946 sub read_config_h($)
1947 {
1948         my ($name) = @_;
1949         my %ret;
1950         open(LF, "<$name") or die("unable to read $name: $!");
1951         while (<LF>) {
1952                 chomp;
1953                 next if not (/^#define /);
1954                 if (/^#define (.*?)[ \t]+(.*?)$/) {
1955                         $ret{$1} = $2;
1956                         next;
1957                 }
1958                 if (/^#define (.*?)[ \t]+$/) {
1959                         $ret{$1} = 1;;
1960                         next;
1961                 }
1962         }
1963         close(LF);
1964         return \%ret;
1965 }
1966
1967 sub provision_ad_dc($$$$$$$)
1968 {
1969         my ($self,
1970             $prefix,
1971             $hostname,
1972             $domain,
1973             $realm,
1974             $force_fips_mode,
1975             $smbconf_args,
1976             $extra_provision_options) = @_;
1977
1978         my $prefix_abs = abs_path($prefix);
1979
1980         my $bindir_abs = abs_path($self->{bindir});
1981         my $lockdir="$prefix_abs/lockdir";
1982         my $conffile="$prefix_abs/etc/smb.conf";
1983
1984         my $require_mutexes = "dbwrap_tdb_require_mutexes:* = yes";
1985         if ($ENV{SELFTEST_DONT_REQUIRE_TDB_MUTEX_SUPPORT} // '' eq "1") {
1986                 $require_mutexes = "";
1987         }
1988
1989         my $config_h = {};
1990
1991         if (defined($ENV{CONFIG_H})) {
1992                 $config_h = read_config_h($ENV{CONFIG_H});
1993         }
1994
1995         my $password_hash_gpg_key_ids = "password hash gpg key ids = 4952E40301FAB41A";
1996         $password_hash_gpg_key_ids = "" unless defined($config_h->{HAVE_GPGME});
1997
1998         my $extra_smbconf_options = "
1999         xattr_tdb:file = $prefix_abs/statedir/xattr.tdb
2000
2001         dbwrap_tdb_mutexes:* = yes
2002         ${require_mutexes}
2003
2004         ${password_hash_gpg_key_ids}
2005
2006         kernel oplocks = no
2007         kernel change notify = no
2008         smb2 leases = no
2009         smb2 disable oplock break retry = yes
2010         server multi channel support = yes
2011
2012         logging = file
2013         printing = bsd
2014         printcap name = /dev/null
2015
2016         max protocol = SMB3
2017         read only = no
2018
2019         smbd:sharedelay = 100000
2020         smbd:writetimeupdatedelay = 500000
2021         create mask = 755
2022         dos filemode = yes
2023         check parent directory delete on close = yes
2024
2025         dcerpc endpoint servers = -winreg -srvsvc
2026
2027         printcap name = /dev/null
2028
2029         addprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -a -s $conffile --
2030         deleteprinter command = $ENV{SRCDIR_ABS}/source3/script/tests/printing/modprinter.pl -d -s $conffile --
2031
2032         printing = vlp
2033         print command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb print %p %s
2034         lpq command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpq %p
2035         lp rm command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lprm %p %j
2036         lp pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lppause %p %j
2037         lp resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb lpresume %p %j
2038         queue pause command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queuepause %p
2039         queue resume command = $bindir_abs/vlp tdbfile=$lockdir/vlp.tdb queueresume %p
2040         lpq cache time = 0
2041         print notify backchannel = yes
2042
2043         CVE_2020_1472:warn_about_unused_debug_level = 3
2044         CVE_2022_38023:warn_about_unused_debug_level = 3
2045         CVE_2022_38023:error_debug_level = 2
2046         server reject md5 schannel:schannel2\$ = no
2047         server reject md5 schannel:schannel3\$ = no
2048         server reject md5 schannel:schannel8\$ = no
2049         server reject md5 schannel:schannel9\$ = no
2050         server reject md5 schannel:torturetest\$ = no
2051         server reject md5 schannel:tests4u2proxywk\$ = no
2052         server reject md5 schannel:tests4u2selfbdc\$ = no
2053         server reject md5 schannel:tests4u2selfwk\$ = no
2054         server reject md5 schannel:torturepacbdc\$ = no
2055         server reject md5 schannel:torturepacwksta\$ = no
2056         server reject md5 schannel:samlogontest\$ = no
2057         server require schannel:schannel0\$ = no
2058         server require schannel:schannel1\$ = no
2059         server require schannel:schannel2\$ = no
2060         server require schannel:schannel3\$ = no
2061         server require schannel:schannel4\$ = no
2062         server require schannel:schannel5\$ = no
2063         server require schannel:schannel6\$ = no
2064         server require schannel:schannel7\$ = no
2065         server require schannel:schannel8\$ = no
2066         server require schannel:schannel9\$ = no
2067         server require schannel:schannel10\$ = no
2068         server require schannel:schannel11\$ = no
2069         server require schannel:torturetest\$ = no
2070         server schannel require seal:schannel0\$ = no
2071         server schannel require seal:schannel1\$ = no
2072         server schannel require seal:schannel2\$ = no
2073         server schannel require seal:schannel3\$ = no
2074         server schannel require seal:schannel4\$ = no
2075         server schannel require seal:schannel5\$ = no
2076         server schannel require seal:schannel6\$ = no
2077         server schannel require seal:schannel7\$ = no
2078         server schannel require seal:schannel8\$ = no
2079         server schannel require seal:schannel9\$ = no
2080         server schannel require seal:schannel10\$ = no
2081         server schannel require seal:schannel11\$ = no
2082         server schannel require seal:torturetest\$ = no
2083
2084         auth event notification = true
2085         dsdb event notification = true
2086         dsdb password event notification = true
2087         dsdb group change notification = true
2088         $smbconf_args
2089 ";
2090
2091         my $extra_smbconf_shares = "
2092
2093 [tmpenc]
2094         copy = tmp
2095         smb encrypt = required
2096
2097 [tmpcase]
2098         copy = tmp
2099         case sensitive = yes
2100
2101 [tmpguest]
2102         copy = tmp
2103         guest ok = yes
2104
2105 [hideunread]
2106         copy = tmp
2107         hide unreadable = yes
2108
2109 [durable]
2110         copy = tmp
2111         kernel share modes = no
2112         kernel oplocks = no
2113         posix locking = no
2114
2115 [print\$]
2116         copy = tmp
2117
2118 [print1]
2119         copy = tmp
2120         printable = yes
2121
2122 [print2]
2123         copy = print1
2124 [print3]
2125         copy = print1
2126 [print4]
2127         copy = print1
2128         guest ok = yes
2129 [lp]
2130         copy = print1
2131 ";
2132
2133         push (@{$extra_provision_options}, "--backend-store=$self->{default_ldb_backend}");
2134         print "PROVISIONING AD DC...\n";
2135         my $ret = $self->provision($prefix,
2136                                    "domain controller",
2137                                    $hostname,
2138                                    $domain,
2139                                    $realm,
2140                                    "2008",
2141                                    "locDCpass1",
2142                                    undef,
2143                                    undef,
2144                                    $force_fips_mode,
2145                                    $extra_smbconf_options,
2146                                    $extra_smbconf_shares,
2147                                    $extra_provision_options);
2148         unless (defined $ret) {
2149                 return undef;
2150         }
2151
2152         unless($self->add_wins_config("$prefix/private")) {
2153                 warn("Unable to add wins configuration");
2154                 return undef;
2155         }
2156
2157         return $ret;
2158 }
2159
2160 sub provision_chgdcpass($$)
2161 {
2162         my ($self, $prefix) = @_;
2163
2164         print "PROVISIONING CHGDCPASS...\n";
2165         # This environment disallows the use of this password
2166         # (and also removes the default AD complexity checks)
2167         my $unacceptable_password = "Paßßword-widk3Dsle32jxdBdskldsk55klASKQ";
2168
2169         # This environment also sets some settings that are unusual,
2170         # to test specific behaviours.  In particular, this
2171         # environment fails to correctly support DRSUAPI_DRS_GET_ANC
2172         # like Samba before 4.5 and DRSUAPI_DRS_GET_TGT before 4.8
2173         #
2174         # Additionally, disabling DRSUAPI_DRS_GET_TGT causes all links
2175         # to be sent last (in the final chunk), which is like Samba
2176         # before 4.8.
2177
2178         my $extra_smb_conf = "
2179         check password script = $self->{srcdir}/selftest/checkpassword_arg1.sh ${unacceptable_password}
2180         allow dcerpc auth level connect:lsarpc = yes
2181         dcesrv:max auth states = 8
2182         drs:broken_samba_4.5_get_anc_emulation = true
2183         drs:get_tgt_support = false
2184 ";
2185         my $extra_provision_options = ["--dns-backend=BIND9_DLZ"];
2186         my $ret = $self->provision($prefix,
2187                                    "domain controller",
2188                                    "chgdcpass",
2189                                    "CHDCDOMAIN",
2190                                    "chgdcpassword.samba.example.com",
2191                                    "2008",
2192                                    "chgDCpass1",
2193                                    undef,
2194                                    undef,
2195                                    undef,
2196                                    $extra_smb_conf,
2197                                    "",
2198                                    $extra_provision_options);
2199         unless (defined $ret) {
2200                 return undef;
2201         }
2202
2203         unless($self->add_wins_config("$prefix/private")) {
2204                 warn("Unable to add wins configuration");
2205                 return undef;
2206         }
2207         
2208         # Remove secrets.tdb from this environment to test that we
2209         # still start up on systems without the new matching
2210         # secrets.tdb records.
2211         unless (unlink("$ret->{PRIVATEDIR}/secrets.tdb") || unlink("$ret->{PRIVATEDIR}/secrets.ntdb")) {
2212                 warn("Unable to remove $ret->{PRIVATEDIR}/secrets.tdb added during provision");
2213                 return undef;
2214         }
2215
2216         $ret->{UNACCEPTABLE_PASSWORD} = $unacceptable_password;
2217
2218         return $ret;
2219 }
2220
2221 sub teardown_env_terminate($$)
2222 {
2223         my ($self, $envvars) = @_;
2224         my $pid;
2225
2226         # This should cause samba to terminate gracefully
2227         my $smbcontrol = Samba::bindir_path($self, "smbcontrol");
2228         my $cmd = "";
2229         $cmd .= "$smbcontrol samba shutdown $envvars->{CONFIGURATION}";
2230         my $ret = system($cmd);
2231         if ($ret != 0) {
2232                 warn "'$cmd' failed with '$ret'\n";
2233         }
2234
2235         # This should cause samba to terminate gracefully
2236         close($envvars->{STDIN_PIPE});
2237
2238         $pid = $envvars->{SAMBA_PID};
2239         my $count = 0;
2240         my $childpid;
2241
2242         # This should give it time to write out the gcov data
2243         until ($count > 15) {
2244             if (Samba::cleanup_child($pid, "samba") != 0) {
2245                 return;
2246             }
2247             sleep(1);
2248             $count++;
2249         }
2250
2251         # After 15 Seconds, work out why this thing is still alive
2252         warn "server process $pid took more than $count seconds to exit, showing backtrace:\n";
2253         system("$self->{srcdir}/selftest/gdb_backtrace $pid");
2254
2255         until ($count > 30) {
2256             if (Samba::cleanup_child($pid, "samba") != 0) {
2257                 return;
2258             }
2259             sleep(1);
2260             $count++;
2261         }
2262
2263         if (kill(0, $pid)) {
2264             warn "server process $pid took more than $count seconds to exit, sending SIGTERM\n";
2265             kill "TERM", $pid;
2266         }
2267
2268         until ($count > 40) {
2269             if (Samba::cleanup_child($pid, "samba") != 0) {
2270                 return;
2271             }
2272             sleep(1);
2273             $count++;
2274         }
2275         # If it is still around, kill it
2276         if (kill(0, $pid)) {
2277             warn "server process $pid took more than $count seconds to exit, killing\n with SIGKILL\n";
2278             kill 9, $pid;
2279         }
2280         return;
2281 }
2282
2283 sub teardown_env($$)
2284 {
2285         my ($self, $envvars) = @_;
2286         teardown_env_terminate($self, $envvars);
2287
2288         print $self->getlog_env($envvars);
2289
2290         return;
2291 }
2292
2293 sub getlog_env($$)
2294 {
2295         my ($self, $envvars) = @_;
2296         my $title = "SAMBA LOG of: $envvars->{NETBIOSNAME} pid $envvars->{SAMBA_PID}\n";
2297         my $out = $title;
2298
2299         open(LOG, "<$envvars->{SAMBA_TEST_LOG}");
2300
2301         seek(LOG, $envvars->{SAMBA_TEST_LOG_POS}, SEEK_SET);
2302         while (<LOG>) {
2303                 $out .= $_;
2304         }
2305         $envvars->{SAMBA_TEST_LOG_POS} = tell(LOG);
2306         close(LOG);
2307
2308         return "" if $out eq $title;
2309
2310         return $out;
2311 }
2312
2313 sub check_env($$)
2314 {
2315         my ($self, $envvars) = @_;
2316         my $samba_pid = $envvars->{SAMBA_PID};
2317
2318         if (not defined($samba_pid)) {
2319             return 0;
2320         } elsif ($samba_pid > 0) {
2321             my $childpid = Samba::cleanup_child($samba_pid, "samba");
2322
2323             if ($childpid == 0) {
2324                 return 1;
2325             }
2326             return 0;
2327         } else {
2328             return 1;
2329         }
2330 }
2331
2332 # Declare the environments Samba4 makes available.
2333 # To be set up, they will be called as
2334 #   samba4->setup_$envname($self, $path, $dep_1_vars, $dep_2_vars, ...)
2335 # The interdependencies between the testenvs are declared below. Some testenvs
2336 # are dependent on another testenv running first, e.g. vampire_dc is dependent
2337 # on ad_dc_ntvfs because vampire_dc joins ad_dc_ntvfs's domain. All DCs are
2338 # dependent on dns_hub, which handles resolving DNS queries for the realm.
2339 %Samba4::ENV_DEPS = (
2340         # name               => [dep_1, dep_2, ...],
2341         dns_hub              => [],
2342         ad_dc_ntvfs          => ["dns_hub"],
2343         ad_dc_fips           => ["dns_hub"],
2344         ad_dc                => ["dns_hub"],
2345         ad_dc_smb1           => ["dns_hub"],
2346         ad_dc_smb1_done      => ["ad_dc_smb1"],
2347         ad_dc_no_nss         => ["dns_hub"],
2348         ad_dc_no_ntlm        => ["dns_hub"],
2349
2350         fl2008r2dc           => ["ad_dc"],
2351         fl2003dc             => ["ad_dc"],
2352         fl2000dc             => ["ad_dc"],
2353
2354         vampire_2000_dc      => ["fl2000dc"],
2355         vampire_dc           => ["ad_dc_ntvfs"],
2356         promoted_dc          => ["ad_dc_ntvfs"],
2357
2358         rodc                 => ["ad_dc_ntvfs"],
2359         rpc_proxy            => ["ad_dc_ntvfs"],
2360         chgdcpass            => ["dns_hub"],
2361
2362         s4member_dflt_domain => ["ad_dc_ntvfs"],
2363         s4member             => ["ad_dc_ntvfs"],
2364
2365         # envs that test the server process model
2366         proclimitdc          => ["dns_hub"],
2367         preforkrestartdc     => ["dns_hub"],
2368
2369         # backup/restore testenvs
2370         backupfromdc         => ["dns_hub"],
2371         customdc             => ["dns_hub"],
2372         restoredc            => ["backupfromdc"],
2373         renamedc             => ["backupfromdc"],
2374         offlinebackupdc      => ["backupfromdc"],
2375         labdc                => ["backupfromdc"],
2376
2377         # aliases in order to split autbuild tasks
2378         fl2008dc             => ["ad_dc"],
2379         ad_dc_default        => ["ad_dc"],
2380         ad_dc_default_smb1   => ["ad_dc_smb1"],
2381         ad_dc_default_smb1_done   => ["ad_dc_default_smb1"],
2382         ad_dc_slowtests      => ["ad_dc"],
2383         ad_dc_backup         => ["ad_dc"],
2384
2385         schema_dc      => ["dns_hub"],
2386         schema_pair_dc => ["schema_dc"],
2387
2388         none                 => [],
2389 );
2390
2391 %Samba4::ENV_DEPS_POST = (
2392         schema_dc => ["schema_pair_dc"],
2393 );
2394
2395 sub return_alias_env
2396 {
2397         my ($self, $path, $env) = @_;
2398
2399         # just an alias
2400         return $env;
2401 }
2402
2403 sub setup_fl2008dc
2404 {
2405         my ($self, $path) = @_;
2406
2407         my $extra_args = ["--base-schema=2008_R2"];
2408         my $env = $self->provision_ad_dc_ntvfs($path, $extra_args);
2409         if (defined $env) {
2410                 if (not defined($self->check_or_start($env, "standard"))) {
2411                     warn("Failed to start fl2008dc");
2412                         return undef;
2413                 }
2414         }
2415         return $env;
2416 }
2417
2418 sub setup_ad_dc_default
2419 {
2420         my ($self, $path, $dep_env) = @_;
2421         return $self->return_alias_env($path, $dep_env)
2422 }
2423
2424 sub setup_ad_dc_default_smb1
2425 {
2426         my ($self, $path, $dep_env) = @_;
2427         return $self->return_alias_env($path, $dep_env)
2428 }
2429
2430 sub setup_ad_dc_default_smb1_done
2431 {
2432         my ($self, $path, $dep_env) = @_;
2433         return $self->return_alias_env($path, $dep_env)
2434 }
2435
2436 sub setup_ad_dc_slowtests
2437 {
2438         my ($self, $path, $dep_env) = @_;
2439         return $self->return_alias_env($path, $dep_env)
2440 }
2441
2442 sub setup_ad_dc_backup
2443 {
2444         my ($self, $path, $dep_env) = @_;
2445         return $self->return_alias_env($path, $dep_env)
2446 }
2447
2448 sub setup_s4member
2449 {
2450         my ($self, $path, $dc_vars) = @_;
2451
2452         my $env = $self->provision_s4member($path, $dc_vars, "s4member");
2453
2454         if (defined $env) {
2455                 if (not defined($self->check_or_start($env, "standard"))) {
2456                         return undef;
2457                 }
2458         }
2459
2460         return $env;
2461 }
2462
2463 sub setup_s4member_dflt_domain
2464 {
2465         my ($self, $path, $dc_vars) = @_;
2466
2467         my $env = $self->provision_s4member($path, $dc_vars, "s4member_dflt",
2468                                             "winbind use default domain = yes");
2469
2470         if (defined $env) {
2471                 if (not defined($self->check_or_start($env, "standard"))) {
2472                         return undef;
2473                 }
2474         }
2475
2476         return $env;
2477 }
2478
2479 sub setup_rpc_proxy
2480 {
2481         my ($self, $path, $dc_vars) = @_;
2482
2483         my $env = $self->provision_rpc_proxy($path, $dc_vars);
2484
2485         if (defined $env) {
2486                 if (not defined($self->check_or_start($env, "standard"))) {
2487                         return undef;
2488                 }
2489         }
2490         return $env;
2491 }
2492
2493 sub setup_ad_dc_ntvfs
2494 {
2495         my ($self, $path) = @_;
2496
2497         my $env = $self->provision_ad_dc_ntvfs($path, undef);
2498         if (defined $env) {
2499                 if (not defined($self->check_or_start($env, "standard"))) {
2500                     warn("Failed to start ad_dc_ntvfs");
2501                         return undef;
2502                 }
2503         }
2504         return $env;
2505 }
2506
2507 sub setup_chgdcpass
2508 {
2509         my ($self, $path) = @_;
2510
2511         my $env = $self->provision_chgdcpass($path);
2512         if (defined $env) {
2513                 if (not defined($self->check_or_start($env, "standard"))) {
2514                         return undef;
2515                 }
2516         }
2517         return $env;
2518 }
2519
2520 sub setup_fl2000dc
2521 {
2522         my ($self, $path, $dc_vars) = @_;
2523
2524         my $env = $self->provision_fl2000dc($path);
2525         if (defined $env) {
2526                 if (not defined($self->check_or_start($env, "standard"))) {
2527                         return undef;
2528                 }
2529
2530                 $env = $self->setup_trust($env, $dc_vars, "external", "--no-aes-keys --direction=outgoing");
2531         }
2532
2533         return $env;
2534 }
2535
2536 sub setup_fl2003dc
2537 {
2538         my ($self, $path, $dc_vars) = @_;
2539
2540         my $env = $self->provision_fl2003dc($path);
2541
2542         if (defined $env) {
2543                 if (not defined($self->check_or_start($env, "standard"))) {
2544                         return undef;
2545                 }
2546
2547                 $env = $self->setup_trust($env, $dc_vars, "external", "--no-aes-keys");
2548         }
2549         return $env;
2550 }
2551
2552 sub setup_fl2008r2dc
2553 {
2554         my ($self, $path, $dc_vars) = @_;
2555
2556         my $env = $self->provision_fl2008r2dc($path);
2557
2558         if (defined $env) {
2559                 if (not defined($self->check_or_start($env, "standard"))) {
2560                         return undef;
2561                 }
2562
2563                 my $upn_array = ["$env->{REALM}.upn"];
2564                 my $spn_array = ["$env->{REALM}.spn"];
2565
2566                 if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2567                         return undef;
2568                 }
2569
2570                 $env = $self->setup_trust($env, $dc_vars, "forest", "");
2571         }
2572
2573         return $env;
2574 }
2575
2576 sub setup_vampire_dc
2577 {
2578         return setup_generic_vampire_dc(@_, "2008");
2579 }
2580
2581 sub setup_vampire_2000_dc
2582 {
2583         return setup_generic_vampire_dc(@_, "2000");
2584 }
2585
2586 sub setup_generic_vampire_dc
2587 {
2588         my ($self, $path, $dc_vars, $fl) = @_;
2589
2590         my $env = $self->provision_vampire_dc($path, $dc_vars, $fl);
2591
2592         if (defined $env) {
2593                 if (not defined($self->check_or_start($env, "single"))) {
2594                         return undef;
2595                 }
2596
2597                 # force replicated DC to update repsTo/repsFrom
2598                 # for vampired partitions
2599                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2600
2601                 # as 'vampired' dc may add data in its local replica
2602                 # we need to synchronize data between DCs
2603                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2604                 my $cmd = $self->get_cmd_env_vars($env);
2605                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2606                 $cmd .= " $dc_vars->{CONFIGURATION}";
2607                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2608                 # replicate Configuration NC
2609                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2610                 unless(system($cmd_repl) == 0) {
2611                         warn("Failed to replicate\n$cmd_repl");
2612                         return undef;
2613                 }
2614                 # replicate Default NC
2615                 $cmd_repl = "$cmd \"$base_dn\"";
2616                 unless(system($cmd_repl) == 0) {
2617                         warn("Failed to replicate\n$cmd_repl");
2618                         return undef;
2619                 }
2620
2621                 # Pull in a full set of changes from the main DC
2622                 $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2623                 $cmd = $self->get_cmd_env_vars($env);
2624                 $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2625                 $cmd .= " $dc_vars->{CONFIGURATION}";
2626                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2627                 # replicate Configuration NC
2628                 $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2629                 unless(system($cmd_repl) == 0) {
2630                         warn("Failed to replicate\n$cmd_repl");
2631                         return undef;
2632                 }
2633                 # replicate Default NC
2634                 $cmd_repl = "$cmd \"$base_dn\"";
2635                 unless(system($cmd_repl) == 0) {
2636                         warn("Failed to replicate\n$cmd_repl");
2637                         return undef;
2638                 }
2639         }
2640
2641         return $env;
2642 }
2643
2644 sub setup_promoted_dc
2645 {
2646         my ($self, $path, $dc_vars) = @_;
2647
2648         my $env = $self->provision_promoted_dc($path, $dc_vars);
2649
2650         if (defined $env) {
2651                 if (not defined($self->check_or_start($env, "single"))) {
2652                         return undef;
2653                 }
2654
2655                 # force source and replicated DC to update repsTo/repsFrom
2656                 # for vampired partitions
2657                 my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2658                 my $cmd = $self->get_cmd_env_vars($env);
2659                 # as 'vampired' dc may add data in its local replica
2660                 # we need to synchronize data between DCs
2661                 my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2662                 $cmd .= " $samba_tool drs replicate $env->{DC_SERVER} $env->{SERVER}";
2663                 $cmd .= " $dc_vars->{CONFIGURATION}";
2664                 $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2665                 # replicate Configuration NC
2666                 my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2667                 unless(system($cmd_repl) == 0) {
2668                         warn("Failed to replicate\n$cmd_repl");
2669                         return undef;
2670                 }
2671                 # replicate Default NC
2672                 $cmd_repl = "$cmd \"$base_dn\"";
2673                 unless(system($cmd_repl) == 0) {
2674                         warn("Failed to replicate\n$cmd_repl");
2675                         return undef;
2676                 }
2677         }
2678
2679         return $env;
2680 }
2681
2682 sub setup_rodc
2683 {
2684         my ($self, $path, $dc_vars) = @_;
2685
2686         my $env = $self->provision_rodc($path, $dc_vars);
2687
2688         unless ($env) {
2689                 return undef;
2690         }
2691
2692         if (not defined($self->check_or_start($env, "standard"))) {
2693             return undef;
2694         }
2695
2696         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
2697         my $cmd = $self->get_cmd_env_vars($env);
2698
2699         my $base_dn = "DC=".join(",DC=", split(/\./, $dc_vars->{REALM}));
2700         $cmd .= " $samba_tool drs replicate $env->{SERVER} $env->{DC_SERVER}";
2701         $cmd .= " $dc_vars->{CONFIGURATION}";
2702         $cmd .= " -U$dc_vars->{DC_USERNAME}\%$dc_vars->{DC_PASSWORD}";
2703         # replicate Configuration NC
2704         my $cmd_repl = "$cmd \"CN=Configuration,$base_dn\"";
2705         unless(system($cmd_repl) == 0) {
2706             warn("Failed to replicate\n$cmd_repl");
2707             return undef;
2708         }
2709         # replicate Default NC
2710         $cmd_repl = "$cmd \"$base_dn\"";
2711         unless(system($cmd_repl) == 0) {
2712             warn("Failed to replicate\n$cmd_repl");
2713             return undef;
2714         }
2715
2716         return $env;
2717 }
2718
2719 sub _setup_ad_dc
2720 {
2721         my ($self, $path, $conf_opts, $server, $dom) = @_;
2722
2723         # If we didn't build with ADS, pretend this env was never available
2724         if (not $self->{target3}->have_ads()) {
2725                return "UNKNOWN";
2726         }
2727
2728         if (!defined($conf_opts)) {
2729                 $conf_opts = "";
2730         }
2731         if (!defined($server)) {
2732                 $server = "addc";
2733         }
2734         if (!defined($dom)) {
2735                 $dom = "addom.samba.example.com";
2736         }
2737         my $env = $self->provision_ad_dc($path, $server, "ADDOMAIN",
2738                                          $dom,
2739                                          undef,
2740                                          $conf_opts,
2741                                          undef);
2742         unless ($env) {
2743                 return undef;
2744         }
2745
2746         if (not defined($self->check_or_start($env, "prefork"))) {
2747             return undef;
2748         }
2749
2750         my $upn_array = ["$env->{REALM}.upn"];
2751         my $spn_array = ["$env->{REALM}.spn"];
2752
2753         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2754                 return undef;
2755         }
2756
2757         return $env;
2758 }
2759
2760 sub setup_ad_dc
2761 {
2762         my ($self, $path) = @_;
2763         return _setup_ad_dc($self, $path, undef, undef, undef);
2764 }
2765
2766 sub setup_ad_dc_smb1
2767 {
2768         my ($self, $path) = @_;
2769         my $conf_opts = "
2770 [global]
2771         client min protocol = CORE
2772         server min protocol = LANMAN1
2773
2774         # needed for 'samba.tests.auth_log' tests
2775         server require schannel:ADDCSMB1\$ = no
2776         server schannel require seal:ADDCSMB1\$ = no
2777 ";
2778         return _setup_ad_dc($self, $path, $conf_opts, "addcsmb1", "addom2.samba.example.com");
2779 }
2780
2781 sub setup_ad_dc_smb1_done
2782 {
2783         my ($self, $path, $dep_env) = @_;
2784         return $self->return_alias_env($path, $dep_env);
2785 }
2786
2787 sub setup_ad_dc_no_nss
2788 {
2789         my ($self, $path) = @_;
2790
2791         # If we didn't build with ADS, pretend this env was never available
2792         if (not $self->{target3}->have_ads()) {
2793                return "UNKNOWN";
2794         }
2795
2796         my $env = $self->provision_ad_dc($path,
2797                                          "addc_no_nss",
2798                                          "ADNONSSDOMAIN",
2799                                          "adnonssdom.samba.example.com",
2800                                          undef,
2801                                          "",
2802                                          undef);
2803         unless ($env) {
2804                 return undef;
2805         }
2806
2807         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2808         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2809
2810         if (not defined($self->check_or_start($env, "single"))) {
2811             return undef;
2812         }
2813
2814         my $upn_array = ["$env->{REALM}.upn"];
2815         my $spn_array = ["$env->{REALM}.spn"];
2816
2817         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2818                 return undef;
2819         }
2820
2821         return $env;
2822 }
2823
2824 sub setup_ad_dc_no_ntlm
2825 {
2826         my ($self, $path) = @_;
2827
2828         # If we didn't build with ADS, pretend this env was never available
2829         if (not $self->{target3}->have_ads()) {
2830                return "UNKNOWN";
2831         }
2832
2833         my $env = $self->provision_ad_dc($path,
2834                                          "addc_no_ntlm",
2835                                          "ADNONTLMDOMAIN",
2836                                          "adnontlmdom.samba.example.com",
2837                                          undef,
2838                                          "ntlm auth = disabled\nnt hash store = never",
2839                                          undef);
2840         unless ($env) {
2841                 return undef;
2842         }
2843
2844         if (not defined($self->check_or_start($env, "prefork"))) {
2845             return undef;
2846         }
2847
2848         my $upn_array = ["$env->{REALM}.upn"];
2849         my $spn_array = ["$env->{REALM}.spn"];
2850
2851         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2852                 return undef;
2853         }
2854
2855         return $env;
2856 }
2857
2858 sub setup_ad_dc_fips
2859 {
2860         my ($self, $path) = @_;
2861
2862         # If we didn't build with ADS, pretend this env was never available
2863         if (not $self->{target3}->have_ads()) {
2864                return "UNKNOWN";
2865         }
2866
2867         my $env = $self->provision_ad_dc($path,
2868                                          "fipsdc",
2869                                          "FIPSDOMAIN",
2870                                          "fips.samba.example.com",
2871                                          1,
2872                                          "",
2873                                          undef);
2874         unless ($env) {
2875                 return undef;
2876         }
2877
2878         if (not defined($self->check_or_start($env, "prefork"))) {
2879             return undef;
2880         }
2881
2882         my $upn_array = ["$env->{REALM}.upn"];
2883         my $spn_array = ["$env->{REALM}.spn"];
2884
2885         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2886                 return undef;
2887         }
2888
2889         return $env;
2890 }
2891
2892 #
2893 # AD DC test environment used solely to test pre-fork process restarts.
2894 # As processes get killed off and restarted it should not be used for other
2895 sub setup_preforkrestartdc
2896 {
2897         my ($self, $path) = @_;
2898
2899         # If we didn't build with ADS, pretend this env was never available
2900         if (not $self->{target3}->have_ads()) {
2901                return "UNKNOWN";
2902         }
2903
2904         # note DC name must be <= 15 chars so we use 'prockill' instead of
2905         # 'preforkrestart'
2906         my $env = $self->provision_ad_dc($path,
2907                                          "prockilldc",
2908                                          "PROCKILLDOMAIN",
2909                                          "prockilldom.samba.example.com",
2910                                          undef,
2911                                          "prefork backoff increment = 5\nprefork maximum backoff=10",
2912                                          undef);
2913         unless ($env) {
2914                 return undef;
2915         }
2916
2917         # We treat processes in this environment cruelly, sometimes
2918         # sending them SIGSEGV signals. We don't need gdb_backtrace
2919         # dissecting these fake crashes in precise detail.
2920         $env->{PLEASE_NO_GDB_BACKTRACE} = '1';
2921
2922         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2923         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2924
2925         if (not defined($self->check_or_start($env, "prefork"))) {
2926             return undef;
2927         }
2928
2929         my $upn_array = ["$env->{REALM}.upn"];
2930         my $spn_array = ["$env->{REALM}.spn"];
2931
2932         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2933                 return undef;
2934         }
2935
2936         return $env;
2937 }
2938
2939 #
2940 # ad_dc test environment used solely to test standard process model connection
2941 # process limits. As the limit is set artificially low it should not be used
2942 # for other tests.
2943 sub setup_proclimitdc
2944 {
2945         my ($self, $path) = @_;
2946
2947         # If we didn't build with ADS, pretend this env was never available
2948         if (not $self->{target3}->have_ads()) {
2949                return "UNKNOWN";
2950         }
2951
2952         my $env = $self->provision_ad_dc($path,
2953                                          "proclimitdc",
2954                                          "PROCLIMITDOM",
2955                                          "proclimit.samba.example.com",
2956                                          undef,
2957                                          "max smbd processes = 20",
2958                                          undef);
2959         unless ($env) {
2960                 return undef;
2961         }
2962
2963         $env->{NSS_WRAPPER_MODULE_SO_PATH} = undef;
2964         $env->{NSS_WRAPPER_MODULE_FN_PREFIX} = undef;
2965
2966         if (not defined($self->check_or_start($env, "standard"))) {
2967             return undef;
2968         }
2969
2970         my $upn_array = ["$env->{REALM}.upn"];
2971         my $spn_array = ["$env->{REALM}.spn"];
2972
2973         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
2974                 return undef;
2975         }
2976
2977         return $env;
2978 }
2979
2980 # Used to test a live upgrade of the schema on a 2 DC network.
2981 sub setup_schema_dc
2982 {
2983         my ($self, $path) = @_;
2984
2985         # provision the PDC using an older base schema
2986         my $provision_args = ["--base-schema=2008_R2", "--backend-store=$self->{default_ldb_backend}"];
2987
2988         my $env = $self->provision_ad_dc($path,
2989                                          "liveupgrade1dc",
2990                                          "SCHEMADOMAIN",
2991                                          "schema.samba.example.com",
2992                                          undef,
2993                                          "drs: max link sync = 2",
2994                                          $provision_args);
2995         unless ($env) {
2996                 return undef;
2997         }
2998
2999         if (not defined($self->check_or_start($env, "prefork"))) {
3000             return undef;
3001         }
3002
3003         my $upn_array = ["$env->{REALM}.upn"];
3004         my $spn_array = ["$env->{REALM}.spn"];
3005
3006         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
3007                 return undef;
3008         }
3009
3010         return $env;
3011 }
3012
3013 # the second DC in the live schema upgrade pair
3014 sub setup_schema_pair_dc
3015 {
3016         # note: dcvars contains the env info for the dependent testenv ('schema_dc')
3017         my ($self, $prefix, $dcvars) = @_;
3018         print "Preparing SCHEMA UPGRADE PAIR DC...\n";
3019
3020         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "liveupgrade2dc",
3021                                                     $dcvars->{DOMAIN},
3022                                                     $dcvars->{REALM},
3023                                                     $dcvars->{PASSWORD},
3024                                                     "");
3025
3026         my $samba_tool =  Samba::bindir_path($self, "samba-tool");
3027         my $cmd_vars = $self->get_cmd_env_vars($env);
3028
3029         my $join_cmd = $cmd_vars;
3030         $join_cmd .= "$samba_tool domain join $env->{CONFIGURATION} $dcvars->{REALM} DC --realm=$dcvars->{REALM}";
3031         $join_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD} ";
3032         $join_cmd .= " --backend-store=$self->{default_ldb_backend}";
3033
3034         my $upgrade_cmd = $cmd_vars;
3035         $upgrade_cmd .= "$samba_tool domain schemaupgrade $dcvars->{CONFIGURATION}";
3036         $upgrade_cmd .= " -U$dcvars->{USERNAME}\%$dcvars->{PASSWORD}";
3037
3038         my $repl_cmd = $cmd_vars;
3039         $repl_cmd .= "$samba_tool drs replicate $env->{SERVER} $dcvars->{SERVER}";
3040         $repl_cmd .= " CN=Schema,CN=Configuration,DC=schema,DC=samba,DC=example,DC=com";
3041         $repl_cmd .= " -U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
3042
3043         unless (system($join_cmd) == 0) {
3044                 warn("Join failed\n$join_cmd");
3045                 return undef;
3046         }
3047
3048         $env->{DC_SERVER} = $dcvars->{SERVER};
3049         $env->{DC_SERVER_IP} = $dcvars->{SERVER_IP};
3050         $env->{DC_SERVER_IPV6} = $dcvars->{SERVER_IPV6};
3051         $env->{DC_NETBIOSNAME} = $dcvars->{NETBIOSNAME};
3052
3053         # start samba for the new DC
3054         if (not defined($self->check_or_start($env, "standard"))) {
3055             return undef;
3056         }
3057
3058         unless (system($upgrade_cmd) == 0) {
3059                 warn("Schema upgrade failed\n$upgrade_cmd");
3060                 return undef;
3061         }
3062
3063         unless (system($repl_cmd) == 0) {
3064                 warn("Post-update schema replication failed\n$repl_cmd");
3065                 return undef;
3066         }
3067
3068         return $env;
3069 }
3070
3071 # Sets up a DC that's solely used to do a domain backup from. We then use the
3072 # backupfrom-DC to create the restore-DC - this proves that the backup/restore
3073 # process will create a Samba DC that will actually start up.
3074 # We don't use the backup-DC for anything else because its domain will conflict
3075 # with the restore DC.
3076 sub setup_backupfromdc
3077 {
3078         my ($self, $path) = @_;
3079
3080         # If we didn't build with ADS, pretend this env was never available
3081         if (not $self->{target3}->have_ads()) {
3082                return "UNKNOWN";
3083         }
3084
3085         my $provision_args = ["--site=Backup-Site"];
3086
3087         my $env = $self->provision_ad_dc($path,
3088                                          "backupfromdc",
3089                                          "BACKUPDOMAIN",
3090                                          "backupdom.samba.example.com",
3091                                          undef,
3092                                          "samba kcc command = /bin/true",
3093                                          $provision_args);
3094         unless ($env) {
3095                 return undef;
3096         }
3097
3098         if (not defined($self->check_or_start($env))) {
3099             return undef;
3100         }
3101
3102         my $upn_array = ["$env->{REALM}.upn"];
3103         my $spn_array = ["$env->{REALM}.spn"];
3104
3105         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
3106                 return undef;
3107         }
3108
3109         # Set up a dangling forward link to an expunged object
3110         #
3111         # We need this to ensure that the "samba-tool domain backup rename"
3112         # that is part of the creation of the labdc environment can
3113         # cope with this situation on the source DC.
3114
3115         if (not $self->write_ldb_file("$env->{PRIVATEDIR}/sam.ldb", "
3116 dn: ou=linktest,dc=backupdom,dc=samba,dc=example,dc=com
3117 objectclass: organizationalUnit
3118 -
3119
3120 dn: cn=linkto,ou=linktest,dc=backupdom,dc=samba,dc=example,dc=com
3121 objectclass: msExchConfigurationContainer
3122 -
3123
3124 dn: cn=linkfrom,ou=linktest,dc=backupdom,dc=samba,dc=example,dc=com
3125 objectclass: msExchConfigurationContainer
3126 addressBookRoots: cn=linkto,ou=linktest,dc=backupdom,dc=samba,dc=example,dc=com
3127 -
3128
3129 ")) {
3130             return undef;
3131         }
3132         my $ldbdel = Samba::bindir_path($self, "ldbdel");
3133         my $cmd = "$ldbdel -H $env->{PRIVATEDIR}/sam.ldb cn=linkto,ou=linktest,dc=backupdom,dc=samba,dc=example,dc=com";
3134
3135         unless(system($cmd) == 0) {
3136                 warn("Failed to delete link target: \n$cmd");
3137                 return undef;
3138         }
3139
3140         # Expunge will ensure that linkto is totally wiped from the DB
3141         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3142         $cmd = "$samba_tool  domain tombstones expunge --tombstone-lifetime=0 $env->{CONFIGURATION}";
3143
3144         unless(system($cmd) == 0) {
3145                 warn("Failed to expunge link target: \n$cmd");
3146                 return undef;
3147         }
3148         return $env;
3149 }
3150
3151 # returns the server/user-auth params needed to run an online backup cmd
3152 sub get_backup_server_args
3153 {
3154         # dcvars contains the env info for the backup DC testenv
3155         my ($self, $dcvars) = @_;
3156         my $server = $dcvars->{DC_SERVER_IP};
3157         my $server_args = "--server=$server ";
3158         $server_args .= "-U$dcvars->{DC_USERNAME}\%$dcvars->{DC_PASSWORD}";
3159         $server_args .= " $dcvars->{CONFIGURATION}";
3160
3161         return $server_args;
3162 }
3163
3164 # Creates a backup of a running testenv DC
3165 sub create_backup
3166 {
3167         # note: dcvars contains the env info for the backup DC testenv
3168         my ($self, $env, $dcvars, $backupdir, $backup_cmd) = @_;
3169
3170         # get all the env variables we pass in with the samba-tool command
3171         # Note: use the backupfrom-DC's krb5.conf to do the backup
3172         my $overwrite = undef;
3173         $overwrite->{KRB5_CONFIG} = $dcvars->{KRB5_CONFIG};
3174         my $cmd_env = $self->get_cmd_env_vars($env, $overwrite);
3175
3176         # use samba-tool to create a backup from the 'backupfromdc' DC
3177         my $cmd = "";
3178         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3179
3180         $cmd .= "$cmd_env $samba_tool domain backup $backup_cmd";
3181         $cmd .= " --targetdir=$backupdir";
3182
3183         print "Executing: $cmd\n";
3184         unless(system($cmd) == 0) {
3185                 warn("Failed to create backup using: \n$cmd");
3186                 return undef;
3187         }
3188
3189         # get the name of the backup file created
3190         opendir(DIR, $backupdir);
3191         my @files = grep(/\.tar/, readdir(DIR));
3192         closedir(DIR);
3193
3194         if(scalar @files != 1) {
3195                 warn("Backup file not found in directory $backupdir\n");
3196                 return undef;
3197         }
3198         my $backup_file = "$backupdir/$files[0]";
3199         print "Using backup file $backup_file...\n";
3200
3201         return $backup_file;
3202 }
3203
3204 # Restores a backup-file to populate a testenv for a new DC
3205 sub restore_backup_file
3206 {
3207         my ($self, $backup_file, $restore_opts, $restoredir, $smbconf) = @_;
3208
3209         # pass the restore command the testenv's smb.conf that we've already
3210         # generated. But move it to a temp-dir first, so that the restore doesn't
3211         # overwrite it
3212         my $tmpdir = File::Temp->newdir();
3213         my $tmpconf = "$tmpdir/smb.conf";
3214         my $cmd = "cp $smbconf $tmpconf";
3215         unless(system($cmd) == 0) {
3216                 warn("Failed to backup smb.conf using: \n$cmd");
3217                 return -1;
3218         }
3219
3220         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3221         $cmd = "$samba_tool domain backup restore --backup-file=$backup_file";
3222         $cmd .= " --targetdir=$restoredir $restore_opts --configfile=$tmpconf";
3223
3224         print "Executing: $cmd\n";
3225         unless(system($cmd) == 0) {
3226                 warn("Failed to restore backup using: \n$cmd");
3227                 return -1;
3228         }
3229
3230         print "Restore complete\n";
3231         return 0
3232 }
3233
3234 # sets up the initial directory and returns the new testenv's env info
3235 # (without actually doing a 'domain join')
3236 sub prepare_dc_testenv
3237 {
3238         my ($self, $prefix, $dcname, $domain, $realm,
3239                 $password, $conf_options, $dnsupdate_options) = @_;
3240
3241         my $ctx = $self->provision_raw_prepare($prefix, "domain controller",
3242                                                $dcname,
3243                                                $domain,
3244                                                $realm,
3245                                                undef,
3246                                                "2008",
3247                                                $password,
3248                                                undef,
3249                                                undef);
3250
3251         # the restore uses a slightly different state-dir location to other testenvs
3252         $ctx->{statedir} = "$ctx->{prefix_abs}/state";
3253         push(@{$ctx->{directories}}, "$ctx->{statedir}");
3254
3255         # add support for sysvol/netlogon/tmp shares
3256         $ctx->{share} = "$ctx->{prefix_abs}/share";
3257         push(@{$ctx->{directories}}, "$ctx->{share}");
3258         push(@{$ctx->{directories}}, "$ctx->{share}/test1");
3259
3260         if (defined($dnsupdate_options)) {
3261                 $ctx->{samba_dnsupdate} .= $dnsupdate_options;
3262         }
3263
3264         $ctx->{smb_conf_extra_options} = "
3265         $conf_options
3266         max xmit = 32K
3267         server max protocol = SMB2
3268         samba kcc command = /bin/true
3269         xattr_tdb:file = $ctx->{statedir}/xattr.tdb
3270
3271 [sysvol]
3272         path = $ctx->{statedir}/sysvol
3273         read only = no
3274
3275 [netlogon]
3276         path = $ctx->{statedir}/sysvol/$ctx->{dnsname}/scripts
3277         read only = no
3278
3279 [tmp]
3280         path = $ctx->{share}
3281         read only = no
3282         posix:sharedelay = 10000
3283         posix:oplocktimeout = 3
3284         posix:writetimeupdatedelay = 50000
3285
3286 [test1]
3287         path = $ctx->{share}/test1
3288         read only = no
3289         posix:sharedelay = 100000
3290         posix:oplocktimeout = 3
3291         posix:writetimeupdatedelay = 500000
3292 ";
3293
3294         my $env = $self->provision_raw_step1($ctx);
3295
3296     return ($env, $ctx);
3297 }
3298
3299
3300 # Set up a DC testenv solely by using the samba-tool domain backup/restore
3301 # commands. This proves that we can backup an online DC ('backupfromdc') and
3302 # use the backup file to create a valid, working samba DC.
3303 sub setup_restoredc
3304 {
3305         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3306         my ($self, $prefix, $dcvars) = @_;
3307         print "Preparing RESTORE DC...\n";
3308
3309         # we arbitrarily designate the restored DC as having SMBv1 disabled
3310         my $extra_conf = "
3311         server min protocol = SMB2
3312         client min protocol = SMB2
3313         prefork children = 1";
3314         my $dnsupdate_options = " --use-samba-tool --no-credentials";
3315
3316         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "restoredc",
3317                                                     $dcvars->{DOMAIN},
3318                                                     $dcvars->{REALM},
3319                                                     $dcvars->{PASSWORD},
3320                                                     $extra_conf,
3321                                                     $dnsupdate_options);
3322
3323         # create a backup of the 'backupfromdc'
3324         my $backupdir = File::Temp->newdir();
3325         my $server_args = $self->get_backup_server_args($dcvars);
3326         my $backup_args = "online $server_args";
3327         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3328                                                $backup_args);
3329         unless($backup_file) {
3330                 return undef;
3331         }
3332
3333         # restore the backup file to populate the restore-DC testenv
3334         my $restore_dir = abs_path($prefix);
3335         my $ret = $self->restore_backup_file($backup_file,
3336                                              "--newservername=$env->{SERVER}",
3337                                              $restore_dir, $env->{SERVERCONFFILE});
3338         unless ($ret == 0) {
3339                 return undef;
3340         }
3341
3342         #
3343         # As we create a the same domain as a clone
3344         # we need a separate resolv.conf!
3345         #
3346         $ctx->{resolv_conf} = "$ctx->{etcdir}/resolv.conf";
3347         $ctx->{dns_ipv4} = $ctx->{ipv4};
3348         $ctx->{dns_ipv6} = $ctx->{ipv6};
3349         Samba::mk_resolv_conf($ctx);
3350         $env->{RESOLV_CONF} = $ctx->{resolv_conf};
3351
3352         # start samba for the restored DC
3353         if (not defined($self->check_or_start($env))) {
3354             return undef;
3355         }
3356
3357         return $env;
3358 }
3359
3360 # Set up a DC testenv solely by using the 'samba-tool domain backup rename' and
3361 # restore commands. This proves that we can backup and rename an online DC
3362 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
3363 sub setup_renamedc
3364 {
3365         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3366         my ($self, $prefix, $dcvars) = @_;
3367         print "Preparing RENAME DC...\n";
3368         my $extra_conf = "prefork children = 1";
3369
3370         my $realm = "renamedom.samba.example.com";
3371         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "renamedc",
3372                                                     "RENAMEDOMAIN", $realm,
3373                                                     $dcvars->{PASSWORD}, $extra_conf);
3374
3375         # create a backup of the 'backupfromdc' which renames the domain
3376         my $backupdir = File::Temp->newdir();
3377         my $server_args = $self->get_backup_server_args($dcvars);
3378         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
3379         $backup_args .= " --backend-store=tdb";
3380         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3381                                                $backup_args);
3382         unless($backup_file) {
3383                 return undef;
3384         }
3385
3386         # restore the backup file to populate the rename-DC testenv
3387         my $restore_dir = abs_path($prefix);
3388         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3389         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3390                                              $restore_dir, $env->{SERVERCONFFILE});
3391         unless ($ret == 0) {
3392                 return undef;
3393         }
3394
3395         # start samba for the restored DC
3396         if (not defined($self->check_or_start($env))) {
3397             return undef;
3398         }
3399
3400         my $upn_array = ["$env->{REALM}.upn"];
3401         my $spn_array = ["$env->{REALM}.spn"];
3402
3403         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
3404                 return undef;
3405         }
3406
3407         return $env;
3408 }
3409
3410 # Set up a DC testenv solely by using the 'samba-tool domain backup offline' and
3411 # restore commands. This proves that we do an offline backup of a local DC
3412 # ('backupfromdc') and use the backup file to create a valid, working samba DC.
3413 sub setup_offlinebackupdc
3414 {
3415         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3416         my ($self, $prefix, $dcvars) = @_;
3417         print "Preparing OFFLINE BACKUP DC...\n";
3418         my $extra_conf = "prefork children = 1";
3419         my $dnsupdate_options = " --use-samba-tool --no-credentials";
3420
3421         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "offlinebackupdc",
3422                                                     $dcvars->{DOMAIN},
3423                                                     $dcvars->{REALM},
3424                                                     $dcvars->{PASSWORD},
3425                                                     $extra_conf,
3426                                                     $dnsupdate_options);
3427
3428         # create an offline backup of the 'backupfromdc' target
3429         my $backupdir = File::Temp->newdir();
3430         my $cmd = "offline --configfile $dcvars->{SERVERCONFFILE}";
3431         my $backup_file = $self->create_backup($env, $dcvars,
3432                                                $backupdir, $cmd);
3433
3434         unless($backup_file) {
3435                 return undef;
3436         }
3437
3438         # restore the backup file to populate the rename-DC testenv
3439         my $restore_dir = abs_path($prefix);
3440         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3441         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3442                                              $restore_dir, $env->{SERVERCONFFILE});
3443         unless ($ret == 0) {
3444                 return undef;
3445         }
3446
3447         #
3448         # As we create a the same domain as a clone
3449         # we need a separate resolv.conf!
3450         #
3451         $ctx->{resolv_conf} = "$ctx->{etcdir}/resolv.conf";
3452         $ctx->{dns_ipv4} = $ctx->{ipv4};
3453         $ctx->{dns_ipv6} = $ctx->{ipv6};
3454         Samba::mk_resolv_conf($ctx);
3455         $env->{RESOLV_CONF} = $ctx->{resolv_conf};
3456
3457         # re-create the testenv's krb5.conf (the restore may have overwritten it)
3458         Samba::mk_krb5_conf($ctx);
3459
3460         # start samba for the restored DC
3461         if (not defined($self->check_or_start($env))) {
3462             return undef;
3463         }
3464
3465         return $env;
3466 }
3467
3468 # Set up a DC testenv solely by using the samba-tool 'domain backup rename' and
3469 # restore commands, using the --no-secrets option. This proves that we can
3470 # create a realistic lab environment from an online DC ('backupfromdc').
3471 sub setup_labdc
3472 {
3473         # note: dcvars contains the env info for the dependent testenv ('backupfromdc')
3474         my ($self, $prefix, $dcvars) = @_;
3475         print "Preparing LAB-DOMAIN DC...\n";
3476         my $extra_conf = "prefork children = 1";
3477
3478         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, "labdc",
3479                                                     "LABDOMAIN",
3480                                                     "labdom.samba.example.com",
3481                                                     $dcvars->{PASSWORD}, $extra_conf);
3482
3483         # create a backup of the 'backupfromdc' which renames the domain and uses
3484         # the --no-secrets option to scrub any sensitive info
3485         my $backupdir = File::Temp->newdir();
3486         my $server_args = $self->get_backup_server_args($dcvars);
3487         my $backup_args = "rename $env->{DOMAIN} $env->{REALM} $server_args";
3488         $backup_args .= " --no-secrets --backend-store=$self->{default_ldb_backend}";
3489         my $backup_file = $self->create_backup($env, $dcvars, $backupdir,
3490                                                $backup_args);
3491         unless($backup_file) {
3492                 return undef;
3493         }
3494
3495         # restore the backup file to populate the lab-DC testenv
3496         my $restore_dir = abs_path($prefix);
3497         my $restore_opts =  "--newservername=$env->{SERVER} --host-ip=$env->{SERVER_IP}";
3498         my $ret = $self->restore_backup_file($backup_file, $restore_opts,
3499                                              $restore_dir, $env->{SERVERCONFFILE});
3500         unless ($ret == 0) {
3501                 return undef;
3502         }
3503
3504         # because we don't include any secrets in the backup, we need to reset the
3505         # admin user's password back to what the testenv expects
3506         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3507         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3508         $cmd .= "--newpassword=$env->{PASSWORD} -H $restore_dir/private/sam.ldb";
3509         $cmd .= " $env->{CONFIGURATION}";
3510
3511         unless(system($cmd) == 0) {
3512                 warn("Failed to reset admin's password: \n$cmd");
3513                 return undef;
3514         }
3515
3516         # start samba for the restored DC
3517         if (not defined($self->check_or_start($env))) {
3518             return undef;
3519         }
3520
3521         my $upn_array = ["$env->{REALM}.upn"];
3522         my $spn_array = ["$env->{REALM}.spn"];
3523
3524         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
3525                 return undef;
3526         }
3527
3528         return $env;
3529 }
3530
3531 # Inspects a backup *.tar.bz2 file and determines the realm/domain it contains
3532 sub get_backup_domain_realm
3533 {
3534         my ($self, $backup_file) = @_;
3535
3536         print "Determining REALM/DOMAIN values in backup...\n";
3537
3538         # The backup will have the correct domain/realm values in the smb.conf.
3539         # So we can work out the env variables the testenv should use based on
3540         # that. Let's start by extracting the smb.conf
3541         my $tar = Archive::Tar->new($backup_file);
3542         my $tmpdir = File::Temp->newdir();
3543         my $smbconf = "$tmpdir/smb.conf";
3544
3545         # note that the filepaths within the tar-file differ slightly for online
3546         # and offline backups
3547         if ($tar->contains_file("etc/smb.conf")) {
3548                 $tar->extract_file("etc/smb.conf", $smbconf);
3549         } elsif ($tar->contains_file("./etc/smb.conf")) {
3550                 $tar->extract_file("./etc/smb.conf", $smbconf);
3551         } else {
3552                 warn("Could not find smb.conf in $backup_file");
3553                 return undef, undef;
3554         }
3555
3556         # make sure we don't try to create locks/sockets in the default install
3557         # location (i.e. /usr/local/samba/)
3558         my $options = "--option=\"private dir = $tmpdir\"";
3559         $options .=  " --option=\"lock dir = $tmpdir\"";
3560
3561         # now use testparm to read the values we're interested in
3562         my $testparm = Samba::bindir_path($self, "testparm");
3563         my $domain = `$testparm $smbconf -sl --parameter-name=WORKGROUP $options`;
3564         my $realm = `$testparm $smbconf -sl --parameter-name=REALM $options`;
3565         chomp $realm;
3566         chomp $domain;
3567         print "Backup-file REALM is $realm, DOMAIN is $domain\n";
3568
3569         return ($domain, $realm);
3570 }
3571
3572 # This spins up a custom testenv that can be based on any backup-file you want.
3573 # This is just intended for manual testing (rather than automated test-cases)
3574 sub setup_customdc
3575 {
3576         my ($self, $prefix) = @_;
3577         print "Preparing CUSTOM RESTORE DC...\n";
3578         my $dc_name = "customdc";
3579         my $password = "locDCpass1";
3580         my $backup_file = $ENV{'BACKUP_FILE'};
3581         my $dnsupdate_options = " --use-samba-tool --no-credentials";
3582
3583         # user must specify a backup file to restore via an ENV variable, i.e.
3584         # BACKUP_FILE=backup-blah.tar.bz2 SELFTEST_TESTENV=customdc make testenv
3585         if (not defined($backup_file)) {
3586                 warn("Please specify BACKUP_FILE");
3587                 return undef;
3588         }
3589
3590         # work out the correct domain/realm env values from the backup-file
3591         my ($domain, $realm) = $self->get_backup_domain_realm($backup_file);
3592         if ($domain eq '' or $realm eq '') {
3593                 warn("Could not determine domain or realm");
3594                 return undef;
3595         }
3596
3597         # create a placeholder directory and smb.conf, as well as the env vars.
3598         my ($env, $ctx) = $self->prepare_dc_testenv($prefix, $dc_name,
3599                                                     $domain, $realm, $password, "",
3600                                                     $dnsupdate_options);
3601
3602         # restore the specified backup file to populate the testenv
3603         my $restore_dir = abs_path($prefix);
3604         my $ret = $self->restore_backup_file($backup_file,
3605                                              "--newservername=$env->{SERVER}",
3606                                              $restore_dir, $env->{SERVERCONFFILE});
3607         unless ($ret == 0) {
3608                 return undef;
3609         }
3610
3611         #
3612         # As we create a the same domain as a clone
3613         # we need a separate resolv.conf!
3614         #
3615         $ctx->{resolv_conf} = "$ctx->{etcdir}/resolv.conf";
3616         $ctx->{dns_ipv4} = $ctx->{ipv4};
3617         $ctx->{dns_ipv6} = $ctx->{ipv6};
3618         Samba::mk_resolv_conf($ctx);
3619         $env->{RESOLV_CONF} = $ctx->{resolv_conf};
3620
3621         # Change the admin password to the testenv default, just in case it's
3622         # different, or in case this was a --no-secrets backup
3623         my $samba_tool = Samba::bindir_path($self, "samba-tool");
3624         my $cmd = "$samba_tool user setpassword $env->{USERNAME} ";
3625         $cmd .= "--newpassword=$password -H $restore_dir/private/sam.ldb";
3626         $cmd .= " $env->{CONFIGURATION}";
3627
3628         unless(system($cmd) == 0) {
3629                 warn("Failed to reset admin's password: \n$cmd");
3630                 return undef;
3631         }
3632
3633         # re-create the testenv's krb5.conf (the restore may have overwritten it,
3634         # if the backup-file was an offline backup)
3635         Samba::mk_krb5_conf($ctx);
3636
3637         # start samba for the restored DC
3638         if (not defined($self->check_or_start($env))) {
3639             return undef;
3640         }
3641
3642         # if this was a backup-rename, then we may need to setup namespaces
3643         my $upn_array = ["$env->{REALM}.upn"];
3644         my $spn_array = ["$env->{REALM}.spn"];
3645
3646         if ($self->setup_namespaces($env, $upn_array, $spn_array) != 0) {
3647                 return undef;
3648         }
3649
3650         return $env;
3651 }
3652
3653 sub setup_none
3654 {
3655         my ($self, $path) = @_;
3656
3657         my $ret = {
3658                 KRB5_CONFIG => abs_path($path) . "/no_krb5.conf",
3659                 SAMBA_PID => -1,
3660         }
3661 }
3662
3663 1;