5aa2e79d135c38a632c99db4a54a76c60a9e66e2
[samba.git] / wintest / test-s4-howto.py
1 #!/usr/bin/env python
2
3 '''automated testing of the steps of the Samba4 HOWTO'''
4
5 import sys, os
6 import wintest, pexpect, time
7
8 def check_prerequesites(t):
9     t.info("Checking prerequesites")
10     t.setvar('HOSTNAME', t.cmd_output("hostname -s").strip())
11     if os.getuid() != 0:
12         raise Exception("You must run this script as root")
13     t.putenv("KRB5_CONFIG", '${PREFIX}/private/krb5.conf')
14     t.run_cmd('ifconfig ${INTERFACE} ${INTERFACE_NET} up')
15     if t.getvar('INTERFACE_IPV6'):
16         t.run_cmd('ifconfig ${INTERFACE} inet6 del ${INTERFACE_IPV6}/64', checkfail=False)
17         t.run_cmd('ifconfig ${INTERFACE} inet6 add ${INTERFACE_IPV6}/64 up')
18
19 def build_s4(t):
20     '''build samba4'''
21     t.info('Building s4')
22     t.chdir('${SOURCETREE}/source4')
23     t.putenv('CC', 'ccache gcc')
24     t.run_cmd('make reconfigure || ./configure --enable-auto-reconfigure --enable-developer --prefix=${PREFIX} -C')
25     t.run_cmd('make -j')
26     t.run_cmd('rm -rf ${PREFIX}')
27     t.run_cmd('make -j install')
28
29
30 def provision_s4(t, func_level="2008"):
31     '''provision s4 as a DC'''
32     t.info('Provisioning s4')
33     t.chdir('${PREFIX}')
34     t.del_files(["var", "private"])
35     t.run_cmd("rm -f etc/smb.conf")
36     provision=['sbin/provision',
37                '--realm=${LCREALM}',
38                '--domain=${DOMAIN}',
39                '--adminpass=${PASSWORD1}',
40                '--server-role=domain controller',
41                '--function-level=%s' % func_level,
42                '-d${DEBUGLEVEL}',
43                '--option=interfaces=${INTERFACE}',
44                '--host-ip=${INTERFACE_IP}',
45                '--option=bind interfaces only=yes',
46                '--option=rndc command=${RNDC} -c${PREFIX}/etc/rndc.conf']
47     if t.getvar('INTERFACE_IPV6'):
48         provision.append('--host-ip6=${INTERFACE_IPV6}')
49     t.run_cmd(provision)
50     t.run_cmd('bin/samba-tool newuser testallowed ${PASSWORD1}')
51     t.run_cmd('bin/samba-tool newuser testdenied ${PASSWORD1}')
52     t.run_cmd('bin/samba-tool group addmembers "Allowed RODC Password Replication Group" testallowed')
53
54
55 def start_s4(t):
56     '''startup samba4'''
57     t.info('Starting Samba4')
58     t.chdir("${PREFIX}")
59     t.run_cmd('killall -9 -q samba smbd nmbd winbindd', checkfail=False)
60     t.run_cmd(['sbin/samba',
61              '--option', 'panic action=gnome-terminal -e "gdb --pid %PID%"'])
62     t.port_wait("${INTERFACE_IP}", 139)
63
64 def stop_vms(t):
65     '''Shut down any existing alive VMs, so they do not collide with what we are doing'''
66     t.info('Shutting down any of our VMs already running')
67     vms = t.get_vms()
68     for v in vms:
69         t.vm_poweroff(v, checkfail=False)
70
71 def test_smbclient(t):
72     '''test smbclient'''
73     t.info('Testing smbclient')
74     t.chdir('${PREFIX}')
75     t.cmd_contains("bin/smbclient --version", ["Version 4.0"])
76     t.retry_cmd('bin/smbclient -L ${INTERFACE_IP} -U%', ["netlogon", "sysvol", "IPC Service"])
77     child = t.pexpect_spawn('bin/smbclient //${INTERFACE_IP}/netlogon -Uadministrator%${PASSWORD1}')
78     child.expect("smb:")
79     child.sendline("dir")
80     child.expect("blocks available")
81     child.sendline("mkdir testdir")
82     child.expect("smb:")
83     child.sendline("cd testdir")
84     child.expect('testdir')
85     child.sendline("cd ..")
86     child.sendline("rmdir testdir")
87
88
89 def create_shares(t):
90     '''create some test shares'''
91     t.info("Adding test shares")
92     t.chdir('${PREFIX}')
93     t.write_file("etc/smb.conf", '''
94 [test]
95        path = ${PREFIX}/test
96        read only = no
97 [profiles]
98        path = ${PREFIX}/var/profiles
99        read only = no
100     ''',
101                  mode='a')
102     t.run_cmd("mkdir -p test")
103     t.run_cmd("mkdir -p var/profiles")
104
105
106 def set_nameserver(t, nameserver):
107     '''set the nameserver in resolv.conf'''
108     t.write_file("/etc/resolv.conf.wintest", '''
109 # Generated by wintest, the Samba v Windows automated testing system
110 nameserver %s
111
112 # your original resolv.conf appears below:
113 ''' % t.substitute(nameserver))
114     child = t.pexpect_spawn("cat /etc/resolv.conf", crlf=False)
115     i = child.expect(['your original resolv.conf appears below:', pexpect.EOF])
116     if i == 0:
117         child.expect(pexpect.EOF)
118     contents = child.before.lstrip().replace('\r', '')
119     t.write_file('/etc/resolv.conf.wintest', contents, mode='a')
120     t.write_file('/etc/resolv.conf.wintest-bak', contents)
121     t.run_cmd("mv -f /etc/resolv.conf.wintest /etc/resolv.conf")
122     t.resolv_conf_backup = '/etc/resolv.conf.wintest-bak';
123
124
125 def restore_resolv_conf(t):
126     '''restore the /etc/resolv.conf after testing is complete'''
127     if getattr(t, 'resolv_conf_backup', False):
128         t.info("restoring /etc/resolv.conf")
129         t.run_cmd("mv -f %s /etc/resolv.conf" % t.resolv_conf_backup)
130
131
132 def rndc_cmd(t, cmd, checkfail=True):
133     '''run a rndc command'''
134     t.run_cmd("${RNDC} -c ${PREFIX}/etc/rndc.conf %s" % cmd, checkfail=checkfail)
135
136
137 def configure_bind(t):
138     t.chdir('${PREFIX}')
139
140     nameserver = t.get_nameserver()
141     if nameserver == t.getvar('INTERFACE_IP'):
142         raise RuntimeError("old /etc/resolv.conf must not contain %s as a nameserver, this will create loops with the generated dns configuration" % nameserver)
143     t.setvar('DNSSERVER', nameserver)
144
145     if t.getvar('INTERFACE_IPV6'):
146         ipv6_listen = 'listen-on-v6 port 53 { ${INTERFACE_IPV6}; };'
147     else:
148         ipv6_listen = ''
149     t.setvar('BIND_LISTEN_IPV6', ipv6_listen)
150
151     t.write_file("etc/named.conf", '''
152 options {
153         listen-on port 53 { ${INTERFACE_IP};  };
154         ${BIND_LISTEN_IPV6}
155         directory       "${PREFIX}/var/named";
156         dump-file       "${PREFIX}/var/named/data/cache_dump.db";
157         pid-file        "${PREFIX}/var/named/named.pid";
158         statistics-file "${PREFIX}/var/named/data/named_stats.txt";
159         memstatistics-file "${PREFIX}/var/named/data/named_mem_stats.txt";
160         allow-query     { any; };
161         recursion yes;
162         tkey-gssapi-keytab "${PREFIX}/private/dns.keytab";
163         max-cache-ttl 10;
164         max-ncache-ttl 10;
165
166         forward only;
167         forwarders {
168                   ${DNSSERVER};
169         };
170
171 };
172
173 key "rndc-key" {
174         algorithm hmac-md5;
175         secret "lA/cTrno03mt5Ju17ybEYw==";
176 };
177  
178 controls {
179         inet ${INTERFACE_IP} port 953
180         allow { any; } keys { "rndc-key"; };
181 };
182
183 include "${PREFIX}/private/named.conf";
184 ''')
185
186     # add forwarding for the windows domains
187     domains = t.get_domains()
188     for d in domains:
189         t.write_file('etc/named.conf',
190                      '''
191 zone "%s" IN {
192       type forward;
193       forward only;
194       forwarders {
195          %s;
196       };
197 };
198 ''' % (d, domains[d]),
199                      mode='a')
200
201
202     t.write_file("etc/rndc.conf", '''
203 # Start of rndc.conf
204 key "rndc-key" {
205         algorithm hmac-md5;
206         secret "lA/cTrno03mt5Ju17ybEYw==";
207 };
208
209 options {
210         default-key "rndc-key";
211         default-server  ${INTERFACE_IP};
212         default-port 953;
213 };
214 ''')
215
216     set_nameserver(t, t.getvar('INTERFACE_IP'))
217
218
219 def stop_bind(t):
220     '''Stop our private BIND from listening and operating'''
221     rndc_cmd(t, "stop", checkfail=False)
222     t.port_wait("${INTERFACE_IP}", 53, wait_for_fail=True)
223
224     t.run_cmd("rm -rf var/named")
225
226
227 def start_bind(t):
228     '''restart the test environment version of bind'''
229     t.info("Restarting bind9")
230     t.chdir('${PREFIX}')
231
232     set_nameserver(t, t.getvar('INTERFACE_IP'))
233
234     t.run_cmd("mkdir -p var/named/data")
235     t.run_cmd("chown -R ${BIND_USER} var/named")
236
237     t.bind_child = t.run_child("${BIND9} -u ${BIND_USER} -n 1 -c ${PREFIX}/etc/named.conf -g")
238
239     t.port_wait("${INTERFACE_IP}", 53)
240     rndc_cmd(t, "flush")
241
242 def restart_bind(t):
243     configure_bind(t)
244     stop_bind(t)
245     start_bind(t)
246
247 def test_dns(t):
248     '''test that DNS is OK'''
249     t.info("Testing DNS")
250     t.cmd_contains("host -t SRV _ldap._tcp.${LCREALM}.",
251                  ['_ldap._tcp.${LCREALM} has SRV record 0 100 389 ${HOSTNAME}.${LCREALM}'])
252     t.cmd_contains("host -t SRV  _kerberos._udp.${LCREALM}.",
253                  ['_kerberos._udp.${LCREALM} has SRV record 0 100 88 ${HOSTNAME}.${LCREALM}'])
254     t.cmd_contains("host -t A ${HOSTNAME}.${LCREALM}",
255                  ['${HOSTNAME}.${LCREALM} has address'])
256
257 def test_kerberos(t):
258     '''test that kerberos is OK'''
259     t.info("Testing kerberos")
260     t.run_cmd("kdestroy")
261     t.kinit("administrator@${REALM}", "${PASSWORD1}")
262     # this copes with the differences between MIT and Heimdal klist
263     t.cmd_contains("klist", ["rincipal", "administrator@${REALM}"])
264
265
266 def test_dyndns(t):
267     '''test that dynamic DNS is working'''
268     t.chdir('${PREFIX}')
269     t.run_cmd("sbin/samba_dnsupdate --fail-immediately")
270     rndc_cmd(t, "flush")
271
272
273 def run_winjoin(t, vm):
274     '''join a windows box to our domain'''
275     t.setwinvars(vm)
276
277     t.info("Joining a windows box to the domain")
278     t.vm_poweroff("${WIN_VM}", checkfail=False)
279     t.vm_restore("${WIN_VM}", "${WIN_SNAPSHOT}")
280     child = t.open_telnet("${WIN_HOSTNAME}", "${WIN_USER}", "${WIN_PASS}", set_time=True, set_ip=True)
281     child.sendline("netdom join ${WIN_HOSTNAME} /Domain:${LCREALM} /PasswordD:${PASSWORD1} /UserD:administrator")
282     child.expect("The command completed successfully")
283     child.expect("C:")
284     child.sendline("shutdown /r -t 0")
285     t.wait_reboot()
286     child = t.open_telnet("${WIN_HOSTNAME}", "${WIN_USER}", "${WIN_PASS}", set_time=True, set_ip=True)
287     child.sendline("ipconfig /registerdns")
288     child.expect("Registration of the DNS resource records for all adapters of this computer has been initiated. Any errors will be reported in the Event Viewer")
289     child.expect("C:")
290
291 def test_winjoin(t, vm):
292     t.info("Checking the windows join is OK")
293     t.chdir('${PREFIX}')
294     t.port_wait("${WIN_IP}", 139)
295     t.retry_cmd('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Uadministrator@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"], retries=100)
296     t.cmd_contains("host -t A ${WIN_HOSTNAME}.${LCREALM}.", ['has address'])
297     t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
298     t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -k no -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
299     t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -k yes -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
300     child = t.open_telnet("${WIN_HOSTNAME}", "${DOMAIN}\\administrator", "${PASSWORD1}")
301     child.sendline("net use t: \\\\${HOSTNAME}.${LCREALM}\\test")
302     child.expect("The command completed successfully")
303     t.vm_poweroff("${WIN_VM}")
304
305
306 def run_dcpromo(t, vm):
307     '''run a dcpromo on windows'''
308     t.setwinvars(vm)
309
310     t.info("Joining a windows VM ${WIN_VM} to the domain as a DC using dcpromo")
311     t.vm_poweroff("${WIN_VM}", checkfail=False)
312     t.vm_restore("${WIN_VM}", "${WIN_SNAPSHOT}")
313     child = t.open_telnet("${WIN_HOSTNAME}", "administrator", "${WIN_PASS}", set_ip=True)
314     child.sendline("copy /Y con answers.txt")
315     child.sendline('''
316 [DCINSTALL]
317 RebootOnSuccess=Yes
318 RebootOnCompletion=Yes
319 ReplicaOrNewDomain=Replica
320 ReplicaDomainDNSName=${LCREALM}
321 SiteName=Default-First-Site-Name
322 InstallDNS=No
323 ConfirmGc=Yes
324 CreateDNSDelegation=No
325 UserDomain=${LCREALM}
326 UserName=${LCREALM}\\administrator
327 Password=${PASSWORD1}
328 DatabasePath="C:\Windows\NTDS"
329 LogPath="C:\Windows\NTDS"
330 SYSVOLPath="C:\Windows\SYSVOL"
331 SafeModeAdminPassword=${PASSWORD1}
332 \1a
333 ''')
334     child.expect("copied.")
335     child.expect("C:")
336     child.expect("C:")
337     child.sendline("dcpromo /answer:answers.txt")
338     i = child.expect(["You must restart this computer", "failed", "Active Directory Domain Services was not installed", "C:"], timeout=120)
339     if i == 1 or i == 2:
340         raise Exception("dcpromo failed")
341     t.wait_reboot()
342
343
344 def test_dcpromo(t, vm):
345     '''test that dcpromo worked'''
346     t.info("Checking the dcpromo join is OK")
347     t.chdir('${PREFIX}')
348     t.port_wait("${WIN_IP}", 139)
349     t.retry_cmd("host -t A ${WIN_HOSTNAME}.${LCREALM}. ${INTERFACE_IP}",
350                 ['${WIN_HOSTNAME}.${LCREALM} has address'],
351                 retries=30, delay=10, casefold=True)
352     t.retry_cmd('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Uadministrator@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
353     t.cmd_contains("host -t A ${WIN_HOSTNAME}.${LCREALM}.", ['has address'])
354     t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
355
356     t.cmd_contains("bin/samba-tool drs kcc ${HOSTNAME}.${LCREALM} -Uadministrator@${LCREALM}%${PASSWORD1}", ['Consistency check', 'successful'])
357     t.retry_cmd("bin/samba-tool drs kcc ${WIN_HOSTNAME}.${LCREALM} -Uadministrator@${LCREALM}%${PASSWORD1}", ['Consistency check', 'successful'])
358
359     t.kinit("administrator@${REALM}", "${PASSWORD1}")
360
361     # the first replication will transfer the dnsHostname attribute
362     t.cmd_contains("bin/samba-tool drs replicate ${HOSTNAME}.${LCREALM} ${WIN_HOSTNAME} CN=Configuration,${BASEDN} -k yes", ["was successful"])
363
364     for nc in [ '${BASEDN}', 'CN=Configuration,${BASEDN}', 'CN=Schema,CN=Configuration,${BASEDN}' ]:
365         t.cmd_contains("bin/samba-tool drs replicate ${HOSTNAME}.${LCREALM} ${WIN_HOSTNAME}.${LCREALM} %s -k yes" % nc, ["was successful"])
366         t.cmd_contains("bin/samba-tool drs replicate ${WIN_HOSTNAME}.${LCREALM} ${HOSTNAME}.${LCREALM} %s -k yes" % nc, ["was successful"])
367
368     t.cmd_contains("bin/samba-tool drs showrepl ${HOSTNAME}.${LCREALM} -k yes",
369                  [ "INBOUND NEIGHBORS",
370                    "${BASEDN}",
371                    "Last attempt .* was successful",
372                    "CN=Configuration,${BASEDN}",
373                    "Last attempt .* was successful",
374                    "CN=Configuration,${BASEDN}", # cope with either order
375                    "Last attempt .* was successful",
376                    "OUTBOUND NEIGHBORS",
377                    "${BASEDN}",
378                    "Last success",
379                    "CN=Configuration,${BASEDN}",
380                    "Last success",
381                    "CN=Configuration,${BASEDN}",
382                    "Last success"],
383                    ordered=True,
384                    regex=True)
385
386     t.cmd_contains("bin/samba-tool drs showrepl ${WIN_HOSTNAME}.${LCREALM} -k yes",
387                  [ "INBOUND NEIGHBORS",
388                    "${BASEDN}",
389                    "Last attempt .* was successful",
390                    "CN=Configuration,${BASEDN}",
391                    "Last attempt .* was successful",
392                    "CN=Configuration,${BASEDN}",
393                    "Last attempt .* was successful",
394                    "OUTBOUND NEIGHBORS",
395                    "${BASEDN}",
396                    "Last success",
397                    "CN=Configuration,${BASEDN}",
398                    "Last success",
399                    "CN=Configuration,${BASEDN}",
400                    "Last success" ],
401                    ordered=True,
402                    regex=True)
403
404     child = t.open_telnet("${WIN_HOSTNAME}", "${DOMAIN}\\administrator", "${PASSWORD1}", set_time=True)
405     child.sendline("net use t: \\\\${HOSTNAME}.${LCREALM}\\test")
406
407     retries = 10
408     i = child.expect(["The command completed successfully", "The network path was not found"])
409     while i == 1 and retries > 0:
410         child.expect("C:")
411         time.sleep(2)
412         child.sendline("net use t: \\\\${HOSTNAME}.${LCREALM}\\test")
413         i = child.expect(["The command completed successfully", "The network path was not found"])
414         retries -=1
415
416     t.run_net_time(child)
417
418     t.info("Checking if showrepl is happy")
419     child.sendline("repadmin /showrepl")
420     child.expect("${BASEDN}")
421     child.expect("was successful")
422     child.expect("CN=Configuration,${BASEDN}")
423     child.expect("was successful")
424     child.expect("CN=Schema,CN=Configuration,${BASEDN}")
425     child.expect("was successful")
426
427     t.info("Checking if new users propogate to windows")
428     t.retry_cmd('bin/samba-tool newuser test2 ${PASSWORD2}', ["created successfully"])
429     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k no", ['Sharename', 'Remote IPC'])
430     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k yes", ['Sharename', 'Remote IPC'])
431
432     t.info("Checking if new users on windows propogate to samba")
433     child.sendline("net user test3 ${PASSWORD3} /add")
434     while True:
435         i = child.expect(["The command completed successfully",
436                           "The directory service was unable to allocate a relative identifier"])
437         if i == 0:
438             break
439         time.sleep(2)
440
441     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${LCREALM} -Utest3%${PASSWORD3} -k no", ['Sharename', 'IPC'])
442     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${LCREALM} -Utest3%${PASSWORD3} -k yes", ['Sharename', 'IPC'])
443
444     t.info("Checking propogation of user deletion")
445     t.run_cmd('bin/samba-tool user delete test2 -Uadministrator@${LCREALM}%${PASSWORD1}')
446     child.sendline("net user test3 /del")
447     child.expect("The command completed successfully")
448
449     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k no", ['LOGON_FAILURE'])
450     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${LCREALM} -Utest3%${PASSWORD3} -k no", ['LOGON_FAILURE'])
451     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k yes", ['LOGON_FAILURE'])
452     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${LCREALM} -Utest3%${PASSWORD3} -k yes", ['LOGON_FAILURE'])
453     t.vm_poweroff("${WIN_VM}")
454
455
456 def run_dcpromo_rodc(t, vm):
457     '''run a RODC dcpromo to join a windows DC to the samba domain'''
458     t.setwinvars(vm)
459     t.info("Joining a w2k8 box to the domain as a RODC")
460     t.vm_poweroff("${WIN_VM}", checkfail=False)
461     t.vm_restore("${WIN_VM}", "${WIN_SNAPSHOT}")
462     child = t.open_telnet("${WIN_HOSTNAME}", "administrator", "${WIN_PASS}", set_ip=True)
463     child.sendline("copy /Y con answers.txt")
464     child.sendline('''
465 [DCInstall]
466 ReplicaOrNewDomain=ReadOnlyReplica
467 ReplicaDomainDNSName=${LCREALM}
468 PasswordReplicationDenied="BUILTIN\Administrators"
469 PasswordReplicationDenied="BUILTIN\Server Operators"
470 PasswordReplicationDenied="BUILTIN\Backup Operators"
471 PasswordReplicationDenied="BUILTIN\Account Operators"
472 PasswordReplicationDenied="${DOMAIN}\Denied RODC Password Replication Group"
473 PasswordReplicationAllowed="${DOMAIN}\Allowed RODC Password Replication Group"
474 DelegatedAdmin="${DOMAIN}\\Administrator"
475 SiteName=Default-First-Site-Name
476 InstallDNS=No
477 ConfirmGc=Yes
478 CreateDNSDelegation=No
479 UserDomain=${LCREALM}
480 UserName=${LCREALM}\\administrator
481 Password=${PASSWORD1}
482 DatabasePath="C:\Windows\NTDS"
483 LogPath="C:\Windows\NTDS"
484 SYSVOLPath="C:\Windows\SYSVOL"
485 SafeModeAdminPassword=${PASSWORD1}
486 RebootOnCompletion=No
487 \1a
488 ''')
489     child.expect("copied.")
490     child.sendline("dcpromo /answer:answers.txt")
491     i = child.expect(["You must restart this computer", "failed"], timeout=120)
492     if i != 0:
493         raise Exception("dcpromo failed")
494     child.sendline("shutdown -r -t 0")
495     t.wait_reboot()
496
497
498
499 def test_dcpromo_rodc(t, vm):
500     '''test the RODC dcpromo worked'''
501     t.info("Checking the w2k8 RODC join is OK")
502     t.chdir('${PREFIX}')
503     t.port_wait("${WIN_IP}", 139)
504     t.retry_cmd('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Uadministrator@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
505     t.cmd_contains("host -t A ${WIN_HOSTNAME}.${LCREALM}.", ['has address'])
506     t.cmd_contains('bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utestallowed@${LCREALM}%${PASSWORD1}', ["C$", "IPC$", "Sharename"])
507     child = t.open_telnet("${WIN_HOSTNAME}", "${DOMAIN}\\administrator", "${PASSWORD1}", set_time=True)
508     child.sendline("net use t: \\\\${HOSTNAME}.${LCREALM}\\test")
509     child.expect("The command completed successfully")
510
511     t.info("Checking if showrepl is happy")
512     child.sendline("repadmin /showrepl")
513     child.expect("${BASEDN}")
514     child.expect("was successful")
515     child.expect("CN=Configuration,${BASEDN}")
516     child.expect("was successful")
517     child.expect("CN=Configuration,${BASEDN}")
518     child.expect("was successful")
519
520     t.info("Checking if new users are available on windows")
521     t.run_cmd('bin/samba-tool newuser test2 ${PASSWORD2}')
522     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k yes", ['Sharename', 'Remote IPC'])
523     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k no", ['LOGON_FAILURE'])
524     t.retry_cmd("bin/samba-tool drs replicate ${WIN_HOSTNAME}.${LCREALM} ${HOSTNAME}.${LCREALM} ${BASEDN} -k yes", ["was successful"])
525     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k no", ['Sharename', 'Remote IPC'])
526     t.run_cmd('bin/samba-tool user delete test2 -Uadministrator@${LCREALM}%${PASSWORD1}')
527     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k yes", ['LOGON_FAILURE'])
528     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${LCREALM} -Utest2%${PASSWORD2} -k no", ['LOGON_FAILURE'])
529     t.vm_poweroff("${WIN_VM}")
530
531
532 def prep_join_as_dc(t, vm):
533     '''start VM and shutdown Samba in preperation to join a windows domain as a DC'''
534     t.setwinvars(vm)
535     t.info("Starting VMs for joining ${WIN_VM} as a second DC using samba-tool join DC")
536     t.chdir('${PREFIX}')
537     t.run_cmd('killall -9 -q samba smbd nmbd winbindd', checkfail=False)
538     t.vm_poweroff("${WIN_VM}", checkfail=False)
539     t.vm_restore("${WIN_VM}", "${WIN_SNAPSHOT}")
540     rndc_cmd(t, 'flush')
541     t.run_cmd("rm -rf etc/smb.conf private")
542     child = t.open_telnet("${WIN_HOSTNAME}", "${WIN_DOMAIN}\\administrator", "${WIN_PASS}", set_time=True)
543     t.get_ipconfig(child)
544
545 def join_as_dc(t, vm):
546     '''join a windows domain as a DC'''
547     t.setwinvars(vm)
548     t.info("Joining ${WIN_VM} as a second DC using samba-tool join DC")
549     t.port_wait("${WIN_IP}", 389)
550     t.retry_cmd("host -t SRV _ldap._tcp.${WIN_REALM} ${WIN_IP}", ['has SRV record'] )
551
552     t.retry_cmd("bin/samba-tool drs showrepl ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator%${WIN_PASS}", ['INBOUND NEIGHBORS'] )
553     t.run_cmd('bin/samba-tool join ${WIN_REALM} DC -Uadministrator%${WIN_PASS} -d${DEBUGLEVEL} --option=interfaces=${INTERFACE}')
554     t.run_cmd('bin/samba-tool drs kcc ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
555
556
557 def test_join_as_dc(t, vm):
558     '''test the join of a windows domain as a DC'''
559     t.info("Checking the DC join is OK")
560     t.chdir('${PREFIX}')
561     t.retry_cmd('bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}', ["C$", "IPC$", "Sharename"])
562     t.cmd_contains("host -t A ${HOSTNAME}.${WIN_REALM}.", ['has address'])
563     child = t.open_telnet("${WIN_HOSTNAME}", "${WIN_DOMAIN}\\administrator", "${WIN_PASS}", set_time=True)
564
565     t.info("Forcing kcc runs, and replication")
566     t.run_cmd('bin/samba-tool drs kcc ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
567     t.run_cmd('bin/samba-tool drs kcc ${HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
568
569     t.kinit("administrator@${WIN_REALM}", "${WIN_PASS}")
570     for nc in [ '${WIN_BASEDN}', 'CN=Configuration,${WIN_BASEDN}', 'CN=Schema,CN=Configuration,${WIN_BASEDN}' ]:
571         t.cmd_contains("bin/samba-tool drs replicate ${HOSTNAME}.${WIN_REALM} ${WIN_HOSTNAME}.${WIN_REALM} %s -k yes" % nc, ["was successful"])
572         t.cmd_contains("bin/samba-tool drs replicate ${WIN_HOSTNAME}.${WIN_REALM} ${HOSTNAME}.${WIN_REALM} %s -k yes" % nc, ["was successful"])
573
574     retries = 10
575     i = 1
576     while i == 1 and retries > 0:
577         child.sendline("net use t: \\\\${HOSTNAME}.${WIN_REALM}\\test")
578         i = child.expect(["The command completed successfully", "The network path was not found"])
579         child.expect("C:")
580         if i == 1:
581             time.sleep(2)
582         retries -=1
583
584     t.info("Checking if showrepl is happy")
585     child.sendline("repadmin /showrepl")
586     child.expect("${WIN_BASEDN}")
587     child.expect("was successful")
588     child.expect("CN=Configuration,${WIN_BASEDN}")
589     child.expect("was successful")
590     child.expect("CN=Configuration,${WIN_BASEDN}")
591     child.expect("was successful")
592
593     t.info("Checking if new users propogate to windows")
594     t.retry_cmd('bin/samba-tool newuser test2 ${PASSWORD2}', ["created successfully"])
595     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${WIN_REALM} -Utest2%${PASSWORD2} -k no", ['Sharename', 'Remote IPC'])
596     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${WIN_REALM} -Utest2%${PASSWORD2} -k yes", ['Sharename', 'Remote IPC'])
597
598     t.info("Checking if new users on windows propogate to samba")
599     child.sendline("net user test3 ${PASSWORD3} /add")
600     child.expect("The command completed successfully")
601     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k no", ['Sharename', 'IPC'])
602     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k yes", ['Sharename', 'IPC'])
603
604     t.info("Checking propogation of user deletion")
605     t.run_cmd('bin/samba-tool user delete test2 -Uadministrator@${WIN_REALM}%${WIN_PASS}')
606     child.sendline("net user test3 /del")
607     child.expect("The command completed successfully")
608
609     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${WIN_REALM} -Utest2%${PASSWORD2} -k no", ['LOGON_FAILURE'])
610     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k no", ['LOGON_FAILURE'])
611     t.retry_cmd("bin/smbclient -L ${WIN_HOSTNAME}.${WIN_REALM} -Utest2%${PASSWORD2} -k yes", ['LOGON_FAILURE'])
612     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k yes", ['LOGON_FAILURE'])
613     t.vm_poweroff("${WIN_VM}")
614
615
616 def join_as_rodc(t, vm):
617     '''join a windows domain as a RODC'''
618     t.setwinvars(vm)
619     t.info("Joining ${WIN_VM} as a RODC using samba-tool join DC")
620     t.port_wait("${WIN_IP}", 389)
621     t.retry_cmd("host -t SRV _ldap._tcp.${WIN_REALM} ${WIN_IP}", ['has SRV record'] )
622     t.retry_cmd("bin/samba-tool drs showrepl ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator%${WIN_PASS}", ['INBOUND NEIGHBORS'] )
623     t.run_cmd('bin/samba-tool join ${WIN_REALM} RODC -Uadministrator%${WIN_PASS} -d${DEBUGLEVEL} --option=interfaces=${INTERFACE}')
624     t.run_cmd('bin/samba-tool drs kcc ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
625
626
627 def test_join_as_rodc(t, vm):
628     '''test a windows domain RODC join'''
629     t.info("Checking the RODC join is OK")
630     t.chdir('${PREFIX}')
631     t.retry_cmd('bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}', ["C$", "IPC$", "Sharename"])
632     t.cmd_contains("host -t A ${HOSTNAME}.${WIN_REALM}.", ['has address'])
633     child = t.open_telnet("${WIN_HOSTNAME}", "${WIN_DOMAIN}\\administrator", "${WIN_PASS}", set_time=True)
634
635     t.info("Forcing kcc runs, and replication")
636     t.run_cmd('bin/samba-tool drs kcc ${HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
637     t.run_cmd('bin/samba-tool drs kcc ${WIN_HOSTNAME}.${WIN_REALM} -Uadministrator@${WIN_REALM}%${WIN_PASS}')
638
639     t.kinit("administrator@${WIN_REALM}", "${WIN_PASS}")
640     for nc in [ '${WIN_BASEDN}', 'CN=Configuration,${WIN_BASEDN}', 'CN=Schema,CN=Configuration,${WIN_BASEDN}' ]:
641         t.cmd_contains("bin/samba-tool drs replicate ${HOSTNAME}.${WIN_REALM} ${WIN_HOSTNAME}.${WIN_REALM} %s -k yes" % nc, ["was successful"])
642
643     retries = 10
644     i = 1
645     while i == 1 and retries > 0:
646         child.sendline("net use t: \\\\${HOSTNAME}.${WIN_REALM}\\test")
647         i = child.expect(["The command completed successfully", "The network path was not found"])
648         child.expect("C:")
649         if i == 1:
650             time.sleep(2)
651         retries -=1
652
653     t.info("Checking if showrepl is happy")
654     child.sendline("repadmin /showrepl")
655     child.expect("DSA invocationID")
656
657     t.cmd_contains("bin/samba-tool drs showrepl ${WIN_HOSTNAME}.${WIN_REALM} -k yes",
658                  [ "INBOUND NEIGHBORS",
659                    "OUTBOUND NEIGHBORS",
660                    "${WIN_BASEDN}",
661                    "Last attempt .* was successful",
662                    "CN=Configuration,${WIN_BASEDN}",
663                    "Last attempt .* was successful",
664                    "CN=Configuration,${WIN_BASEDN}",
665                    "Last attempt .* was successful" ],
666                    ordered=True,
667                    regex=True)
668
669     t.info("Checking if new users on windows propogate to samba")
670     child.sendline("net user test3 ${PASSWORD3} /add")
671     child.expect("The command completed successfully")
672     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k no", ['Sharename', 'IPC'])
673     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k yes", ['Sharename', 'IPC'])
674
675     # should this work?
676     t.info("Checking if new users propogate to windows")
677     t.cmd_contains('bin/samba-tool newuser test2 ${PASSWORD2}', ['No RID Set DN'])
678
679     t.info("Checking propogation of user deletion")
680     child.sendline("net user test3 /del")
681     child.expect("The command completed successfully")
682
683     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k no", ['LOGON_FAILURE'])
684     t.retry_cmd("bin/smbclient -L ${HOSTNAME}.${WIN_REALM} -Utest3%${PASSWORD3} -k yes", ['LOGON_FAILURE'])
685     t.vm_poweroff("${WIN_VM}")
686
687
688 def run_dcpromo_as_first_dc(t, vm, func_level=None):
689     t.setwinvars(vm)
690     t.info("Configuring a windows VM ${WIN_VM} at the first DC in the domain using dcpromo")
691     child = t.open_telnet("${WIN_HOSTNAME}", "administrator", "${WIN_PASS}", set_time=True)
692     if t.get_is_dc(child):
693         return
694
695     if func_level == '2008r2':
696         t.setvar("FUNCTION_LEVEL_INT", str(4))
697     elif func_level == '2003':
698         t.setvar("FUNCTION_LEVEL_INT", str(1))
699     else:
700         t.setvar("FUNCTION_LEVEL_INT", str(0))
701
702     child = t.open_telnet("${WIN_HOSTNAME}", "administrator", "${WIN_PASS}", set_ip=True)
703
704     """This server must therefore not yet be a directory server, so we must promote it"""
705     child.sendline("copy /Y con answers.txt")
706     child.sendline('''
707 [DCInstall]
708 ; New forest promotion
709 ReplicaOrNewDomain=Domain
710 NewDomain=Forest
711 NewDomainDNSName=${WIN_REALM}
712 ForestLevel=${FUNCTION_LEVEL_INT}
713 DomainNetbiosName=${WIN_DOMAIN}
714 DomainLevel=${FUNCTION_LEVEL_INT}
715 InstallDNS=Yes
716 ConfirmGc=Yes
717 CreateDNSDelegation=No
718 DatabasePath="C:\Windows\NTDS"
719 LogPath="C:\Windows\NTDS"
720 SYSVOLPath="C:\Windows\SYSVOL"
721 ; Set SafeModeAdminPassword to the correct value prior to using the unattend file
722 SafeModeAdminPassword=${WIN_PASS}
723 ; Run-time flags (optional)
724 RebootOnCompletion=No
725 \1a
726 ''')
727     child.expect("copied.")
728     child.expect("C:")
729     child.expect("C:")
730     child.sendline("dcpromo /answer:answers.txt")
731     i = child.expect(["You must restart this computer", "failed", "Active Directory Domain Services was not installed", "C:"], timeout=120)
732     if i == 1 or i == 2:
733         raise Exception("dcpromo failed")
734     child.sendline("shutdown -r -t 0")
735     t.port_wait("${WIN_IP}", 139, wait_for_fail=True)
736     t.port_wait("${WIN_IP}", 139)
737
738
739 def test_howto(t):
740     '''test the Samba4 howto'''
741
742     check_prerequesites(t)
743
744     # we don't need fsync safety in these tests
745     t.putenv('TDB_NO_FSYNC', '1')
746
747     if not t.skip("configure_bind"):
748         configure_bind(t)
749     if not t.skip("stop_bind"):
750         stop_bind(t)
751     if not t.skip("stop_vms"):
752         stop_vms(t)
753
754     if not t.skip("build"):
755         build_s4(t)
756
757     if not t.skip("provision"):
758         provision_s4(t)
759
760     if not t.skip("create-shares"):
761         create_shares(t)
762
763     if not t.skip("starts4"):
764         start_s4(t)
765     if not t.skip("smbclient"):
766         test_smbclient(t)
767     if not t.skip("configure_bind2"):
768         configure_bind(t)
769     if not t.skip("start_bind"):
770         start_bind(t)
771     if not t.skip("dns"):
772         test_dns(t)
773     if not t.skip("kerberos"):
774         test_kerberos(t)
775     if not t.skip("dyndns"):
776         test_dyndns(t)
777
778     if t.have_vm('WINDOWS7') and not t.skip("windows7"):
779         run_winjoin(t, "WINDOWS7")
780         test_winjoin(t, "WINDOWS7")
781
782     if t.have_vm('WINXP') and not t.skip("winxp"):
783         run_winjoin(t, "WINXP")
784         test_winjoin(t, "WINXP")
785
786     if t.have_vm('W2K8R2C') and not t.skip("dcpromo_rodc"):
787         t.info("Testing w2k8r2 RODC dcpromo")
788         run_dcpromo_rodc(t, "W2K8R2C")
789         test_dcpromo_rodc(t, "W2K8R2C")
790
791     if t.have_vm('W2K8R2B') and not t.skip("dcpromo_w2k8r2"):
792         t.info("Testing w2k8r2 dcpromo")
793         run_dcpromo(t, "W2K8R2B")
794         test_dcpromo(t, "W2K8R2B")
795
796     if t.have_vm('W2K8B') and not t.skip("dcpromo_w2k8"):
797         t.info("Testing w2k8 dcpromo")
798         run_dcpromo(t, "W2K8B")
799         test_dcpromo(t, "W2K8B")
800
801     if t.have_vm('W2K3B') and not t.skip("dcpromo_w2k3"):
802         t.info("Testing w2k3 dcpromo")
803         t.info("Changing to 2003 functional level")
804         provision_s4(t, func_level='2003')
805         create_shares(t)
806         start_s4(t)
807         test_smbclient(t)
808         restart_bind(t)
809         test_dns(t)
810         test_kerberos(t)
811         test_dyndns(t)
812         run_dcpromo(t, "W2K3B")
813         test_dcpromo(t, "W2K3B")
814
815     if t.have_vm('W2K8R2A') and not t.skip("join_w2k8r2"):
816         prep_join_as_dc(t, "W2K8R2A")
817         run_dcpromo_as_first_dc(t, "W2K8R2A", func_level='2008r2')
818         join_as_dc(t, "W2K8R2A")
819         create_shares(t)
820         start_s4(t)
821         test_dyndns(t)
822         test_join_as_dc(t, "W2K8R2A")
823
824     if t.have_vm('W2K8R2A') and not t.skip("join_rodc"):
825         prep_join_as_dc(t, "W2K8R2A")
826         run_dcpromo_as_first_dc(t, "W2K8R2A", func_level='2008r2')
827         join_as_rodc(t, "W2K8R2A")
828         create_shares(t)
829         start_s4(t)
830         test_dyndns(t)
831         test_join_as_rodc(t, "W2K8R2A")
832
833     if t.have_vm('W2K3A') and not t.skip("join_w2k3"):
834         prep_join_as_dc(t, "W2K3A")
835         run_dcpromo_as_first_dc(t, "W2K3A", func_level='2003')
836         join_as_dc(t, "W2K3A")
837         create_shares(t)
838         start_s4(t)
839         test_dyndns(t)
840         test_join_as_dc(t, "W2K3A")
841
842     t.info("Howto test: All OK")
843
844
845 def test_cleanup(t):
846     '''cleanup after tests'''
847     t.info("Cleaning up ...")
848     restore_resolv_conf(t)
849     if getattr(t, 'bind_child', False):
850         t.bind_child.kill()
851
852
853 if __name__ == '__main__':
854     t = wintest.wintest()
855
856     t.setup("test-s4-howto.py", "source4")
857
858     try:
859         test_howto(t)
860     except:
861         if not t.opts.nocleanup:
862             test_cleanup(t)
863         raise
864
865     if not t.opts.nocleanup:
866         test_cleanup(t)
867     t.info("S4 howto test: All OK")