s4-provision Add support for fixing the DC rid to a particular value
[amitay/samba.git] / source4 / scripting / python / samba / upgrade.py
index f40f2cffe7f5ac58a655290d0cb3e6729c3fd1f5..351581c6eecd26ff3ab7596f347e4a0683dc2b9b 100644 (file)
@@ -1,23 +1,36 @@
-#!/usr/bin/python
+# backend code for upgrading from Samba3
+# Copyright Jelmer Vernooij 2005-2007
 #
-#      backend code for upgrading from Samba3
-#      Copyright Jelmer Vernooij 2005-2007
-#      Released under the GNU GPL v3 or later
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 
 """Support code for upgrading from Samba 3 to Samba 4."""
 
-from provision import findnss, provision, FILL_DRS
+__docformat__ = "restructuredText"
+
 import grp
 import ldb
 import time
 import pwd
-import uuid
-import registry
-from samba import Ldb
-from samba.samdb import SamDB
 
-def import_sam_policy(samldb, samba3_policy, domaindn):
+from samba import Ldb, registry
+from samba.param import LoadParm
+from samba.provision import provision, FILL_FULL
+from samba.samba3 import passdb
+from samba.samba3 import param as s3param
+
+def import_sam_policy(samldb, policy, dn):
     """Import a Samba 3 policy database."""
     samldb.modify_ldif("""
 dn: %s
@@ -33,7 +46,7 @@ samba3UserMustLogonToChangePassword: %d
 samba3BadLockoutMinutes: %d
 samba3DisconnectTime: %d
 
-""" % (dn, policy.min_password_length, 
+""" % (dn, policy.min_password_length,
     policy.password_history, policy.minimum_password_age,
     policy.maximum_password_age, policy.lockout_duration,
     policy.reset_count_minutes, policy.user_must_logon_to_change_password,
@@ -42,7 +55,7 @@ samba3DisconnectTime: %d
 
 def import_sam_account(samldb,acc,domaindn,domainsid):
     """Import a Samba 3 SAM account.
-    
+
     :param samldb: Samba 4 SAM Database handle
     :param acc: Samba 3 account
     :param domaindn: Domain DN
@@ -58,7 +71,7 @@ def import_sam_account(samldb,acc,domaindn,domainsid):
 
     if acc.fullname is None:
         acc.fullname = acc.username
-    
+
     assert acc.fullname is not None
     assert acc.nt_username is not None
 
@@ -77,8 +90,8 @@ def import_sam_account(samldb,acc,domaindn,domainsid):
         "samba3Domain": acc.domain,
         "samba3DirDrive": acc.dir_drive,
         "samba3MungedDial": acc.munged_dial,
-        "samba3Homedir": acc.homedir, 
-        "samba3LogonScript": acc.logon_script, 
+        "samba3Homedir": acc.homedir,
+        "samba3LogonScript": acc.logon_script,
         "samba3ProfilePath": acc.profile_path,
         "samba3Workstations": acc.workstations,
         "samba3KickOffTime": str(acc.kickoff_time),
@@ -94,7 +107,7 @@ def import_sam_account(samldb,acc,domaindn,domainsid):
 
 def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
     """Upgrade a SAM group.
-    
+
     :param samldb: SAM database.
     :param gid: Group GID
     :param sid_name_use: SID name use
@@ -108,7 +121,7 @@ def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn)
 
     if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"):
         return None
-    
+
     if gid == -1:
         gr = grp.getgrnam(nt_name)
     else:
@@ -120,12 +133,12 @@ def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn)
         unixname = gr.gr_name
 
     assert unixname is not None
-    
+
     samldb.add({
         "dn": "cn=%s,%s" % (nt_name, domaindn),
         "objectClass": ["top", "group"],
         "description": comment,
-        "cn": nt_name, 
+        "cn": nt_name,
         "objectSid": sid,
         "unixName": unixname,
         "samba3SidNameUse": str(sid_name_use)
@@ -159,7 +172,7 @@ def import_idmap(samdb,samba3_idmap,domaindn):
 
 def import_wins(samba4_winsdb, samba3_winsdb):
     """Import settings from a Samba3 WINS database.
-    
+
     :param samba4_winsdb: WINS database to import to
     :param samba3_winsdb: WINS database to import from
     """
@@ -207,73 +220,6 @@ def import_wins(samba4_winsdb, samba3_winsdb):
                        "objectClass": "winsMaxVersion",
                        "maxVersion": str(version_id)})
 
-def upgrade_provision(samba3, setup_dir, message, credentials, session_info, smbconf, targetdir):
-    oldconf = samba3.get_conf()
-
-    if oldconf.get("domain logons") == "True":
-        serverrole = "domain controller"
-    else:
-        if oldconf.get("security") == "user":
-            serverrole = "standalone"
-        else:
-            serverrole = "member server"
-
-    domainname = oldconf.get("workgroup")
-    if domainname:
-        domainname = str(domainname)
-    realm = oldconf.get("realm")
-    netbiosname = oldconf.get("netbios name")
-
-    secrets_db = samba3.get_secrets_db()
-    
-    if domainname is None:
-        domainname = secrets_db.domains()[0]
-        message("No domain specified in smb.conf file, assuming '%s'" % domainname)
-    
-    if realm is None:
-        realm = domainname.lower()
-        message("No realm specified in smb.conf file, assuming '%s'\n" % realm)
-
-    domainguid = secrets_db.get_domain_guid(domainname)
-    domainsid = secrets_db.get_sid(domainname)
-    if domainsid is None:
-        message("Can't find domain secrets for '%s'; using random SID\n" % domainname)
-    
-    if netbiosname is not None:
-        machinepass = secrets_db.get_machine_password(netbiosname)
-    else:
-        machinepass = None
-    
-    result = provision(setup_dir=setup_dir, message=message, 
-                       samdb_fill=FILL_DRS, smbconf=smbconf, session_info=session_info, 
-                       credentials=credentials, realm=realm, 
-                       domain=domainname, domainsid=domainsid, domainguid=domainguid, 
-                       machinepass=machinepass, serverrole=serverrole, targetdir=targetdir)
-
-    import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
-
-    # FIXME: import_registry(registry.Registry(), samba3.get_registry())
-
-    # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
-    
-    groupdb = samba3.get_groupmapping_db()
-    for sid in groupdb.groupsids():
-        (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
-        # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
-
-    # FIXME: Aliases
-
-    passdb = samba3.get_sam_db()
-    for name in passdb:
-        user = passdb[name]
-        #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid)
-
-    if hasattr(passdb, 'ldap_url'):
-        message("Enabling Samba3 LDAP mappings for SAM database")
-
-        enable_samba3sam(result.samdb, passdb.ldap_url)
-
-
 def enable_samba3sam(samdb, ldapurl):
     """Enable Samba 3 LDAP URL database.
 
@@ -291,7 +237,7 @@ replace: @LIST
 
 
 smbconf_keep = [
-    "dos charset", 
+    "dos charset",
     "unix charset",
     "display charset",
     "comment",
@@ -335,8 +281,6 @@ smbconf_keep = [
     "write raw",
     "disable netbios",
     "nt status support",
-    "announce version",
-    "announce as",
     "max mux",
     "max xmit",
     "name resolve order",
@@ -388,11 +332,11 @@ def upgrade_smbconf(oldconf,mark):
     """Remove configuration variables not present in Samba4
 
     :param oldconf: Old configuration structure
-    :param mark: Whether removed configuration variables should be 
+    :param mark: Whether removed configuration variables should be
         kept in the new configuration as "samba3:<name>"
     """
     data = oldconf.data()
-    newconf = param_init()
+    newconf = LoadParm()
 
     for s in data:
         for p in data[s]:
@@ -433,3 +377,120 @@ def import_registry(samba4_registry, samba3_regdb):
             key_handle.set_value(value_name, value_type, value_data)
 
 
+def upgrade_from_samba3(samba3, logger, session_info, smbconf, targetdir):
+    """Upgrade from samba3 database to samba4 AD database
+    """
+
+    # Read samba3 smb.conf
+    oldconf = s3param.get_context();
+    oldconf.load(smbconf)
+
+    if oldconf.get("domain logons"):
+        serverrole = "domain controller"
+    else:
+        if oldconf.get("security") == "user":
+            serverrole = "standalone"
+        else:
+            serverrole = "member server"
+
+    domainname = oldconf.get("workgroup")
+    realm = oldconf.get("realm")
+    netbiosname = oldconf.get("netbios name")
+
+    # secrets db
+    secrets_db = samba3.get_secrets_db()
+
+    if not domainname:
+        domainname = secrets_db.domains()[0]
+        logger.warning("No domain specified in smb.conf file, assuming '%s'",
+                domainname)
+
+    if not realm:
+        if oldconf.get("domain logons"):
+            logger.warning("No realm specified in smb.conf file and being a DC. That upgrade path doesn't work! Please add a 'realm' directive to your old smb.conf to let us know which one you want to use (generally it's the upcased DNS domainname).")
+            return
+        else:
+            realm = domainname.upper()
+            logger.warning("No realm specified in smb.conf file, assuming '%s'",
+                    realm)
+
+    # Find machine account and password
+    machinepass = None
+    machinerid = None
+    machinesid = None
+    next_rid = 1000
+
+    try:
+        machinepass = secrets_db.get_machine_password(netbiosname)
+    except:
+        pass
+
+    # We must close the direct pytdb database before the C code loads it
+    secrets_db.close()
+
+    # We must load the group mapping into memory before the passdb code touches it
+    groupdb = samba3.get_groupmapping_db()
+    for sid in groupdb.groupsids():
+        (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
+        # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
+    groupdb.close()
+
+    passdb.set_secrets_dir(samba3.libdir)
+
+    try:
+        domainsid = str(passdb.get_global_sam_sid())
+    except:
+        pass
+
+    try:
+        machineacct = old_passdb.getsampwnam('%s$' % netbiosname)
+        machinesid, machinerid = machineacct.user_sid.split()
+    except:
+        pass
+
+    if domainsid is None:
+        logger.warning("Can't find domain secrets for '%s'; using random SID",
+            domainname)
+
+    # Import users from old passdb backend
+    old_passdb = passdb.PDB(oldconf.get('passdb backend'))
+    userlist = old_passdb.search_users(0)
+    userdata = {}
+    for entry in userlist:
+        if machinerid and machinerid == entry['rid']:
+            continue
+        username = entry['account_name']
+        if entry['rid'] < 1000:
+            print("Skipping wellknown rid=%d (for username=%s)\n" % (entry['rid'], username))
+            continue
+        if entry['rid'] >= next_rid:
+            next_rid = entry['rid'] + 1
+        
+        userdata[username] = old_passdb.getsampwnam(username)
+
+    # Do full provision
+    result = provision(logger, session_info, None,
+                       targetdir=targetdir, realm=realm, domain=domainname,
+                       domainsid=domainsid, next_rid=next_rid,
+                       dc_rid=machinerid,
+                       hostname=netbiosname, machinepass=machinepass,
+                       serverrole=serverrole, samdb_fill=FILL_FULL)
+
+    import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
+
+    # FIXME: import_registry(registry.Registry(), samba3.get_registry())
+
+    # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
+
+    # FIXME: Aliases
+
+    # Export users to samba4 backend
+    new_smbconf = result.lp.configfile
+    newconf = s3param.get_context()
+    newconf.load(new_smbconf)
+
+    new_passdb = passdb.PDB('samba4')
+
+    for username in userdata:
+        print "adding user %s" % username
+        new_passdb.add_sam_account(userdata[username])