2 # Unix SMB/CIFS implementation.
3 # backend code for provisioning a Samba4 server
5 # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007-2008
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2008-2009
7 # Copyright (C) Oliver Liebel <oliver@itc.li> 2008-2009
9 # Based on the original in EJS:
10 # Copyright (C) Andrew Tridgell <tridge@samba.org> 2005
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 3 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 """Functions for setting up a Samba configuration (LDB and LDAP backends)."""
28 from base64 import b64encode
39 from ldb import SCOPE_BASE, SCOPE_ONELEVEL, LdbError, timestring
41 from samba import Ldb, read_and_sub_file, setup_file
42 from samba.credentials import Credentials, DONT_USE_KERBEROS
43 from samba.schema import Schema
46 class SlapdAlreadyRunning(Exception):
48 def __init__(self, uri):
50 super(SlapdAlreadyRunning, self).__init__("Another slapd Instance "
51 "seems already running on this host, listening to %s." %
55 class BackendResult(object):
57 def report_logger(self, logger):
58 """Rerport this result to a particular logger.
61 raise NotImplementedError(self.report_logger)
64 class LDAPBackendResult(BackendResult):
66 def __init__(self, slapd_command_escaped, ldapdir):
67 self.slapd_command_escaped = slapd_command_escaped
68 self.ldapdir = ldapdir
70 def report_logger(self, logger):
71 if self.slapd_command_escaped is not None:
72 # now display slapd_command_file.txt to show how slapd must be
75 "Use later the following commandline to start slapd, then Samba:")
76 logger.info(self.slapd_command_escaped)
78 "This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh",
82 class ProvisionBackend(object):
84 def __init__(self, backend_type, paths=None, lp=None,
85 names=None, logger=None):
86 """Provision a backend for samba4"""
89 self.credentials = None
93 self.type = backend_type
95 # Set a default - the code for "existing" below replaces this
96 self.ldap_backend_type = backend_type
99 """Initialize the backend."""
100 raise NotImplementedError(self.init)
103 """Start the backend."""
104 raise NotImplementedError(self.start)
107 """Shutdown the backend."""
108 raise NotImplementedError(self.shutdown)
110 def post_setup(self):
113 :return: A BackendResult or None
115 raise NotImplementedError(self.post_setup)
118 class LDBBackend(ProvisionBackend):
121 self.credentials = None
123 # Wipe the old sam.ldb databases away
124 shutil.rmtree(self.paths.samdb + ".d", True)
132 def post_setup(self):
136 class ExistingBackend(ProvisionBackend):
138 def __init__(self, backend_type, paths=None, lp=None,
139 names=None, logger=None, ldapi_uri=None):
141 super(ExistingBackend, self).__init__(backend_type=backend_type,
143 names=names, logger=logger,
144 ldap_backend_forced_uri=ldapi_uri)
147 # Check to see that this 'existing' LDAP backend in fact exists
148 ldapi_db = Ldb(self.ldapi_uri)
149 ldapi_db.search(base="", scope=SCOPE_BASE,
150 expression="(objectClass=OpenLDAProotDSE)")
152 # For now, assume existing backends at least emulate OpenLDAP
153 self.ldap_backend_type = "openldap"
156 class LDAPBackend(ProvisionBackend):
158 def __init__(self, backend_type, paths=None, lp=None,
159 names=None, logger=None, domainsid=None,
160 schema=None, hostname=None, ldapadminpass=None,
161 slapd_path=None, ldap_backend_extra_port=None,
162 ldap_backend_forced_uri=None, ldap_dryrun_mode=False):
164 super(LDAPBackend, self).__init__(backend_type=backend_type,
166 names=names, logger=logger)
168 self.domainsid = domainsid
170 self.hostname = hostname
172 self.ldapdir = os.path.join(paths.private_dir, "ldap")
173 self.ldapadminpass = ldapadminpass
175 self.slapd_path = slapd_path
176 self.slapd_command = None
177 self.slapd_command_escaped = None
178 self.slapd_pid = os.path.join(self.ldapdir, "slapd.pid")
180 self.ldap_backend_extra_port = ldap_backend_extra_port
181 self.ldap_dryrun_mode = ldap_dryrun_mode
183 if ldap_backend_forced_uri is not None:
184 self.ldap_uri = ldap_backend_forced_uri
186 self.ldap_uri = "ldapi://%s" % urllib.quote(
187 os.path.join(self.ldapdir, "ldapi"), safe="")
189 if not os.path.exists(self.ldapdir):
190 os.mkdir(self.ldapdir)
193 from samba.provision import ProvisioningError
194 # we will shortly start slapd with ldapi for final provisioning. first
195 # check with ldapsearch -> rootDSE via self.ldap_uri if another
196 # instance of slapd is already running
198 ldapi_db = Ldb(self.ldap_uri)
199 ldapi_db.search(base="", scope=SCOPE_BASE,
200 expression="(objectClass=OpenLDAProotDSE)")
202 f = open(self.slapd_pid, "r")
204 if err != errno.ENOENT:
211 self.logger.info("Check for slapd process with PID: %s and terminate it manually." % p)
212 raise SlapdAlreadyRunning(self.ldap_uri)
214 # XXX: We should never be catching all Ldb errors
217 # Try to print helpful messages when the user has not specified the
219 if self.slapd_path is None:
220 raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
221 if not os.path.exists(self.slapd_path):
222 self.logger.warning("Path (%s) to slapd does not exist!",
225 if not os.path.isdir(self.ldapdir):
226 os.makedirs(self.ldapdir, 0700)
228 # Put the LDIF of the schema into a database so we can search on
229 # it to generate schema-dependent configurations in Fedora DS and
231 schemadb_path = os.path.join(self.ldapdir, "schema-tmp.ldb")
233 os.unlink(schemadb_path)
237 self.schema.write_to_tmp_ldb(schemadb_path)
239 self.credentials = Credentials()
240 self.credentials.guess(self.lp)
241 # Kerberos to an ldapi:// backend makes no sense (we also force EXTERNAL)
242 self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
243 self.credentials.set_username("samba-admin")
244 self.credentials.set_password(self.ldapadminpass)
245 self.credentials.set_forced_sasl_mech("EXTERNAL")
253 from samba.provision import ProvisioningError
254 self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
255 ldap_backend_script = os.path.join(self.ldapdir, "ldap_backend_startup.sh")
256 f = open(ldap_backend_script, 'w')
258 f.write("#!/bin/sh\n" + self.slapd_command_escaped + " $@\n")
262 os.chmod(ldap_backend_script, 0755)
264 # Now start the slapd, so we can provision onto it. We keep the
265 # subprocess context around, to kill this off at the successful
267 self.slapd = subprocess.Popen(self.slapd_provision_command,
268 close_fds=True, shell=False)
271 while self.slapd.poll() is None:
272 # Wait until the socket appears
275 ldapi_db = Ldb(self.ldap_uri, lp=self.lp, credentials=self.credentials)
276 ldapi_db.search(base="", scope=SCOPE_BASE,
277 expression="(objectClass=OpenLDAProotDSE)")
278 # If we have got here, then we must have a valid connection to
285 self.logger.error("Could not connect to slapd started with: %s" % "\'" + "\' \'".join(self.slapd_provision_command) + "\'")
286 raise ProvisioningError("slapd never accepted a connection within 15 seconds of starting")
288 self.logger.error("Could not start slapd with: %s" % "\'" + "\' \'".join(self.slapd_provision_command) + "\'")
289 raise ProvisioningError("slapd died before we could make a connection to it")
292 # if an LDAP backend is in use, terminate slapd after final provision
293 # and check its proper termination
294 if self.slapd.poll() is None:
296 if getattr(self.slapd, "terminate", None) is not None:
297 self.slapd.terminate()
299 # Older python versions don't have .terminate()
301 os.kill(self.slapd.pid, signal.SIGTERM)
303 # and now wait for it to die
304 self.slapd.communicate()
306 def post_setup(self):
307 return LDAPBackendResult(self.slapd_command_escaped,
311 class OpenLDAPBackend(LDAPBackend):
313 def __init__(self, backend_type, paths=None, lp=None,
314 credentials=None, names=None, logger=None, domainsid=None,
315 schema=None, hostname=None, ldapadminpass=None, slapd_path=None,
316 ldap_backend_extra_port=None, ldap_dryrun_mode=False,
317 ol_mmr_urls=None, nosync=False, ldap_backend_forced_uri=None):
318 from samba.provision import setup_path
319 super(OpenLDAPBackend, self).__init__( backend_type=backend_type,
321 names=names, logger=logger,
322 domainsid=domainsid, schema=schema, hostname=hostname,
323 ldapadminpass=ldapadminpass, slapd_path=slapd_path,
324 ldap_backend_extra_port=ldap_backend_extra_port,
325 ldap_backend_forced_uri=ldap_backend_forced_uri,
326 ldap_dryrun_mode=ldap_dryrun_mode)
328 self.ol_mmr_urls = ol_mmr_urls
331 self.slapdconf = os.path.join(self.ldapdir, "slapd.conf")
332 self.modulesconf = os.path.join(self.ldapdir, "modules.conf")
333 self.memberofconf = os.path.join(self.ldapdir, "memberof.conf")
334 self.olmmrserveridsconf = os.path.join(self.ldapdir, "mmr_serverids.conf")
335 self.olmmrsyncreplconf = os.path.join(self.ldapdir, "mmr_syncrepl.conf")
336 self.olcdir = os.path.join(self.ldapdir, "slapd.d")
337 self.olcseedldif = os.path.join(self.ldapdir, "olc_seed.ldif")
339 self.schema = Schema(self.domainsid,
340 schemadn=self.names.schemadn, files=[
341 setup_path("schema_samba4.ldif")])
343 def setup_db_dir(self, dbdir):
344 """Create a database directory.
346 :param dbdir: Database directory.
348 if not os.path.exists(dbdir):
349 os.makedirs(dbdir, 0700)
352 from samba.provision import ProvisioningError, setup_path
353 # Wipe the directories so we can start
354 shutil.rmtree(os.path.join(self.ldapdir, "db"), True)
356 # Allow the test scripts to turn off fsync() for OpenLDAP as for TDB
360 nosync_config = "dbnosync"
362 lnkattr = self.schema.linked_attributes()
363 refint_attributes = ""
364 memberof_config = "# Generated from Samba4 schema\n"
365 for att in lnkattr.keys():
366 if lnkattr[att] is not None:
367 refint_attributes = refint_attributes + " " + att
369 memberof_config += read_and_sub_file(
370 setup_path("memberof.conf"), {
372 "MEMBEROF_ATTR" : lnkattr[att] })
374 refint_config = read_and_sub_file(setup_path("refint.conf"),
375 { "LINK_ATTRS" : refint_attributes})
377 attrs = ["linkID", "lDAPDisplayName"]
378 res = self.schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=self.names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
380 for i in range(0, len(res)):
381 index_attr = res[i]["lDAPDisplayName"][0]
382 if index_attr == "objectGUID":
383 index_attr = "entryUUID"
385 index_config += "index " + index_attr + " eq\n"
387 # generate serverids, ldap-urls and syncrepl-blocks for mmr hosts
389 mmr_replicator_acl = ""
390 mmr_serverids_config = ""
391 mmr_syncrepl_schema_config = ""
392 mmr_syncrepl_config_config = ""
393 mmr_syncrepl_domaindns_config = ""
394 mmr_syncrepl_forestdns_config = ""
395 mmr_syncrepl_user_config = ""
398 if self.ol_mmr_urls is not None:
399 # For now, make these equal
400 mmr_pass = self.ldapadminpass
402 url_list = filter(None,self.ol_mmr_urls.split(','))
404 self.logger.info("Using LDAP-URL: "+url)
405 if len(url_list) == 1:
406 raise ProvisioningError("At least 2 LDAP-URLs needed for MMR!")
408 mmr_on_config = "MirrorMode On"
409 mmr_replicator_acl = " by dn=cn=replicator,cn=samba read"
412 serverid = serverid + 1
413 mmr_serverids_config += read_and_sub_file(
414 setup_path("mmr_serverids.conf"), {
415 "SERVERID": str(serverid),
419 mmr_syncrepl_schema_config += read_and_sub_file(
420 setup_path("mmr_syncrepl.conf"), {
422 "MMRDN": self.names.schemadn,
424 "MMR_PASSWORD": mmr_pass})
427 mmr_syncrepl_config_config += read_and_sub_file(
428 setup_path("mmr_syncrepl.conf"), {
430 "MMRDN": self.names.configdn,
432 "MMR_PASSWORD": mmr_pass})
435 mmr_syncrepl_domaindns_config += read_and_sub_file(
436 setup_path("mmr_syncrepl.conf"), {
438 "MMRDN": "dc=DomainDNSZones," + self.names.domaindn,
440 "MMR_PASSWORD": mmr_pass})
443 mmr_syncrepl_forestdns_config += read_and_sub_file(
444 setup_path("mmr_syncrepl.conf"), {
446 "MMRDN": "dc=ForestDNSZones," + self.names.domaindn,
448 "MMR_PASSWORD": mmr_pass})
451 mmr_syncrepl_user_config += read_and_sub_file(
452 setup_path("mmr_syncrepl.conf"), {
454 "MMRDN": self.names.domaindn,
456 "MMR_PASSWORD": mmr_pass })
457 # OpenLDAP cn=config initialisation
458 olc_syncrepl_config = ""
460 # if mmr = yes, generate cn=config-replication directives
461 # and olc_seed.lif for the other mmr-servers
462 if self.ol_mmr_urls is not None:
464 olc_serverids_config = ""
465 olc_syncrepl_seed_config = ""
466 olc_mmr_config += read_and_sub_file(
467 setup_path("olc_mmr.conf"), {})
470 serverid = serverid + 1
471 olc_serverids_config += read_and_sub_file(
472 setup_path("olc_serverid.conf"), {
473 "SERVERID" : str(serverid), "LDAPSERVER" : url })
476 olc_syncrepl_config += read_and_sub_file(
477 setup_path("olc_syncrepl.conf"), {
478 "RID" : str(rid), "LDAPSERVER" : url,
479 "MMR_PASSWORD": mmr_pass})
481 olc_syncrepl_seed_config += read_and_sub_file(
482 setup_path("olc_syncrepl_seed.conf"), {
483 "RID" : str(rid), "LDAPSERVER" : url})
485 setup_file(setup_path("olc_seed.ldif"), self.olcseedldif,
486 {"OLC_SERVER_ID_CONF": olc_serverids_config,
487 "OLC_PW": self.ldapadminpass,
488 "OLC_SYNCREPL_CONF": olc_syncrepl_seed_config})
491 setup_file(setup_path("slapd.conf"), self.slapdconf,
492 {"DNSDOMAIN": self.names.dnsdomain,
493 "LDAPDIR": self.ldapdir,
494 "DOMAINDN": self.names.domaindn,
495 "CONFIGDN": self.names.configdn,
496 "SCHEMADN": self.names.schemadn,
497 "MEMBEROF_CONFIG": memberof_config,
498 "MIRRORMODE": mmr_on_config,
499 "REPLICATOR_ACL": mmr_replicator_acl,
500 "MMR_SERVERIDS_CONFIG": mmr_serverids_config,
501 "MMR_SYNCREPL_SCHEMA_CONFIG": mmr_syncrepl_schema_config,
502 "MMR_SYNCREPL_CONFIG_CONFIG": mmr_syncrepl_config_config,
503 "MMR_SYNCREPL_DOMAINDNS_CONFIG": mmr_syncrepl_domaindns_config,
504 "MMR_SYNCREPL_FORESTDNS_CONFIG": mmr_syncrepl_forestdns_config,
505 "MMR_SYNCREPL_USER_CONFIG": mmr_syncrepl_user_config,
506 "OLC_SYNCREPL_CONFIG": olc_syncrepl_config,
507 "OLC_MMR_CONFIG": olc_mmr_config,
508 "REFINT_CONFIG": refint_config,
509 "INDEX_CONFIG": index_config,
510 "ADMIN_UID": str(os.getuid()),
511 "NOSYNC": nosync_config,})
513 self.setup_db_dir(os.path.join(self.ldapdir, "db", "forestdns"))
514 self.setup_db_dir(os.path.join(self.ldapdir, "db", "domaindns"))
515 self.setup_db_dir(os.path.join(self.ldapdir, "db", "user"))
516 self.setup_db_dir(os.path.join(self.ldapdir, "db", "config"))
517 self.setup_db_dir(os.path.join(self.ldapdir, "db", "schema"))
518 self.setup_db_dir(os.path.join(self.ldapdir, "db", "samba"))
520 if self.ol_mmr_urls is not None:
525 cn_samba = read_and_sub_file(
526 setup_path("cn=samba.ldif"),
527 { "LDAPADMINPASS": self.ldapadminpass,
528 "MMR_PASSWORD": mmr_pass,
531 mapping = "schema-map-openldap-2.3"
532 backend_schema = "backend-schema.schema"
534 f = open(setup_path(mapping), 'r')
536 backend_schema_data = self.schema.convert_to_openldap(
537 "openldap", f.read())
540 assert backend_schema_data is not None
541 f = open(os.path.join(self.ldapdir, backend_schema), 'w')
543 f.write(backend_schema_data)
547 # now we generate the needed strings to start slapd automatically,
548 if self.ldap_backend_extra_port is not None:
549 # When we use MMR, we can't use 0.0.0.0 as it uses the name
550 # specified there as part of it's clue as to it's own name,
551 # and not to replicate to itself
552 if self.ol_mmr_urls is None:
553 server_port_string = "ldap://0.0.0.0:%d" % self.ldap_backend_extra_port
555 server_port_string = "ldap://%s.%s:%d" (self.names.hostname,
556 self.names.dnsdomain, self.ldap_backend_extra_port)
558 server_port_string = ""
560 # Prepare the 'result' information - the commands to return in
562 self.slapd_provision_command = [self.slapd_path, "-F" + self.olcdir,
565 # copy this command so we have two version, one with -d0 and only
566 # ldapi (or the forced ldap_uri), and one with all the listen commands
567 self.slapd_command = list(self.slapd_provision_command)
569 self.slapd_provision_command.extend([self.ldap_uri, "-d0"])
571 if server_port_string is not "":
572 uris = uris + " " + server_port_string
574 self.slapd_command.append(uris)
576 # Wipe the old sam.ldb databases away
577 shutil.rmtree(self.olcdir, True)
578 os.makedirs(self.olcdir, 0770)
580 # If we were just looking for crashes up to this point, it's a
581 # good time to exit before we realise we don't have OpenLDAP on
583 if self.ldap_dryrun_mode:
586 slapd_cmd = [self.slapd_path, "-Ttest", "-n", "0", "-f",
587 self.slapdconf, "-F", self.olcdir]
588 retcode = subprocess.call(slapd_cmd, close_fds=True, shell=False)
591 self.logger.error("conversion from slapd.conf to cn=config failed slapd started with: %s" % "\'" + "\' \'".join(slapd_cmd) + "\'")
592 raise ProvisioningError("conversion from slapd.conf to cn=config failed")
594 if not os.path.exists(os.path.join(self.olcdir, "cn=config.ldif")):
595 raise ProvisioningError("conversion from slapd.conf to cn=config failed")
597 # Don't confuse the admin by leaving the slapd.conf around
598 os.remove(self.slapdconf)
600 cn_samba_cmd = [self.slapd_path, "-Tadd", "-b", "cn=samba", "-F", self.olcdir]
601 p = subprocess.Popen(cn_samba_cmd, stdin=subprocess.PIPE, shell=False)
602 p.stdin.write(cn_samba)
606 class FDSBackend(LDAPBackend):
608 def __init__(self, backend_type, paths=None, lp=None,
609 names=None, logger=None, domainsid=None,
610 schema=None, hostname=None, ldapadminpass=None, slapd_path=None,
611 ldap_backend_extra_port=None, ldap_dryrun_mode=False, root=None,
614 from samba.provision import setup_path
616 super(FDSBackend, self).__init__(backend_type=backend_type,
618 names=names, logger=logger,
619 domainsid=domainsid, schema=schema, hostname=hostname,
620 ldapadminpass=ldapadminpass, slapd_path=slapd_path,
621 ldap_backend_extra_port=ldap_backend_extra_port,
622 ldap_backend_forced_uri=ldap_backend_forced_uri,
623 ldap_dryrun_mode=ldap_dryrun_mode)
626 self.setup_ds_path = setup_ds_path
627 self.ldap_instance = self.names.netbiosname.lower()
629 self.sambadn = "CN=Samba"
631 self.fedoradsinf = os.path.join(self.ldapdir, "fedorads.inf")
632 self.partitions_ldif = os.path.join(self.ldapdir,
633 "fedorads-partitions.ldif")
634 self.sasl_ldif = os.path.join(self.ldapdir, "fedorads-sasl.ldif")
635 self.dna_ldif = os.path.join(self.ldapdir, "fedorads-dna.ldif")
636 self.pam_ldif = os.path.join(self.ldapdir, "fedorads-pam.ldif")
637 self.refint_ldif = os.path.join(self.ldapdir, "fedorads-refint.ldif")
638 self.linked_attrs_ldif = os.path.join(self.ldapdir,
639 "fedorads-linked-attributes.ldif")
640 self.index_ldif = os.path.join(self.ldapdir, "fedorads-index.ldif")
641 self.samba_ldif = os.path.join(self.ldapdir, "fedorads-samba.ldif")
643 self.samba3_schema = setup_path(
644 "../../examples/LDAP/samba.schema")
645 self.samba3_ldif = os.path.join(self.ldapdir, "samba3.ldif")
647 self.retcode = subprocess.call(["bin/oLschema2ldif",
648 "-I", self.samba3_schema,
649 "-O", self.samba3_ldif,
650 "-b", self.names.domaindn],
651 close_fds=True, shell=False)
653 if self.retcode != 0:
654 raise Exception("Unable to convert Samba 3 schema.")
656 self.schema = Schema(
658 schemadn=self.names.schemadn,
659 files=[setup_path("schema_samba4.ldif"), self.samba3_ldif],
660 additional_prefixmap=["1000:1.3.6.1.4.1.7165.2.1",
661 "1001:1.3.6.1.4.1.7165.2.2"])
664 from samba.provision import ProvisioningError, setup_path
665 if self.ldap_backend_extra_port is not None:
666 serverport = "ServerPort=%d" % self.ldap_backend_extra_port
670 setup_file(setup_path("fedorads.inf"), self.fedoradsinf,
672 "HOSTNAME": self.hostname,
673 "DNSDOMAIN": self.names.dnsdomain,
674 "LDAPDIR": self.ldapdir,
675 "DOMAINDN": self.names.domaindn,
676 "LDAP_INSTANCE": self.ldap_instance,
677 "LDAPMANAGERDN": self.names.ldapmanagerdn,
678 "LDAPMANAGERPASS": self.ldapadminpass,
679 "SERVERPORT": serverport})
681 setup_file(setup_path("fedorads-partitions.ldif"),
682 self.partitions_ldif,
683 {"CONFIGDN": self.names.configdn,
684 "SCHEMADN": self.names.schemadn,
685 "SAMBADN": self.sambadn,
688 setup_file(setup_path("fedorads-sasl.ldif"), self.sasl_ldif,
689 {"SAMBADN": self.sambadn,
692 setup_file(setup_path("fedorads-dna.ldif"), self.dna_ldif,
693 {"DOMAINDN": self.names.domaindn,
694 "SAMBADN": self.sambadn,
695 "DOMAINSID": str(self.domainsid),
698 setup_file(setup_path("fedorads-pam.ldif"), self.pam_ldif)
700 lnkattr = self.schema.linked_attributes()
702 f = open(setup_path("fedorads-refint-delete.ldif"), 'r')
704 refint_config = f.read()
711 for attr in lnkattr.keys():
712 if lnkattr[attr] is not None:
713 refint_config += read_and_sub_file(
714 setup_path("fedorads-refint-add.ldif"),
715 { "ARG_NUMBER" : str(argnum),
716 "LINK_ATTR" : attr })
717 memberof_config += read_and_sub_file(
718 setup_path("fedorads-linked-attributes.ldif"),
719 { "MEMBER_ATTR" : attr,
720 "MEMBEROF_ATTR" : lnkattr[attr] })
721 index_config += read_and_sub_file(
722 setup_path("fedorads-index.ldif"), { "ATTR" : attr })
725 f = open(self.refint_ldif, 'w')
727 f.write(refint_config)
730 f = open(self.linked_attrs_ldif, 'w')
732 f.write(memberof_config)
736 attrs = ["lDAPDisplayName"]
737 res = self.schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=self.names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
739 for i in range(0, len(res)):
740 attr = res[i]["lDAPDisplayName"][0]
742 if attr == "objectGUID":
745 index_config += read_and_sub_file(
746 setup_path("fedorads-index.ldif"), { "ATTR" : attr })
748 f = open(self.index_ldif, 'w')
750 f.write(index_config)
754 setup_file(setup_path("fedorads-samba.ldif"), self.samba_ldif, {
755 "SAMBADN": self.sambadn,
756 "LDAPADMINPASS": self.ldapadminpass
759 mapping = "schema-map-fedora-ds-1.0"
760 backend_schema = "99_ad.ldif"
762 # Build a schema file in Fedora DS format
763 f = open(setup_path(mapping), 'r')
765 backend_schema_data = self.schema.convert_to_openldap("fedora-ds",
769 assert backend_schema_data is not None
770 f = open(os.path.join(self.ldapdir, backend_schema), 'w')
772 f.write(backend_schema_data)
776 self.credentials.set_bind_dn(self.names.ldapmanagerdn)
778 # Destory the target directory, or else setup-ds.pl will complain
779 fedora_ds_dir = os.path.join(self.ldapdir,
780 "slapd-" + self.ldap_instance)
781 shutil.rmtree(fedora_ds_dir, True)
783 self.slapd_provision_command = [self.slapd_path, "-D", fedora_ds_dir,
784 "-i", self.slapd_pid]
785 # In the 'provision' command line, stay in the foreground so we can
787 self.slapd_provision_command.append("-d0")
789 #the command for the final run is the normal script
790 self.slapd_command = [os.path.join(self.ldapdir,
791 "slapd-" + self.ldap_instance, "start-slapd")]
793 # If we were just looking for crashes up to this point, it's a
794 # good time to exit before we realise we don't have Fedora DS on
795 if self.ldap_dryrun_mode:
798 # Try to print helpful messages when the user has not specified the
799 # path to the setup-ds tool
800 if self.setup_ds_path is None:
801 raise ProvisioningError("Fedora DS LDAP-Backend must be setup with path to setup-ds, e.g. --setup-ds-path=\"/usr/sbin/setup-ds.pl\"!")
802 if not os.path.exists(self.setup_ds_path):
803 self.logger.warning("Path (%s) to slapd does not exist!",
806 # Run the Fedora DS setup utility
807 retcode = subprocess.call([self.setup_ds_path, "--silent", "--file",
808 self.fedoradsinf], close_fds=True, shell=False)
810 raise ProvisioningError("setup-ds failed")
813 retcode = subprocess.call([
814 os.path.join(self.ldapdir, "slapd-" + self.ldap_instance, "ldif2db"), "-s", self.sambadn, "-i", self.samba_ldif],
815 close_fds=True, shell=False)
817 raise ProvisioningError("ldif2db failed")
819 def post_setup(self):
820 ldapi_db = Ldb(self.ldap_uri, credentials=self.credentials)
822 # configure in-directory access control on Fedora DS via the aci
823 # attribute (over a direct ldapi:// socket)
824 aci = """(targetattr = "*") (version 3.0;acl "full access to all by samba-admin";allow (all)(userdn = "ldap:///CN=samba-admin,%s");)""" % self.sambadn
827 m["aci"] = ldb.MessageElement([aci], ldb.FLAG_MOD_REPLACE, "aci")
829 for dnstring in (self.names.domaindn, self.names.configdn,
830 self.names.schemadn):
831 m.dn = ldb.Dn(ldapi_db, dnstring)
833 return LDAPBackendResult(self.credentials, self.slapd_command_escaped,