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 from samba
.samba3
import passdb
30 from samba
.samba3
import param
as s3param
31 from samba
.common
import get_bytes
33 def fetch_uint32(db
, key
):
39 return struct
.unpack("<L", data
)[0]
42 def fetch_int32(db
, key
):
48 return struct
.unpack("<l", data
)[0]
51 class DbDatabase(object):
52 """Simple Samba 3 TDB database reader."""
53 def __init__(self
, file):
56 :param file: Path of the file to open, appending .tdb or .ntdb.
58 self
.db
= tdb
.Tdb(file + ".tdb", flags
=os
.O_RDONLY
)
61 def _check_version(self
):
65 """Close resources associated with this object."""
69 class Registry(DbDatabase
):
70 """Simple read-only support for reading the Samba3 registry.
72 :note: This object uses the same syntax for registry key paths as
73 Samba 3. This particular format uses forward slashes for key path
74 separators and abbreviations for the predefined key names.
75 e.g.: HKLM/Software/Bar.
78 """Return the number of keys."""
79 return len(self
.keys())
82 """Return list with all the keys."""
83 return [k
.rstrip(b
"\x00") for k
in self
.db
if not k
.startswith(REGISTRY_VALUE_PREFIX
)]
85 def subkeys(self
, key
):
86 """Retrieve the subkeys for the specified key.
89 :return: list with key names
91 data
= self
.db
.get(key
+ b
"\x00")
94 (num
, ) = struct
.unpack("<L", data
[0:4])
95 keys
= data
[4:].split(b
"\0")
96 assert keys
[-1] == b
""
98 assert len(keys
) == num
101 def values(self
, key
):
102 """Return a dictionary with the values set for a specific key.
104 :param key: Key to retrieve values for.
105 :return: Dictionary with value names as key, tuple with type and
107 data
= self
.db
.get(REGISTRY_VALUE_PREFIX
+ b
'/' + key
+ b
'\x00')
111 (num
, ) = struct
.unpack("<L", data
[0:4])
115 (name
, data
) = data
.split(b
"\0", 1)
117 (type, ) = struct
.unpack("<L", data
[0:4])
119 (value_len
, ) = struct
.unpack("<L", data
[0:4])
122 ret
[name
] = (type, data
[:value_len
])
123 data
= data
[value_len
:]
128 # High water mark keys
129 IDMAP_HWM_GROUP
= b
"GROUP HWM\0"
130 IDMAP_HWM_USER
= b
"USER HWM\0"
132 IDMAP_GROUP_PREFIX
= b
"GID "
133 IDMAP_USER_PREFIX
= b
"UID "
135 # idmap version determines auto-conversion
139 class IdmapDatabase(DbDatabase
):
140 """Samba 3 ID map database reader."""
142 def _check_version(self
):
143 assert fetch_int32(self
.db
, b
"IDMAP_VERSION\0") == IDMAP_VERSION_V2
146 """Retrieve a list of all ids in this database."""
148 if k
.startswith(IDMAP_USER_PREFIX
):
149 yield k
.rstrip(b
"\0").split(b
" ")
150 if k
.startswith(IDMAP_GROUP_PREFIX
):
151 yield k
.rstrip(b
"\0").split(b
" ")
154 """Retrieve a list of all uids in this database."""
156 if k
.startswith(IDMAP_USER_PREFIX
):
157 yield int(k
[len(IDMAP_USER_PREFIX
):].rstrip(b
"\0"))
160 """Retrieve a list of all gids in this database."""
162 if k
.startswith(IDMAP_GROUP_PREFIX
):
163 yield int(k
[len(IDMAP_GROUP_PREFIX
):].rstrip(b
"\0"))
165 def get_sid(self
, xid
, id_type
):
166 """Retrieve SID associated with a particular id and type.
168 :param xid: UID or GID to retrieve SID for.
169 :param id_type: Type of id specified - 'UID' or 'GID'
171 data
= self
.db
.get(get_bytes("%s %s\0" % (id_type
, str(xid
))))
174 return data
.rstrip("\0")
176 def get_user_sid(self
, uid
):
177 """Retrieve the SID associated with a particular uid.
179 :param uid: UID to retrieve SID for.
180 :return: A SID or None if no mapping was found.
182 data
= self
.db
.get(IDMAP_USER_PREFIX
+ str(uid
).encode() + b
'\0')
185 return data
.rstrip(b
"\0")
187 def get_group_sid(self
, gid
):
188 data
= self
.db
.get(IDMAP_GROUP_PREFIX
+ str(gid
).encode() + b
'\0')
191 return data
.rstrip(b
"\0")
193 def get_user_hwm(self
):
194 """Obtain the user high-water mark."""
195 return fetch_uint32(self
.db
, IDMAP_HWM_USER
)
197 def get_group_hwm(self
):
198 """Obtain the group high-water mark."""
199 return fetch_uint32(self
.db
, IDMAP_HWM_GROUP
)
202 class SecretsDatabase(DbDatabase
):
203 """Samba 3 Secrets database reader."""
205 def get_auth_password(self
):
206 return self
.db
.get(b
"SECRETS/AUTH_PASSWORD")
208 def get_auth_domain(self
):
209 return self
.db
.get(b
"SECRETS/AUTH_DOMAIN")
211 def get_auth_user(self
):
212 return self
.db
.get(b
"SECRETS/AUTH_USER")
214 def get_domain_guid(self
, host
):
215 return self
.db
.get(b
"SECRETS/DOMGUID/%s" % host
)
219 if k
.startswith("SECRETS/LDAP_BIND_PW/"):
220 yield k
[len("SECRETS/LDAP_BIND_PW/"):].rstrip("\0")
223 """Iterate over domains in this database.
225 :return: Iterator over the names of domains in this database.
228 if k
.startswith("SECRETS/SID/"):
229 yield k
[len("SECRETS/SID/"):].rstrip("\0")
231 def get_ldap_bind_pw(self
, host
):
232 return self
.db
.get(get_bytes("SECRETS/LDAP_BIND_PW/%s" % host
))
234 def get_afs_keyfile(self
, host
):
235 return self
.db
.get(get_bytes("SECRETS/AFS_KEYFILE/%s" % host
))
237 def get_machine_sec_channel_type(self
, host
):
238 return fetch_uint32(self
.db
, get_bytes("SECRETS/MACHINE_SEC_CHANNEL_TYPE/%s" % host
))
240 def get_machine_last_change_time(self
, host
):
241 return fetch_uint32(self
.db
, "SECRETS/MACHINE_LAST_CHANGE_TIME/%s" % host
)
243 def get_machine_password(self
, host
):
244 return self
.db
.get(get_bytes("SECRETS/MACHINE_PASSWORD/%s" % host
))
246 def get_machine_acc(self
, host
):
247 return self
.db
.get(get_bytes("SECRETS/$MACHINE.ACC/%s" % host
))
249 def get_domtrust_acc(self
, host
):
250 return self
.db
.get(get_bytes("SECRETS/$DOMTRUST.ACC/%s" % host
))
252 def trusted_domains(self
):
254 if k
.startswith("SECRETS/$DOMTRUST.ACC/"):
255 yield k
[len("SECRETS/$DOMTRUST.ACC/"):].rstrip("\0")
257 def get_random_seed(self
):
258 return self
.db
.get(b
"INFO/random_seed")
260 def get_sid(self
, host
):
261 return self
.db
.get(get_bytes("SECRETS/SID/%s" % host
.upper()))
264 SHARE_DATABASE_VERSION_V1
= 1
265 SHARE_DATABASE_VERSION_V2
= 2
268 class ShareInfoDatabase(DbDatabase
):
269 """Samba 3 Share Info database reader."""
271 def _check_version(self
):
272 assert fetch_int32(self
.db
, "INFO/version\0") in (SHARE_DATABASE_VERSION_V1
, SHARE_DATABASE_VERSION_V2
)
274 def get_secdesc(self
, name
):
275 """Obtain the security descriptor on a particular share.
277 :param name: Name of the share
279 secdesc
= self
.db
.get(get_bytes("SECDESC/%s" % name
))
280 # FIXME: Run ndr_pull_security_descriptor
284 class Shares(object):
285 """Container for share objects."""
286 def __init__(self
, lp
, shareinfo
):
288 self
.shareinfo
= shareinfo
291 """Number of shares."""
292 return len(self
.lp
) - 1
295 """Iterate over the share names."""
296 return self
.lp
.__iter
__()
299 def shellsplit(text
):
300 """Very simple shell-like line splitting.
302 :param text: Text to split.
303 :return: List with parts of the line as strings.
310 inquotes
= not inquotes
311 elif c
in ("\t", "\n", " ") and not inquotes
:
322 class WinsDatabase(object):
323 """Samba 3 WINS database reader."""
324 def __init__(self
, file):
327 assert f
.readline().rstrip("\n") == "VERSION 1 0"
328 for l
in f
.readlines():
329 if l
[0] == "#": # skip comments
331 entries
= shellsplit(l
.rstrip("\n"))
333 ttl
= int(entries
[1])
336 while "." in entries
[i
]:
337 ips
.append(entries
[i
])
339 nb_flags
= int(entries
[i
][:-1], 16)
340 assert name
not in self
.entries
, "Name %s exists twice" % name
341 self
.entries
[name
] = (ttl
, ips
, nb_flags
)
344 def __getitem__(self
, name
):
345 return self
.entries
[name
]
348 return len(self
.entries
)
351 return iter(self
.entries
)
354 """Return the entries in this WINS database."""
355 return self
.entries
.items()
357 def close(self
): # for consistency
361 class Samba3(object):
362 """Samba 3 configuration and state data reader."""
364 def __init__(self
, smbconfpath
, s3_lp_ctx
=None):
365 """Open the configuration and data for a Samba 3 installation.
367 :param smbconfpath: Path to the smb.conf file.
368 :param s3_lp_ctx: Samba3 Loadparm context
370 self
.smbconfpath
= smbconfpath
374 self
.lp
= s3param
.get_context()
375 self
.lp
.load(smbconfpath
)
377 def statedir_path(self
, path
):
378 if path
[0] == "/" or path
[0] == ".":
380 return os
.path
.join(self
.lp
.get("state directory"), path
)
382 def privatedir_path(self
, path
):
383 if path
[0] == "/" or path
[0] == ".":
385 return os
.path
.join(self
.lp
.get("private dir"), path
)
390 def get_sam_db(self
):
391 return passdb
.PDB(self
.lp
.get('passdb backend'))
393 def get_registry(self
):
394 return Registry(self
.statedir_path("registry"))
396 def get_secrets_db(self
):
397 return SecretsDatabase(self
.privatedir_path("secrets"))
399 def get_shareinfo_db(self
):
400 return ShareInfoDatabase(self
.statedir_path("share_info"))
402 def get_idmap_db(self
):
403 return IdmapDatabase(self
.statedir_path("winbindd_idmap"))
405 def get_wins_db(self
):
406 return WinsDatabase(self
.statedir_path("wins.dat"))
408 def get_shares(self
):
409 return Shares(self
.get_conf(), self
.get_shareinfo_db())