def setUp(self): super(SimpleTdbTests, self).setUp() if tdb.__version__.startswith("2"): self.tdb = tdb.Tdb(tempfile.mkstemp()[1], tdb.DEFAULT, os.O_CREAT|os.O_RDWR) else: self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT|os.O_RDWR) self.assertNotEqual(None, self.tdb)
def __init__(self, file): """Open a file. :param file: Path of the file to open (appending "2" if TDB2 enabled). """ if tdb.__version__.startswith("2"): self.tdb = tdb.Tdb(file + "2", flags=os.O_RDONLY) else: self.tdb = tdb.Tdb(file, flags=os.O_RDONLY) self._check_version()
def test_double_close(self): # No hash size in tdb2. if tdb.__version__.startswith("2"): self.tdb = tdb.Tdb(tempfile.mkstemp()[1], tdb.DEFAULT, os.O_CREAT | os.O_RDWR) else: self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR) self.assertNotEqual(None, self.tdb) # ensure that double close does not crash python self.tdb.close() self.tdb.close()
def removePrivileges(sambaSID, privileges): # type: (bytes, list) -> None with SetUID(0): tdbKey = b'PRIV_%s\x00' % (sambaSID, ) tdbFile = tdb.Tdb(SAMBA_POLICY_TDB) tdbFile.lock_all() privs = tdbFile.get(tdbKey) if privs: for privilege in privileges: if SAMBA_PRIVILEGES.get(privilege): index = SAMBA_PRIVILEGES[privilege]["index"] number = SAMBA_PRIVILEGES[privilege]["number"] if privs[index] & number: new = chr(privs[index] - number).encode('ISO8859-1') privs = privs[0:index] + new + privs[(index + 1):len(privs)] tdbFile[tdbKey] = privs # delete key if no privileges are assigned if privs == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': tdbFile.delete(tdbKey) tdbFile.unlock_all() tdbFile.close()
def addPrivileges(sambaSID, privileges): listener.setuid(0) try: tdbKey = 'PRIV_%s\x00' % (sambaSID) tdbFile = tdb.Tdb(SAMBA_POLICY_TDB) tdbFile.lock_all() privs = tdbFile.get(tdbKey) if not privs: privs = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' for privilege in privileges: if SAMBA_PRIVILEGES.get(privilege, ""): index = SAMBA_PRIVILEGES[privilege].get("index", 0) number = SAMBA_PRIVILEGES[privilege].get("number", 0) if (ord(privs[index]) & number) == 0: new = chr(ord(privs[index]) + number) privs = privs[0:index] + new + privs[(index + 1):len(privs)] tdbFile[tdbKey] = privs tdbFile.unlock_all() tdbFile.close() finally: listener.unsetuid()
def __init__(self, file): """Open a file. :param file: Path of the file to open, appending .tdb or .ntdb. """ self.db = tdb.Tdb(file + ".tdb", flags=os.O_RDONLY) self._check_version()
def setUp(self): super(CommonTdbTests, self).setUp() self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR) self.assertNotEqual(None, self.tdb) if self.use_text: self.tdb = self.tdb.text
def __init__(self, file): """Open a file. :param file: Path of the file to open. """ self.tdb = tdb.Tdb(file, flags=os.O_RDONLY) self._check_version()
def removePrivileges(sambaSID, privileges): listener.setuid(0) try: tdbKey = 'PRIV_%s\x00' % (sambaSID) tdbFile = tdb.Tdb(SAMBA_POLICY_TDB) tdbFile.lock_all() privs = tdbFile.get(tdbKey) if privs: for privilege in privileges: if SAMBA_PRIVILEGES.get(privilege, ""): index = SAMBA_PRIVILEGES[privilege].get("index", "") number = SAMBA_PRIVILEGES[privilege].get("number", "") if ord(privs[index]) & number: new = chr(ord(privs[index]) - number) privs = privs[0:index] + new + privs[(index + 1):len(privs)] tdbFile[tdbKey] = privs # delete key if no privileges are assigned if privs == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': tdbFile.delete(tdbKey) tdbFile.unlock_all() tdbFile.close() finally: listener.unsetuid()
def test_double_close(self): self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR) self.assertNotEqual(None, self.tdb) # ensure that double close does not crash python self.tdb.close() self.tdb.close()
def test_double_close(self): # No hash size in tdb2. if tdb.__version__.startswith("2"): self.tdb = tdb.Tdb(tempfile.mkstemp()[1], tdb.DEFAULT, os.O_CREAT|os.O_RDWR) else: self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT|os.O_RDWR) self.assertNotEqual(None, self.tdb) # ensure that double close does not crash python self.tdb.close() self.tdb.close() # Check that further operations do not crash python self.assertRaises(RuntimeError, lambda: self.tdb.transaction_start()) self.assertRaises(RuntimeError, lambda: self.tdb["bar"])
def open_tdb(self): secret_path = f'{SMBPath.PRIVATEDIR.platform()}/secrets.tdb' if os.path.isfile(secret_path): self.tdb = tdb.open(secret_path, self.flags) else: self.tdb = tdb.Tdb(secret_path, 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR) self.is_open = True
def __init__(self, file): """Open a file. :param file: Path of the file to open, appending .tdb or .ntdb. """ if os.path.exists(file + ".ntdb"): self.db = ntdb.Ntdb(file + ".ntdb", flags=os.O_RDONLY) else: self.db = tdb.Tdb(file + ".tdb", flags=os.O_RDONLY) self._check_version()
def __init__(self, name, options): self.name = str(name) tdb_type = options.get('backend', 'PERSISTENT') tdb_flags = tdb.DEFAULT open_flags = os.O_CREAT | os.O_RDWR open_mode = 0o600 if not tdb_flags & tdb.INTERNAL: name = f'{TDBPath[tdb_type].value}/{name}.tdb' self.hdl = tdb.Tdb(name, 0, tdb_flags, open_flags, open_mode) self.options = copy.deepcopy(options) super().__init__()
def get_gencache_sid(self, tdb_key): gencache = tdb.Tdb('/tmp/gencache.tdb', 0, tdb.DEFAULT, os.O_RDONLY) try: tdb_val = gencache.get(tdb_key) finally: gencache.close() if tdb_val is None: return None decoded_sid = tdb_val[8:-5].decode() if decoded_sid == '-': return None return decoded_sid
def apply(cls, cur, **kwargs): # Mimetise what mapistore_interface.c (mapistore_init) does # to get the mapping path if 'lp' in kwargs: mapping_path = kwargs['lp'].private_path("mapistore") else: lp = LoadParm() lp.load_default() mapping_path = lp.private_path("mapistore") if mapping_path is None: return cur.execute("START TRANSACTION") try: # Get all mailboxes cur.execute("SELECT name FROM mailboxes") for row in cur.fetchall(): username = row[0] path = "{0}/{1}/replica_mapping.tdb".format( mapping_path, username) try: tdb_file = tdb.Tdb(path, 0, tdb.DEFAULT, os.O_RDONLY) for k in tdb_file.iterkeys(): # Check if the key is an integer try: repl_id = int(k, base=16) cls._insert_map(cur, username, repl_id, tdb_file[k]) except ValueError: # Cannot convert to int, so no repl_id continue except IOError: # Cannot read any replica mapping continue cur.execute("COMMIT") except Exception as e: print("Error migrating TDB files into the database {}, rollback". format(e), file=sys.stderr) cur.execute("ROLLBACK") raise
def __init__(self, path=None): import tdb self.path = path if path is None: self.db = {} else: if path not in mapdbs(): mapdbs()[path] = tdb.Tdb(path, self.TDB_HASH_SIZE, tdb.DEFAULT, os.O_RDWR | os.O_CREAT) self.db = mapdbs()[path] try: if int(self.db[b"version"]) not in (2, 3): trace.warning( "SHA Map is incompatible (%s -> %d), rebuilding database.", self.db[b"version"], self.TDB_MAP_VERSION) self.db.clear() except KeyError: pass self.db[b"version"] = b'%d' % self.TDB_MAP_VERSION
def __init__(self, path=None): self.path = path if path is None: self.db = {} else: import tdb if not mapdbs().has_key(path): mapdbs()[path] = tdb.Tdb(path, TDB_HASH_SIZE, tdb.DEFAULT, os.O_RDWR | os.O_CREAT) self.db = mapdbs()[path] try: if int(self.db["version"]) != TDB_MAP_VERSION: trace.warning( "SHA Map is incompatible (%s -> %d), rebuilding database.", self.db["version"], TDB_MAP_VERSION) self.db.clear() self.db["version"] = str(TDB_MAP_VERSION) except KeyError: self.db["version"] = str(TDB_MAP_VERSION)
def get_gencache_names(self, idmap_domain): out = [] known_doms = [x['domain_info']['name'] for x in idmap_domain] gencache = tdb.Tdb('/tmp/gencache.tdb', 0, tdb.DEFAULT, os.O_RDONLY) try: for k in gencache.keys(): if k[:8] != b'NAME2SID': continue key = k[:-1].decode() name = key.split('/', 1)[1] dom = name.split('\\')[0] if dom not in known_doms: continue out.append(name) finally: gencache.close() return out
def addPrivileges(sambaSID, privileges): # type: (bytes, list) -> None with SetUID(0): tdbKey = b'PRIV_%s\x00' % (sambaSID, ) tdbFile = tdb.Tdb(SAMBA_POLICY_TDB) tdbFile.lock_all() privs = tdbFile.get(tdbKey) if not privs: privs = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' for privilege in privileges: if SAMBA_PRIVILEGES.get(privilege): index = SAMBA_PRIVILEGES[privilege]["index"] number = SAMBA_PRIVILEGES[privilege]["number"] if (privs[index] & number) == 0: new = chr(privs[index] + number).encode('ISO8859-1') privs = privs[0:index] + new + privs[(index + 1):len(privs)] tdbFile[tdbKey] = privs tdbFile.unlock_all() tdbFile.close()
def test_repr(self): self.tdb = tdb.Tdb() # repr used to crash on internal db self.assertEquals(repr(self.tdb), "Tdb(<internal>)")
#!/usr/bin/env python # Trivial reimplementation of tdbdump in Python from __future__ import print_function import tdb, sys if len(sys.argv) < 2: print("Usage: tdbdump.py <tdb-file>") sys.exit(1) db = tdb.Tdb(sys.argv[1]) for (k, v) in db.items(): print("{\nkey(%d) = %r\ndata(%d) = %r\n}" % (len(k), k, len(v), v))
def __init__(self, log_file): if os.path.isfile(log_file): self.log = tdb.open(log_file) else: self.log = tdb.Tdb(log_file, 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR)
from inspect import getabsfile, getmembers import tdb, ldb import sys # Get script dir (follow symlinks) def mypath(): if getattr(sys, 'frozen', False): sp = abspath(sys.executable) else: # __file__ alt sp = getabsfile(mypath) return dirname(realpath(sp)) tb = tdb.Tdb(join(mypath(), 'samba/private/secrets.tdb')) assert isinstance(tb, tdb.Tdb) print type(tb) print dir(tb) print getattr(tb, 'filename', '<>') if 10 > 9999: for m in getmembers(tb): print m print '----' for k in tb.iterkeys(): print '{' print "key(%d) = %r" % (len(k), k) print "val(%d) = %r" % (len(tb[k]), tb[k]) print '}'
def setUp(self): super(SimpleTdbTests, self).setUp() self.tdb = tdb.Tdb(tempfile.mkstemp()[1], 0, tdb.DEFAULT, os.O_CREAT | os.O_RDWR) self.assertNotEqual(None, self.tdb)
if __name__ == '__main__': parse = argparse.ArgumentParser(description='Sysvol replication tool') parse.add_argument('server', help='FQDN of server to replicate sysvol from') args = parse.parse_args() parser = optparse.OptionParser() lp = getopt.SambaOptions(parser).get_loadparm() creds = getopt.CredentialsOptions(parser).get_credentials(lp, fallback_machine=True) conn = smb.SMB(args.server, 'sysvol', lp=lp, creds=creds) gpo_versions = '%s/%s' % (lp.get('path', 'sysvol'), 'versions.tdb') if os.path.isfile(gpo_versions): vers_f = tdb.open(gpo_versions) else: vers_f = tdb.Tdb(gpo_versions, 0, tdb.DEFAULT, os.O_CREAT|os.O_RDWR) gpo_path = win_path_join(lp.get('realm').lower(), 'Policies') gpos = [x['name'] for x in conn.list(gpo_path)] for gpo in gpos: s_gpo_path = win_path_join(gpo_path, gpo) # Check if the version has changed fname = win_path_join(s_gpo_path, 'GPT.INI') data = conn.loadfile(fname) gpt_ini = ConfigParser() gpt_ini.readfp(StringIO(data)) new_vers = gpt_ini.get('General', 'Version') old_vers = vers_f.get(gpo) if (old_vers and old_vers != new_vers) or not old_vers: vers_f.transaction_start() vers_f.store(gpo, new_vers)