# backend code for upgrading from Samba3
# Copyright Jelmer Vernooij 2005-2007
+# Copyright Andrew Bartlett 2011
#
# 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
__docformat__ = "restructuredText"
-import grp
import ldb
import time
import pwd
from samba.provision import provision, FILL_FULL, ProvisioningError
from samba.samba3 import passdb
from samba.samba3 import param as s3param
-from samba.dcerpc import lsa
+from samba.dcerpc import lsa, samr, security
from samba.dcerpc.security import dom_sid
from samba import dsdb
from samba.ndr import ndr_pack
+from samba import unix2nttime
def import_sam_policy(samdb, policy, logger):
m = ldb.Message()
m.dn = samdb.get_default_basedn()
- m['a01'] = ldb.MessageElement(str(policy['min password length']), ldb.FLAG_MOD_REPLACE,
- 'minPwdLength')
- m['a02'] = ldb.MessageElement(str(policy['password history']), ldb.FLAG_MOD_REPLACE,
- 'pwdHistoryLength')
- m['a03'] = ldb.MessageElement(str(policy['minimum password age']), ldb.FLAG_MOD_REPLACE,
- 'minPwdAge')
- m['a04'] = ldb.MessageElement(str(policy['maximum password age']), ldb.FLAG_MOD_REPLACE,
- 'maxPwdAge')
- m['a05'] = ldb.MessageElement(str(policy['lockout duration']), ldb.FLAG_MOD_REPLACE,
- 'lockoutDuration')
+ m['a01'] = ldb.MessageElement(str(policy['min password length']),
+ ldb.FLAG_MOD_REPLACE, 'minPwdLength')
+ m['a02'] = ldb.MessageElement(str(policy['password history']),
+ ldb.FLAG_MOD_REPLACE, 'pwdHistoryLength')
+
+ min_pw_age_unix = policy['minimum password age']
+ min_pw_age_nt = 0 - unix2nttime(min_pw_age_unix)
+ m['a03'] = ldb.MessageElement(str(min_pw_age_nt), ldb.FLAG_MOD_REPLACE,
+ 'minPwdAge')
+
+ max_pw_age_unix = policy['maximum password age']
+ if (max_pw_age_unix == 0xFFFFFFFF):
+ max_pw_age_nt = 0
+ else:
+ max_pw_age_nt = unix2nttime(max_pw_age_unix)
+
+ m['a04'] = ldb.MessageElement(str(max_pw_age_nt), ldb.FLAG_MOD_REPLACE,
+ 'maxPwdAge')
+
+ lockout_duration_mins = policy['lockout duration']
+ lockout_duration_nt = unix2nttime(lockout_duration_mins * 60)
+
+ m['a05'] = ldb.MessageElement(str(lockout_duration_nt),
+ ldb.FLAG_MOD_REPLACE, 'lockoutDuration')
try:
samdb.modify(m)
try:
m = ldb.Message()
m.dn = msg[0]['dn']
- m['xidNumber'] = ldb.MessageElement(str(xid), ldb.FLAG_MOD_REPLACE, 'xidNumber')
- m['type'] = ldb.MessageElement(xid_type, ldb.FLAG_MOD_REPLACE, 'type')
+ m['xidNumber'] = ldb.MessageElement(
+ str(xid), ldb.FLAG_MOD_REPLACE, 'xidNumber')
+ m['type'] = ldb.MessageElement(
+ xid_type, ldb.FLAG_MOD_REPLACE, 'type')
idmapdb.modify(m)
except ldb.LdbError, e:
- logger.warn('Could not modify idmap entry for sid=%s, id=%s, type=%s (%s)',
- str(sid), str(xid), xid_type, str(e))
+ logger.warn(
+ 'Could not modify idmap entry for sid=%s, id=%s, type=%s (%s)',
+ str(sid), str(xid), xid_type, str(e))
else:
try:
idmapdb.add({"dn": "CN=%s" % str(sid),
"type": xid_type,
"xidNumber": str(xid)})
except ldb.LdbError, e:
- logger.warn('Could not add idmap entry for sid=%s, id=%s, type=%s (%s)',
- str(sid), str(xid), xid_type, str(e))
+ logger.warn(
+ 'Could not add idmap entry for sid=%s, id=%s, type=%s (%s)',
+ str(sid), str(xid), xid_type, str(e))
def import_idmap(idmapdb, samba3, logger):
try:
samba3_idmap = samba3.get_idmap_db()
- except IOError as (errno, strerror):
- logger.warn('Cannot open idmap database, Ignoring: ({0}): {1}'.format(errno, strerror))
+ except IOError, e:
+ logger.warn('Cannot open idmap database, Ignoring: %s', str(e))
return
currentxid = max(samba3_idmap.get_user_hwm(), samba3_idmap.get_group_hwm())
m = ldb.Message()
m.dn = ldb.Dn(idmapdb, 'CN=CONFIG')
- m['lowerbound'] = ldb.MessageElement(str(lowerbound), ldb.FLAG_MOD_REPLACE, 'lowerBound')
- m['xidNumber'] = ldb.MessageElement(str(currentxid), ldb.FLAG_MOD_REPLACE, 'xidNumber')
+ m['lowerbound'] = ldb.MessageElement(
+ str(lowerbound), ldb.FLAG_MOD_REPLACE, 'lowerBound')
+ m['xidNumber'] = ldb.MessageElement(
+ str(currentxid), ldb.FLAG_MOD_REPLACE, 'xidNumber')
idmapdb.modify(m)
for id_type, xid in samba3_idmap.ids():
# First try to see if we already have this entry
try:
- msg = samdb.search(base='<SID=%s>' % str(groupmap.sid), scope=ldb.SCOPE_BASE)
+ msg = samdb.search(
+ base='<SID=%s>' % str(groupmap.sid), scope=ldb.SCOPE_BASE)
found = True
except ldb.LdbError, (ecode, emsg):
if ecode == ldb.ERR_NO_SUCH_OBJECT:
str(groupmap.sid), groupmap.nt_name, msg[0]['sAMAccountName'][0])
else:
if groupmap.sid_name_use == lsa.SID_NAME_WKN_GRP:
- return
+ # In a lot of Samba3 databases, aliases are marked as well known groups
+ (group_dom_sid, rid) = groupmap.sid.split()
+ if (group_dom_sid != security.dom_sid(security.SID_BUILTIN)):
+ return
m = ldb.Message()
m.dn = ldb.Dn(samdb, "CN=%s,CN=Users,%s" % (groupmap.nt_name, samdb.get_default_basedn()))
m['a04'] = ldb.MessageElement(groupmap.comment, ldb.FLAG_MOD_ADD, 'description')
m['a05'] = ldb.MessageElement(groupmap.nt_name, ldb.FLAG_MOD_ADD, 'sAMAccountName')
- if groupmap.sid_name_use == lsa.SID_NAME_ALIAS:
+ # Fix up incorrect 'well known' groups that are actually builtin (per test above) to be aliases
+ if groupmap.sid_name_use == lsa.SID_NAME_ALIAS or groupmap.sid_name_use == lsa.SID_NAME_WKN_GRP:
m['a06'] = ldb.MessageElement(str(dsdb.GTYPE_SECURITY_DOMAIN_LOCAL_GROUP), ldb.FLAG_MOD_ADD, 'groupType')
try:
"""
for member_sid in members:
m = ldb.Message()
- m.dn = ldb.Dn(samdb, "<SID=%s" % str(group.sid))
- m['a01'] = ldb.MessageElement("<SID=%s>" % str(member_sid), ldb.FLAG_MOD_REPLACE, 'member')
+ m.dn = ldb.Dn(samdb, "<SID=%s>" % str(group.sid))
+ m['a01'] = ldb.MessageElement("<SID=%s>" % str(member_sid), ldb.FLAG_MOD_ADD, 'member')
try:
samdb.modify(m)
- except ldb.LdbError, e:
- logger.warn("Could not add member to group '%s'", groupmap.nt_name)
+ except ldb.LdbError, (ecode, emsg):
+ if ecode == ldb.ERR_ENTRY_ALREADY_EXISTS:
+ logger.info("skipped re-adding member '%s' to group '%s': %s", member_sid, group.sid, emsg)
+ elif ecode == ldb.ERR_NO_SUCH_OBJECT:
+ raise ProvisioningError("Could not add member '%s' to group '%s' as either group or user record doesn't exist: %s" % (member_sid, group.sid, emsg))
+ else:
+ raise ProvisioningError("Could not add member '%s' to group '%s': %s" % (member_sid, group.sid, emsg))
def import_wins(samba4_winsdb, samba3_winsdb):
:param samba4_winsdb: WINS database to import to
:param samba3_winsdb: WINS database to import from
"""
+
version_id = 0
for (name, (ttl, ips, nb_flags)) in samba3_winsdb.items():
- version_id+=1
+ version_id += 1
type = int(name.split("#", 1)[1], 16)
else:
rState = 0x1 # released
- nType = ((nb_flags & 0x60)>>5)
+ nType = ((nb_flags & 0x60) >> 5)
samba4_winsdb.add({"dn": "name=%s,type=0x%s" % tuple(name.split("#")),
"type": name.split("#")[1],
"objectClass": "winsMaxVersion",
"maxVersion": str(version_id)})
+
def enable_samba3sam(samdb, ldapurl):
"""Enable Samba 3 LDAP URL database.
"host msdfs",
"winbind separator"]
-def upgrade_smbconf(oldconf,mark):
+
+def upgrade_smbconf(oldconf, mark):
"""Remove configuration variables not present in Samba4
:param oldconf: Old configuration structure
if keep:
newconf.set(s, p, oldconf.get(s, p))
elif mark:
- newconf.set(s, "samba3:"+p, oldconf.get(s,p))
+ newconf.set(s, "samba3:" + p, oldconf.get(s, p))
return newconf
'HKLM': registry.HKEY_LOCAL_MACHINE,
}
+
def import_registry(samba4_registry, samba3_regdb):
"""Import a Samba 3 registry database into the Samba 4 registry.
netbiosname = samba3.lp.get("netbios name")
# secrets db
- secrets_db = samba3.get_secrets_db()
+ try:
+ secrets_db = samba3.get_secrets_db()
+ except IOError, e:
+ raise ProvisioningError("Could not open '%s', the Samba3 secrets database: %s. Perhaps you specified the incorrect smb.conf, --testparm or --dbdir option?" % (samba3.privatedir_path("secrets.tdb"), str(e)))
if not domainname:
domainname = secrets_db.domains()[0]
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
+ except KeyError:
+ machinepass = None
# We must close the direct pytdb database before the C code loads it
secrets_db.close()
# Get machine account, sid, rid
try:
machineacct = s3db.getsampwnam('%s$' % netbiosname)
+ except passdb.error:
+ machinerid = None
+ machinesid = None
+ else:
machinesid, machinerid = machineacct.user_sid.split()
- except:
- pass
# Export account policy
logger.info("Exporting account policy")
sid, rid = group.sid.split()
if sid == domainsid:
if rid >= next_rid:
- next_rid = rid + 1
+ next_rid = rid + 1
# Get members for each group/alias
if group.sid_name_use == lsa.SID_NAME_ALIAS:
elif group.sid_name_use == lsa.SID_NAME_DOM_GRP:
try:
members = s3db.enum_group_members(group.sid)
- except:
+ except passdb.error:
continue
+ groupmembers[group.nt_name] = members
elif group.sid_name_use == lsa.SID_NAME_WKN_GRP:
- logger.warn("Ignoring 'well known' group '%s' (should already be in AD, and have no members)",
- group.nt_name, group.sid_name_use)
- continue
+ (group_dom_sid, rid) = group.sid.split()
+ if (group_dom_sid != security.dom_sid(security.SID_BUILTIN)):
+ logger.warn("Ignoring 'well known' group '%s' (should already be in AD, and have no members)",
+ group.nt_name)
+ continue
+ # A number of buggy databases mix up well known groups and aliases.
+ members = s3db.enum_aliasmem(group.sid)
else:
logger.warn("Ignoring group '%s' with sid_name_use=%d",
group.nt_name, group.sid_name_use)
continue
- groupmembers[group.nt_name] = members
-
# Export users from old passdb backend
logger.info("Exporting users")
continue
if entry['rid'] >= next_rid:
next_rid = entry['rid'] + 1
-
- userdata[username] = s3db.getsampwnam(username)
+
+ user = s3db.getsampwnam(username)
+ acct_type = (user.acct_ctrl & (samr.ACB_NORMAL|samr.ACB_WSTRUST|samr.ACB_SVRTRUST|samr.ACB_DOMTRUST))
+ if (acct_type == samr.ACB_NORMAL or acct_type == samr.ACB_WSTRUST or acct_type == samr.ACB_SVRTRUST):
+ pass
+ elif acct_type == samr.ACB_DOMTRUST:
+ logger.warn(" Skipping inter-domain trust from domain %s, this trust must be re-created as an AD trust" % username[:-1])
+ continue
+ elif acct_type == (samr.ACB_NORMAL|samr.ACB_WSTRUST) and username[-1] == '$':
+ logger.warn(" Fixing account %s which had both ACB_NORMAL (U) and ACB_WSTRUST (W) set. Account will be marked as ACB_WSTRUST (W), i.e. as a domain member" % username)
+ user.acct_ctrl = (user.acct_ctrl & ~samr.ACB_NORMAL)
+ else:
+ raise ProvisioningError("""Failed to upgrade due to invalid account %s, account control flags 0x%08X must have exactly one of
+ACB_NORMAL (N, 0x%08X), ACB_WSTRUST (W 0x%08X), ACB_SVRTRUST (S 0x%08X) or ACB_DOMTRUST (D 0x%08X).
+
+Please fix this account before attempting to upgrade again
+"""
+ % (user.acct_flags, username,
+ samr.ACB_NORMAL, samr.ACB_WSTRUST, samr.ACB_SVRTRUST, samr.ACB_DOMTRUST))
+
+ userdata[username] = user
try:
- uids[username] = s3db.sid_to_id(userdata[username].user_sid)[0]
- except:
+ uids[username] = s3db.sid_to_id(user.user_sid)[0]
+ except passdb.error:
try:
uids[username] = pwd.getpwnam(username).pw_uid
- except:
+ except KeyError:
pass
if not admin_user and username.lower() == 'root':
logger.info("Next rid = %d", next_rid)
+ # Check for same username/groupname
+ group_names = set([g.nt_name for g in grouplist])
+ user_names = set([u['account_name'] for u in userlist])
+ common_names = group_names.intersection(user_names)
+ if common_names:
+ logger.error("Following names are both user names and group names:")
+ for name in common_names:
+ logger.error(" %s" % name)
+ raise ProvisioningError("Please remove common user/group names before upgrade.")
+
+ # Check for same user sid/group sid
+ group_sids = set([str(g.sid) for g in grouplist])
+ user_sids = set(["%s-%u" % (domainsid, u['rid']) for u in userlist])
+ common_sids = group_sids.intersection(user_sids)
+ if common_sids:
+ logger.error("Following sids are both user and group sids:")
+ for sid in common_sids:
+ logger.error(" %s" % str(sid))
+ raise ProvisioningError("Please remove duplicate sid entries before upgrade.")
+
+ if serverrole == "domain controller":
+ dns_backend = "BIND9_FLATFILE"
+ else:
+ dns_backend = "NONE"
+
# Do full provision
result = provision(logger, session_info, None,
targetdir=targetdir, realm=realm, domain=domainname,
domainsid=str(domainsid), next_rid=next_rid,
dc_rid=machinerid,
+ dom_for_fun_level=dsdb.DS_DOMAIN_FUNCTION_2003,
hostname=netbiosname, machinepass=machinepass,
serverrole=serverrole, samdb_fill=FILL_FULL,
- useeadb=useeadb)
+ useeadb=useeadb, dns_backend=dns_backend)
# Import WINS database
logger.info("Importing WINS database")
- import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
+
+ samba3_winsdb = None
+ try:
+ samba3_winsdb = samba3.get_wins_db()
+ except IOError, e:
+ logger.warn('Cannot open wins database, Ignoring: %s', str(e))
+
+ if samba3_winsdb:
+ import_wins(Ldb(result.paths.winsdb), samba3_winsdb)
# Set Account policy
logger.info("Importing Account policy")