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
37 from samba import read_and_sub_file
40 from ldb import SCOPE_BASE, SCOPE_ONELEVEL, LdbError, timestring
41 from credentials import Credentials, DONT_USE_KERBEROS
42 from samba import setup_file
44 def setup_db_config(setup_path, dbdir):
45 """Setup a Berkeley database.
47 :param setup_path: Setup path function.
48 :param dbdir: Database directory."""
49 if not os.path.isdir(os.path.join(dbdir, "bdb-logs")):
50 os.makedirs(os.path.join(dbdir, "bdb-logs"), 0700)
51 if not os.path.isdir(os.path.join(dbdir, "tmp")):
52 os.makedirs(os.path.join(dbdir, "tmp"), 0700)
54 setup_file(setup_path("DB_CONFIG"), os.path.join(dbdir, "DB_CONFIG"),
57 class ProvisionBackend(object):
58 def __init__(self, backend_type, paths=None, setup_path=None, lp=None, credentials=None,
59 names=None, message=None,
60 hostname=None, root=None,
61 schema=None, ldapadminpass=None,
62 ldap_backend_extra_port=None,
64 setup_ds_path=None, slapd_path=None,
65 nosync=False, ldap_dryrun_mode=False,
67 """Provision an LDAP backend for samba4
69 This works for OpenLDAP and Fedora DS
72 self.setup_path = setup_path
73 self.slapd_command = None
74 self.slapd_command_escaped = None
77 self.message = message
78 self.hostname = hostname
81 self.ldapadminpass = ldapadminpass
82 self.ldap_backend_extra_port = ldap_backend_extra_port
83 self.ol_mmr_urls = ol_mmr_urls
84 self.setup_ds_path = setup_ds_path
85 self.slapd_path = slapd_path
87 self.ldap_dryrun_mode = ldap_dryrun_mode
88 self.domainsid = domainsid
90 self.type = backend_type
92 # Set a default - the code for "existing" below replaces this
93 self.ldap_backend_type = backend_type
95 if self.type is "ldb":
96 self.credentials = None
97 self.secrets_credentials = None
99 # Wipe the old sam.ldb databases away
100 shutil.rmtree(paths.samdb + ".d", True)
103 self.ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.ldapdir, "ldapi"), safe="")
105 if self.type == "existing":
106 #Check to see that this 'existing' LDAP backend in fact exists
107 ldapi_db = Ldb(self.ldapi_uri, credentials=credentials)
108 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
109 expression="(objectClass=OpenLDAProotDSE)")
111 # If we have got here, then we must have a valid connection to the LDAP server, with valid credentials supplied
112 self.credentials = credentials
113 # This caused them to be set into the long-term database later in the script.
114 self.secrets_credentials = credentials
116 self.ldap_backend_type = "openldap" #For now, assume existing backends at least emulate OpenLDAP
119 # we will shortly start slapd with ldapi for final provisioning. first check with ldapsearch -> rootDSE via self.ldapi_uri
120 # if another instance of slapd is already running
122 ldapi_db = Ldb(self.ldapi_uri)
123 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
124 expression="(objectClass=OpenLDAProotDSE)");
126 f = open(paths.slapdpid, "r")
129 message("Check for slapd Process with PID: " + str(p) + " and terminate it manually.")
133 raise ProvisioningError("Warning: Another slapd Instance seems already running on this host, listening to " + self.ldapi_uri + ". Please shut it down before you continue. ")
138 # Try to print helpful messages when the user has not specified the path to slapd
139 if slapd_path is None:
140 raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
141 if not os.path.exists(slapd_path):
143 raise ProvisioningError("Warning: Given Path to slapd does not exist!")
146 if not os.path.isdir(paths.ldapdir):
147 os.makedirs(paths.ldapdir, 0700)
149 # Put the LDIF of the schema into a database so we can search on
150 # it to generate schema-dependent configurations in Fedora DS and
152 schemadb_path = os.path.join(paths.ldapdir, "schema-tmp.ldb")
154 os.unlink(schemadb_path)
158 schema.write_to_tmp_ldb(schemadb_path);
160 self.credentials = Credentials()
161 self.credentials.guess(lp)
162 #Kerberos to an ldapi:// backend makes no sense
163 self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
164 self.credentials.set_password(ldapadminpass)
166 self.secrets_credentials = Credentials()
167 self.secrets_credentials.guess(lp)
168 #Kerberos to an ldapi:// backend makes no sense
169 self.secrets_credentials.set_kerberos_state(DONT_USE_KERBEROS)
170 self.secrets_credentials.set_username("samba-admin")
171 self.secrets_credentials.set_password(ldapadminpass)
182 def post_setup(self):
186 class LDAPBackend(ProvisionBackend):
188 self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
189 setup_file(self.setup_path("ldap_backend_startup.sh"), self.paths.ldapdir + "/ldap_backend_startup.sh", {
190 "SLAPD_COMMAND" : self.slapd_command_escaped})
192 # Now start the slapd, so we can provision onto it. We keep the
193 # subprocess context around, to kill this off at the successful
195 self.slapd = subprocess.Popen(self.slapd_provision_command, close_fds=True, shell=False)
197 while self.slapd.poll() is None:
198 # Wait until the socket appears
200 ldapi_db = Ldb(self.ldapi_uri, lp=self.lp, credentials=self.credentials)
201 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
202 expression="(objectClass=OpenLDAProotDSE)")
203 # If we have got here, then we must have a valid connection to the LDAP server!
209 raise ProvisioningError("slapd died before we could make a connection to it")
212 # if an LDAP backend is in use, terminate slapd after final provision and check its proper termination
213 if self.slapd.poll() is None:
215 if hasattr(self.slapd, "terminate"):
216 self.slapd.terminate()
218 # Older python versions don't have .terminate()
220 os.kill(self.slapd.pid, signal.SIGTERM)
222 #and now wait for it to die
223 self.slapd.communicate()
226 class OpenLDAPBackend(LDAPBackend):
228 # Wipe the directories so we can start
229 shutil.rmtree(os.path.join(self.paths.ldapdir, "db"), True)
231 #Allow the test scripts to turn off fsync() for OpenLDAP as for TDB and LDB
234 nosync_config = "dbnosync"
236 lnkattr = self.schema.linked_attributes()
237 refint_attributes = ""
238 memberof_config = "# Generated from Samba4 schema\n"
239 for att in lnkattr.keys():
240 if lnkattr[att] is not None:
241 refint_attributes = refint_attributes + " " + att
243 memberof_config += read_and_sub_file(self.setup_path("memberof.conf"),
244 { "MEMBER_ATTR" : att ,
245 "MEMBEROF_ATTR" : lnkattr[att] })
247 refint_config = read_and_sub_file(self.setup_path("refint.conf"),
248 { "LINK_ATTRS" : refint_attributes})
250 attrs = ["linkID", "lDAPDisplayName"]
251 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)
253 for i in range (0, len(res)):
254 index_attr = res[i]["lDAPDisplayName"][0]
255 if index_attr == "objectGUID":
256 index_attr = "entryUUID"
258 index_config += "index " + index_attr + " eq\n"
260 # generate serverids, ldap-urls and syncrepl-blocks for mmr hosts
262 mmr_replicator_acl = ""
263 mmr_serverids_config = ""
264 mmr_syncrepl_schema_config = ""
265 mmr_syncrepl_config_config = ""
266 mmr_syncrepl_user_config = ""
269 if self.ol_mmr_urls is not None:
270 # For now, make these equal
271 mmr_pass = self.ldapadminpass
273 url_list=filter(None,self.ol_mmr_urls.split(' '))
274 if (len(url_list) == 1):
275 url_list=filter(None,self.ol_mmr_urls.split(','))
278 mmr_on_config = "MirrorMode On"
279 mmr_replicator_acl = " by dn=cn=replicator,cn=samba read"
283 mmr_serverids_config += read_and_sub_file(self.setup_path("mmr_serverids.conf"),
284 { "SERVERID" : str(serverid),
285 "LDAPSERVER" : url })
288 mmr_syncrepl_schema_config += read_and_sub_file(self.setup_path("mmr_syncrepl.conf"),
290 "MMRDN": self.names.schemadn,
292 "MMR_PASSWORD": mmr_pass})
295 mmr_syncrepl_config_config += read_and_sub_file(self.setup_path("mmr_syncrepl.conf"),
297 "MMRDN": self.names.configdn,
299 "MMR_PASSWORD": mmr_pass})
302 mmr_syncrepl_user_config += read_and_sub_file(self.setup_path("mmr_syncrepl.conf"),
304 "MMRDN": self.names.domaindn,
306 "MMR_PASSWORD": mmr_pass })
307 # OpenLDAP cn=config initialisation
308 olc_syncrepl_config = ""
310 # if mmr = yes, generate cn=config-replication directives
311 # and olc_seed.lif for the other mmr-servers
312 if self.ol_mmr_urls is not None:
314 olc_serverids_config = ""
315 olc_syncrepl_seed_config = ""
316 olc_mmr_config += read_and_sub_file(self.setup_path("olc_mmr.conf"),{})
320 olc_serverids_config += read_and_sub_file(self.setup_path("olc_serverid.conf"),
321 { "SERVERID" : str(serverid),
322 "LDAPSERVER" : url })
325 olc_syncrepl_config += read_and_sub_file(self.setup_path("olc_syncrepl.conf"),
328 "MMR_PASSWORD": mmr_pass})
330 olc_syncrepl_seed_config += read_and_sub_file(self.setup_path("olc_syncrepl_seed.conf"),
334 setup_file(self.setup_path("olc_seed.ldif"), self.paths.olcseedldif,
335 {"OLC_SERVER_ID_CONF": olc_serverids_config,
336 "OLC_PW": self.ldapadminpass,
337 "OLC_SYNCREPL_CONF": olc_syncrepl_seed_config})
340 setup_file(self.setup_path("slapd.conf"), self.paths.slapdconf,
341 {"DNSDOMAIN": self.names.dnsdomain,
342 "LDAPDIR": self.paths.ldapdir,
343 "DOMAINDN": self.names.domaindn,
344 "CONFIGDN": self.names.configdn,
345 "SCHEMADN": self.names.schemadn,
346 "MEMBEROF_CONFIG": memberof_config,
347 "MIRRORMODE": mmr_on_config,
348 "REPLICATOR_ACL": mmr_replicator_acl,
349 "MMR_SERVERIDS_CONFIG": mmr_serverids_config,
350 "MMR_SYNCREPL_SCHEMA_CONFIG": mmr_syncrepl_schema_config,
351 "MMR_SYNCREPL_CONFIG_CONFIG": mmr_syncrepl_config_config,
352 "MMR_SYNCREPL_USER_CONFIG": mmr_syncrepl_user_config,
353 "OLC_SYNCREPL_CONFIG": olc_syncrepl_config,
354 "OLC_MMR_CONFIG": olc_mmr_config,
355 "REFINT_CONFIG": refint_config,
356 "INDEX_CONFIG": index_config,
357 "NOSYNC": nosync_config})
359 setup_db_config(self.setup_path, os.path.join(self.paths.ldapdir, "db", "user"))
360 setup_db_config(self.setup_path, os.path.join(self.paths.ldapdir, "db", "config"))
361 setup_db_config(self.setup_path, os.path.join(self.paths.ldapdir, "db", "schema"))
363 if not os.path.exists(os.path.join(self.paths.ldapdir, "db", "samba", "cn=samba")):
364 os.makedirs(os.path.join(self.paths.ldapdir, "db", "samba", "cn=samba"), 0700)
366 setup_file(self.setup_path("cn=samba.ldif"),
367 os.path.join(self.paths.ldapdir, "db", "samba", "cn=samba.ldif"),
368 { "UUID": str(uuid.uuid4()),
369 "LDAPTIME": timestring(int(time.time()))} )
370 setup_file(self.setup_path("cn=samba-admin.ldif"),
371 os.path.join(self.paths.ldapdir, "db", "samba", "cn=samba", "cn=samba-admin.ldif"),
372 {"LDAPADMINPASS_B64": b64encode(self.ldapadminpass),
373 "UUID": str(uuid.uuid4()),
374 "LDAPTIME": timestring(int(time.time()))} )
376 if self.ol_mmr_urls is not None:
377 setup_file(self.setup_path("cn=replicator.ldif"),
378 os.path.join(self.paths.ldapdir, "db", "samba", "cn=samba", "cn=replicator.ldif"),
379 {"MMR_PASSWORD_B64": b64encode(mmr_pass),
380 "UUID": str(uuid.uuid4()),
381 "LDAPTIME": timestring(int(time.time()))} )
384 mapping = "schema-map-openldap-2.3"
385 backend_schema = "backend-schema.schema"
387 backend_schema_data = self.schema.ldb.convert_schema_to_openldap("openldap", open(self.setup_path(mapping), 'r').read())
388 assert backend_schema_data is not None
389 open(os.path.join(self.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
391 # now we generate the needed strings to start slapd automatically,
393 if self.ldap_backend_extra_port is not None:
394 # When we use MMR, we can't use 0.0.0.0 as it uses the name
395 # specified there as part of it's clue as to it's own name,
396 # and not to replicate to itself
397 if self.ol_mmr_urls is None:
398 server_port_string = "ldap://0.0.0.0:%d" % self.ldap_backend_extra_port
400 server_port_string = "ldap://" + self.names.hostname + "." + self.names.dnsdomain +":%d" % self.ldap_backend_extra_port
402 server_port_string = ""
404 # Prepare the 'result' information - the commands to return in particular
405 self.slapd_provision_command = [self.slapd_path]
407 self.slapd_provision_command.append("-F" + self.paths.olcdir)
409 self.slapd_provision_command.append("-h")
411 # copy this command so we have two version, one with -d0 and only ldapi, and one with all the listen commands
412 self.slapd_command = list(self.slapd_provision_command)
414 self.slapd_provision_command.append(self.ldapi_uri)
415 self.slapd_provision_command.append("-d0")
417 uris = self.ldapi_uri
418 if server_port_string is not "":
419 uris = uris + " " + server_port_string
421 self.slapd_command.append(uris)
423 # Set the username - done here because Fedora DS still uses the admin DN and simple bind
424 self.credentials.set_username("samba-admin")
426 # If we were just looking for crashes up to this point, it's a
427 # good time to exit before we realise we don't have OpenLDAP on
429 if self.ldap_dryrun_mode:
432 # Finally, convert the configuration into cn=config style!
433 if not os.path.isdir(self.paths.olcdir):
434 os.makedirs(self.paths.olcdir, 0770)
436 retcode = subprocess.call([self.slapd_path, "-Ttest", "-f", self.paths.slapdconf, "-F", self.paths.olcdir], close_fds=True, shell=False)
438 # We can't do this, as OpenLDAP is strange. It gives an error
439 # output to the above, but does the conversion sucessfully...
442 # raise ProvisioningError("conversion from slapd.conf to cn=config failed")
444 if not os.path.exists(os.path.join(self.paths.olcdir, "cn=config.ldif")):
445 raise ProvisioningError("conversion from slapd.conf to cn=config failed")
447 # Don't confuse the admin by leaving the slapd.conf around
448 os.remove(self.paths.slapdconf)
451 class FDSBackend(LDAPBackend):
453 if self.ldap_backend_extra_port is not None:
454 serverport = "ServerPort=%d" % self.ldap_backend_extra_port
458 setup_file(self.setup_path("fedorads.inf"), self.paths.fedoradsinf,
460 "HOSTNAME": self.hostname,
461 "DNSDOMAIN": self.names.dnsdomain,
462 "LDAPDIR": self.paths.ldapdir,
463 "DOMAINDN": self.names.domaindn,
464 "LDAPMANAGERDN": self.names.ldapmanagerdn,
465 "LDAPMANAGERPASS": self.ldapadminpass,
466 "SERVERPORT": serverport})
468 setup_file(self.setup_path("fedorads-partitions.ldif"), self.paths.fedoradspartitions,
469 {"CONFIGDN": self.names.configdn,
470 "SCHEMADN": self.names.schemadn,
471 "SAMBADN": self.names.sambadn,
474 setup_file(self.setup_path("fedorads-sasl.ldif"), self.paths.fedoradssasl,
475 {"SAMBADN": self.names.sambadn,
478 setup_file(self.setup_path("fedorads-dna.ldif"), self.paths.fedoradsdna,
479 {"DOMAINDN": self.names.domaindn,
480 "SAMBADN": self.names.sambadn,
481 "DOMAINSID": str(self.domainsid),
484 setup_file(self.setup_path("fedorads-pam.ldif"), self.paths.fedoradspam)
486 lnkattr = self.schema.linked_attributes()
488 refint_config = data = open(self.setup_path("fedorads-refint-delete.ldif"), 'r').read()
493 for attr in lnkattr.keys():
494 if lnkattr[attr] is not None:
495 refint_config += read_and_sub_file(self.setup_path("fedorads-refint-add.ldif"),
496 { "ARG_NUMBER" : str(argnum) ,
497 "LINK_ATTR" : attr })
498 memberof_config += read_and_sub_file(self.setup_path("fedorads-linked-attributes.ldif"),
499 { "MEMBER_ATTR" : attr ,
500 "MEMBEROF_ATTR" : lnkattr[attr] })
501 index_config += read_and_sub_file(self.setup_path("fedorads-index.ldif"),
505 open(self.paths.fedoradsrefint, 'w').write(refint_config)
506 open(self.paths.fedoradslinkedattributes, 'w').write(memberof_config)
508 attrs = ["lDAPDisplayName"]
509 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)
511 for i in range (0, len(res)):
512 attr = res[i]["lDAPDisplayName"][0]
514 if attr == "objectGUID":
517 index_config += read_and_sub_file(self.setup_path("fedorads-index.ldif"),
520 open(self.paths.fedoradsindex, 'w').write(index_config)
522 setup_file(self.setup_path("fedorads-samba.ldif"), self.paths.fedoradssamba,
523 {"SAMBADN": self.names.sambadn,
524 "LDAPADMINPASS": self.ldapadminpass
527 mapping = "schema-map-fedora-ds-1.0"
528 backend_schema = "99_ad.ldif"
530 # Build a schema file in Fedora DS format
531 backend_schema_data = self.schema.ldb.convert_schema_to_openldap("fedora-ds", open(self.setup_path(mapping), 'r').read())
532 assert backend_schema_data is not None
533 open(os.path.join(self.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
535 self.credentials.set_bind_dn(self.names.ldapmanagerdn)
537 # Destory the target directory, or else setup-ds.pl will complain
538 fedora_ds_dir = os.path.join(self.paths.ldapdir, "slapd-samba4")
539 shutil.rmtree(fedora_ds_dir, True)
541 self.slapd_provision_command = [self.slapd_path, "-D", fedora_ds_dir, "-i", self.paths.slapdpid];
542 #In the 'provision' command line, stay in the foreground so we can easily kill it
543 self.slapd_provision_command.append("-d0")
545 #the command for the final run is the normal script
546 self.slapd_command = [os.path.join(self.paths.ldapdir, "slapd-samba4", "start-slapd")]
548 # If we were just looking for crashes up to this point, it's a
549 # good time to exit before we realise we don't have Fedora DS on
550 if self.ldap_dryrun_mode:
553 # Try to print helpful messages when the user has not specified the path to the setup-ds tool
554 if self.setup_ds_path is None:
555 raise ProvisioningError("Warning: Fedora DS LDAP-Backend must be setup with path to setup-ds, e.g. --setup-ds-path=\"/usr/sbin/setup-ds.pl\"!")
556 if not os.path.exists(self.setup_ds_path):
557 self.message (self.setup_ds_path)
558 raise ProvisioningError("Warning: Given Path to slapd does not exist!")
560 # Run the Fedora DS setup utility
561 retcode = subprocess.call([self.setup_ds_path, "--silent", "--file", self.paths.fedoradsinf], close_fds=True, shell=False)
563 raise ProvisioningError("setup-ds failed")
566 retcode = subprocess.call([
567 os.path.join(self.paths.ldapdir, "slapd-samba4", "ldif2db"), "-s", self.names.sambadn, "-i", self.paths.fedoradssamba],
568 close_fds=True, shell=False)
570 raise("ldib2db failed")
572 def post_setup(self):
573 ldapi_db = Ldb(self.ldapi_uri, credentials=self.credentials)
575 # delete default SASL mappings
576 res = ldapi_db.search(expression="(!(cn=samba-admin mapping))", base="cn=mapping,cn=sasl,cn=config", scope=SCOPE_ONELEVEL, attrs=["dn"])
578 # configure in-directory access control on Fedora DS via the aci attribute (over a direct ldapi:// socket)
579 for i in range (0, len(res)):
580 dn = str(res[i]["dn"])
583 aci = """(targetattr = "*") (version 3.0;acl "full access to all by samba-admin";allow (all)(userdn = "ldap:///CN=samba-admin,%s");)""" % self.names.sambadn
586 m["aci"] = ldb.MessageElement([aci], ldb.FLAG_MOD_REPLACE, "aci")
588 m.dn = ldb.Dn(1, self.names.domaindn)
591 m.dn = ldb.Dn(1, self.names.configdn)
594 m.dn = ldb.Dn(1, self.names.schemadn)