1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 """Support for reading Samba 3 data files."""
20 __docformat__ = "restructuredText"
22 REGISTRY_VALUE_PREFIX = b"SAMBA_REGVAL"
23 REGISTRY_DB_VERSION = 1
29 import samba.samba3.passdb
30 from samba.samba3 import param as s3param
32 def fetch_uint32(db, key):
38 return struct.unpack("<L", data)[0]
41 def fetch_int32(db, key):
47 return struct.unpack("<l", data)[0]
50 class DbDatabase(object):
51 """Simple Samba 3 TDB database reader."""
52 def __init__(self, file):
55 :param file: Path of the file to open, appending .tdb or .ntdb.
57 self.db = tdb.Tdb(file + ".tdb", flags=os.O_RDONLY)
60 def _check_version(self):
64 """Close resources associated with this object."""
68 class Registry(DbDatabase):
69 """Simple read-only support for reading the Samba3 registry.
71 :note: This object uses the same syntax for registry key paths as
72 Samba 3. This particular format uses forward slashes for key path
73 separators and abbreviations for the predefined key names.
74 e.g.: HKLM/Software/Bar.
77 """Return the number of keys."""
78 return len(self.keys())
81 """Return list with all the keys."""
82 return [k.rstrip(b"\x00") for k in self.db if not k.startswith(REGISTRY_VALUE_PREFIX)]
84 def subkeys(self, key):
85 """Retrieve the subkeys for the specified key.
88 :return: list with key names
90 data = self.db.get(b"%s\x00" % key)
93 (num, ) = struct.unpack("<L", data[0:4])
94 keys = data[4:].split(b"\0")
95 assert keys[-1] == b""
97 assert len(keys) == num
100 def values(self, key):
101 """Return a dictionary with the values set for a specific key.
103 :param key: Key to retrieve values for.
104 :return: Dictionary with value names as key, tuple with type and
106 data = self.db.get(b"%s/%s\x00" % (REGISTRY_VALUE_PREFIX, key))
110 (num, ) = struct.unpack("<L", data[0:4])
114 (name, data) = data.split(b"\0", 1)
116 (type, ) = struct.unpack("<L", data[0:4])
118 (value_len, ) = struct.unpack("<L", data[0:4])
121 ret[name] = (type, data[:value_len])
122 data = data[value_len:]
127 # High water mark keys
128 IDMAP_HWM_GROUP = "GROUP HWM\0"
129 IDMAP_HWM_USER = "USER HWM\0"
131 IDMAP_GROUP_PREFIX = "GID "
132 IDMAP_USER_PREFIX = "UID "
134 # idmap version determines auto-conversion
137 class IdmapDatabase(DbDatabase):
138 """Samba 3 ID map database reader."""
140 def _check_version(self):
141 assert fetch_int32(self.db, "IDMAP_VERSION\0") == IDMAP_VERSION_V2
144 """Retrieve a list of all ids in this database."""
145 for k in self.db.iterkeys():
146 if k.startswith(IDMAP_USER_PREFIX):
147 yield k.rstrip("\0").split(" ")
148 if k.startswith(IDMAP_GROUP_PREFIX):
149 yield k.rstrip("\0").split(" ")
152 """Retrieve a list of all uids in this database."""
153 for k in self.db.iterkeys():
154 if k.startswith(IDMAP_USER_PREFIX):
155 yield int(k[len(IDMAP_USER_PREFIX):].rstrip("\0"))
158 """Retrieve a list of all gids in this database."""
159 for k in self.db.iterkeys():
160 if k.startswith(IDMAP_GROUP_PREFIX):
161 yield int(k[len(IDMAP_GROUP_PREFIX):].rstrip("\0"))
163 def get_sid(self, xid, id_type):
164 """Retrive SID associated with a particular id and type.
166 :param xid: UID or GID to retrive SID for.
167 :param id_type: Type of id specified - 'UID' or 'GID'
169 data = self.db.get("%s %s\0" % (id_type, str(xid)))
172 return data.rstrip("\0")
174 def get_user_sid(self, uid):
175 """Retrieve the SID associated with a particular uid.
177 :param uid: UID to retrieve SID for.
178 :return: A SID or None if no mapping was found.
180 data = self.db.get("%s%d\0" % (IDMAP_USER_PREFIX, uid))
183 return data.rstrip("\0")
185 def get_group_sid(self, gid):
186 data = self.db.get("%s%d\0" % (IDMAP_GROUP_PREFIX, gid))
189 return data.rstrip("\0")
191 def get_user_hwm(self):
192 """Obtain the user high-water mark."""
193 return fetch_uint32(self.db, IDMAP_HWM_USER)
195 def get_group_hwm(self):
196 """Obtain the group high-water mark."""
197 return fetch_uint32(self.db, IDMAP_HWM_GROUP)
200 class SecretsDatabase(DbDatabase):
201 """Samba 3 Secrets database reader."""
203 def get_auth_password(self):
204 return self.db.get("SECRETS/AUTH_PASSWORD")
206 def get_auth_domain(self):
207 return self.db.get("SECRETS/AUTH_DOMAIN")
209 def get_auth_user(self):
210 return self.db.get("SECRETS/AUTH_USER")
212 def get_domain_guid(self, host):
213 return self.db.get("SECRETS/DOMGUID/%s" % host)
216 for k in self.db.iterkeys():
217 if k.startswith("SECRETS/LDAP_BIND_PW/"):
218 yield k[len("SECRETS/LDAP_BIND_PW/"):].rstrip("\0")
221 """Iterate over domains in this database.
223 :return: Iterator over the names of domains in this database.
225 for k in self.db.iterkeys():
226 if k.startswith("SECRETS/SID/"):
227 yield k[len("SECRETS/SID/"):].rstrip("\0")
229 def get_ldap_bind_pw(self, host):
230 return self.db.get("SECRETS/LDAP_BIND_PW/%s" % host)
232 def get_afs_keyfile(self, host):
233 return self.db.get("SECRETS/AFS_KEYFILE/%s" % host)
235 def get_machine_sec_channel_type(self, host):
236 return fetch_uint32(self.db, "SECRETS/MACHINE_SEC_CHANNEL_TYPE/%s" % host)
238 def get_machine_last_change_time(self, host):
239 return fetch_uint32(self.db, "SECRETS/MACHINE_LAST_CHANGE_TIME/%s" % host)
241 def get_machine_password(self, host):
242 return self.db.get("SECRETS/MACHINE_PASSWORD/%s" % host)
244 def get_machine_acc(self, host):
245 return self.db.get("SECRETS/$MACHINE.ACC/%s" % host)
247 def get_domtrust_acc(self, host):
248 return self.db.get("SECRETS/$DOMTRUST.ACC/%s" % host)
250 def trusted_domains(self):
251 for k in self.db.iterkeys():
252 if k.startswith("SECRETS/$DOMTRUST.ACC/"):
253 yield k[len("SECRETS/$DOMTRUST.ACC/"):].rstrip("\0")
255 def get_random_seed(self):
256 return self.db.get("INFO/random_seed")
258 def get_sid(self, host):
259 return self.db.get("SECRETS/SID/%s" % host.upper())
262 SHARE_DATABASE_VERSION_V1 = 1
263 SHARE_DATABASE_VERSION_V2 = 2
266 class ShareInfoDatabase(DbDatabase):
267 """Samba 3 Share Info database reader."""
269 def _check_version(self):
270 assert fetch_int32(self.db, "INFO/version\0") in (SHARE_DATABASE_VERSION_V1, SHARE_DATABASE_VERSION_V2)
272 def get_secdesc(self, name):
273 """Obtain the security descriptor on a particular share.
275 :param name: Name of the share
277 secdesc = self.db.get("SECDESC/%s" % name)
278 # FIXME: Run ndr_pull_security_descriptor
282 class Shares(object):
283 """Container for share objects."""
284 def __init__(self, lp, shareinfo):
286 self.shareinfo = shareinfo
289 """Number of shares."""
290 return len(self.lp) - 1
293 """Iterate over the share names."""
294 return self.lp.__iter__()
297 def shellsplit(text):
298 """Very simple shell-like line splitting.
300 :param text: Text to split.
301 :return: List with parts of the line as strings.
308 inquotes = not inquotes
309 elif c in ("\t", "\n", " ") and not inquotes:
320 class WinsDatabase(object):
321 """Samba 3 WINS database reader."""
322 def __init__(self, file):
325 assert f.readline().rstrip("\n") == "VERSION 1 0"
326 for l in f.readlines():
327 if l[0] == "#": # skip comments
329 entries = shellsplit(l.rstrip("\n"))
331 ttl = int(entries[1])
334 while "." in entries[i]:
335 ips.append(entries[i])
337 nb_flags = int(entries[i][:-1], 16)
338 assert not name in self.entries, "Name %s exists twice" % name
339 self.entries[name] = (ttl, ips, nb_flags)
342 def __getitem__(self, name):
343 return self.entries[name]
346 return len(self.entries)
349 return iter(self.entries)
352 """Return the entries in this WINS database."""
353 return self.entries.items()
355 def close(self): # for consistency
359 class Samba3(object):
360 """Samba 3 configuration and state data reader."""
362 def __init__(self, smbconfpath, s3_lp_ctx=None):
363 """Open the configuration and data for a Samba 3 installation.
365 :param smbconfpath: Path to the smb.conf file.
366 :param s3_lp_ctx: Samba3 Loadparm context
368 self.smbconfpath = smbconfpath
372 self.lp = s3param.get_context()
373 self.lp.load(smbconfpath)
375 def statedir_path(self, path):
376 if path[0] == "/" or path[0] == ".":
378 return os.path.join(self.lp.get("state directory"), path)
380 def privatedir_path(self, path):
381 if path[0] == "/" or path[0] == ".":
383 return os.path.join(self.lp.get("private dir"), path)
388 def get_sam_db(self):
389 return passdb.PDB(self.lp.get('passdb backend'))
391 def get_registry(self):
392 return Registry(self.statedir_path("registry"))
394 def get_secrets_db(self):
395 return SecretsDatabase(self.privatedir_path("secrets"))
397 def get_shareinfo_db(self):
398 return ShareInfoDatabase(self.statedir_path("share_info"))
400 def get_idmap_db(self):
401 return IdmapDatabase(self.statedir_path("winbindd_idmap"))
403 def get_wins_db(self):
404 return WinsDatabase(self.statedir_path("wins.dat"))
406 def get_shares(self):
407 return Shares(self.get_conf(), self.get_shareinfo_db())