lib: Fix strv_next for the anchor NULL entry
[Samba.git] / python / samba / upgradehelpers.py
blob3b664fe0512e7532d21ca76d48ad2656d7b1ec23
1 # Helpers for provision stuff
2 # Copyright (C) Matthieu Patou <mat@matws.net> 2009-2012
4 # Based on provision a Samba4 server by
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 """Helpers used for upgrading between different database formats."""
24 import os
25 import re
26 import shutil
27 import samba
29 from samba import Ldb, version, ntacls
30 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE
31 import ldb
32 from samba.provision import (provision_paths_from_lp,
33 getpolicypath, set_gpos_acl, create_gpo_struct,
34 provision, ProvisioningError,
35 setsysvolacl, secretsdb_self_join)
36 from samba.provision.common import FILL_FULL
37 from samba.dcerpc import xattr, drsblobs, security
38 from samba.dcerpc.misc import SEC_CHAN_BDC
39 from samba.ndr import ndr_unpack
40 from samba.samdb import SamDB
41 from samba import _glue
42 import tempfile
44 # All the ldb related to registry are commented because the path for them is
45 # relative in the provisionPath object
46 # And so opening them create a file in the current directory which is not what
47 # we want
48 # I still keep them commented because I plan soon to make more cleaner
49 ERROR = -1
50 SIMPLE = 0x00
51 CHANGE = 0x01
52 CHANGESD = 0x02
53 GUESS = 0x04
54 PROVISION = 0x08
55 CHANGEALL = 0xff
57 hashAttrNotCopied = set(["dn", "whenCreated", "whenChanged", "objectGUID",
58 "uSNCreated", "replPropertyMetaData", "uSNChanged", "parentGUID",
59 "objectCategory", "distinguishedName", "nTMixedDomain",
60 "showInAdvancedViewOnly", "instanceType", "msDS-Behavior-Version",
61 "nextRid", "cn", "versionNumber", "lmPwdHistory", "pwdLastSet",
62 "ntPwdHistory", "unicodePwd","dBCSPwd", "supplementalCredentials",
63 "gPCUserExtensionNames", "gPCMachineExtensionNames","maxPwdAge", "secret",
64 "possibleInferiors", "privilege", "sAMAccountType"])
67 class ProvisionLDB(object):
69 def __init__(self):
70 self.sam = None
71 self.secrets = None
72 self.idmap = None
73 self.privilege = None
74 self.hkcr = None
75 self.hkcu = None
76 self.hku = None
77 self.hklm = None
79 def dbs(self):
80 return (self.sam, self.secrets, self.idmap, self.privilege)
82 def startTransactions(self):
83 for db in self.dbs():
84 db.transaction_start()
85 # TO BE DONE
86 # self.hkcr.transaction_start()
87 # self.hkcu.transaction_start()
88 # self.hku.transaction_start()
89 # self.hklm.transaction_start()
91 def groupedRollback(self):
92 ok = True
93 for db in self.dbs():
94 try:
95 db.transaction_cancel()
96 except Exception:
97 ok = False
98 return ok
99 # TO BE DONE
100 # self.hkcr.transaction_cancel()
101 # self.hkcu.transaction_cancel()
102 # self.hku.transaction_cancel()
103 # self.hklm.transaction_cancel()
105 def groupedCommit(self):
106 try:
107 for db in self.dbs():
108 db.transaction_prepare_commit()
109 except Exception:
110 return self.groupedRollback()
111 # TO BE DONE
112 # self.hkcr.transaction_prepare_commit()
113 # self.hkcu.transaction_prepare_commit()
114 # self.hku.transaction_prepare_commit()
115 # self.hklm.transaction_prepare_commit()
116 try:
117 for db in self.dbs():
118 db.transaction_commit()
119 except Exception:
120 return self.groupedRollback()
122 # TO BE DONE
123 # self.hkcr.transaction_commit()
124 # self.hkcu.transaction_commit()
125 # self.hku.transaction_commit()
126 # self.hklm.transaction_commit()
127 return True
130 def get_ldbs(paths, creds, session, lp):
131 """Return LDB object mapped on most important databases
133 :param paths: An object holding the different importants paths for provision object
134 :param creds: Credential used for openning LDB files
135 :param session: Session to use for openning LDB files
136 :param lp: A loadparam object
137 :return: A ProvisionLDB object that contains LDB object for the different LDB files of the provision"""
139 ldbs = ProvisionLDB()
141 ldbs.sam = SamDB(paths.samdb, session_info=session, credentials=creds, lp=lp, options=["modules:samba_dsdb"])
142 ldbs.secrets = Ldb(paths.secrets, session_info=session, credentials=creds, lp=lp)
143 ldbs.idmap = Ldb(paths.idmapdb, session_info=session, credentials=creds, lp=lp)
144 ldbs.privilege = Ldb(paths.privilege, session_info=session, credentials=creds, lp=lp)
145 # ldbs.hkcr = Ldb(paths.hkcr, session_info=session, credentials=creds, lp=lp)
146 # ldbs.hkcu = Ldb(paths.hkcu, session_info=session, credentials=creds, lp=lp)
147 # ldbs.hku = Ldb(paths.hku, session_info=session, credentials=creds, lp=lp)
148 # ldbs.hklm = Ldb(paths.hklm, session_info=session, credentials=creds, lp=lp)
150 return ldbs
153 def usn_in_range(usn, range):
154 """Check if the usn is in one of the range provided.
155 To do so, the value is checked to be between the lower bound and
156 higher bound of a range
158 :param usn: A integer value corresponding to the usn that we want to update
159 :param range: A list of integer representing ranges, lower bounds are in
160 the even indices, higher in odd indices
161 :return: True if the usn is in one of the range, False otherwise
164 idx = 0
165 cont = True
166 ok = False
167 while cont:
168 if idx == len(range):
169 cont = False
170 continue
171 if usn < int(range[idx]):
172 if idx %2 == 1:
173 ok = True
174 cont = False
175 if usn == int(range[idx]):
176 cont = False
177 ok = True
178 idx = idx + 1
179 return ok
182 def get_paths(param, targetdir=None, smbconf=None):
183 """Get paths to important provision objects (smb.conf, ldb files, ...)
185 :param param: Param object
186 :param targetdir: Directory where the provision is (or will be) stored
187 :param smbconf: Path to the smb.conf file
188 :return: A list with the path of important provision objects"""
189 if targetdir is not None:
190 if not os.path.exists(targetdir):
191 os.mkdir(targetdir)
192 etcdir = os.path.join(targetdir, "etc")
193 if not os.path.exists(etcdir):
194 os.makedirs(etcdir)
195 smbconf = os.path.join(etcdir, "smb.conf")
196 if smbconf is None:
197 smbconf = param.default_path()
199 if not os.path.exists(smbconf):
200 raise ProvisioningError("Unable to find smb.conf")
202 lp = param.LoadParm()
203 lp.load(smbconf)
204 paths = provision_paths_from_lp(lp, lp.get("realm"))
205 return paths
207 def update_policyids(names, samdb):
208 """Update policy ids that could have changed after sam update
210 :param names: List of key provision parameters
211 :param samdb: An Ldb object conntected with the sam DB
213 # policy guid
214 res = samdb.search(expression="(displayName=Default Domain Policy)",
215 base="CN=Policies,CN=System," + str(names.rootdn),
216 scope=SCOPE_ONELEVEL, attrs=["cn","displayName"])
217 names.policyid = str(res[0]["cn"]).replace("{","").replace("}","")
218 # dc policy guid
219 res2 = samdb.search(expression="(displayName=Default Domain Controllers"
220 " Policy)",
221 base="CN=Policies,CN=System," + str(names.rootdn),
222 scope=SCOPE_ONELEVEL, attrs=["cn","displayName"])
223 if len(res2) == 1:
224 names.policyid_dc = str(res2[0]["cn"]).replace("{","").replace("}","")
225 else:
226 names.policyid_dc = None
229 def newprovision(names, session, smbconf, provdir, logger):
230 """Create a new provision.
232 This provision will be the reference for knowing what has changed in the
233 since the latest upgrade in the current provision
235 :param names: List of provision parameters
236 :param creds: Credentials for the authentification
237 :param session: Session object
238 :param smbconf: Path to the smb.conf file
239 :param provdir: Directory where the provision will be stored
240 :param logger: A Logger
242 if os.path.isdir(provdir):
243 shutil.rmtree(provdir)
244 os.mkdir(provdir)
245 logger.info("Provision stored in %s", provdir)
246 return provision(logger, session, smbconf=smbconf,
247 targetdir=provdir, samdb_fill=FILL_FULL, realm=names.realm,
248 domain=names.domain, domainguid=names.domainguid,
249 domainsid=names.domainsid, ntdsguid=names.ntdsguid,
250 policyguid=names.policyid, policyguid_dc=names.policyid_dc,
251 hostname=names.netbiosname.lower(), hostip=None, hostip6=None,
252 invocationid=names.invocation, adminpass=names.adminpass,
253 krbtgtpass=None, machinepass=None, dnspass=None, root=None,
254 nobody=None, users=None,
255 serverrole="domain controller",
256 backend_type=None, ldapadminpass=None, ol_mmr_urls=None,
257 slapd_path=None,
258 dom_for_fun_level=names.domainlevel, dns_backend=names.dns_backend,
259 useeadb=True, use_ntvfs=True)
262 def dn_sort(x, y):
263 """Sorts two DNs in the lexicographical order it and put higher level DN
264 before.
266 So given the dns cn=bar,cn=foo and cn=foo the later will be return as
267 smaller
269 :param x: First object to compare
270 :param y: Second object to compare
272 p = re.compile(r'(?<!\\), ?')
273 tab1 = p.split(str(x))
274 tab2 = p.split(str(y))
275 minimum = min(len(tab1), len(tab2))
276 len1 = len(tab1)-1
277 len2 = len(tab2)-1
278 # Note: python range go up to upper limit but do not include it
279 for i in range(0, minimum):
280 ret = cmp(tab1[len1-i], tab2[len2-i])
281 if ret != 0:
282 return ret
283 else:
284 if i == minimum-1:
285 assert len1!=len2,"PB PB PB" + " ".join(tab1)+" / " + " ".join(tab2)
286 if len1 > len2:
287 return 1
288 else:
289 return -1
290 return ret
293 def identic_rename(ldbobj, dn):
294 """Perform a back and forth rename to trigger renaming on attribute that
295 can't be directly modified.
297 :param lbdobj: An Ldb Object
298 :param dn: DN of the object to manipulate
300 (before, after) = str(dn).split('=', 1)
301 # we need to use relax to avoid the subtree_rename constraints
302 ldbobj.rename(dn, ldb.Dn(ldbobj, "%s=foo%s" % (before, after)), ["relax:0"])
303 ldbobj.rename(ldb.Dn(ldbobj, "%s=foo%s" % (before, after)), dn, ["relax:0"])
306 def update_secrets(newsecrets_ldb, secrets_ldb, messagefunc):
307 """Update secrets.ldb
309 :param newsecrets_ldb: An LDB object that is connected to the secrets.ldb
310 of the reference provision
311 :param secrets_ldb: An LDB object that is connected to the secrets.ldb
312 of the updated provision
315 messagefunc(SIMPLE, "Update of secrets.ldb")
316 reference = newsecrets_ldb.search(base="@MODULES", scope=SCOPE_BASE)
317 current = secrets_ldb.search(base="@MODULES", scope=SCOPE_BASE)
318 assert reference, "Reference modules list can not be empty"
319 if len(current) == 0:
320 # No modules present
321 delta = secrets_ldb.msg_diff(ldb.Message(), reference[0])
322 delta.dn = reference[0].dn
323 secrets_ldb.add(reference[0])
324 else:
325 delta = secrets_ldb.msg_diff(current[0], reference[0])
326 delta.dn = current[0].dn
327 secrets_ldb.modify(delta)
329 reference = newsecrets_ldb.search(expression="objectClass=top", base="",
330 scope=SCOPE_SUBTREE, attrs=["dn"])
331 current = secrets_ldb.search(expression="objectClass=top", base="",
332 scope=SCOPE_SUBTREE, attrs=["dn"])
333 hash_new = {}
334 hash = {}
335 listMissing = []
336 listPresent = []
338 empty = ldb.Message()
339 for i in range(0, len(reference)):
340 hash_new[str(reference[i]["dn"]).lower()] = reference[i]["dn"]
342 # Create a hash for speeding the search of existing object in the
343 # current provision
344 for i in range(0, len(current)):
345 hash[str(current[i]["dn"]).lower()] = current[i]["dn"]
347 for k in hash_new.keys():
348 if not hash.has_key(k):
349 listMissing.append(hash_new[k])
350 else:
351 listPresent.append(hash_new[k])
353 for entry in listMissing:
354 reference = newsecrets_ldb.search(expression="distinguishedName=%s" % entry,
355 base="", scope=SCOPE_SUBTREE)
356 current = secrets_ldb.search(expression="distinguishedName=%s" % entry,
357 base="", scope=SCOPE_SUBTREE)
358 delta = secrets_ldb.msg_diff(empty, reference[0])
359 for att in hashAttrNotCopied:
360 delta.remove(att)
361 messagefunc(CHANGE, "Entry %s is missing from secrets.ldb" %
362 reference[0].dn)
363 for att in delta:
364 messagefunc(CHANGE, " Adding attribute %s" % att)
365 delta.dn = reference[0].dn
366 secrets_ldb.add(delta)
368 for entry in listPresent:
369 reference = newsecrets_ldb.search(expression="distinguishedName=%s" % entry,
370 base="", scope=SCOPE_SUBTREE)
371 current = secrets_ldb.search(expression="distinguishedName=%s" % entry, base="",
372 scope=SCOPE_SUBTREE)
373 delta = secrets_ldb.msg_diff(current[0], reference[0])
374 for att in hashAttrNotCopied:
375 delta.remove(att)
376 for att in delta:
377 if att == "name":
378 messagefunc(CHANGE, "Found attribute name on %s,"
379 " must rename the DN" % (current[0].dn))
380 identic_rename(secrets_ldb, reference[0].dn)
381 else:
382 delta.remove(att)
384 for entry in listPresent:
385 reference = newsecrets_ldb.search(expression="distinguishedName=%s" % entry, base="",
386 scope=SCOPE_SUBTREE)
387 current = secrets_ldb.search(expression="distinguishedName=%s" % entry, base="",
388 scope=SCOPE_SUBTREE)
389 delta = secrets_ldb.msg_diff(current[0], reference[0])
390 for att in hashAttrNotCopied:
391 delta.remove(att)
392 for att in delta:
393 if att == "msDS-KeyVersionNumber":
394 delta.remove(att)
395 if att != "dn":
396 messagefunc(CHANGE,
397 "Adding/Changing attribute %s to %s" %
398 (att, current[0].dn))
400 delta.dn = current[0].dn
401 secrets_ldb.modify(delta)
403 res2 = secrets_ldb.search(expression="(samaccountname=dns)",
404 scope=SCOPE_SUBTREE, attrs=["dn"])
406 if len(res2) == 1:
407 messagefunc(SIMPLE, "Remove old dns account")
408 secrets_ldb.delete(res2[0]["dn"])
411 def getOEMInfo(samdb, rootdn):
412 """Return OEM Information on the top level Samba4 use to store version
413 info in this field
415 :param samdb: An LDB object connect to sam.ldb
416 :param rootdn: Root DN of the domain
417 :return: The content of the field oEMInformation (if any)
419 res = samdb.search(expression="(objectClass=*)", base=str(rootdn),
420 scope=SCOPE_BASE, attrs=["dn", "oEMInformation"])
421 if len(res) > 0 and res[0].get("oEMInformation"):
422 info = res[0]["oEMInformation"]
423 return info
424 else:
425 return ""
428 def updateOEMInfo(samdb, rootdn):
429 """Update the OEMinfo field to add information about upgrade
431 :param samdb: an LDB object connected to the sam DB
432 :param rootdn: The string representation of the root DN of
433 the provision (ie. DC=...,DC=...)
435 res = samdb.search(expression="(objectClass=*)", base=rootdn,
436 scope=SCOPE_BASE, attrs=["dn", "oEMInformation"])
437 if len(res) > 0:
438 if res[0].get("oEMInformation"):
439 info = str(res[0]["oEMInformation"])
440 else:
441 info = ""
442 info = "%s, upgrade to %s" % (info, version)
443 delta = ldb.Message()
444 delta.dn = ldb.Dn(samdb, str(res[0]["dn"]))
445 delta["oEMInformation"] = ldb.MessageElement(info, ldb.FLAG_MOD_REPLACE,
446 "oEMInformation" )
447 samdb.modify(delta)
449 def update_gpo(paths, samdb, names, lp, message):
450 """Create missing GPO file object if needed
452 dir = getpolicypath(paths.sysvol, names.dnsdomain, names.policyid)
453 if not os.path.isdir(dir):
454 create_gpo_struct(dir)
456 if names.policyid_dc is None:
457 raise ProvisioningError("Policy ID for Domain controller is missing")
458 dir = getpolicypath(paths.sysvol, names.dnsdomain, names.policyid_dc)
459 if not os.path.isdir(dir):
460 create_gpo_struct(dir)
462 def increment_calculated_keyversion_number(samdb, rootdn, hashDns):
463 """For a given hash associating dn and a number, this function will
464 update the replPropertyMetaData of each dn in the hash, so that the
465 calculated value of the msDs-KeyVersionNumber is equal or superior to the
466 one associated to the given dn.
468 :param samdb: An SamDB object pointing to the sam
469 :param rootdn: The base DN where we want to start
470 :param hashDns: A hash with dn as key and number representing the
471 minimum value of msDs-KeyVersionNumber that we want to
472 have
474 entry = samdb.search(expression='(objectClass=user)',
475 base=ldb.Dn(samdb,str(rootdn)),
476 scope=SCOPE_SUBTREE, attrs=["msDs-KeyVersionNumber"],
477 controls=["search_options:1:2"])
478 done = 0
479 hashDone = {}
480 if len(entry) == 0:
481 raise ProvisioningError("Unable to find msDs-KeyVersionNumber")
482 else:
483 for e in entry:
484 if hashDns.has_key(str(e.dn).lower()):
485 val = e.get("msDs-KeyVersionNumber")
486 if not val:
487 val = "0"
488 version = int(str(hashDns[str(e.dn).lower()]))
489 if int(str(val)) < version:
490 done = done + 1
491 samdb.set_attribute_replmetadata_version(str(e.dn),
492 "unicodePwd",
493 version, True)
494 def delta_update_basesamdb(refsampath, sampath, creds, session, lp, message):
495 """Update the provision container db: sam.ldb
496 This function is aimed for alpha9 and newer;
498 :param refsampath: Path to the samdb in the reference provision
499 :param sampath: Path to the samdb in the upgraded provision
500 :param creds: Credential used for openning LDB files
501 :param session: Session to use for openning LDB files
502 :param lp: A loadparam object
503 :return: A msg_diff object with the difference between the @ATTRIBUTES
504 of the current provision and the reference provision
507 message(SIMPLE,
508 "Update base samdb by searching difference with reference one")
509 refsam = Ldb(refsampath, session_info=session, credentials=creds,
510 lp=lp, options=["modules:"])
511 sam = Ldb(sampath, session_info=session, credentials=creds, lp=lp,
512 options=["modules:"])
514 empty = ldb.Message()
515 deltaattr = None
516 reference = refsam.search(expression="")
518 for refentry in reference:
519 entry = sam.search(expression="distinguishedName=%s" % refentry["dn"],
520 scope=SCOPE_SUBTREE)
521 if not len(entry):
522 delta = sam.msg_diff(empty, refentry)
523 message(CHANGE, "Adding %s to sam db" % str(refentry.dn))
524 if str(refentry.dn) == "@PROVISION" and\
525 delta.get(samba.provision.LAST_PROVISION_USN_ATTRIBUTE):
526 delta.remove(samba.provision.LAST_PROVISION_USN_ATTRIBUTE)
527 delta.dn = refentry.dn
528 sam.add(delta)
529 else:
530 delta = sam.msg_diff(entry[0], refentry)
531 if str(refentry.dn) == "@ATTRIBUTES":
532 deltaattr = sam.msg_diff(refentry, entry[0])
533 if str(refentry.dn) == "@PROVISION" and\
534 delta.get(samba.provision.LAST_PROVISION_USN_ATTRIBUTE):
535 delta.remove(samba.provision.LAST_PROVISION_USN_ATTRIBUTE)
536 if len(delta.items()) > 1:
537 delta.dn = refentry.dn
538 sam.modify(delta)
540 return deltaattr
543 def construct_existor_expr(attrs):
544 """Construct a exists or LDAP search expression.
546 :param attrs: List of attribute on which we want to create the search
547 expression.
548 :return: A string representing the expression, if attrs is empty an
549 empty string is returned
551 expr = ""
552 if len(attrs) > 0:
553 expr = "(|"
554 for att in attrs:
555 expr = "%s(%s=*)"%(expr,att)
556 expr = "%s)"%expr
557 return expr
559 def update_machine_account_password(samdb, secrets_ldb, names):
560 """Update (change) the password of the current DC both in the SAM db and in
561 secret one
563 :param samdb: An LDB object related to the sam.ldb file of a given provision
564 :param secrets_ldb: An LDB object related to the secrets.ldb file of a given
565 provision
566 :param names: List of key provision parameters"""
568 expression = "samAccountName=%s$" % names.netbiosname
569 secrets_msg = secrets_ldb.search(expression=expression,
570 attrs=["secureChannelType"])
571 if int(secrets_msg[0]["secureChannelType"][0]) == SEC_CHAN_BDC:
572 res = samdb.search(expression=expression, attrs=[])
573 assert(len(res) == 1)
575 msg = ldb.Message(res[0].dn)
576 machinepass = samba.generate_random_password(128, 255)
577 mputf16 = machinepass.encode('utf-16-le')
578 msg["clearTextPassword"] = ldb.MessageElement(mputf16,
579 ldb.FLAG_MOD_REPLACE,
580 "clearTextPassword")
581 samdb.modify(msg)
583 res = samdb.search(expression=("samAccountName=%s$" % names.netbiosname),
584 attrs=["msDs-keyVersionNumber"])
585 assert(len(res) == 1)
586 kvno = int(str(res[0]["msDs-keyVersionNumber"]))
587 secChanType = int(secrets_msg[0]["secureChannelType"][0])
589 secretsdb_self_join(secrets_ldb, domain=names.domain,
590 realm=names.realm,
591 domainsid=names.domainsid,
592 dnsdomain=names.dnsdomain,
593 netbiosname=names.netbiosname,
594 machinepass=machinepass,
595 key_version_number=kvno,
596 secure_channel_type=secChanType)
597 else:
598 raise ProvisioningError("Unable to find a Secure Channel"
599 "of type SEC_CHAN_BDC")
601 def update_dns_account_password(samdb, secrets_ldb, names):
602 """Update (change) the password of the dns both in the SAM db and in
603 secret one
605 :param samdb: An LDB object related to the sam.ldb file of a given provision
606 :param secrets_ldb: An LDB object related to the secrets.ldb file of a given
607 provision
608 :param names: List of key provision parameters"""
610 expression = "samAccountName=dns-%s" % names.netbiosname
611 secrets_msg = secrets_ldb.search(expression=expression)
612 if len(secrets_msg) == 1:
613 res = samdb.search(expression=expression, attrs=[])
614 assert(len(res) == 1)
616 msg = ldb.Message(res[0].dn)
617 machinepass = samba.generate_random_password(128, 255)
618 mputf16 = machinepass.encode('utf-16-le')
619 msg["clearTextPassword"] = ldb.MessageElement(mputf16,
620 ldb.FLAG_MOD_REPLACE,
621 "clearTextPassword")
623 samdb.modify(msg)
625 res = samdb.search(expression=expression,
626 attrs=["msDs-keyVersionNumber"])
627 assert(len(res) == 1)
628 kvno = str(res[0]["msDs-keyVersionNumber"])
630 msg = ldb.Message(secrets_msg[0].dn)
631 msg["secret"] = ldb.MessageElement(machinepass,
632 ldb.FLAG_MOD_REPLACE,
633 "secret")
634 msg["msDS-KeyVersionNumber"] = ldb.MessageElement(kvno,
635 ldb.FLAG_MOD_REPLACE,
636 "msDS-KeyVersionNumber")
638 secrets_ldb.modify(msg)
640 def update_krbtgt_account_password(samdb, names):
641 """Update (change) the password of the krbtgt account
643 :param samdb: An LDB object related to the sam.ldb file of a given provision
644 :param names: List of key provision parameters"""
646 expression = "samAccountName=krbtgt"
647 res = samdb.search(expression=expression, attrs=[])
648 assert(len(res) == 1)
650 msg = ldb.Message(res[0].dn)
651 machinepass = samba.generate_random_password(128, 255)
652 mputf16 = machinepass.encode('utf-16-le')
653 msg["clearTextPassword"] = ldb.MessageElement(mputf16,
654 ldb.FLAG_MOD_REPLACE,
655 "clearTextPassword")
657 samdb.modify(msg)
659 def search_constructed_attrs_stored(samdb, rootdn, attrs):
660 """Search a given sam DB for calculated attributes that are
661 still stored in the db.
663 :param samdb: An LDB object pointing to the sam
664 :param rootdn: The base DN where the search should start
665 :param attrs: A list of attributes to be searched
666 :return: A hash with attributes as key and an array of
667 array. Each array contains the dn and the associated
668 values for this attribute as they are stored in the
669 sam."""
671 hashAtt = {}
672 expr = construct_existor_expr(attrs)
673 if expr == "":
674 return hashAtt
675 entry = samdb.search(expression=expr, base=ldb.Dn(samdb, str(rootdn)),
676 scope=SCOPE_SUBTREE, attrs=attrs,
677 controls=["search_options:1:2","bypassoperational:0"])
678 if len(entry) == 0:
679 # Nothing anymore
680 return hashAtt
682 for ent in entry:
683 for att in attrs:
684 if ent.get(att):
685 if hashAtt.has_key(att):
686 hashAtt[att][str(ent.dn).lower()] = str(ent[att])
687 else:
688 hashAtt[att] = {}
689 hashAtt[att][str(ent.dn).lower()] = str(ent[att])
691 return hashAtt
693 def findprovisionrange(samdb, basedn):
694 """ Find ranges of usn grouped by invocation id and then by timestamp
695 rouned at 1 minute
697 :param samdb: An LDB object pointing to the samdb
698 :param basedn: The DN of the forest
700 :return: A two level dictionary with invoication id as the
701 first level, timestamp as the second one and then
702 max, min, and number as subkeys, representing respectivily
703 the maximum usn for the range, the minimum usn and the number
704 of object with usn in this range.
706 nb_obj = 0
707 hash_id = {}
709 res = samdb.search(base=basedn, expression="objectClass=*",
710 scope=ldb.SCOPE_SUBTREE,
711 attrs=["replPropertyMetaData"],
712 controls=["search_options:1:2"])
714 for e in res:
715 nb_obj = nb_obj + 1
716 obj = ndr_unpack(drsblobs.replPropertyMetaDataBlob,
717 str(e["replPropertyMetaData"])).ctr
719 for o in obj.array:
720 # like a timestamp but with the resolution of 1 minute
721 minutestamp =_glue.nttime2unix(o.originating_change_time)/60
722 hash_ts = hash_id.get(str(o.originating_invocation_id))
724 if hash_ts is None:
725 ob = {}
726 ob["min"] = o.originating_usn
727 ob["max"] = o.originating_usn
728 ob["num"] = 1
729 ob["list"] = [str(e.dn)]
730 hash_ts = {}
731 else:
732 ob = hash_ts.get(minutestamp)
733 if ob is None:
734 ob = {}
735 ob["min"] = o.originating_usn
736 ob["max"] = o.originating_usn
737 ob["num"] = 1
738 ob["list"] = [str(e.dn)]
739 else:
740 if ob["min"] > o.originating_usn:
741 ob["min"] = o.originating_usn
742 if ob["max"] < o.originating_usn:
743 ob["max"] = o.originating_usn
744 if not (str(e.dn) in ob["list"]):
745 ob["num"] = ob["num"] + 1
746 ob["list"].append(str(e.dn))
747 hash_ts[minutestamp] = ob
748 hash_id[str(o.originating_invocation_id)] = hash_ts
750 return (hash_id, nb_obj)
752 def print_provision_ranges(dic, limit_print, dest, samdb_path, invocationid):
753 """ print the differents ranges passed as parameter
755 :param dic: A dictionnary as returned by findprovisionrange
756 :param limit_print: minimum number of object in a range in order to print it
757 :param dest: Destination directory
758 :param samdb_path: Path to the sam.ldb file
759 :param invoicationid: Invocation ID for the current provision
761 ldif = ""
763 for id in dic:
764 hash_ts = dic[id]
765 sorted_keys = []
766 sorted_keys.extend(hash_ts.keys())
767 sorted_keys.sort()
769 kept_record = []
770 for k in sorted_keys:
771 obj = hash_ts[k]
772 if obj["num"] > limit_print:
773 dt = _glue.nttime2string(_glue.unix2nttime(k*60))
774 print "%s # of modification: %d \tmin: %d max: %d" % (dt , obj["num"],
775 obj["min"],
776 obj["max"])
777 if hash_ts[k]["num"] > 600:
778 kept_record.append(k)
780 # Let's try to concatenate consecutive block if they are in the almost same minutestamp
781 for i in range(0, len(kept_record)):
782 if i != 0:
783 key1 = kept_record[i]
784 key2 = kept_record[i-1]
785 if key1 - key2 == 1:
786 # previous record is just 1 minute away from current
787 if int(hash_ts[key1]["min"]) == int(hash_ts[key2]["max"]) + 1:
788 # Copy the highest USN in the previous record
789 # and mark the current as skipped
790 hash_ts[key2]["max"] = hash_ts[key1]["max"]
791 hash_ts[key1]["skipped"] = True
793 for k in kept_record:
794 obj = hash_ts[k]
795 if obj.get("skipped") is None:
796 ldif = "%slastProvisionUSN: %d-%d;%s\n" % (ldif, obj["min"],
797 obj["max"], id)
799 if ldif != "":
800 file = tempfile.mktemp(dir=dest, prefix="usnprov", suffix=".ldif")
801 print
802 print "To track the USNs modified/created by provision and upgrade proivsion,"
803 print " the following ranges are proposed to be added to your provision sam.ldb: \n%s" % ldif
804 print "We recommend to review them, and if it's correct to integrate the following ldif: %s in your sam.ldb" % file
805 print "You can load this file like this: ldbadd -H %s %s\n"%(str(samdb_path),file)
806 ldif = "dn: @PROVISION\nprovisionnerID: %s\n%s" % (invocationid, ldif)
807 open(file,'w').write(ldif)
809 def int64range2str(value):
810 """Display the int64 range stored in value as xxx-yyy
812 :param value: The int64 range
813 :return: A string of the representation of the range
816 lvalue = long(value)
817 str = "%d-%d" % (lvalue&0xFFFFFFFF, lvalue>>32)
818 return str