s4:upgrade.py - readd accidentally removed empty lines
[Samba/ekacnet.git] / source4 / scripting / python / samba / upgrade.py
blobc26448c0e4c747a9eeaeb8a147f2c78605739529
1 #!/usr/bin/python
3 # backend code for upgrading from Samba3
4 # Copyright Jelmer Vernooij 2005-2007
5 # Copyright Matthias Dieter Wallnoefer 2009
6 # Released under the GNU GPL v3 or later
9 """Support code for upgrading from Samba 3 to Samba 4."""
11 __docformat__ = "restructuredText"
13 from provision import provision
14 import grp
15 import ldb
16 import time
17 import pwd
18 import registry
19 from samba import Ldb
20 from samba.param import LoadParm
22 def import_sam_policy(samldb, policy, dn):
23 """Import a Samba 3 policy database."""
24 samldb.modify_ldif("""
25 dn: %s
26 changetype: modify
27 replace: minPwdLength
28 minPwdLength: %d
29 pwdHistoryLength: %d
30 minPwdAge: %d
31 maxPwdAge: %d
32 lockoutDuration: %d
33 samba3ResetCountMinutes: %d
34 samba3UserMustLogonToChangePassword: %d
35 samba3BadLockoutMinutes: %d
36 samba3DisconnectTime: %d
38 """ % (dn, policy.min_password_length,
39 policy.password_history, policy.minimum_password_age,
40 policy.maximum_password_age, policy.lockout_duration,
41 policy.reset_count_minutes, policy.user_must_logon_to_change_password,
42 policy.bad_lockout_minutes, policy.disconnect_time))
45 def import_sam_account(samldb,acc,domaindn,domainsid):
46 """Import a Samba 3 SAM account.
48 :param samldb: Samba 4 SAM Database handle
49 :param acc: Samba 3 account
50 :param domaindn: Domain DN
51 :param domainsid: Domain SID."""
52 if acc.nt_username is None or acc.nt_username == "":
53 acc.nt_username = acc.username
55 if acc.fullname is None:
56 try:
57 acc.fullname = pwd.getpwnam(acc.username)[4].split(",")[0]
58 except KeyError:
59 pass
61 if acc.fullname is None:
62 acc.fullname = acc.username
64 assert acc.fullname is not None
65 assert acc.nt_username is not None
67 samldb.add({
68 "dn": "cn=%s,%s" % (acc.fullname, domaindn),
69 "objectClass": ["top", "user"],
70 "lastLogon": str(acc.logon_time),
71 "lastLogoff": str(acc.logoff_time),
72 "unixName": acc.username,
73 "sAMAccountName": acc.nt_username,
74 "cn": acc.nt_username,
75 "description": acc.acct_desc,
76 "primaryGroupID": str(acc.group_rid),
77 "badPwdcount": str(acc.bad_password_count),
78 "logonCount": str(acc.logon_count),
79 "samba3Domain": acc.domain,
80 "samba3DirDrive": acc.dir_drive,
81 "samba3MungedDial": acc.munged_dial,
82 "samba3Homedir": acc.homedir,
83 "samba3LogonScript": acc.logon_script,
84 "samba3ProfilePath": acc.profile_path,
85 "samba3Workstations": acc.workstations,
86 "samba3KickOffTime": str(acc.kickoff_time),
87 "samba3BadPwdTime": str(acc.bad_password_time),
88 "samba3PassLastSetTime": str(acc.pass_last_set_time),
89 "samba3PassCanChangeTime": str(acc.pass_can_change_time),
90 "samba3PassMustChangeTime": str(acc.pass_must_change_time),
91 "objectSid": "%s-%d" % (domainsid, acc.user_rid),
92 "lmPwdHash:": acc.lm_password,
93 "ntPwdHash:": acc.nt_password,
97 def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
98 """Upgrade a SAM group.
100 :param samldb: SAM database.
101 :param gid: Group GID
102 :param sid_name_use: SID name use
103 :param nt_name: NT Group Name
104 :param comment: NT Group Comment
105 :param domaindn: Domain DN
108 if sid_name_use == 5: # Well-known group
109 return None
111 if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"):
112 return None
114 if gid == -1:
115 gr = grp.getgrnam(nt_name)
116 else:
117 gr = grp.getgrgid(gid)
119 if gr is None:
120 unixname = "UNKNOWN"
121 else:
122 unixname = gr.gr_name
124 assert unixname is not None
126 samldb.add({
127 "dn": "cn=%s,%s" % (nt_name, domaindn),
128 "objectClass": ["top", "group"],
129 "description": comment,
130 "cn": nt_name,
131 "objectSid": sid,
132 "unixName": unixname,
133 "samba3SidNameUse": str(sid_name_use)
137 def import_idmap(samdb,samba3_idmap,domaindn):
138 """Import idmap data.
140 :param samdb: SamDB handle.
141 :param samba3_idmap: Samba 3 IDMAP database to import from
142 :param domaindn: Domain DN.
144 samdb.add({
145 "dn": domaindn,
146 "userHwm": str(samba3_idmap.get_user_hwm()),
147 "groupHwm": str(samba3_idmap.get_group_hwm())})
149 for uid in samba3_idmap.uids():
150 samdb.add({"dn": "SID=%s,%s" % (samba3_idmap.get_user_sid(uid), domaindn),
151 "SID": samba3_idmap.get_user_sid(uid),
152 "type": "user",
153 "unixID": str(uid)})
155 for gid in samba3_idmap.uids():
156 samdb.add({"dn": "SID=%s,%s" % (samba3_idmap.get_group_sid(gid), domaindn),
157 "SID": samba3_idmap.get_group_sid(gid),
158 "type": "group",
159 "unixID": str(gid)})
162 def import_wins(samba4_winsdb, samba3_winsdb):
163 """Import settings from a Samba3 WINS database.
165 :param samba4_winsdb: WINS database to import to
166 :param samba3_winsdb: WINS database to import from
168 version_id = 0
170 for (name, (ttl, ips, nb_flags)) in samba3_winsdb.items():
171 version_id+=1
173 type = int(name.split("#", 1)[1], 16)
175 if type == 0x1C:
176 rType = 0x2
177 elif type & 0x80:
178 if len(ips) > 1:
179 rType = 0x2
180 else:
181 rType = 0x1
182 else:
183 if len(ips) > 1:
184 rType = 0x3
185 else:
186 rType = 0x0
188 if ttl > time.time():
189 rState = 0x0 # active
190 else:
191 rState = 0x1 # released
193 nType = ((nb_flags & 0x60)>>5)
195 samba4_winsdb.add({"dn": "name=%s,type=0x%s" % tuple(name.split("#")),
196 "type": name.split("#")[1],
197 "name": name.split("#")[0],
198 "objectClass": "winsRecord",
199 "recordType": str(rType),
200 "recordState": str(rState),
201 "nodeType": str(nType),
202 "expireTime": ldb.timestring(ttl),
203 "isStatic": "0",
204 "versionID": str(version_id),
205 "address": ips})
207 samba4_winsdb.add({"dn": "cn=VERSION",
208 "cn": "VERSION",
209 "objectClass": "winsMaxVersion",
210 "maxVersion": str(version_id)})
212 def enable_samba3sam(samdb, ldapurl):
213 """Enable Samba 3 LDAP URL database.
215 :param samdb: SAM Database.
216 :param ldapurl: Samba 3 LDAP URL
218 samdb.modify_ldif("""
219 dn: @MODULES
220 changetype: modify
221 replace: @LIST
222 @LIST: samldb,operational,objectguid,rdn_name,samba3sam
223 """)
225 samdb.add({"dn": "@MAP=samba3sam", "@MAP_URL": ldapurl})
228 smbconf_keep = [
229 "dos charset",
230 "unix charset",
231 "display charset",
232 "comment",
233 "path",
234 "directory",
235 "workgroup",
236 "realm",
237 "netbios name",
238 "netbios aliases",
239 "netbios scope",
240 "server string",
241 "interfaces",
242 "bind interfaces only",
243 "security",
244 "auth methods",
245 "encrypt passwords",
246 "null passwords",
247 "obey pam restrictions",
248 "password server",
249 "smb passwd file",
250 "private dir",
251 "passwd chat",
252 "password level",
253 "lanman auth",
254 "ntlm auth",
255 "client NTLMv2 auth",
256 "client lanman auth",
257 "client plaintext auth",
258 "read only",
259 "hosts allow",
260 "hosts deny",
261 "log level",
262 "debuglevel",
263 "log file",
264 "smb ports",
265 "large readwrite",
266 "max protocol",
267 "min protocol",
268 "unicode",
269 "read raw",
270 "write raw",
271 "disable netbios",
272 "nt status support",
273 "announce version",
274 "announce as",
275 "max mux",
276 "max xmit",
277 "name resolve order",
278 "max wins ttl",
279 "min wins ttl",
280 "time server",
281 "unix extensions",
282 "use spnego",
283 "server signing",
284 "client signing",
285 "max connections",
286 "paranoid server security",
287 "socket options",
288 "strict sync",
289 "max print jobs",
290 "printable",
291 "print ok",
292 "printer name",
293 "printer",
294 "map system",
295 "map hidden",
296 "map archive",
297 "preferred master",
298 "prefered master",
299 "local master",
300 "browseable",
301 "browsable",
302 "wins server",
303 "wins support",
304 "csc policy",
305 "strict locking",
306 "preload",
307 "auto services",
308 "lock dir",
309 "lock directory",
310 "pid directory",
311 "socket address",
312 "copy",
313 "include",
314 "available",
315 "volume",
316 "fstype",
317 "panic action",
318 "msdfs root",
319 "host msdfs",
320 "winbind separator"]
322 def upgrade_smbconf(oldconf,mark):
323 """Remove configuration variables not present in Samba4
325 :param oldconf: Old configuration structure
326 :param mark: Whether removed configuration variables should be
327 kept in the new configuration as "samba3:<name>"
329 data = oldconf.data()
330 newconf = LoadParm()
332 for s in data:
333 for p in data[s]:
334 keep = False
335 for k in smbconf_keep:
336 if smbconf_keep[k] == p:
337 keep = True
338 break
340 if keep:
341 newconf.set(s, p, oldconf.get(s, p))
342 elif mark:
343 newconf.set(s, "samba3:"+p, oldconf.get(s,p))
345 return newconf
347 SAMBA3_PREDEF_NAMES = {
348 'HKLM': registry.HKEY_LOCAL_MACHINE,
351 def import_registry(samba4_registry, samba3_regdb):
352 """Import a Samba 3 registry database into the Samba 4 registry.
354 :param samba4_registry: Samba 4 registry handle.
355 :param samba3_regdb: Samba 3 registry database handle.
357 def ensure_key_exists(keypath):
358 (predef_name, keypath) = keypath.split("/", 1)
359 predef_id = SAMBA3_PREDEF_NAMES[predef_name]
360 keypath = keypath.replace("/", "\\")
361 return samba4_registry.create_key(predef_id, keypath)
363 for key in samba3_regdb.keys():
364 key_handle = ensure_key_exists(key)
365 for subkey in samba3_regdb.subkeys(key):
366 ensure_key_exists(subkey)
367 for (value_name, (value_type, value_data)) in samba3_regdb.values(key).items():
368 key_handle.set_value(value_name, value_type, value_data)
371 def upgrade_provision(samba3, setup_dir, message, credentials, session_info,
372 smbconf, targetdir):
373 oldconf = samba3.get_conf()
375 if oldconf.get("domain logons") == "True":
376 serverrole = "domain controller"
377 else:
378 if oldconf.get("security") == "user":
379 serverrole = "standalone"
380 else:
381 serverrole = "member server"
383 domainname = oldconf.get("workgroup")
384 realm = oldconf.get("realm")
385 netbiosname = oldconf.get("netbios name")
387 secrets_db = samba3.get_secrets_db()
389 if domainname is None:
390 domainname = secrets_db.domains()[0]
391 message("No domain specified in smb.conf file, assuming '%s'" % domainname)
393 if realm is None:
394 if oldconf.get("domain logons") == "True":
395 message("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).")
396 return
397 else:
398 realm = domainname.upper()
399 message("No realm specified in smb.conf file, assuming '%s'" % realm)
401 domainguid = secrets_db.get_domain_guid(domainname)
402 domainsid = secrets_db.get_sid(domainname)
403 if domainsid is None:
404 message("Can't find domain secrets for '%s'; using random SID" % domainname)
406 if netbiosname is not None:
407 machinepass = secrets_db.get_machine_password(netbiosname)
408 else:
409 machinepass = None
411 result = provision(setup_dir=setup_dir, message=message,
412 session_info=session_info, credentials=credentials,
413 targetdir=targetdir, realm=realm, domain=domainname,
414 domainguid=domainguid, domainsid=domainsid,
415 hostname=netbiosname, machinepass=machinepass,
416 serverrole=serverrole)
418 import_wins(Ldb(result.paths.winsdb), samba3.get_wins_db())
420 # FIXME: import_registry(registry.Registry(), samba3.get_registry())
422 # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
424 groupdb = samba3.get_groupmapping_db()
425 for sid in groupdb.groupsids():
426 (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
427 # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
429 # FIXME: Aliases
431 passdb = samba3.get_sam_db()
432 for name in passdb:
433 user = passdb[name]
434 #FIXME: import_sam_account(result.samdb, user, domaindn, domainsid)
436 if hasattr(passdb, 'ldap_url'):
437 message("Enabling Samba3 LDAP mappings for SAM database")
439 enable_samba3sam(result.samdb, passdb.ldap_url)