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
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.
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.
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/>.
27 import samba.getopt as options
33 from samba.net import Net, LIBNET_JOIN_AUTOMATIC
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 (
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,
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
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()
74 class cmd_domain_export_keytab(Command):
75 """Dumps kerberos keys of the domain into a keytab"""
77 synopsis = "%prog <keytab> [options]"
79 takes_optiongroups = {
80 "sambaopts": options.SambaOptions,
81 "credopts": options.CredentialsOptions,
82 "versionopts": options.VersionOptions,
86 Option("--principal", help="extract only this principal", type=str),
89 takes_args = ["keytab"]
91 def run(self, keytab, credopts=None, sambaopts=None, versionopts=None, principal=None):
92 lp = sambaopts.get_loadparm()
94 net.export_keytab(keytab=keytab, principal=principal)
97 class cmd_domain_info(Command):
98 """Print basic info about a domain and the DC passed as parameter"""
100 synopsis = "%prog <ip_address> [options]"
105 takes_optiongroups = {
106 "sambaopts": options.SambaOptions,
107 "credopts": options.CredentialsOptions,
108 "versionopts": options.VersionOptions,
111 takes_args = ["address"]
113 def run(self, address, credopts=None, sambaopts=None, versionopts=None):
114 lp = sambaopts.get_loadparm()
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
125 raise CommandError("Invalid IP address '" + address + "'!")
128 class cmd_domain_join(Command):
129 """Joins domain as either member or backup domain controller"""
131 synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]"
133 takes_optiongroups = {
134 "sambaopts": options.SambaOptions,
135 "versionopts": options.VersionOptions,
136 "credopts": options.CredentialsOptions,
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)")
151 takes_args = ["domain", "role?"]
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)
161 site = "Default-First-Site-Name"
163 netbios_name = lp.get("netbios name")
168 if role is None or role == "MEMBER":
169 (join_password, sid, domain_name) = net.join_member(domain,
171 LIBNET_JOIN_AUTOMATIC,
172 machinepass=machinepass)
174 self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid))
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)
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)
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)
197 raise CommandError("Invalid role '%s' (possible values: MEMBER, DC, RODC, SUBDOMAIN)" % role)
201 class cmd_domain_demote(Command):
202 """Demote ourselves from the role of Domain Controller"""
204 synopsis = "%prog [options]"
207 Option("--server", help="DC to force replication before demote", type=str),
208 Option("--targetdir", help="where provision is stored", type=str),
211 takes_optiongroups = {
212 "sambaopts": options.SambaOptions,
213 "credopts": options.CredentialsOptions,
214 "versionopts": options.VersionOptions,
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)
223 netbios_name = lp.get("netbios name")
224 samdb = SamDB(session_info=system_session(), credentials=creds, lp=lp)
226 res = samdb.search(expression='(&(objectClass=computer)(serverReferenceBL=*))', attrs=["dnsHostName", "name"])
228 raise CommandError("Unable to search for servers")
231 raise CommandError("You are the latest server in the domain")
235 if str(e["name"]).lower() != netbios_name.lower():
236 server = e["dnsHostName"]
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,
243 if len(msg) == 0 or "options" not in msg[0]:
244 raise CommandError("Failed to find options on %s" % ntds_guid)
247 dsa_options = int(str(msg[0]['options']))
249 res = samdb.search(expression="(fSMORoleOwner=%s)" % str(ntds_dn),
250 controls=["search_options:1:2"])
253 raise CommandError("Current DC is still the owner of %d role(s), use the role command to transfer roles to another DC")
255 print "Using %s as partner server for the demotion" % server
256 (drsuapiBind, drsuapi_handle, supportedExtensions) = drsuapi_connect(server, lp, creds)
258 print "Desactivating inbound replication"
263 dsa_options |= DS_NTDSDSA_OPT_DISABLE_INBOUND_REPL
264 nmsg["options"] = ldb.MessageElement(str(dsa_options), ldb.FLAG_MOD_REPLACE, "options")
267 if not (dsa_options & DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL) and not samdb.am_rodc():
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()):
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")
280 raise CommandError("Error while sending a DsReplicaSync for partion %s" % str(part), e)
282 remote_samdb = SamDB(url="ldap://%s" % server,
283 session_info=system_session(),
284 credentials=creds, lp=lp)
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"])
292 uac = int(str(res[0]["userAccountControl"]))
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")
299 raise CommandError("Error while changing account control", e)
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")
306 raise CommandError("Unable to find object with samaccountName = %s$"
307 " in the remote dc" % netbios_name.upper())
311 uac ^= (UF_SERVER_TRUST_ACCOUNT|UF_TRUSTED_FOR_DELEGATION)
312 uac |= UF_WORKSTATION_TRUST_ACCOUNT
317 msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
318 ldb.FLAG_MOD_REPLACE,
319 "userAccountControl")
321 remote_samdb.modify(msg)
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")
328 raise CommandError("Error while changing account control", e)
330 parent = msg.dn.parent()
332 rdn = string.replace(rdn, ",%s" % str(parent), "")
333 # Let's move to the Computer container
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)
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):
345 res = remote_samdb.search(base=computer_dn, expression="%s-%d" % (rdn, i),
346 scope=ldb.SCOPE_ONELEVEL)
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")
357 msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
358 ldb.FLAG_MOD_REPLACE,
359 "userAccountControl")
361 remote_samdb.modify(msg)
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))
367 newrdn = "%s-%d" % (rdn, i)
370 newdn = ldb.Dn(remote_samdb, "%s,%s" % (newrdn, str(computer_dn)))
371 remote_samdb.rename(dc_dn, newdn)
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")
381 msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
382 ldb.FLAG_MOD_REPLACE,
383 "userAccountControl")
385 remote_samdb.modify(msg)
386 raise CommandError("Error while renaming %s to %s" % (str(dc_dn), str(newdn)), e)
389 server_dsa_dn = samdb.get_serverName()
390 domain = remote_samdb.get_root_basedn()
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")
403 msg["userAccountControl"] = ldb.MessageElement("%d" % uac,
404 ldb.FLAG_MOD_REPLACE,
405 "userAccountControl")
407 remote_samdb.modify(msg)
408 remote_samdb.rename(newdn, dc_dn)
409 raise CommandError("Error while sending a removeDsServer", e)
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"):
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:
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"):
425 remote_samdb.delete(ldb.Dn(remote_samdb,
426 "%s,%s" % (s, str(newdn))))
427 except ldb.LdbError, l:
430 self.outf.write("Demote successfull\n")
433 class cmd_domain_level(Command):
434 """Raises domain and forest function levels"""
436 synopsis = "%prog (show|raise <options>) [options]"
438 takes_optiongroups = {
439 "sambaopts": options.SambaOptions,
440 "credopts": options.CredentialsOptions,
441 "versionopts": options.VersionOptions,
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)")
454 takes_args = ["subcommand"]
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)
461 samdb = SamDB(url=H, session_info=system_session(),
462 credentials=creds, lp=lp)
464 domain_dn = samdb.domain_dn()
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
470 res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
471 attrs=["msDS-Behavior-Version", "nTMixedDomain"])
472 assert len(res_domain) == 1
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
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])
484 min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value
486 if int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
487 min_level_dc = int(msg["msDS-Behavior-Version"][0])
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!")
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!")
499 raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!")
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)!")
512 if level_forest == DS_DOMAIN_FUNCTION_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:
518 elif level_forest == DS_DOMAIN_FUNCTION_2008:
520 elif level_forest == DS_DOMAIN_FUNCTION_2008_R2:
523 outstr = "higher than 2008 R2"
524 self.message("Forest function level: (Windows) " + outstr)
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:
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:
534 elif level_domain == DS_DOMAIN_FUNCTION_2008:
536 elif level_domain == DS_DOMAIN_FUNCTION_2008_R2:
539 outstr = "higher than 2008 R2"
540 self.message("Domain function level: (Windows) " + outstr)
542 if min_level_dc == DS_DOMAIN_FUNCTION_2000:
544 elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
546 elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
548 elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
551 outstr = "higher than 2008 R2"
552 self.message("Lowest function level of a DC: (Windows) " + outstr)
554 elif subcommand == "raise":
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
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!")
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!")
571 # Deactivate mixed/interim domain support
572 if level_domain_mixed != 0:
573 # Directly on the base DN
575 m.dn = ldb.Dn(samdb, domain_dn)
576 m["nTMixedDomain"] = ldb.MessageElement("0",
577 ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
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")
586 except ldb.LdbError, (enum, emsg):
587 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
590 # Directly on the base DN
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")
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")
606 except ldb.LdbError, (enum, emsg):
607 if enum != ldb.ERR_UNWILLING_TO_PERFORM:
610 level_domain = new_level_domain
611 msgs.append("Domain function level changed!")
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!")
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")
630 msgs.append("Forest function level changed!")
631 msgs.append("All changes applied successfully!")
632 self.message("\n".join(msgs))
634 raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
637 class cmd_domain_passwordsettings(Command):
638 """Sets password settings
640 Password complexity, history length, minimum password length, the minimum
641 and maximum password age) on a Samba4 server.
644 synopsis = "%prog (show|set <options>) [options]"
646 takes_optiongroups = {
647 "sambaopts": options.SambaOptions,
648 "versionopts": options.VersionOptions,
649 "credopts": options.CredentialsOptions,
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),
670 takes_args = ["subcommand"]
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,
676 lp = sambaopts.get_loadparm()
677 creds = credopts.get_credentials(lp)
679 samdb = SamDB(url=H, session_info=system_session(),
680 credentials=creds, lp=lp)
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)
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])
692 cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
693 if int(res[0]["maxPwdAge"][0]) == -0x8000000000000000:
696 cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
698 raise CommandError("Could not retrieve password properties!", e)
700 if subcommand == "show":
701 self.message("Password informations for domain '%s'" % domain_dn)
703 if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
704 self.message("Password complexity: on")
706 self.message("Password complexity: off")
707 if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
708 self.message("Store plaintext passwords: on")
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":
718 m.dn = ldb.Dn(samdb, domain_dn)
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!")
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!")
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")
740 if history_length is not None:
741 if history_length == "default":
744 pwd_hist_len = int(history_length)
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!")
749 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
750 ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
751 msgs.append("Password history length changed!")
753 if min_pwd_length is not None:
754 if min_pwd_length == "default":
757 min_pwd_len = int(min_pwd_length)
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!")
762 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
763 ldb.FLAG_MOD_REPLACE, "minPwdLength")
764 msgs.append("Minimum password length changed!")
766 if min_pwd_age is not None:
767 if min_pwd_age == "default":
770 min_pwd_age = int(min_pwd_age)
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!")
776 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
778 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
779 ldb.FLAG_MOD_REPLACE, "minPwdAge")
780 msgs.append("Minimum password age changed!")
782 if max_pwd_age is not None:
783 if max_pwd_age == "default":
786 max_pwd_age = int(max_pwd_age)
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!")
793 max_pwd_age_ticks = -0x8000000000000000
795 max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
797 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
798 ldb.FLAG_MOD_REPLACE, "maxPwdAge")
799 msgs.append("Maximum password age changed!")
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))
805 raise CommandError("You must specify at least one option to set. Try --help")
807 msgs.append("All changes applied successfully!")
808 self.message("\n".join(msgs))
810 raise CommandError("Wrong argument '%s'!" % subcommand)
813 class cmd_domain_samba3upgrade(Command):
814 """Upgrade from Samba3 database to Samba4 AD database.
816 Specify either a directory with all samba3 databases and state files (with --dbdir) or
817 samba3 testparm utility (with --testparm).
820 synopsis = "%prog [options] <samba3_smb_conf>"
822 takes_optiongroups = {
823 "sambaopts": options.SambaOptions,
824 "versionopts": options.VersionOptions
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"),
840 takes_args = ["smbconf"]
842 def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None,
843 quiet=False, verbose=False, use_xattrs=None, sambaopts=None, versionopts=None):
845 if not os.path.exists(smbconf):
846 raise CommandError("File %s does not exist" % smbconf)
848 if testparm and not os.path.exists(testparm):
849 raise CommandError("Testparm utility %s does not exist" % testparm)
851 if dbdir and not os.path.exists(dbdir):
852 raise CommandError("Directory %s does not exist" % dbdir)
854 if not dbdir and not testparm:
855 raise CommandError("Please specify either dbdir or testparm")
857 logger = self.get_logger()
859 logger.setLevel(logging.DEBUG)
861 logger.setLevel(logging.WARNING)
863 logger.setLevel(logging.INFO)
865 if dbdir and testparm:
866 logger.warning("both dbdir and testparm specified, ignoring dbdir.")
869 lp = sambaopts.get_loadparm()
871 s3conf = s3param.get_context()
874 s3conf.set("realm", sambaopts.realm)
876 if targetdir is not None:
877 if not os.path.isdir(targetdir):
881 if use_xattrs == "yes":
883 elif use_xattrs == "auto" and not s3conf.get("posix:eadb"):
885 tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(targetdir))
887 tmpfile = tempfile.NamedTemporaryFile(dir=os.path.abspath(os.path.dirname(lp.get("private dir"))))
890 samba.ntacls.setntacl(lp, tmpfile.name,
891 "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
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.")
900 # Set correct default values from dbdir or testparm
903 paths["state directory"] = dbdir
904 paths["private dir"] = dbdir
905 paths["lock directory"] = dbdir
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"]
916 s3conf.set(p, paths[p])
918 # load smb.conf parameters
919 logger.info("Reading smb.conf")
921 samba3 = Samba3(smbconf, s3conf)
923 logger.info("Provisioning")
924 upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(),
927 class cmd_domain(SuperCommand):
928 """Domain management"""
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()