s4-s3-upgrade rename samba-tool domain samba3upgrade --libdir to --dbdir for clarity
[samba.git] / source4 / scripting / python / samba / netcmd / domain.py
index d76b092aba9a24231d6146a7c3405635b137302e..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, LIBNET_JOIN_AUTOMATIC
-from samba.dcerpc.misc import SEC_CHAN_WKSTA
-from samba.join import join_RODC, join_DC
+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
@@ -39,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,
@@ -48,12 +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_export_keytab(Command):
     """Dumps kerberos keys of the domain into a keytab"""
 
-    synopsis = "%prog domain exportkeytab <keytab> [options]"
+    synopsis = "%prog <keytab> [options]"
 
     takes_options = [
         ]
@@ -70,12 +79,13 @@ class cmd_domain_export_keytab(Command):
 class cmd_domain_join(Command):
     """Joins domain as either member or backup domain controller *"""
 
-    synopsis = "%prog domain join <dnsdomain> [DC|RODC|MEMBER] [options]"
+    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"),
@@ -85,7 +95,7 @@ class cmd_domain_join(Command):
 
     def run(self, domain, role=None, sambaopts=None, credopts=None,
             versionopts=None, server=None, site=None, targetdir=None,
-            domain_critical_only=False):
+            domain_critical_only=False, parent_domain=None):
         lp = sambaopts.get_loadparm()
         creds = credopts.get_credentials(lp)
         net = Net(creds, lp, server=credopts.ipaddress)
@@ -115,6 +125,13 @@ class cmd_domain_join(Command):
                       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)
 
@@ -123,7 +140,7 @@ class cmd_domain_join(Command):
 class cmd_domain_level(Command):
     """Raises domain and forest function levels"""
 
-    synopsis = "%prog domain level (show|raise <options>) [options]"
+    synopsis = "%prog (show|raise <options>) [options]"
 
     takes_options = [
         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
@@ -147,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
 
@@ -155,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
@@ -262,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:
@@ -282,7 +298,7 @@ class cmd_domain_level(Command):
                 # 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")
@@ -307,8 +323,7 @@ class cmd_domain_level(Command):
                 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")
@@ -324,7 +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> [options]"
+    synopsis = "%prog <accountname> [options]"
 
     takes_args = ["secret"]
 
@@ -355,7 +370,7 @@ class cmd_domain_passwordsettings(Command):
     and maximum password age) on a Samba4 server.
     """
 
-    synopsis = "%prog domain passwordsettings (show|set <options>) [options]"
+    synopsis = "%prog (show|set <options>) [options]"
 
     takes_options = [
         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
@@ -512,6 +527,111 @@ 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"""
@@ -522,3 +642,4 @@ class cmd_domain(SuperCommand):
     subcommands["level"] = cmd_domain_level()
     subcommands["machinepassword"] = cmd_domain_machinepassword()
     subcommands["passwordsettings"] = cmd_domain_passwordsettings()
+    subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()