r26608: More improvements to the upgrade code.
[jelmer/samba4-debian.git] / source / scripting / python / samba / upgrade.py
1 #!/usr/bin/python
2 #
3 #       backend code for upgrading from Samba3
4 #       Copyright Jelmer Vernooij 2005-2007
5 #       Released under the GNU GPL v3 or later
6 #
7
8 """Support code for upgrading from Samba 3 to Samba 4."""
9
10 from provision import findnss, provision
11 import grp
12 import ldb
13 import pwd
14 import uuid
15 import registry
16 from samba import Ldb
17 from samba.samdb import SamDB
18
19 def import_sam_policy(samldb, samba3_policy, domaindn):
20     samldb.modify_ldif("""
21 dn: %s
22 changetype: modify
23 replace: minPwdLength
24 minPwdLength: %d
25 pwdHistoryLength: %d
26 minPwdAge: %d
27 maxPwdAge: %d
28 lockoutDuration: %d
29 samba3ResetCountMinutes: %d
30 samba3UserMustLogonToChangePassword: %d
31 samba3BadLockoutMinutes: %d
32 samba3DisconnectTime: %d
33
34 """ % (dn, policy.min_password_length, 
35     policy.password_history, policy.minimum_password_age,
36     policy.maximum_password_age, policy.lockout_duration,
37     policy.reset_count_minutes, policy.user_must_logon_to_change_password,
38     policy.bad_lockout_minutes, policy.disconnect_time))
39
40
41 def import_sam_account(samldb,acc,domaindn,domainsid):
42     """Import a Samba 3 SAM account.
43     
44     :param samldb: Samba 4 SAM Database handle
45     :param acc: Samba 3 account
46     :param domaindn: Domain DN
47     :param domainsid: Domain SID."""
48     if acc.nt_username is None or acc.nt_username == "":
49         acc.nt_username = acc.username
50
51     if acc.fullname is None:
52         try:
53             acc.fullname = pwd.getpwnam(acc.username)[4].split(",")[0]
54         except KeyError:
55             pass
56
57     if acc.fullname is None:
58         acc.fullname = acc.username
59     
60     assert acc.fullname is not None
61     assert acc.nt_username is not None
62
63     samldb.add({
64         "dn": "cn=%s,%s" % (acc.fullname, domaindn),
65         "objectClass": ["top", "user"],
66         "lastLogon": str(acc.logon_time),
67         "lastLogoff": str(acc.logoff_time),
68         "unixName": acc.username,
69         "sAMAccountName": acc.nt_username,
70         "cn": acc.nt_username,
71         "description": acc.acct_desc,
72         "primaryGroupID": str(acc.group_rid),
73         "badPwdcount": str(acc.bad_password_count),
74         "logonCount": str(acc.logon_count),
75         "samba3Domain": acc.domain,
76         "samba3DirDrive": acc.dir_drive,
77         "samba3MungedDial": acc.munged_dial,
78         "samba3Homedir": acc.homedir, 
79         "samba3LogonScript": acc.logon_script, 
80         "samba3ProfilePath": acc.profile_path,
81         "samba3Workstations": acc.workstations,
82         "samba3KickOffTime": str(acc.kickoff_time),
83         "samba3BadPwdTime": str(acc.bad_password_time),
84         "samba3PassLastSetTime": str(acc.pass_last_set_time),
85         "samba3PassCanChangeTime": str(acc.pass_can_change_time),
86         "samba3PassMustChangeTime": str(acc.pass_must_change_time),
87         "objectSid": "%s-%d" % (domainsid, acc.user_rid),
88         "lmPwdHash:": acc.lm_password,
89         "ntPwdHash:": acc.nt_password,
90         })
91
92
93 def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
94     """Upgrade a SAM group.
95     
96     :param samldb: SAM database.
97     :param gid: Group GID
98     :param sid_name_use: SID name use
99     :param nt_name: NT Group Name
100     :param comment: NT Group Comment
101     :param domaindn: Domain DN
102     """
103
104     if sid_name_use == 5: # Well-known group
105         return None
106
107     if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"):
108         return None
109     
110     if gid == -1:
111         gr = grp.getgrnam(nt_name)
112     else:
113         gr = grp.getgrgid(gid)
114
115     if gr is None:
116         unixname = "UNKNOWN"
117     else:
118         unixname = gr.gr_name
119
120     assert unixname is not None
121     
122     samldb.add({
123         "dn": "cn=%s,%s" % (nt_name, domaindn),
124         "objectClass": ["top", "group"],
125         "description": comment,
126         "cn": nt_name, 
127         "objectSid": sid,
128         "unixName": unixname,
129         "samba3SidNameUse": str(sid_name_use)
130         })
131
132
133 def import_idmap(samdb,samba3_idmap,domaindn):
134     """Import idmap data.
135
136     :param samdb: SamDB handle.
137     :param samba3_idmap: Samba 3 IDMAP database to import from
138     :param domaindn: Domain DN.
139     """
140     samdb.add({
141         "dn": domaindn,
142         "userHwm": str(samba3_idmap.get_user_hwm()),
143         "groupHwm": str(samba3_idmap.get_group_hwm())})
144
145     for uid in samba3_idmap.uids():
146         samdb.add({"dn": "SID=%s,%s" % (samba3_idmap.get_user_sid(uid), domaindn),
147                           "SID": samba3_idmap.get_user_sid(uid),
148                           "type": "user",
149                           "unixID": str(uid)})
150
151     for gid in samba3_idmap.uids():
152         samdb.add({"dn": "SID=%s,%s" % (samba3_idmap.get_group_sid(gid), domaindn),
153                           "SID": samba3_idmap.get_group_sid(gid),
154                           "type": "group",
155                           "unixID": str(gid)})
156
157
158 def import_wins(samba4_winsdb, samba3_winsdb):
159     """Import settings from a Samba3 WINS database.
160     
161     :param samba4_winsdb: WINS database to import to
162     :param samba3_winsdb: WINS database to import from
163     """
164     version_id = 0
165     import time
166
167     for (name, (ttl, ips, nb_flags)) in samba3_winsdb.items():
168         version_id+=1
169
170         type = int(name.split("#", 1)[1], 16)
171
172         if type == 0x1C:
173             rType = 0x2
174         elif type & 0x80:
175             if len(ips) > 1:
176                 rType = 0x2
177             else:
178                 rType = 0x1
179         else:
180             if len(ips) > 1:
181                 rType = 0x3
182             else:
183                 rType = 0x0
184
185         if ttl > time.time():
186             rState = 0x0 # active
187         else:
188             rState = 0x1 # released
189
190         nType = ((nb_flags & 0x60)>>5)
191
192         samba4_winsdb.add({"dn": "name=%s,type=0x%s" % tuple(name.split("#")),
193                            "type": name.split("#")[1],
194                            "name": name.split("#")[0],
195                            "objectClass": "winsRecord",
196                            "recordType": str(rType),
197                            "recordState": str(rState),
198                            "nodeType": str(nType),
199                            "expireTime": ldb.timestring(ttl),
200                            "isStatic": "0",
201                            "versionID": str(version_id),
202                            "address": ips})
203
204     samba4_winsdb.add({"dn": "CN=VERSION",
205                        "objectClass": "winsMaxVersion",
206                        "maxVersion": str(version_id)})
207
208 def upgrade_provision(samba3, setup_dir, message, credentials, session_info, lp, paths):
209     oldconf = samba3.get_conf()
210
211     if oldconf.get("domain logons") == "True":
212         serverrole = "domain controller"
213     else:
214         if oldconf.get("security") == "user":
215             serverrole = "standalone"
216         else:
217             serverrole = "member server"
218
219     lp.set("server role", serverrole)
220     domainname = oldconf.get("workgroup")
221     if domainname:
222         domainname = str(domainname)
223     lp.set("workgroup", domainname)
224     realm = oldconf.get("realm")
225     netbiosname = oldconf.get("netbios name")
226
227     secrets_db = samba3.get_secrets_db()
228     
229     if domainname is None:
230         domainname = secrets_db.domains()[0]
231         message("No domain specified in smb.conf file, assuming '%s'" % domainname)
232     
233     if realm is None:
234         realm = domainname.lower()
235         message("No realm specified in smb.conf file, assuming '%s'\n" % realm)
236     lp.set("realm", realm)
237
238     domainguid = secrets_db.get_domain_guid(domainname)
239     domainsid = secrets_db.get_sid(domainname)
240     if domainsid is None:
241         message("Can't find domain secrets for '%s'; using random SID\n" % domainname)
242     
243     if netbiosname is not None:
244         machinepass = secrets_db.get_machine_password(netbiosname)
245     else:
246         machinepass = None
247     
248     domaindn = provision(lp=lp, setup_dir=setup_dir, message=message, blank=True, ldapbackend=None, 
249                          paths=paths, session_info=session_info, credentials=credentials, realm=realm, 
250                          domain=domainname, domainsid=domainsid, domainguid=domainguid, 
251                          machinepass=machinepass, serverrole=serverrole)
252
253     samdb = SamDB(paths.samdb, credentials=credentials, lp=lp, session_info=session_info)
254
255     import_wins(Ldb(paths.winsdb), samba3.get_wins_db())
256
257     # FIXME: import_registry(registry.Registry(), samba3.get_registry())
258
259     # FIXME: import_idmap(samdb,samba3.get_idmap_db(),domaindn)
260     
261     groupdb = samba3.get_groupmapping_db()
262     for sid in groupdb.groupsids():
263         (gid, sid_name_use, nt_name, comment) = groupdb.get_group(sid)
264         # FIXME: import_sam_group(samdb, sid, gid, sid_name_use, nt_name, comment, domaindn)
265
266     # FIXME: Aliases
267
268     passdb = samba3.get_sam_db()
269     for name in passdb:
270         user = passdb[name]
271         #FIXME: import_sam_account(samdb, user, domaindn, domainsid)
272
273     if hasattr(passdb, 'ldap_url'):
274         message("Enabling Samba3 LDAP mappings for SAM database")
275
276         enable_samba3sam(samdb, passdb.ldap_url)
277
278
279 def enable_samba3sam(samdb, ldapurl):
280     """Enable Samba 3 LDAP URL database.
281
282     :param samdb: SAM Database.
283     :param ldapurl: Samba 3 LDAP URL
284     """
285     samdb.modify_ldif("""
286 dn: @MODULES
287 changetype: modify
288 replace: @LIST
289 @LIST: samldb,operational,objectguid,rdn_name,samba3sam
290 """)
291
292     samdb.add({"dn": "@MAP=samba3sam", "@MAP_URL": ldapurl})
293
294
295 smbconf_keep = [
296     "dos charset", 
297     "unix charset",
298     "display charset",
299     "comment",
300     "path",
301     "directory",
302     "workgroup",
303     "realm",
304     "netbios name",
305     "netbios aliases",
306     "netbios scope",
307     "server string",
308     "interfaces",
309     "bind interfaces only",
310     "security",
311     "auth methods",
312     "encrypt passwords",
313     "null passwords",
314     "obey pam restrictions",
315     "password server",
316     "smb passwd file",
317     "private dir",
318     "passwd chat",
319     "password level",
320     "lanman auth",
321     "ntlm auth",
322     "client NTLMv2 auth",
323     "client lanman auth",
324     "client plaintext auth",
325     "read only",
326     "hosts allow",
327     "hosts deny",
328     "log level",
329     "debuglevel",
330     "log file",
331     "smb ports",
332     "large readwrite",
333     "max protocol",
334     "min protocol",
335     "unicode",
336     "read raw",
337     "write raw",
338     "disable netbios",
339     "nt status support",
340     "announce version",
341     "announce as",
342     "max mux",
343     "max xmit",
344     "name resolve order",
345     "max wins ttl",
346     "min wins ttl",
347     "time server",
348     "unix extensions",
349     "use spnego",
350     "server signing",
351     "client signing",
352     "max connections",
353     "paranoid server security",
354     "socket options",
355     "strict sync",
356     "max print jobs",
357     "printable",
358     "print ok",
359     "printer name",
360     "printer",
361     "map system",
362     "map hidden",
363     "map archive",
364     "preferred master",
365     "prefered master",
366     "local master",
367     "browseable",
368     "browsable",
369     "wins server",
370     "wins support",
371     "csc policy",
372     "strict locking",
373     "preload",
374     "auto services",
375     "lock dir",
376     "lock directory",
377     "pid directory",
378     "socket address",
379     "copy",
380     "include",
381     "available",
382     "volume",
383     "fstype",
384     "panic action",
385     "msdfs root",
386     "host msdfs",
387     "winbind separator"]
388
389 def upgrade_smbconf(oldconf,mark):
390     """Remove configuration variables not present in Samba4
391
392     :param oldconf: Old configuration structure
393     :param mark: Whether removed configuration variables should be 
394         kept in the new configuration as "samba3:<name>"
395     """
396     data = oldconf.data()
397     newconf = param_init()
398
399     for s in data:
400         for p in data[s]:
401             keep = False
402             for k in smbconf_keep:
403                 if smbconf_keep[k] == p:
404                     keep = True
405                     break
406
407             if keep:
408                 newconf.set(s, p, oldconf.get(s, p))
409             elif mark:
410                 newconf.set(s, "samba3:"+p, oldconf.get(s,p))
411
412     return newconf
413
414 SAMBA3_PREDEF_NAMES = {
415         'HKLM': registry.HKEY_LOCAL_MACHINE,
416 }
417
418 def import_registry(samba4_registry, samba3_regdb):
419     """Import a Samba 3 registry database into the Samba 4 registry.
420
421     :param samba4_registry: Samba 4 registry handle.
422     :param samba3_regdb: Samba 3 registry database handle.
423     """
424     def ensure_key_exists(keypath):
425         (predef_name, keypath) = keypath.split("/", 1)
426         predef_id = SAMBA3_PREDEF_NAMES[predef_name]
427         keypath = keypath.replace("/", "\\")
428         return samba4_registry.create_key(predef_id, keypath)
429
430     for key in samba3_regdb.keys():
431         key_handle = ensure_key_exists(key)
432         for subkey in samba3_regdb.subkeys(key):
433             ensure_key_exists(subkey)
434         for (value_name, (value_type, value_data)) in samba3_regdb.values(key).items():
435             key_handle.set_value(value_name, value_type, value_data)
436
437
438 def upgrade(subobj, samba3, message, paths, session_info, credentials):
439     ret = 0
440     samdb = Ldb(paths.samdb, session_info=session_info, credentials=credentials)
441
442     message("Writing configuration")
443     newconf = upgrade_smbconf(samba3.configuration,True)
444     newconf.save(paths.smbconf)
445
446     message("Importing account policies")
447     samdb.modify_ldif(upgrade_sam_policy(samba3,subobj.BASEDN))
448     regdb = Ldb(paths.hklm)
449
450     regdb.modify("""
451 dn: value=RefusePasswordChange,key=Parameters,key=Netlogon,key=Services,key=CurrentControlSet,key=System,HIVE=NONE
452 replace: type
453 type: 4
454 replace: data
455 data: %d
456 """ % policy.refuse_machine_password_change)
457
458     message("Importing users")
459     for account in samba3.samaccounts:
460         msg = "... " + account.username
461         ldif = upgrade_sam_account(samdb, accounts,subobj.BASEDN,subobj.DOMAINSID)
462         try:
463             samdb.add(ldif)
464         except LdbError, e:
465             # FIXME: Ignore 'Record exists' errors
466             msg += "... error: " + str(e)
467             ret += 1; 
468         message(msg)
469
470     message("Importing groups")
471     for mapping in samba3.groupmappings:
472         msg = "... " + mapping.nt_name
473         ldif = upgrade_sam_group(mapping, subobj.BASEDN)
474         if ldif is not None:
475             try:
476                 samdb.add(ldif)
477             except LdbError, e:
478                 # FIXME: Ignore 'Record exists' errors
479                 msg += "... error: " + str(e)
480                 ret += 1
481         message(msg)
482
483     message("Importing WINS data")
484     winsdb = Ldb(paths.winsdb)
485     ldb_erase(winsdb)
486
487     ldif = upgrade_wins(samba3)
488     winsdb.add(ldif)
489
490