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."""
29 from samba
.common
import cmp
30 from samba
import Ldb
, version
, ntacls
31 from ldb
import SCOPE_SUBTREE
, SCOPE_ONELEVEL
, SCOPE_BASE
33 from samba
.provision
import (provision_paths_from_lp
,
34 getpolicypath
, create_gpo_struct
,
35 provision
, ProvisioningError
,
37 from samba
.provision
.common
import FILL_FULL
38 from samba
.dcerpc
import drsblobs
39 from samba
.dcerpc
.misc
import SEC_CHAN_BDC
40 from samba
.ndr
import ndr_unpack
41 from samba
.samdb
import SamDB
42 from samba
import _glue
45 # All the ldb related to registry are commented because the path for them is
46 # relative in the provisionPath object
47 # And so opening them create a file in the current directory which is not what
49 # I still keep them commented because I plan soon to make more cleaner
58 hashAttrNotCopied
= set(["dn", "whenCreated", "whenChanged", "objectGUID",
59 "uSNCreated", "replPropertyMetaData", "uSNChanged", "parentGUID",
60 "objectCategory", "distinguishedName", "nTMixedDomain",
61 "showInAdvancedViewOnly", "instanceType", "msDS-Behavior-Version",
62 "nextRid", "cn", "versionNumber", "lmPwdHistory", "pwdLastSet",
63 "ntPwdHistory", "unicodePwd", "dBCSPwd", "supplementalCredentials",
64 "gPCUserExtensionNames", "gPCMachineExtensionNames", "maxPwdAge", "secret",
65 "possibleInferiors", "privilege", "sAMAccountType"])
68 class ProvisionLDB(object):
81 return (self
.sam
, self
.secrets
, self
.idmap
, self
.privilege
)
83 def startTransactions(self
):
85 db
.transaction_start()
87 # self.hkcr.transaction_start()
88 # self.hkcu.transaction_start()
89 # self.hku.transaction_start()
90 # self.hklm.transaction_start()
92 def groupedRollback(self
):
96 db
.transaction_cancel()
101 # self.hkcr.transaction_cancel()
102 # self.hkcu.transaction_cancel()
103 # self.hku.transaction_cancel()
104 # self.hklm.transaction_cancel()
106 def groupedCommit(self
):
108 for db
in self
.dbs():
109 db
.transaction_prepare_commit()
111 return self
.groupedRollback()
113 # self.hkcr.transaction_prepare_commit()
114 # self.hkcu.transaction_prepare_commit()
115 # self.hku.transaction_prepare_commit()
116 # self.hklm.transaction_prepare_commit()
118 for db
in self
.dbs():
119 db
.transaction_commit()
121 return self
.groupedRollback()
124 # self.hkcr.transaction_commit()
125 # self.hkcu.transaction_commit()
126 # self.hku.transaction_commit()
127 # self.hklm.transaction_commit()
131 def get_ldbs(paths
, creds
, session
, lp
):
132 """Return LDB object mapped on most important databases
134 :param paths: An object holding the different importants paths for provision object
135 :param creds: Credential used for openning LDB files
136 :param session: Session to use for openning LDB files
137 :param lp: A loadparam object
138 :return: A ProvisionLDB object that contains LDB object for the different LDB files of the provision"""
140 ldbs
= ProvisionLDB()
142 ldbs
.sam
= SamDB(paths
.samdb
,
143 session_info
=session
,
146 options
=["modules:samba_dsdb"],
148 ldbs
.secrets
= Ldb(paths
.secrets
, session_info
=session
, credentials
=creds
, lp
=lp
)
149 ldbs
.idmap
= Ldb(paths
.idmapdb
, session_info
=session
, credentials
=creds
, lp
=lp
)
150 ldbs
.privilege
= Ldb(paths
.privilege
, session_info
=session
, credentials
=creds
, lp
=lp
)
151 # ldbs.hkcr = Ldb(paths.hkcr, session_info=session, credentials=creds, lp=lp)
152 # ldbs.hkcu = Ldb(paths.hkcu, session_info=session, credentials=creds, lp=lp)
153 # ldbs.hku = Ldb(paths.hku, session_info=session, credentials=creds, lp=lp)
154 # ldbs.hklm = Ldb(paths.hklm, session_info=session, credentials=creds, lp=lp)
159 def usn_in_range(usn
, range):
160 """Check if the usn is in one of the range provided.
161 To do so, the value is checked to be between the lower bound and
162 higher bound of a range
164 :param usn: A integer value corresponding to the usn that we want to update
165 :param range: A list of integer representing ranges, lower bounds are in
166 the even indices, higher in odd indices
167 :return: True if the usn is in one of the range, False otherwise
174 if idx
== len(range):
177 if usn
< int(range[idx
]):
181 if usn
== int(range[idx
]):
188 def get_paths(param
, targetdir
=None, smbconf
=None):
189 """Get paths to important provision objects (smb.conf, ldb files, ...)
191 :param param: Param object
192 :param targetdir: Directory where the provision is (or will be) stored
193 :param smbconf: Path to the smb.conf file
194 :return: A list with the path of important provision objects"""
195 if targetdir
is not None:
196 if not os
.path
.exists(targetdir
):
198 etcdir
= os
.path
.join(targetdir
, "etc")
199 if not os
.path
.exists(etcdir
):
201 smbconf
= os
.path
.join(etcdir
, "smb.conf")
203 smbconf
= param
.default_path()
205 if not os
.path
.exists(smbconf
):
206 raise ProvisioningError("Unable to find smb.conf at %s" % smbconf
)
208 lp
= param
.LoadParm()
210 paths
= provision_paths_from_lp(lp
, lp
.get("realm"))
214 def update_policyids(names
, samdb
):
215 """Update policy ids that could have changed after sam update
217 :param names: List of key provision parameters
218 :param samdb: An Ldb object conntected with the sam DB
221 res
= samdb
.search(expression
="(displayName=Default Domain Policy)",
222 base
="CN=Policies,CN=System," + str(names
.rootdn
),
223 scope
=SCOPE_ONELEVEL
, attrs
=["cn", "displayName"])
224 names
.policyid
= str(res
[0]["cn"]).replace("{", "").replace("}", "")
226 res2
= samdb
.search(expression
="(displayName=Default Domain Controllers"
228 base
="CN=Policies,CN=System," + str(names
.rootdn
),
229 scope
=SCOPE_ONELEVEL
, attrs
=["cn", "displayName"])
231 names
.policyid_dc
= str(res2
[0]["cn"]).replace("{", "").replace("}", "")
233 names
.policyid_dc
= None
236 def newprovision(names
, session
, smbconf
, provdir
, logger
, base_schema
=None):
237 """Create a new provision.
239 This provision will be the reference for knowing what has changed in the
240 since the latest upgrade in the current provision
242 :param names: List of provision parameters
243 :param creds: Credentials for the authentification
244 :param session: Session object
245 :param smbconf: Path to the smb.conf file
246 :param provdir: Directory where the provision will be stored
247 :param logger: A Logger
249 if os
.path
.isdir(provdir
):
250 shutil
.rmtree(provdir
)
252 logger
.info("Provision stored in %s", provdir
)
253 return provision(logger
, session
, smbconf
=smbconf
,
254 targetdir
=provdir
, samdb_fill
=FILL_FULL
, realm
=names
.realm
,
255 domain
=names
.domain
, domainguid
=names
.domainguid
,
256 domainsid
=names
.domainsid
, ntdsguid
=names
.ntdsguid
,
257 policyguid
=names
.policyid
, policyguid_dc
=names
.policyid_dc
,
258 hostname
=names
.netbiosname
.lower(), hostip
=None, hostip6
=None,
259 invocationid
=names
.invocation
, adminpass
=names
.adminpass
,
260 krbtgtpass
=None, machinepass
=None, dnspass
=None, root
=None,
261 nobody
=None, users
=None,
262 serverrole
="domain controller",
263 dom_for_fun_level
=names
.domainlevel
, dns_backend
=names
.dns_backend
,
264 useeadb
=True, use_ntvfs
=True, base_schema
=base_schema
)
268 """Sorts two DNs in the lexicographical order it and put higher level DN
271 So given the dns cn=bar,cn=foo and cn=foo the later will be return as
274 :param x: First object to compare
275 :param y: Second object to compare
277 p
= re
.compile(r
'(?<!\\), ?')
278 tab1
= p
.split(str(x
))
279 tab2
= p
.split(str(y
))
280 minimum
= min(len(tab1
), len(tab2
))
283 # Note: python range go up to upper limit but do not include it
284 for i
in range(0, minimum
):
285 ret
= cmp(tab1
[len1
- i
], tab2
[len2
- i
])
290 assert len1
!= len2
, "PB PB PB" + " ".join(tab1
) + " / " + " ".join(tab2
)
298 def identic_rename(ldbobj
, dn
):
299 """Perform a back and forth rename to trigger renaming on attribute that
300 can't be directly modified.
302 :param lbdobj: An Ldb Object
303 :param dn: DN of the object to manipulate
305 (before
, after
) = str(dn
).split('=', 1)
306 # we need to use relax to avoid the subtree_rename constraints
307 ldbobj
.rename(dn
, ldb
.Dn(ldbobj
, "%s=foo%s" % (before
, after
)), ["relax:0"])
308 ldbobj
.rename(ldb
.Dn(ldbobj
, "%s=foo%s" % (before
, after
)), dn
, ["relax:0"])
311 def update_secrets(newsecrets_ldb
, secrets_ldb
, messagefunc
):
312 """Update secrets.ldb
314 :param newsecrets_ldb: An LDB object that is connected to the secrets.ldb
315 of the reference provision
316 :param secrets_ldb: An LDB object that is connected to the secrets.ldb
317 of the updated provision
320 messagefunc(SIMPLE
, "Update of secrets.ldb")
321 reference
= newsecrets_ldb
.search(base
="@MODULES", scope
=SCOPE_BASE
)
322 current
= secrets_ldb
.search(base
="@MODULES", scope
=SCOPE_BASE
)
323 assert reference
, "Reference modules list can not be empty"
324 if len(current
) == 0:
326 delta
= secrets_ldb
.msg_diff(ldb
.Message(), reference
[0])
327 delta
.dn
= reference
[0].dn
328 secrets_ldb
.add(reference
[0])
330 delta
= secrets_ldb
.msg_diff(current
[0], reference
[0])
331 delta
.dn
= current
[0].dn
332 secrets_ldb
.modify(delta
)
334 reference
= newsecrets_ldb
.search(expression
="objectClass=top", base
="",
335 scope
=SCOPE_SUBTREE
, attrs
=["dn"])
336 current
= secrets_ldb
.search(expression
="objectClass=top", base
="",
337 scope
=SCOPE_SUBTREE
, attrs
=["dn"])
343 empty
= ldb
.Message()
344 for i
in range(0, len(reference
)):
345 hash_new
[str(reference
[i
]["dn"]).lower()] = reference
[i
]["dn"]
347 # Create a hash for speeding the search of existing object in the
349 for i
in range(0, len(current
)):
350 hash[str(current
[i
]["dn"]).lower()] = current
[i
]["dn"]
352 for k
in hash_new
.keys():
354 listMissing
.append(hash_new
[k
])
356 listPresent
.append(hash_new
[k
])
358 for entry
in listMissing
:
359 reference
= newsecrets_ldb
.search(expression
="distinguishedName=%s" % entry
,
360 base
="", scope
=SCOPE_SUBTREE
)
361 delta
= secrets_ldb
.msg_diff(empty
, reference
[0])
362 for att
in hashAttrNotCopied
:
364 messagefunc(CHANGE
, "Entry %s is missing from secrets.ldb" %
367 messagefunc(CHANGE
, " Adding attribute %s" % att
)
368 delta
.dn
= reference
[0].dn
369 secrets_ldb
.add(delta
)
371 for entry
in listPresent
:
372 reference
= newsecrets_ldb
.search(expression
="distinguishedName=%s" % entry
,
373 base
="", scope
=SCOPE_SUBTREE
)
374 current
= secrets_ldb
.search(expression
="distinguishedName=%s" % entry
, base
="",
376 delta
= secrets_ldb
.msg_diff(current
[0], reference
[0])
377 for att
in hashAttrNotCopied
:
381 messagefunc(CHANGE
, "Found attribute name on %s,"
382 " must rename the DN" % (current
[0].dn
))
383 identic_rename(secrets_ldb
, reference
[0].dn
)
387 for entry
in listPresent
:
388 reference
= newsecrets_ldb
.search(expression
="distinguishedName=%s" % entry
, base
="",
390 current
= secrets_ldb
.search(expression
="distinguishedName=%s" % entry
, base
="",
392 delta
= secrets_ldb
.msg_diff(current
[0], reference
[0])
393 for att
in hashAttrNotCopied
:
396 if att
== "msDS-KeyVersionNumber":
400 "Adding/Changing attribute %s to %s" %
401 (att
, current
[0].dn
))
403 delta
.dn
= current
[0].dn
404 secrets_ldb
.modify(delta
)
406 res2
= secrets_ldb
.search(expression
="(samaccountname=dns)",
407 scope
=SCOPE_SUBTREE
, attrs
=["dn"])
410 messagefunc(SIMPLE
, "Remove old dns account")
411 secrets_ldb
.delete(res2
[0]["dn"])
414 def getOEMInfo(samdb
, rootdn
):
415 """Return OEM Information on the top level Samba4 use to store version
418 :param samdb: An LDB object connect to sam.ldb
419 :param rootdn: Root DN of the domain
420 :return: The content of the field oEMInformation (if any)
422 res
= samdb
.search(expression
="(objectClass=*)", base
=str(rootdn
),
423 scope
=SCOPE_BASE
, attrs
=["dn", "oEMInformation"])
424 if len(res
) > 0 and res
[0].get("oEMInformation"):
425 info
= res
[0]["oEMInformation"]
431 def updateOEMInfo(samdb
, rootdn
):
432 """Update the OEMinfo field to add information about upgrade
434 :param samdb: an LDB object connected to the sam DB
435 :param rootdn: The string representation of the root DN of
436 the provision (ie. DC=...,DC=...)
438 res
= samdb
.search(expression
="(objectClass=*)", base
=rootdn
,
439 scope
=SCOPE_BASE
, attrs
=["dn", "oEMInformation"])
441 if res
[0].get("oEMInformation"):
442 info
= str(res
[0]["oEMInformation"])
445 info
= "%s, upgrade to %s" % (info
, version
)
446 delta
= ldb
.Message()
447 delta
.dn
= ldb
.Dn(samdb
, str(res
[0]["dn"]))
448 delta
["oEMInformation"] = ldb
.MessageElement(info
, ldb
.FLAG_MOD_REPLACE
,
453 def update_gpo(paths
, samdb
, names
, lp
, message
):
454 """Create missing GPO file object if needed
456 dir = getpolicypath(paths
.sysvol
, names
.dnsdomain
, names
.policyid
)
457 if not os
.path
.isdir(dir):
458 create_gpo_struct(dir)
460 if names
.policyid_dc
is None:
461 raise ProvisioningError("Policy ID for Domain controller is missing")
462 dir = getpolicypath(paths
.sysvol
, names
.dnsdomain
, names
.policyid_dc
)
463 if not os
.path
.isdir(dir):
464 create_gpo_struct(dir)
467 def increment_calculated_keyversion_number(samdb
, rootdn
, hashDns
):
468 """For a given hash associating dn and a number, this function will
469 update the replPropertyMetaData of each dn in the hash, so that the
470 calculated value of the msDs-KeyVersionNumber is equal or superior to the
471 one associated to the given dn.
473 :param samdb: An SamDB object pointing to the sam
474 :param rootdn: The base DN where we want to start
475 :param hashDns: A hash with dn as key and number representing the
476 minimum value of msDs-KeyVersionNumber that we want to
479 entry
= samdb
.search(expression
='(objectClass=user)',
480 base
=ldb
.Dn(samdb
, str(rootdn
)),
481 scope
=SCOPE_SUBTREE
, attrs
=["msDs-KeyVersionNumber"],
482 controls
=["search_options:1:2"])
485 raise ProvisioningError("Unable to find msDs-KeyVersionNumber")
488 if str(e
.dn
).lower() in hashDns
:
489 val
= e
.get("msDs-KeyVersionNumber")
492 version
= int(str(hashDns
[str(e
.dn
).lower()]))
493 if int(str(val
)) < version
:
495 samdb
.set_attribute_replmetadata_version(str(e
.dn
),
500 def delta_update_basesamdb(refsampath
, sampath
, creds
, session
, lp
, message
):
501 """Update the provision container db: sam.ldb
502 This function is aimed for alpha9 and newer;
504 :param refsampath: Path to the samdb in the reference provision
505 :param sampath: Path to the samdb in the upgraded provision
506 :param creds: Credential used for openning LDB files
507 :param session: Session to use for openning LDB files
508 :param lp: A loadparam object
509 :return: A msg_diff object with the difference between the @ATTRIBUTES
510 of the current provision and the reference provision
514 "Update base samdb by searching difference with reference one")
515 refsam
= Ldb(refsampath
, session_info
=session
, credentials
=creds
,
516 lp
=lp
, options
=["modules:"])
517 sam
= Ldb(sampath
, session_info
=session
, credentials
=creds
, lp
=lp
,
518 options
=["modules:"])
520 empty
= ldb
.Message()
522 reference
= refsam
.search(expression
="")
524 for refentry
in reference
:
525 entry
= sam
.search(expression
="distinguishedName=%s" % refentry
["dn"],
528 delta
= sam
.msg_diff(empty
, refentry
)
529 message(CHANGE
, "Adding %s to sam db" % str(refentry
.dn
))
530 if str(refentry
.dn
) == "@PROVISION" and\
531 delta
.get(samba
.provision
.LAST_PROVISION_USN_ATTRIBUTE
):
532 delta
.remove(samba
.provision
.LAST_PROVISION_USN_ATTRIBUTE
)
533 delta
.dn
= refentry
.dn
536 delta
= sam
.msg_diff(entry
[0], refentry
)
537 if str(refentry
.dn
) == "@ATTRIBUTES":
538 deltaattr
= sam
.msg_diff(refentry
, entry
[0])
539 if str(refentry
.dn
) == "@PROVISION" and\
540 delta
.get(samba
.provision
.LAST_PROVISION_USN_ATTRIBUTE
):
541 delta
.remove(samba
.provision
.LAST_PROVISION_USN_ATTRIBUTE
)
542 if len(delta
.items()) > 1:
543 delta
.dn
= refentry
.dn
549 def construct_existor_expr(attrs
):
550 """Construct a exists or LDAP search expression.
552 :param attrs: List of attribute on which we want to create the search
554 :return: A string representing the expression, if attrs is empty an
555 empty string is returned
561 expr
= "%s(%s=*)" %(expr
, att
)
566 def update_machine_account_password(samdb
, secrets_ldb
, names
):
567 """Update (change) the password of the current DC both in the SAM db and in
570 :param samdb: An LDB object related to the sam.ldb file of a given provision
571 :param secrets_ldb: An LDB object related to the secrets.ldb file of a given
573 :param names: List of key provision parameters"""
575 expression
= "samAccountName=%s$" % names
.netbiosname
576 secrets_msg
= secrets_ldb
.search(expression
=expression
,
577 attrs
=["secureChannelType"])
578 if int(secrets_msg
[0]["secureChannelType"][0]) == SEC_CHAN_BDC
:
579 res
= samdb
.search(expression
=expression
, attrs
=[])
580 assert(len(res
) == 1)
582 msg
= ldb
.Message(res
[0].dn
)
583 machinepass
= samba
.generate_random_machine_password(120, 120)
584 mputf16
= machinepass
.encode('utf-16-le')
585 msg
["clearTextPassword"] = ldb
.MessageElement(mputf16
,
586 ldb
.FLAG_MOD_REPLACE
,
590 res
= samdb
.search(expression
=("samAccountName=%s$" % names
.netbiosname
),
591 attrs
=["msDs-keyVersionNumber"])
592 assert(len(res
) == 1)
593 kvno
= int(str(res
[0]["msDs-keyVersionNumber"]))
594 secChanType
= int(secrets_msg
[0]["secureChannelType"][0])
596 secretsdb_self_join(secrets_ldb
, domain
=names
.domain
,
598 domainsid
=names
.domainsid
,
599 dnsdomain
=names
.dnsdomain
,
600 netbiosname
=names
.netbiosname
,
601 machinepass
=machinepass
,
602 key_version_number
=kvno
,
603 secure_channel_type
=secChanType
)
605 raise ProvisioningError("Unable to find a Secure Channel"
606 "of type SEC_CHAN_BDC")
609 def update_dns_account_password(samdb
, secrets_ldb
, names
):
610 """Update (change) the password of the dns both in the SAM db and in
613 :param samdb: An LDB object related to the sam.ldb file of a given provision
614 :param secrets_ldb: An LDB object related to the secrets.ldb file of a given
616 :param names: List of key provision parameters"""
618 expression
= "samAccountName=dns-%s" % names
.netbiosname
619 secrets_msg
= secrets_ldb
.search(expression
=expression
)
620 if len(secrets_msg
) == 1:
621 res
= samdb
.search(expression
=expression
, attrs
=[])
622 assert(len(res
) == 1)
624 msg
= ldb
.Message(res
[0].dn
)
625 machinepass
= samba
.generate_random_password(128, 255)
626 mputf16
= machinepass
.encode('utf-16-le')
627 msg
["clearTextPassword"] = ldb
.MessageElement(mputf16
,
628 ldb
.FLAG_MOD_REPLACE
,
633 res
= samdb
.search(expression
=expression
,
634 attrs
=["msDs-keyVersionNumber"])
635 assert(len(res
) == 1)
636 kvno
= str(res
[0]["msDs-keyVersionNumber"])
638 msg
= ldb
.Message(secrets_msg
[0].dn
)
639 msg
["secret"] = ldb
.MessageElement(machinepass
,
640 ldb
.FLAG_MOD_REPLACE
,
642 msg
["msDS-KeyVersionNumber"] = ldb
.MessageElement(kvno
,
643 ldb
.FLAG_MOD_REPLACE
,
644 "msDS-KeyVersionNumber")
646 secrets_ldb
.modify(msg
)
649 def update_krbtgt_account_password(samdb
):
650 """Update (change) the password of the krbtgt account
652 :param samdb: An LDB object related to the sam.ldb file of a given provision"""
654 expression
= "samAccountName=krbtgt"
655 res
= samdb
.search(expression
=expression
, attrs
=[])
656 assert(len(res
) == 1)
658 msg
= ldb
.Message(res
[0].dn
)
659 # Note that the machinepass value is ignored
660 # as the backend (password_hash.c) will generate its
661 # own random values for the krbtgt keys
662 krbtgtpass
= samba
.generate_random_machine_password(128, 255)
663 kputf16
= krbtgtpass
.encode('utf-16-le')
664 msg
["clearTextPassword"] = ldb
.MessageElement(kputf16
,
665 ldb
.FLAG_MOD_REPLACE
,
671 def search_constructed_attrs_stored(samdb
, rootdn
, attrs
):
672 """Search a given sam DB for calculated attributes that are
673 still stored in the db.
675 :param samdb: An LDB object pointing to the sam
676 :param rootdn: The base DN where the search should start
677 :param attrs: A list of attributes to be searched
678 :return: A hash with attributes as key and an array of
679 array. Each array contains the dn and the associated
680 values for this attribute as they are stored in the
684 expr
= construct_existor_expr(attrs
)
687 entry
= samdb
.search(expression
=expr
, base
=ldb
.Dn(samdb
, str(rootdn
)),
688 scope
=SCOPE_SUBTREE
, attrs
=attrs
,
689 controls
=["search_options:1:2", "bypassoperational:0"])
698 hashAtt
[att
][str(ent
.dn
).lower()] = str(ent
[att
])
701 hashAtt
[att
][str(ent
.dn
).lower()] = str(ent
[att
])
706 def findprovisionrange(samdb
, basedn
):
707 """ Find ranges of usn grouped by invocation id and then by timestamp
710 :param samdb: An LDB object pointing to the samdb
711 :param basedn: The DN of the forest
713 :return: A two level dictionary with invoication id as the
714 first level, timestamp as the second one and then
715 max, min, and number as subkeys, representing respectivily
716 the maximum usn for the range, the minimum usn and the number
717 of object with usn in this range.
722 res
= samdb
.search(base
=basedn
, expression
="objectClass=*",
723 scope
=ldb
.SCOPE_SUBTREE
,
724 attrs
=["replPropertyMetaData"],
725 controls
=["search_options:1:2"])
729 obj
= ndr_unpack(drsblobs
.replPropertyMetaDataBlob
,
730 str(e
["replPropertyMetaData"])).ctr
733 # like a timestamp but with the resolution of 1 minute
734 minutestamp
= _glue
.nttime2unix(o
.originating_change_time
) // 60
735 hash_ts
= hash_id
.get(str(o
.originating_invocation_id
))
739 ob
["min"] = o
.originating_usn
740 ob
["max"] = o
.originating_usn
742 ob
["list"] = [str(e
.dn
)]
745 ob
= hash_ts
.get(minutestamp
)
748 ob
["min"] = o
.originating_usn
749 ob
["max"] = o
.originating_usn
751 ob
["list"] = [str(e
.dn
)]
753 if ob
["min"] > o
.originating_usn
:
754 ob
["min"] = o
.originating_usn
755 if ob
["max"] < o
.originating_usn
:
756 ob
["max"] = o
.originating_usn
757 if not (str(e
.dn
) in ob
["list"]):
758 ob
["num"] = ob
["num"] + 1
759 ob
["list"].append(str(e
.dn
))
760 hash_ts
[minutestamp
] = ob
761 hash_id
[str(o
.originating_invocation_id
)] = hash_ts
763 return (hash_id
, nb_obj
)
766 def print_provision_ranges(dic
, limit_print
, dest
, samdb_path
, invocationid
):
767 """ print the differents ranges passed as parameter
769 :param dic: A dictionary as returned by findprovisionrange
770 :param limit_print: minimum number of object in a range in order to print it
771 :param dest: Destination directory
772 :param samdb_path: Path to the sam.ldb file
773 :param invoicationid: Invocation ID for the current provision
780 sorted_keys
.extend(hash_ts
.keys())
784 for k
in sorted_keys
:
786 if obj
["num"] > limit_print
:
787 dt
= _glue
.nttime2string(_glue
.unix2nttime(k
* 60))
788 print("%s # of modification: %d \tmin: %d max: %d" % (dt
, obj
["num"],
791 if hash_ts
[k
]["num"] > 600:
792 kept_record
.append(k
)
794 # Let's try to concatenate consecutive block if they are in the almost same minutestamp
795 for i
in range(0, len(kept_record
)):
797 key1
= kept_record
[i
]
798 key2
= kept_record
[i
- 1]
800 # previous record is just 1 minute away from current
801 if int(hash_ts
[key1
]["min"]) == int(hash_ts
[key2
]["max"]) + 1:
802 # Copy the highest USN in the previous record
803 # and mark the current as skipped
804 hash_ts
[key2
]["max"] = hash_ts
[key1
]["max"]
805 hash_ts
[key1
]["skipped"] = True
807 for k
in kept_record
:
809 if obj
.get("skipped") is None:
810 ldif
= "%slastProvisionUSN: %d-%d;%s\n" % (ldif
, obj
["min"],
814 fd
, file = tempfile
.mkstemp(dir=dest
, prefix
="usnprov", suffix
=".ldif")
816 print("To track the USNs modified/created by provision and upgrade proivsion,")
817 print(" the following ranges are proposed to be added to your provision sam.ldb: \n%s" % ldif
)
818 print("We recommend to review them, and if it's correct to integrate the following ldif: %s in your sam.ldb" % file)
819 print("You can load this file like this: ldbadd -H %s %s\n" %(str(samdb_path
), file))
820 ldif
= "dn: @PROVISION\nprovisionnerID: %s\n%s" % (invocationid
, ldif
)
825 def int64range2str(value
):
826 """Display the int64 range stored in value as xxx-yyy
828 :param value: The int64 range
829 :return: A string of the representation of the range
832 str = "%d-%d" % (lvalue
&0xFFFFFFFF, lvalue
>>32)