samba-tool: dns: Add support for handling TXT records
[samba.git] / source4 / scripting / python / samba / netcmd / domain.py
1 #!/usr/bin/env python
2 #
3 # domain management
4 #
5 # Copyright Matthias Dieter Wallnoefer 2009
6 # Copyright Andrew Kroeger 2009
7 # Copyright Jelmer Vernooij 2009
8 # Copyright Giampaolo Lauria 2011
9 # Copyright Matthieu Patou <mat@matws.net> 2011
10 #
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 #
24
25
26
27 import samba.getopt as options
28 import ldb
29 import string
30 import os
31 import tempfile
32 import logging
33 from samba.net import Net, LIBNET_JOIN_AUTOMATIC
34 import samba.ntacls
35 from samba.join import join_RODC, join_DC, join_subdomain
36 from samba.auth import system_session
37 from samba.samdb import SamDB
38 from samba.dcerpc import drsuapi
39 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT
40 from samba.netcmd import (
41     Command,
42     CommandError,
43     SuperCommand,
44     Option
45     )
46 from samba.netcmd.common import netcmd_get_domain_infos_via_cldap
47 from samba.samba3 import Samba3
48 from samba.samba3 import param as s3param
49 from samba.upgrade import upgrade_from_samba3
50 from samba.drs_utils import (
51                             sendDsReplicaSync, drsuapi_connect, drsException,
52                             sendRemoveDsServer)
53
54
55 from samba.dsdb import (
56     DS_DOMAIN_FUNCTION_2000,
57     DS_DOMAIN_FUNCTION_2003,
58     DS_DOMAIN_FUNCTION_2003_MIXED,
59     DS_DOMAIN_FUNCTION_2008,
60     DS_DOMAIN_FUNCTION_2008_R2,
61     DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL,
62     DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL,
63     UF_WORKSTATION_TRUST_ACCOUNT,
64     UF_SERVER_TRUST_ACCOUNT,
65     UF_TRUSTED_FOR_DELEGATION
66     )
67
68 def get_testparm_var(testparm, smbconf, varname):
69     cmd = "%s -s -l --parameter-name='%s' %s 2>/dev/null" % (testparm, varname, smbconf)
70     output = os.popen(cmd, 'r').readline()
71     return output.strip()
72
73
74 class cmd_domain_export_keytab(Command):
75     """Dumps kerberos keys of the domain into a keytab"""
76
77     synopsis = "%prog <keytab> [options]"
78
79     takes_optiongroups = {
80         "sambaopts": options.SambaOptions,
81         "credopts": options.CredentialsOptions,
82         "versionopts": options.VersionOptions,
83         }
84
85     takes_options = [
86         Option("--principal", help="extract only this principal", type=str),
87         ]
88
89     takes_args = ["keytab"]
90
91     def run(self, keytab, credopts=None, sambaopts=None, versionopts=None, principal=None):
92         lp = sambaopts.get_loadparm()
93         net = Net(None, lp)
94         net.export_keytab(keytab=keytab, principal=principal)
95
96
97 class cmd_domain_info(Command):
98     """Print basic info about a domain and the DC passed as parameter"""
99
100     synopsis = "%prog <ip_address> [options]"
101
102     takes_options = [
103         ]
104
105     takes_optiongroups = {
106         "sambaopts": options.SambaOptions,
107         "credopts": options.CredentialsOptions,
108         "versionopts": options.VersionOptions,
109         }
110
111     takes_args = ["address"]
112
113     def run(self, address, credopts=None, sambaopts=None, versionopts=None):
114         lp = sambaopts.get_loadparm()
115         try:
116             res = netcmd_get_domain_infos_via_cldap(lp, None, address)
117             print "Forest           : %s" % res.forest
118             print "Domain           : %s" % res.dns_domain
119             print "Netbios domain   : %s" % res.domain_name
120             print "DC name          : %s" % res.pdc_dns_name
121             print "DC netbios name  : %s" % res.pdc_name
122             print "Server site      : %s" % res.server_site
123             print "Client site      : %s" % res.client_site
124         except RuntimeError:
125             raise CommandError("Invalid IP address '" + address + "'!")
126
127
128 class cmd_domain_join(Command):
129     """Joins domain as either member or backup domain controller"""
130
131     synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]"
132
133     takes_optiongroups = {
134         "sambaopts": options.SambaOptions,
135         "versionopts": options.VersionOptions,
136         "credopts": options.CredentialsOptions,
137     }
138
139     takes_options = [
140         Option("--server", help="DC to join", type=str),
141         Option("--site", help="site to join", type=str),
142         Option("--targetdir", help="where to store provision", type=str),
143         Option("--parent-domain", help="parent domain to create subdomain under", type=str),
144         Option("--domain-critical-only",
145                help="only replicate critical domain objects",
146                action="store_true"),
147         Option("--machinepass", type=str, metavar="PASSWORD",
148                help="choose machine password (otherwise random)")
149         ]
150
151     takes_args = ["domain", "role?"]
152
153     def run(self, domain, role=None, sambaopts=None, credopts=None,
154             versionopts=None, server=None, site=None, targetdir=None,
155             domain_critical_only=False, parent_domain=None, machinepass=None):
156         lp = sambaopts.get_loadparm()
157         creds = credopts.get_credentials(lp)
158         net = Net(creds, lp, server=credopts.ipaddress)
159
160         if site is None:
161             site = "Default-First-Site-Name"
162
163         netbios_name = lp.get("netbios name")
164
165         if not role is None:
166             role = role.upper()
167
168         if role is None or role == "MEMBER":
169             (join_password, sid, domain_name) = net.join_member(domain,
170                                                                 netbios_name,
171                                                                 LIBNET_JOIN_AUTOMATIC,
172                                                                 machinepass=machinepass)
173
174             self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid))
175             return
176         elif role == "DC":
177             join_DC(server=server, creds=creds, lp=lp, domain=domain,
178                     site=site, netbios_name=netbios_name, targetdir=targetdir,
179                     domain_critical_only=domain_critical_only,
180                     machinepass=machinepass)
181             return
182         elif role == "RODC":
183             join_RODC(server=server, creds=creds, lp=lp, domain=domain,
184                       site=site, netbios_name=netbios_name, targetdir=targetdir,
185                       domain_critical_only=domain_critical_only,
186                       machinepass=machinepass)
187             return
188         elif role == "SUBDOMAIN":
189             netbios_domain = lp.get("workgroup")
190             if parent_domain is None:
191                 parent_domain = ".".join(domain.split(".")[1:])
192             join_subdomain(server=server, creds=creds, lp=lp, dnsdomain=domain, parent_domain=parent_domain,
193                            site=site, netbios_name=netbios_name, netbios_domain=netbios_domain, targetdir=targetdir,
194                            machinepass=machinepass)
195             return
196         else:
197             raise CommandError("Invalid role '%s' (possible values: MEMBER, DC, RODC, SUBDOMAIN)" % role)
198
199
200
201 class cmd_domain_demote(Command):
202     """Demote ourselves from the role of Domain Controller"""
203
204     synopsis = "%prog [options]"
205
206     takes_options = [
207         Option("--server", help="DC to force replication before demote", type=str),
208         Option("--targetdir", help="where provision is stored", type=str),
209         ]
210
211     takes_optiongroups = {
212         "sambaopts": options.SambaOptions,
213         "credopts": options.CredentialsOptions,
214         "versionopts": options.VersionOptions,
215         }
216
217     def run(self, sambaopts=None, credopts=None,
218             versionopts=None, server=None, targetdir=None):
219         lp = sambaopts.get_loadparm()
220         creds = credopts.get_credentials(lp)
221         net = Net(creds, lp, server=credopts.ipaddress)
222
223         netbios_name = lp.get("netbios name")
224         samdb = SamDB(session_info=system_session(), credentials=creds, lp=lp)
225         if not server:
226             res = samdb.search(expression='(&(objectClass=computer)(serverReferenceBL=*))', attrs=["dnsHostName", "name"])
227             if (len(res) == 0):
228                 raise CommandError("Unable to search for servers")
229
230             if (len(res) == 1):
231                 raise CommandError("You are the latest server in the domain")
232
233             server = None
234             for e in res:
235                 if str(e["name"]).lower() != netbios_name.lower():
236                     server = e["dnsHostName"]
237                     break
238
239         ntds_guid = samdb.get_ntds_GUID()
240         msg = samdb.search(base=str(samdb.get_config_basedn()), scope=ldb.SCOPE_SUBTREE,
241                                 expression="(objectGUID=%s)" % ntds_guid,
242                                 attrs=['options'])
243         if len(msg) == 0 or "options" not in msg[0]:
244             raise CommandError("Failed to find options on %s" % ntds_guid)
245
246         ntds_dn = msg[0].dn
247         dsa_options = int(str(msg[0]['options']))
248
249         res = samdb.search(expression="(fSMORoleOwner=%s)" % str(ntds_dn),
250                             controls=["search_options:1:2"])
251
252         if len(res) != 0:
253             raise CommandError("Current DC is still the owner of %d role(s), use the role command to transfer roles to another DC")
254
255         print "Using %s as partner server for the demotion" % server
256         (drsuapiBind, drsuapi_handle, supportedExtensions) = drsuapi_connect(server, lp, creds)
257
258         print "Desactivating inbound replication"
259
260         nmsg = ldb.Message()
261         nmsg.dn = msg[0].dn
262
263         dsa_options |= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
264         nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
265         samdb.modify(nmsg)
266
267         if not (dsa_options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) and not samdb.am_rodc():
268
269             print "Asking partner server %s to synchronize from us" % server
270             for part in (samdb.get_schema_basedn(),
271                             samdb.get_config_basedn(),
272                             samdb.get_root_basedn()):
273                 try:
274                     sendDsReplicaSync(drsuapiBind, drsuapi_handle, ntds_guid, str(part), drsuapi.DRSUAPI_DRS_WRIT_REP)
275                 except drsException, e:
276                     print "Error while demoting, re-enabling inbound replication"
277                     dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
278                     nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
279                     samdb.modify(nmsg)
280                     raise CommandError("Error while sending a DsReplicaSync for partion %s" % str(part), e)
281         try:
282             remote_samdb = SamDB(url="ldap://%s" % server,
283                                 session_info=system_session(),
284                                 credentials=creds, lp=lp)
285
286             print "Changing userControl and container"
287             res = remote_samdb.search(base=str(remote_samdb.get_root_basedn()),
288                                 expression="(&(objectClass=user)(sAMAccountName=%s$))" %
289                                             netbios_name.upper(),
290                                 attrs=["userAccountControl"])
291             dc_dn = res[0].dn
292             uac = int(str(res[0]["userAccountControl"]))
293
294         except Exception, e:
295                 print "Error while demoting, re-enabling inbound replication"
296                 dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
297                 nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
298                 samdb.modify(nmsg)
299                 raise CommandError("Error while changing account control", e)
300
301         if (len(res) != 1):
302             print "Error while demoting, re-enabling inbound replication"
303             dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
304             nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
305             samdb.modify(nmsg)
306             raise CommandError("Unable to find object with samaccountName = %s$"
307                                " in the remote dc" % netbios_name.upper())
308
309         olduac = uac
310
311         uac ^= (UF_SERVER_TRUST_ACCOUNT|UF_TRUSTED_FOR_DELEGATION)
312         uac |= UF_WORKSTATION_TRUST_ACCOUNT
313
314         msg = ldb.Message()
315         msg.dn = dc_dn
316
317         msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
318                                                         ldb.FLAG_MOD_REPLACE,
319                                                         "userAccountControl")
320         try:
321             remote_samdb.modify(msg)
322         except Exception, e:
323             print "Error while demoting, re-enabling inbound replication"
324             dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
325             nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
326             samdb.modify(nmsg)
327
328             raise CommandError("Error while changing account control", e)
329
330         parent = msg.dn.parent()
331         rdn = str(res[0].dn)
332         rdn = string.replace(rdn, ",%s" % str(parent), "")
333         # Let's move to the Computer container
334         i = 0
335         newrdn = rdn
336
337         computer_dn = ldb.Dn(remote_samdb, "CN=Computers,%s" % str(remote_samdb.get_root_basedn()))
338         res = remote_samdb.search(base=computer_dn, expression=rdn, scope=ldb.SCOPE_ONELEVEL)
339
340         if (len(res) != 0):
341             res = remote_samdb.search(base=computer_dn, expression="%s-%d" % (rdn, i),
342                                         scope=ldb.SCOPE_ONELEVEL)
343             while(len(res) != 0 and i < 100):
344                 i = i + 1
345                 res = remote_samdb.search(base=computer_dn, expression="%s-%d" % (rdn, i),
346                                             scope=ldb.SCOPE_ONELEVEL)
347
348             if i == 100:
349                 print "Error while demoting, re-enabling inbound replication"
350                 dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
351                 nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
352                 samdb.modify(nmsg)
353
354                 msg = ldb.Message()
355                 msg.dn = dc_dn
356
357                 msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
358                                                         ldb.FLAG_MOD_REPLACE,
359                                                         "userAccountControl")
360
361                 remote_samdb.modify(msg)
362
363                 raise CommandError("Unable to find a slot for renaming %s,"
364                                     " all names from %s-1 to %s-%d seemed used" %
365                                     (str(dc_dn), rdn, rdn, i - 9))
366
367             newrdn = "%s-%d" % (rdn, i)
368
369         try:
370             newdn = ldb.Dn(remote_samdb, "%s,%s" % (newrdn, str(computer_dn)))
371             remote_samdb.rename(dc_dn, newdn)
372         except Exception, e:
373             print "Error while demoting, re-enabling inbound replication"
374             dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
375             nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
376             samdb.modify(nmsg)
377
378             msg = ldb.Message()
379             msg.dn = dc_dn
380
381             msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
382                                                     ldb.FLAG_MOD_REPLACE,
383                                                     "userAccountControl")
384
385             remote_samdb.modify(msg)
386             raise CommandError("Error while renaming %s to %s" % (str(dc_dn), str(newdn)), e)
387
388
389         server_dsa_dn = samdb.get_serverName()
390         domain = remote_samdb.get_root_basedn()
391
392         try:
393             sendRemoveDsServer(drsuapiBind, drsuapi_handle, server_dsa_dn, domain)
394         except drsException, e:
395             print "Error while demoting, re-enabling inbound replication"
396             dsa_options ^= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
397             nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
398             samdb.modify(nmsg)
399
400             msg = ldb.Message()
401             msg.dn = newdn
402
403             msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
404                                                     ldb.FLAG_MOD_REPLACE,
405                                                     "userAccountControl")
406             print str(dc_dn)
407             remote_samdb.modify(msg)
408             remote_samdb.rename(newdn, dc_dn)
409             raise CommandError("Error while sending a removeDsServer", e)
410
411         for s in ("CN=Entreprise,CN=Microsoft System Volumes,CN=System,CN=Configuration",
412                   "CN=%s,CN=Microsoft System Volumes,CN=System,CN=Configuration" % lp.get("realm"),
413                   "CN=Domain System Volumes (SYSVOL share),CN=File Replication Service,CN=System"):
414             try:
415                 remote_samdb.delete(ldb.Dn(remote_samdb,
416                                     "%s,%s,%s" % (str(rdn), s, str(remote_samdb.get_root_basedn()))))
417             except ldb.LdbError, l:
418                 pass
419
420         for s in ("CN=Entreprise,CN=NTFRS Subscriptions",
421                   "CN=%s, CN=NTFRS Subscriptions" % lp.get("realm"),
422                   "CN=Domain system Volumes (SYSVOL Share), CN=NTFRS Subscriptions",
423                   "CN=NTFRS Subscriptions"):
424             try:
425                 remote_samdb.delete(ldb.Dn(remote_samdb,
426                                     "%s,%s" % (s, str(newdn))))
427             except ldb.LdbError, l:
428                 pass
429
430         self.outf.write("Demote successfull\n")
431
432
433 class cmd_domain_level(Command):
434     """Raises domain and forest function levels"""
435
436     synopsis = "%prog (show|raise <options>) [options]"
437
438     takes_optiongroups = {
439         "sambaopts": options.SambaOptions,
440         "credopts": options.CredentialsOptions,
441         "versionopts": options.VersionOptions,
442         }
443
444     takes_options = [
445         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
446                metavar="URL", dest="H"),
447         Option("--quiet", help="Be quiet", action="store_true"),
448         Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2"],
449             help="The forest function level (2003 | 2008 | 2008_R2)"),
450         Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2"],
451             help="The domain function level (2003 | 2008 | 2008_R2)")
452             ]
453
454     takes_args = ["subcommand"]
455
456     def run(self, subcommand, H=None, forest_level=None, domain_level=None,
457             quiet=False, credopts=None, sambaopts=None, versionopts=None):
458         lp = sambaopts.get_loadparm()
459         creds = credopts.get_credentials(lp, fallback_machine=True)
460
461         samdb = SamDB(url=H, session_info=system_session(),
462             credentials=creds, lp=lp)
463
464         domain_dn = samdb.domain_dn()
465
466         res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
467           scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
468         assert len(res_forest) == 1
469
470         res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
471           attrs=["msDS-Behavior-Version", "nTMixedDomain"])
472         assert len(res_domain) == 1
473
474         res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
475           scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
476           attrs=["msDS-Behavior-Version"])
477         assert len(res_dc_s) >= 1
478
479         try:
480             level_forest = int(res_forest[0]["msDS-Behavior-Version"][0])
481             level_domain = int(res_domain[0]["msDS-Behavior-Version"][0])
482             level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0])
483
484             min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value
485             for msg in res_dc_s:
486                 if int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
487                     min_level_dc = int(msg["msDS-Behavior-Version"][0])
488
489             if level_forest < 0 or level_domain < 0:
490                 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
491             if min_level_dc < 0:
492                 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
493             if level_forest > level_domain:
494                 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
495             if level_domain > min_level_dc:
496                 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
497
498         except KeyError:
499             raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!")
500
501         if subcommand == "show":
502             self.message("Domain and forest function level for domain '%s'" % domain_dn)
503             if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
504                 self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
505             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
506                 self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
507             if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
508                 self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!")
509
510             self.message("")
511
512             if level_forest == DS_DOMAIN_FUNCTION_2000:
513                 outstr = "2000"
514             elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED:
515                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
516             elif level_forest == DS_DOMAIN_FUNCTION_2003:
517                 outstr = "2003"
518             elif level_forest == DS_DOMAIN_FUNCTION_2008:
519                 outstr = "2008"
520             elif level_forest == DS_DOMAIN_FUNCTION_2008_R2:
521                 outstr = "2008 R2"
522             else:
523                 outstr = "higher than 2008 R2"
524             self.message("Forest function level: (Windows) " + outstr)
525
526             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
527                 outstr = "2000 mixed (NT4 DC support)"
528             elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0:
529                 outstr = "2000"
530             elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED:
531                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
532             elif level_domain == DS_DOMAIN_FUNCTION_2003:
533                 outstr = "2003"
534             elif level_domain == DS_DOMAIN_FUNCTION_2008:
535                 outstr = "2008"
536             elif level_domain == DS_DOMAIN_FUNCTION_2008_R2:
537                 outstr = "2008 R2"
538             else:
539                 outstr = "higher than 2008 R2"
540             self.message("Domain function level: (Windows) " + outstr)
541
542             if min_level_dc == DS_DOMAIN_FUNCTION_2000:
543                 outstr = "2000"
544             elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
545                 outstr = "2003"
546             elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
547                 outstr = "2008"
548             elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
549                 outstr = "2008 R2"
550             else:
551                 outstr = "higher than 2008 R2"
552             self.message("Lowest function level of a DC: (Windows) " + outstr)
553
554         elif subcommand == "raise":
555             msgs = []
556
557             if domain_level is not None:
558                 if domain_level == "2003":
559                     new_level_domain = DS_DOMAIN_FUNCTION_2003
560                 elif domain_level == "2008":
561                     new_level_domain = DS_DOMAIN_FUNCTION_2008
562                 elif domain_level == "2008_R2":
563                     new_level_domain = DS_DOMAIN_FUNCTION_2008_R2
564
565                 if new_level_domain <= level_domain and level_domain_mixed == 0:
566                     raise CommandError("Domain function level can't be smaller than or equal to the actual one!")
567
568                 if new_level_domain > min_level_dc:
569                     raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
570
571                 # Deactivate mixed/interim domain support
572                 if level_domain_mixed != 0:
573                     # Directly on the base DN
574                     m = ldb.Message()
575                     m.dn = ldb.Dn(samdb, domain_dn)
576                     m["nTMixedDomain"] = ldb.MessageElement("0",
577                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
578                     samdb.modify(m)
579                     # Under partitions
580                     m = ldb.Message()
581                     m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % ldb.get_config_basedn())
582                     m["nTMixedDomain"] = ldb.MessageElement("0",
583                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
584                     try:
585                         samdb.modify(m)
586                     except ldb.LdbError, (enum, emsg):
587                         if enum != ldb.ERR_UNWILLING_TO_PERFORM:
588                             raise
589
590                 # Directly on the base DN
591                 m = ldb.Message()
592                 m.dn = ldb.Dn(samdb, domain_dn)
593                 m["msDS-Behavior-Version"]= ldb.MessageElement(
594                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
595                             "msDS-Behavior-Version")
596                 samdb.modify(m)
597                 # Under partitions
598                 m = ldb.Message()
599                 m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
600                   + ",CN=Partitions,%s" % ldb.get_config_basedn())
601                 m["msDS-Behavior-Version"]= ldb.MessageElement(
602                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
603                           "msDS-Behavior-Version")
604                 try:
605                     samdb.modify(m)
606                 except ldb.LdbError, (enum, emsg):
607                     if enum != ldb.ERR_UNWILLING_TO_PERFORM:
608                         raise
609
610                 level_domain = new_level_domain
611                 msgs.append("Domain function level changed!")
612
613             if forest_level is not None:
614                 if forest_level == "2003":
615                     new_level_forest = DS_DOMAIN_FUNCTION_2003
616                 elif forest_level == "2008":
617                     new_level_forest = DS_DOMAIN_FUNCTION_2008
618                 elif forest_level == "2008_R2":
619                     new_level_forest = DS_DOMAIN_FUNCTION_2008_R2
620                 if new_level_forest <= level_forest:
621                     raise CommandError("Forest function level can't be smaller than or equal to the actual one!")
622                 if new_level_forest > level_domain:
623                     raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
624                 m = ldb.Message()
625                 m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % ldb.get_config_basedn())
626                 m["msDS-Behavior-Version"]= ldb.MessageElement(
627                   str(new_level_forest), ldb.FLAG_MOD_REPLACE,
628                           "msDS-Behavior-Version")
629                 samdb.modify(m)
630                 msgs.append("Forest function level changed!")
631             msgs.append("All changes applied successfully!")
632             self.message("\n".join(msgs))
633         else:
634             raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
635
636
637 class cmd_domain_passwordsettings(Command):
638     """Sets password settings
639
640     Password complexity, history length, minimum password length, the minimum
641     and maximum password age) on a Samba4 server.
642     """
643
644     synopsis = "%prog (show|set <options>) [options]"
645
646     takes_optiongroups = {
647         "sambaopts": options.SambaOptions,
648         "versionopts": options.VersionOptions,
649         "credopts": options.CredentialsOptions,
650         }
651
652     takes_options = [
653         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
654                metavar="URL", dest="H"),
655         Option("--quiet", help="Be quiet", action="store_true"),
656         Option("--complexity", type="choice", choices=["on","off","default"],
657           help="The password complexity (on | off | default). Default is 'on'"),
658         Option("--store-plaintext", type="choice", choices=["on","off","default"],
659           help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
660         Option("--history-length",
661           help="The password history length (<integer> | default).  Default is 24.", type=str),
662         Option("--min-pwd-length",
663           help="The minimum password length (<integer> | default).  Default is 7.", type=str),
664         Option("--min-pwd-age",
665           help="The minimum password age (<integer in days> | default).  Default is 1.", type=str),
666         Option("--max-pwd-age",
667           help="The maximum password age (<integer in days> | default).  Default is 43.", type=str),
668           ]
669
670     takes_args = ["subcommand"]
671
672     def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None,
673             quiet=False, complexity=None, store_plaintext=None, history_length=None,
674             min_pwd_length=None, credopts=None, sambaopts=None,
675             versionopts=None):
676         lp = sambaopts.get_loadparm()
677         creds = credopts.get_credentials(lp)
678
679         samdb = SamDB(url=H, session_info=system_session(),
680             credentials=creds, lp=lp)
681
682         domain_dn = samdb.domain_dn()
683         res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
684           attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
685                  "minPwdAge", "maxPwdAge"])
686         assert(len(res) == 1)
687         try:
688             pwd_props = int(res[0]["pwdProperties"][0])
689             pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
690             cur_min_pwd_len = int(res[0]["minPwdLength"][0])
691             # ticks -> days
692             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
693             if int(res[0]["maxPwdAge"][0]) == -0x8000000000000000:
694                 cur_max_pwd_age = 0
695             else:
696                 cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
697         except Exception, e:
698             raise CommandError("Could not retrieve password properties!", e)
699
700         if subcommand == "show":
701             self.message("Password informations for domain '%s'" % domain_dn)
702             self.message("")
703             if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
704                 self.message("Password complexity: on")
705             else:
706                 self.message("Password complexity: off")
707             if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
708                 self.message("Store plaintext passwords: on")
709             else:
710                 self.message("Store plaintext passwords: off")
711             self.message("Password history length: %d" % pwd_hist_len)
712             self.message("Minimum password length: %d" % cur_min_pwd_len)
713             self.message("Minimum password age (days): %d" % cur_min_pwd_age)
714             self.message("Maximum password age (days): %d" % cur_max_pwd_age)
715         elif subcommand == "set":
716             msgs = []
717             m = ldb.Message()
718             m.dn = ldb.Dn(samdb, domain_dn)
719
720             if complexity is not None:
721                 if complexity == "on" or complexity == "default":
722                     pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
723                     msgs.append("Password complexity activated!")
724                 elif complexity == "off":
725                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
726                     msgs.append("Password complexity deactivated!")
727
728             if store_plaintext is not None:
729                 if store_plaintext == "on" or store_plaintext == "default":
730                     pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
731                     msgs.append("Plaintext password storage for changed passwords activated!")
732                 elif store_plaintext == "off":
733                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT)
734                     msgs.append("Plaintext password storage for changed passwords deactivated!")
735
736             if complexity is not None or store_plaintext is not None:
737                 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
738                   ldb.FLAG_MOD_REPLACE, "pwdProperties")
739
740             if history_length is not None:
741                 if history_length == "default":
742                     pwd_hist_len = 24
743                 else:
744                     pwd_hist_len = int(history_length)
745
746                 if pwd_hist_len < 0 or pwd_hist_len > 24:
747                     raise CommandError("Password history length must be in the range of 0 to 24!")
748
749                 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
750                   ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
751                 msgs.append("Password history length changed!")
752
753             if min_pwd_length is not None:
754                 if min_pwd_length == "default":
755                     min_pwd_len = 7
756                 else:
757                     min_pwd_len = int(min_pwd_length)
758
759                 if min_pwd_len < 0 or min_pwd_len > 14:
760                     raise CommandError("Minimum password length must be in the range of 0 to 14!")
761
762                 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
763                   ldb.FLAG_MOD_REPLACE, "minPwdLength")
764                 msgs.append("Minimum password length changed!")
765
766             if min_pwd_age is not None:
767                 if min_pwd_age == "default":
768                     min_pwd_age = 1
769                 else:
770                     min_pwd_age = int(min_pwd_age)
771
772                 if min_pwd_age < 0 or min_pwd_age > 998:
773                     raise CommandError("Minimum password age must be in the range of 0 to 998!")
774
775                 # days -> ticks
776                 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
777
778                 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
779                   ldb.FLAG_MOD_REPLACE, "minPwdAge")
780                 msgs.append("Minimum password age changed!")
781
782             if max_pwd_age is not None:
783                 if max_pwd_age == "default":
784                     max_pwd_age = 43
785                 else:
786                     max_pwd_age = int(max_pwd_age)
787
788                 if max_pwd_age < 0 or max_pwd_age > 999:
789                     raise CommandError("Maximum password age must be in the range of 0 to 999!")
790
791                 # days -> ticks
792                 if max_pwd_age == 0:
793                     max_pwd_age_ticks = -0x8000000000000000
794                 else:
795                     max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
796
797                 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
798                   ldb.FLAG_MOD_REPLACE, "maxPwdAge")
799                 msgs.append("Maximum password age changed!")
800
801             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
802                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
803
804             if len(m) == 0:
805                 raise CommandError("You must specify at least one option to set. Try --help")
806             samdb.modify(m)
807             msgs.append("All changes applied successfully!")
808             self.message("\n".join(msgs))
809         else:
810             raise CommandError("Wrong argument '%s'!" % subcommand)
811
812
813 class cmd_domain_samba3upgrade(Command):
814     """Upgrade from Samba3 database to Samba4 AD database.
815
816     Specify either a directory with all samba3 databases and state files (with --dbdir) or
817     samba3 testparm utility (with --testparm).
818     """
819
820     synopsis = "%prog [options] <samba3_smb_conf>"
821
822     takes_optiongroups = {
823         "sambaopts": options.SambaOptions,
824         "versionopts": options.VersionOptions
825     }
826
827     takes_options = [
828         Option("--dbdir", type="string", metavar="DIR",
829                   help="Path to samba3 database directory"),
830         Option("--testparm", type="string", metavar="PATH",
831                   help="Path to samba3 testparm utility from the previous installation.  This allows the default paths of the previous installation to be followed"),
832         Option("--targetdir", type="string", metavar="DIR",
833                   help="Path prefix where the new Samba 4.0 AD domain should be initialised"),
834         Option("--quiet", help="Be quiet", action="store_true"),
835         Option("--verbose", help="Be verbose", action="store_true"),
836         Option("--use-xattrs", type="choice", choices=["yes","no","auto"], metavar="[yes|no|auto]",
837                    help="Define if we should use the native fs capabilities or a tdb file for storing attributes likes ntacl, auto tries to make an inteligent guess based on the user rights and system capabilities", default="auto"),
838     ]
839
840     takes_args = ["smbconf"]
841
842     def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None, 
843             quiet=False, verbose=False, use_xattrs=None, sambaopts=None, versionopts=None):
844
845         if not os.path.exists(smbconf):
846             raise CommandError("File %s does not exist" % smbconf)
847
848         if testparm and not os.path.exists(testparm):
849             raise CommandError("Testparm utility %s does not exist" % testparm)
850
851         if dbdir and not os.path.exists(dbdir):
852             raise CommandError("Directory %s does not exist" % dbdir)
853
854         if not dbdir and not testparm:
855             raise CommandError("Please specify either dbdir or testparm")
856
857         logger = self.get_logger()
858         if verbose:
859             logger.setLevel(logging.DEBUG)
860         elif quiet:
861             logger.setLevel(logging.WARNING)
862         else:
863             logger.setLevel(logging.INFO)
864
865         if dbdir and testparm:
866             logger.warning("both dbdir and testparm specified, ignoring dbdir.")
867             dbdir = None
868
869         lp = sambaopts.get_loadparm()
870
871         s3conf = s3param.get_context()
872
873         if sambaopts.realm:
874             s3conf.set("realm", sambaopts.realm)
875
876         if targetdir is not None:
877             if not os.path.isdir(targetdir):
878                 os.mkdir(targetdir)
879
880         eadb = True
881         if use_xattrs == "yes":
882             eadb = False
883         elif use_xattrs == "auto" and not s3conf.get("posix:eadb"):
884             if targetdir:
885                 tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(targetdir))
886             else:
887                 tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(os.path.dirname(lp.get("private dir"))))
888             try:
889                 try:
890                     samba.ntacls.setntacl(lp, tmpfile.name,
891                                 "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
892                     eadb = False
893                 except Exception:
894                     # FIXME: Don't catch all exceptions here
895                     logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. "
896                                 "If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.")
897             finally:
898                 tmpfile.close()
899
900         # Set correct default values from dbdir or testparm
901         paths = {}
902         if dbdir:
903             paths["state directory"] = dbdir
904             paths["private dir"] = dbdir
905             paths["lock directory"] = dbdir
906         else:
907             paths["state directory"] = get_testparm_var(testparm, smbconf, "state directory")
908             paths["private dir"] = get_testparm_var(testparm, smbconf, "private dir")
909             paths["lock directory"] = get_testparm_var(testparm, smbconf, "lock directory")
910             # "testparm" from Samba 3 < 3.4.x is not aware of the parameter
911             # "state directory", instead make use of "lock directory"
912             if len(paths["state directory"]) == 0:
913                 paths["state directory"] = paths["lock directory"]
914
915         for p in paths:
916             s3conf.set(p, paths[p])
917     
918         # load smb.conf parameters
919         logger.info("Reading smb.conf")
920         s3conf.load(smbconf)
921         samba3 = Samba3(smbconf, s3conf)
922     
923         logger.info("Provisioning")
924         upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(), 
925                             useeadb=eadb)
926
927 class cmd_domain(SuperCommand):
928     """Domain management"""
929
930     subcommands = {}
931     subcommands["demote"] = cmd_domain_demote()
932     subcommands["exportkeytab"] = cmd_domain_export_keytab()
933     subcommands["info"] = cmd_domain_info()
934     subcommands["join"] = cmd_domain_join()
935     subcommands["level"] = cmd_domain_level()
936     subcommands["passwordsettings"] = cmd_domain_passwordsettings()
937     subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()