s4-s3-upgrade rename samba-tool domain samba3upgrade --libdir to --dbdir for clarity
[obnox/samba/samba-obnox.git] / source4 / scripting / python / samba / netcmd / domain.py
index d13f87e798dff7b7aa0d34b6668ab32e3c40af35..715b376657ccd5695edaf007eceb3dbf4fb5ff6c 100644 (file)
 import samba.getopt as options
 import ldb
 import os
+import tempfile
+import logging
 from samba import Ldb
-from samba.net import Net
+from samba.net import Net, LIBNET_JOIN_AUTOMATIC
+import samba.ntacls
+from samba.join import join_RODC, join_DC, join_subdomain
 from samba.auth import system_session
 from samba.samdb import SamDB
 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT
@@ -37,6 +41,9 @@ from samba.netcmd import (
     SuperCommand,
     Option
     )
+from samba.samba3 import Samba3
+from samba.samba3 import param as s3param
+from samba.upgrade import upgrade_from_samba3
 
 from samba.dsdb import (
     DS_DOMAIN_FUNCTION_2000,
@@ -46,17 +53,16 @@ from samba.dsdb import (
     DS_DOMAIN_FUNCTION_2008_R2,
     )
 
+def get_testparm_var(testparm, smbconf, varname):
+    cmd = "%s -s -l --parameter-name='%s' %s 2>/dev/null" % (testparm, varname, smbconf)
+    output = os.popen(cmd, 'r').readline()
+    return output.strip()
 
 
-class cmd_domain_dumpkeys(Command):
+class cmd_domain_export_keytab(Command):
     """Dumps kerberos keys of the domain into a keytab"""
-    synopsis = "%prog domain dumpkeys <keytab>"
 
-    takes_optiongroups = {
-        "sambaopts": options.SambaOptions,
-        "credopts": options.CredentialsOptions,
-        "versionopts": options.VersionOptions,
-        }
+    synopsis = "%prog <keytab> [options]"
 
     takes_options = [
         ]
@@ -70,28 +76,86 @@ class cmd_domain_dumpkeys(Command):
 
 
 
+class cmd_domain_join(Command):
+    """Joins domain as either member or backup domain controller *"""
+
+    synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]"
+
+    takes_options = [
+        Option("--server", help="DC to join", type=str),
+        Option("--site", help="site to join", type=str),
+        Option("--targetdir", help="where to store provision", type=str),
+        Option("--parent-domain", help="parent domain to create subdomain under", type=str),
+        Option("--domain-critical-only",
+               help="only replicate critical domain objects",
+               action="store_true"),
+        ]
+
+    takes_args = ["domain", "role?"]
+
+    def run(self, domain, role=None, sambaopts=None, credopts=None,
+            versionopts=None, server=None, site=None, targetdir=None,
+            domain_critical_only=False, parent_domain=None):
+        lp = sambaopts.get_loadparm()
+        creds = credopts.get_credentials(lp)
+        net = Net(creds, lp, server=credopts.ipaddress)
+
+        if site is None:
+            site = "Default-First-Site-Name"
+
+        netbios_name = lp.get("netbios name")
+
+        if not role is None:
+            role = role.upper()
+
+        if role is None or role == "MEMBER":
+            (join_password, sid, domain_name) = net.join_member(domain,
+                                                                netbios_name,
+                                                                LIBNET_JOIN_AUTOMATIC)
+
+            self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid))
+            return
+        elif role == "DC":
+            join_DC(server=server, creds=creds, lp=lp, domain=domain,
+                    site=site, netbios_name=netbios_name, targetdir=targetdir,
+                    domain_critical_only=domain_critical_only)
+            return
+        elif role == "RODC":
+            join_RODC(server=server, creds=creds, lp=lp, domain=domain,
+                      site=site, netbios_name=netbios_name, targetdir=targetdir,
+                      domain_critical_only=domain_critical_only)
+            return
+        elif role == "SUBDOMAIN":
+            netbios_domain = lp.get("workgroup")
+            if parent_domain is None:
+                parent_domain = ".".join(domain.split(".")[1:])
+            join_subdomain(server=server, creds=creds, lp=lp, dnsdomain=domain, parent_domain=parent_domain,
+                           site=site, netbios_name=netbios_name, netbios_domain=netbios_domain, targetdir=targetdir)
+            return
+        else:
+            raise CommandError("Invalid role %s (possible values: MEMBER, DC, RODC)" % role)
+
+
+
 class cmd_domain_level(Command):
     """Raises domain and forest function levels"""
 
-    synopsis = "%prog domain level (show | raise <options>)"
-
-    takes_optiongroups = {
-        "sambaopts": options.SambaOptions,
-        "credopts": options.CredentialsOptions,
-        "versionopts": options.VersionOptions,
-        }
+    synopsis = "%prog (show|raise <options>) [options]"
 
     takes_options = [
-        Option("-H", help="LDB URL for database or target server", type=str),
+        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
+               metavar="URL", dest="H"),
         Option("--quiet", help="Be quiet", action="store_true"),
-        Option("--forest", type="choice", choices=["2003", "2008", "2008_R2"],
+        Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2"],
             help="The forest function level (2003 | 2008 | 2008_R2)"),
+        Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2"],
+            help="The domain function level (2003 | 2008 | 2008_R2)")
             ]
 
     takes_args = ["subcommand"]
 
-    def run(self, subcommand, H=None, forest=None, domain=None, quiet=False,
-            credopts=None, sambaopts=None, versionopts=None):
+    def run(self, subcommand, H=None, forest_level=None, domain_level=None,
+            quiet=False, credopts=None, sambaopts=None, versionopts=None):
         lp = sambaopts.get_loadparm()
         creds = credopts.get_credentials(lp, fallback_machine=True)
 
@@ -100,7 +164,7 @@ class cmd_domain_level(Command):
 
         domain_dn = samdb.domain_dn()
 
-        res_forest = samdb.search("CN=Partitions,CN=Configuration," + domain_dn,
+        res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
           scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
         assert len(res_forest) == 1
 
@@ -108,7 +172,7 @@ class cmd_domain_level(Command):
           attrs=["msDS-Behavior-Version", "nTMixedDomain"])
         assert len(res_domain) == 1
 
-        res_dc_s = samdb.search("CN=Sites,CN=Configuration," + domain_dn,
+        res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
           scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
           attrs=["msDS-Behavior-Version"])
         assert len(res_dc_s) >= 1
@@ -174,17 +238,29 @@ class cmd_domain_level(Command):
                 outstr = "2008 R2"
             else:
                 outstr = "higher than 2008 R2"
+            self.message("Domain function level: (Windows) " + outstr)
+
+            if min_level_dc == DS_DOMAIN_FUNCTION_2000:
+                outstr = "2000"
+            elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
+                outstr = "2003"
+            elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
+                outstr = "2008"
+            elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
+                outstr = "2008 R2"
+            else:
+                outstr = "higher than 2008 R2"
             self.message("Lowest function level of a DC: (Windows) " + outstr)
 
         elif subcommand == "raise":
             msgs = []
 
-            if domain is not None:
-                if domain == "2003":
+            if domain_level is not None:
+                if domain_level == "2003":
                     new_level_domain = DS_DOMAIN_FUNCTION_2003
-                elif domain == "2008":
+                elif domain_level == "2008":
                     new_level_domain = DS_DOMAIN_FUNCTION_2008
-                elif domain == "2008_R2":
+                elif domain_level == "2008_R2":
                     new_level_domain = DS_DOMAIN_FUNCTION_2008_R2
 
                 if new_level_domain <= level_domain and level_domain_mixed == 0:
@@ -203,8 +279,7 @@ class cmd_domain_level(Command):
                     samdb.modify(m)
                     # Under partitions
                     m = ldb.Message()
-                    m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
-                      + ",CN=Partitions,CN=Configuration," + domain_dn)
+                    m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % ldb.get_config_basedn())
                     m["nTMixedDomain"] = ldb.MessageElement("0",
                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
                     try:
@@ -216,13 +291,14 @@ class cmd_domain_level(Command):
                 # Directly on the base DN
                 m = ldb.Message()
                 m.dn = ldb.Dn(samdb, domain_dn)
-                m["msDS-Behavior-Version"]= ldb.MessageElement(                                                                                             str(new_level_domain), ldb.FLAG_MOD_REPLACE,
+                m["msDS-Behavior-Version"]= ldb.MessageElement(
+                  str(new_level_domain), ldb.FLAG_MOD_REPLACE,
                             "msDS-Behavior-Version")
                 samdb.modify(m)
                 # Under partitions
                 m = ldb.Message()
                 m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
-                  + ",CN=Partitions,CN=Configuration," + domain_dn)
+                  + ",CN=Partitions,%s" % ldb.get_config_basedn())
                 m["msDS-Behavior-Version"]= ldb.MessageElement(
                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
                           "msDS-Behavior-Version")
@@ -235,20 +311,19 @@ class cmd_domain_level(Command):
                 level_domain = new_level_domain
                 msgs.append("Domain function level changed!")
 
-            if forest is not None:
-                if forest == "2003":
+            if forest_level is not None:
+                if forest_level == "2003":
                     new_level_forest = DS_DOMAIN_FUNCTION_2003
-                elif forest == "2008":
+                elif forest_level == "2008":
                     new_level_forest = DS_DOMAIN_FUNCTION_2008
-                elif forest == "2008_R2":
+                elif forest_level == "2008_R2":
                     new_level_forest = DS_DOMAIN_FUNCTION_2008_R2
                 if new_level_forest <= level_forest:
                     raise CommandError("Forest function level can't be smaller equal to the actual one!")
                 if new_level_forest > level_domain:
                     raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
                 m = ldb.Message()
-                m.dn = ldb.Dn(samdb, "CN=Partitions,CN=Configuration,"
-                  + domain_dn)
+                m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % ldb.get_config_basedn())
                 m["msDS-Behavior-Version"]= ldb.MessageElement(
                   str(new_level_forest), ldb.FLAG_MOD_REPLACE,
                           "msDS-Behavior-Version")
@@ -264,13 +339,7 @@ class cmd_domain_level(Command):
 class cmd_domain_machinepassword(Command):
     """Gets a machine password out of our SAM"""
 
-    synopsis = "%prog domain machinepassword <accountname>"
-
-    takes_optiongroups = {
-        "sambaopts": options.SambaOptions,
-        "versionopts": options.VersionOptions,
-        "credopts": options.CredentialsOptions,
-    }
+    synopsis = "%prog <accountname> [options]"
 
     takes_args = ["secret"]
 
@@ -285,7 +354,7 @@ class cmd_domain_machinepassword(Command):
         secretsdb = Ldb(url=url, session_info=system_session(),
             credentials=creds, lp=lp)
         result = secretsdb.search(attrs=["secret"],
-            expression="(&(objectclass=primaryDomain)(samaccountname=%s))" % secret)
+            expression="(&(objectclass=primaryDomain)(samaccountname=%s))" % ldb.binary_encode(secret))
 
         if len(result) != 1:
             raise CommandError("search returned %d records, expected 1" % len(result))
@@ -301,16 +370,11 @@ class cmd_domain_passwordsettings(Command):
     and maximum password age) on a Samba4 server.
     """
 
-    synopsis = "%prog domain passwordsettings (show | set <options>)"
-
-    takes_optiongroups = {
-        "sambaopts": options.SambaOptions,
-        "versionopts": options.VersionOptions,
-        "credopts": options.CredentialsOptions,
-        }
+    synopsis = "%prog (show|set <options>) [options]"
 
     takes_options = [
-        Option("-H", help="LDB URL for database or target server", type=str),
+        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
+               metavar="URL", dest="H"),
         Option("--quiet", help="Be quiet", action="store_true"),
         Option("--complexity", type="choice", choices=["on","off","default"],
           help="The password complexity (on | off | default). Default is 'on'"),
@@ -454,6 +518,8 @@ class cmd_domain_passwordsettings(Command):
             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
 
+            if len(m) == 0:
+                raise CommandError("You must specify at least one option to set. Try --help")
             samdb.modify(m)
             msgs.append("All changes applied successfully!")
             self.message("\n".join(msgs))
@@ -461,12 +527,119 @@ class cmd_domain_passwordsettings(Command):
             raise CommandError("Wrong argument '%s'!" % subcommand)
 
 
+class cmd_domain_samba3upgrade(Command):
+    """Upgrade from Samba3 database to Samba4 AD database.
+
+    Specify either a directory with all samba3 databases and state files (with --dbdir) or
+    samba3 testparm utility (with --testparm).
+    """
+
+    synopsis = "%prog [options] <samba3_smb_conf>"
+
+    takes_optiongroups = {
+        "sambaopts": options.SambaOptions,
+        "versionopts": options.VersionOptions
+    }
+
+    takes_options = [
+        Option("--dbdir", type="string", metavar="DIR",
+                  help="Path to samba3 database directory"),
+        Option("--testparm", type="string", metavar="PATH",
+                  help="Path to samba3 testparm utility from the previous installation.  This allows the default paths of the previous installation to be followed"),
+        Option("--targetdir", type="string", metavar="DIR",
+                  help="Path prefix where the new Samba 4.0 AD domain should be initialised"),
+        Option("--quiet", help="Be quiet"),
+        Option("--use-xattrs", type="choice", choices=["yes","no","auto"], metavar="[yes|no|auto]",
+                   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"),
+    ]
+
+    takes_args = ["smbconf"]
+
+    def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None, 
+            quiet=None, use_xattrs=None, sambaopts=None, versionopts=None):
+
+        if not os.path.exists(smbconf):
+            raise CommandError("File %s does not exist" % smbconf)
+        
+        if testparm and not os.path.exists(testparm):
+            raise CommandError("Testparm utility %s does not exist" % testparm)
+
+        if dbdir and not os.path.exists(dbdir):
+            raise CommandError("Directory %s does not exist" % dbdir)
+
+        if not dbdir and not testparm:
+            raise CommandError("Please specify either dbdir or testparm")
+
+        if dbdir and testparm:
+            self.outf.write("warning: both dbdir and testparm specified, ignoring dbdir.\n")
+            dbdir = None
+
+        logger = self.get_logger()
+        if quiet:
+            logger.setLevel(logging.WARNING)
+        else:
+            logger.setLevel(logging.INFO)
+
+        lp = sambaopts.get_loadparm()
+
+        s3conf = s3param.get_context()
+
+        if sambaopts.realm:
+            s3conf.set("realm", sambaopts.realm)
+
+        eadb = True
+        if use_xattrs == "yes":
+            eadb = False
+        elif use_xattrs == "auto" and not s3conf.get("posix:eadb"):
+            if targetdir:
+                tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(targetdir))
+            else:
+                tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(os.path.dirname(lp.get("private dir"))))
+            try:
+                samba.ntacls.setntacl(lp, tmpfile.name,
+                            "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
+                eadb = False
+            except:
+                # FIXME: Don't catch all exceptions here
+                logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. "
+                            "If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.")
+            tmpfile.close()
+
+        # Set correct default values from dbdir or testparm
+        paths = {}
+        if dbdir:
+            paths["state directory"] = dbdir
+            paths["private dir"] = dbdir
+            paths["lock directory"] = dbdir
+        else:
+            paths["state directory"] = get_testparm_var(testparm, smbconf, "state directory")
+            paths["private dir"] = get_testparm_var(testparm, smbconf, "private dir")
+            paths["lock directory"] = get_testparm_var(testparm, smbconf, "lock directory")
+            # "testparm" from Samba 3 < 3.4.x is not aware of the parameter
+            # "state directory", instead make use of "lock directory"
+            if len(paths["state directory"]) == 0:
+                paths["state directory"] = paths["lock directory"]
+
+        for p in paths:
+            s3conf.set(p, paths[p])
+    
+        # load smb.conf parameters
+        logger.info("Reading smb.conf")
+        s3conf.load(smbconf)
+        samba3 = Samba3(smbconf, s3conf)
+    
+        logger.info("Provisioning")
+        upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(), 
+                            useeadb=eadb)
+
 
 class cmd_domain(SuperCommand):
     """Domain management"""
 
     subcommands = {}
-    subcommands["dumpkeys"] = cmd_domain_dumpkeys()
+    subcommands["exportkeytab"] = cmd_domain_export_keytab()
+    subcommands["join"] = cmd_domain_join()
     subcommands["level"] = cmd_domain_level()
     subcommands["machinepassword"] = cmd_domain_machinepassword()
     subcommands["passwordsettings"] = cmd_domain_passwordsettings()
+    subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()