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.slapd_command = None
73 self.slapd_command_escaped = None
76 self.type = backend_type
78 # Set a default - the code for "existing" below replaces this
79 self.ldap_backend_type = backend_type
81 if self.type is "ldb":
82 self.credentials = None
83 self.secrets_credentials = None
85 # Wipe the old sam.ldb databases away
86 shutil.rmtree(paths.samdb + ".d", True)
89 self.ldapi_uri = "ldapi://" + urllib.quote(os.path.join(paths.ldapdir, "ldapi"), safe="")
91 if self.type == "existing":
92 #Check to see that this 'existing' LDAP backend in fact exists
93 ldapi_db = Ldb(self.ldapi_uri, credentials=credentials)
94 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
95 expression="(objectClass=OpenLDAProotDSE)")
97 # If we have got here, then we must have a valid connection to the LDAP server, with valid credentials supplied
98 self.credentials = credentials
99 # This caused them to be set into the long-term database later in the script.
100 self.secrets_credentials = credentials
102 self.ldap_backend_type = "openldap" #For now, assume existing backends at least emulate OpenLDAP
105 # we will shortly start slapd with ldapi for final provisioning. first check with ldapsearch -> rootDSE via self.ldapi_uri
106 # if another instance of slapd is already running
108 ldapi_db = Ldb(self.ldapi_uri)
109 search_ol_rootdse = ldapi_db.search(base="", scope=SCOPE_BASE,
110 expression="(objectClass=OpenLDAProotDSE)");
112 f = open(paths.slapdpid, "r")
115 message("Check for slapd Process with PID: " + str(p) + " and terminate it manually.")
119 raise ProvisioningError("Warning: Another slapd Instance seems already running on this host, listening to " + self.ldapi_uri + ". Please shut it down before you continue. ")
124 # Try to print helpful messages when the user has not specified the path to slapd
125 if slapd_path is None:
126 raise ProvisioningError("Warning: LDAP-Backend must be setup with path to slapd, e.g. --slapd-path=\"/usr/local/libexec/slapd\"!")
127 if not os.path.exists(slapd_path):
129 raise ProvisioningError("Warning: Given Path to slapd does not exist!")
132 if not os.path.isdir(paths.ldapdir):
133 os.makedirs(paths.ldapdir, 0700)
135 # Put the LDIF of the schema into a database so we can search on
136 # it to generate schema-dependent configurations in Fedora DS and
138 schemadb_path = os.path.join(paths.ldapdir, "schema-tmp.ldb")
140 os.unlink(schemadb_path)
144 schema.write_to_tmp_ldb(schemadb_path);
146 self.credentials = Credentials()
147 self.credentials.guess(lp)
148 #Kerberos to an ldapi:// backend makes no sense
149 self.credentials.set_kerberos_state(DONT_USE_KERBEROS)
151 self.secrets_credentials = Credentials()
152 self.secrets_credentials.guess(lp)
153 #Kerberos to an ldapi:// backend makes no sense
154 self.secrets_credentials.set_kerberos_state(DONT_USE_KERBEROS)
157 if self.type == "fedora-ds":
158 provision_fds_backend(self, setup_path=setup_path,
159 names=names, message=message,
161 ldapadminpass=ldapadminpass, root=root,
163 ldap_backend_extra_port=ldap_backend_extra_port,
164 setup_ds_path=setup_ds_path,
165 slapd_path=slapd_path,
167 ldap_dryrun_mode=ldap_dryrun_mode,
170 elif self.type == "openldap":
171 provision_openldap_backend(self, setup_path=setup_path,
172 names=names, message=message,
174 ldapadminpass=ldapadminpass, root=root,
176 ldap_backend_extra_port=ldap_backend_extra_port,
177 ol_mmr_urls=ol_mmr_urls,
178 slapd_path=slapd_path,
180 ldap_dryrun_mode=ldap_dryrun_mode)
182 raise ProvisioningError("Unknown LDAP backend type selected")
184 self.credentials.set_password(ldapadminpass)
185 self.secrets_credentials.set_username("samba-admin")
186 self.secrets_credentials.set_password(ldapadminpass)
188 self.slapd_command_escaped = "\'" + "\' \'".join(self.slapd_command) + "\'"
189 setup_file(setup_path("ldap_backend_startup.sh"), 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=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")
214 def post_setup(self):
218 class LDAPBackend(ProvisionBackend):
220 # if an LDAP backend is in use, terminate slapd after final provision and check its proper termination
221 if self.slapd.poll() is None:
223 if hasattr(self.slapd, "terminate"):
224 self.slapd.terminate()
226 # Older python versions don't have .terminate()
228 os.kill(self.slapd.pid, signal.SIGTERM)
230 #and now wait for it to die
231 self.slapd.communicate()
234 class OpenLDAPBackend(LDAPBackend):
237 def provision_openldap_backend(result, setup_path=None, names=None,
239 hostname=None, ldapadminpass=None, root=None,
241 ldap_backend_extra_port=None,
243 slapd_path=None, nosync=False,
244 ldap_dryrun_mode=False):
246 # Wipe the directories so we can start
247 shutil.rmtree(os.path.join(result.paths.ldapdir, "db"), True)
249 #Allow the test scripts to turn off fsync() for OpenLDAP as for TDB and LDB
252 nosync_config = "dbnosync"
254 lnkattr = schema.linked_attributes()
255 refint_attributes = ""
256 memberof_config = "# Generated from Samba4 schema\n"
257 for att in lnkattr.keys():
258 if lnkattr[att] is not None:
259 refint_attributes = refint_attributes + " " + att
261 memberof_config += read_and_sub_file(setup_path("memberof.conf"),
262 { "MEMBER_ATTR" : att ,
263 "MEMBEROF_ATTR" : lnkattr[att] })
265 refint_config = read_and_sub_file(setup_path("refint.conf"),
266 { "LINK_ATTRS" : refint_attributes})
268 attrs = ["linkID", "lDAPDisplayName"]
269 res = schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
271 for i in range (0, len(res)):
272 index_attr = res[i]["lDAPDisplayName"][0]
273 if index_attr == "objectGUID":
274 index_attr = "entryUUID"
276 index_config += "index " + index_attr + " eq\n"
278 # generate serverids, ldap-urls and syncrepl-blocks for mmr hosts
280 mmr_replicator_acl = ""
281 mmr_serverids_config = ""
282 mmr_syncrepl_schema_config = ""
283 mmr_syncrepl_config_config = ""
284 mmr_syncrepl_user_config = ""
287 if ol_mmr_urls is not None:
288 # For now, make these equal
289 mmr_pass = ldapadminpass
291 url_list=filter(None,ol_mmr_urls.split(' '))
292 if (len(url_list) == 1):
293 url_list=filter(None,ol_mmr_urls.split(','))
296 mmr_on_config = "MirrorMode On"
297 mmr_replicator_acl = " by dn=cn=replicator,cn=samba read"
301 mmr_serverids_config += read_and_sub_file(setup_path("mmr_serverids.conf"),
302 { "SERVERID" : str(serverid),
303 "LDAPSERVER" : url })
306 mmr_syncrepl_schema_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
308 "MMRDN": names.schemadn,
310 "MMR_PASSWORD": mmr_pass})
313 mmr_syncrepl_config_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
315 "MMRDN": names.configdn,
317 "MMR_PASSWORD": mmr_pass})
320 mmr_syncrepl_user_config += read_and_sub_file(setup_path("mmr_syncrepl.conf"),
322 "MMRDN": names.domaindn,
324 "MMR_PASSWORD": mmr_pass })
325 # OpenLDAP cn=config initialisation
326 olc_syncrepl_config = ""
328 # if mmr = yes, generate cn=config-replication directives
329 # and olc_seed.lif for the other mmr-servers
330 if ol_mmr_urls is not None:
332 olc_serverids_config = ""
333 olc_syncrepl_seed_config = ""
334 olc_mmr_config += read_and_sub_file(setup_path("olc_mmr.conf"),{})
338 olc_serverids_config += read_and_sub_file(setup_path("olc_serverid.conf"),
339 { "SERVERID" : str(serverid),
340 "LDAPSERVER" : url })
343 olc_syncrepl_config += read_and_sub_file(setup_path("olc_syncrepl.conf"),
346 "MMR_PASSWORD": mmr_pass})
348 olc_syncrepl_seed_config += read_and_sub_file(setup_path("olc_syncrepl_seed.conf"),
352 setup_file(setup_path("olc_seed.ldif"), result.paths.olcseedldif,
353 {"OLC_SERVER_ID_CONF": olc_serverids_config,
354 "OLC_PW": ldapadminpass,
355 "OLC_SYNCREPL_CONF": olc_syncrepl_seed_config})
358 setup_file(setup_path("slapd.conf"), result.paths.slapdconf,
359 {"DNSDOMAIN": names.dnsdomain,
360 "LDAPDIR": result.paths.ldapdir,
361 "DOMAINDN": names.domaindn,
362 "CONFIGDN": names.configdn,
363 "SCHEMADN": names.schemadn,
364 "MEMBEROF_CONFIG": memberof_config,
365 "MIRRORMODE": mmr_on_config,
366 "REPLICATOR_ACL": mmr_replicator_acl,
367 "MMR_SERVERIDS_CONFIG": mmr_serverids_config,
368 "MMR_SYNCREPL_SCHEMA_CONFIG": mmr_syncrepl_schema_config,
369 "MMR_SYNCREPL_CONFIG_CONFIG": mmr_syncrepl_config_config,
370 "MMR_SYNCREPL_USER_CONFIG": mmr_syncrepl_user_config,
371 "OLC_SYNCREPL_CONFIG": olc_syncrepl_config,
372 "OLC_MMR_CONFIG": olc_mmr_config,
373 "REFINT_CONFIG": refint_config,
374 "INDEX_CONFIG": index_config,
375 "NOSYNC": nosync_config})
377 setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "user"))
378 setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "config"))
379 setup_db_config(setup_path, os.path.join(result.paths.ldapdir, "db", "schema"))
381 if not os.path.exists(os.path.join(result.paths.ldapdir, "db", "samba", "cn=samba")):
382 os.makedirs(os.path.join(result.paths.ldapdir, "db", "samba", "cn=samba"), 0700)
384 setup_file(setup_path("cn=samba.ldif"),
385 os.path.join(result.paths.ldapdir, "db", "samba", "cn=samba.ldif"),
386 { "UUID": str(uuid.uuid4()),
387 "LDAPTIME": timestring(int(time.time()))} )
388 setup_file(setup_path("cn=samba-admin.ldif"),
389 os.path.join(result.paths.ldapdir, "db", "samba", "cn=samba", "cn=samba-admin.ldif"),
390 {"LDAPADMINPASS_B64": b64encode(ldapadminpass),
391 "UUID": str(uuid.uuid4()),
392 "LDAPTIME": timestring(int(time.time()))} )
394 if ol_mmr_urls is not None:
395 setup_file(setup_path("cn=replicator.ldif"),
396 os.path.join(result.paths.ldapdir, "db", "samba", "cn=samba", "cn=replicator.ldif"),
397 {"MMR_PASSWORD_B64": b64encode(mmr_pass),
398 "UUID": str(uuid.uuid4()),
399 "LDAPTIME": timestring(int(time.time()))} )
402 mapping = "schema-map-openldap-2.3"
403 backend_schema = "backend-schema.schema"
405 backend_schema_data = schema.ldb.convert_schema_to_openldap("openldap", open(setup_path(mapping), 'r').read())
406 assert backend_schema_data is not None
407 open(os.path.join(result.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
409 # now we generate the needed strings to start slapd automatically,
411 if ldap_backend_extra_port is not None:
412 # When we use MMR, we can't use 0.0.0.0 as it uses the name
413 # specified there as part of it's clue as to it's own name,
414 # and not to replicate to itself
415 if ol_mmr_urls is None:
416 server_port_string = "ldap://0.0.0.0:%d" % ldap_backend_extra_port
418 server_port_string = "ldap://" + names.hostname + "." + names.dnsdomain +":%d" % ldap_backend_extra_port
420 server_port_string = ""
422 # Prepare the 'result' information - the commands to return in particular
423 result.slapd_provision_command = [slapd_path]
425 result.slapd_provision_command.append("-F" + result.paths.olcdir)
427 result.slapd_provision_command.append("-h")
429 # copy this command so we have two version, one with -d0 and only ldapi, and one with all the listen commands
430 result.slapd_command = list(result.slapd_provision_command)
432 result.slapd_provision_command.append(result.ldapi_uri)
433 result.slapd_provision_command.append("-d0")
435 uris = result.ldapi_uri
436 if server_port_string is not "":
437 uris = uris + " " + server_port_string
439 result.slapd_command.append(uris)
441 # Set the username - done here because Fedora DS still uses the admin DN and simple bind
442 result.credentials.set_username("samba-admin")
444 # If we were just looking for crashes up to this point, it's a
445 # good time to exit before we realise we don't have OpenLDAP on
450 # Finally, convert the configuration into cn=config style!
451 if not os.path.isdir(result.paths.olcdir):
452 os.makedirs(result.paths.olcdir, 0770)
454 retcode = subprocess.call([slapd_path, "-Ttest", "-f", result.paths.slapdconf, "-F", result.paths.olcdir], close_fds=True, shell=False)
456 # We can't do this, as OpenLDAP is strange. It gives an error
457 # output to the above, but does the conversion sucessfully...
460 # raise ProvisioningError("conversion from slapd.conf to cn=config failed")
462 if not os.path.exists(os.path.join(result.paths.olcdir, "cn=config.ldif")):
463 raise ProvisioningError("conversion from slapd.conf to cn=config failed")
465 # Don't confuse the admin by leaving the slapd.conf around
466 os.remove(result.paths.slapdconf)
469 def provision_fds_backend(result, setup_path=None, names=None,
471 hostname=None, ldapadminpass=None, root=None,
473 ldap_backend_extra_port=None,
477 ldap_dryrun_mode=False,
480 if ldap_backend_extra_port is not None:
481 serverport = "ServerPort=%d" % ldap_backend_extra_port
485 setup_file(setup_path("fedorads.inf"), result.paths.fedoradsinf,
487 "HOSTNAME": hostname,
488 "DNSDOMAIN": names.dnsdomain,
489 "LDAPDIR": result.paths.ldapdir,
490 "DOMAINDN": names.domaindn,
491 "LDAPMANAGERDN": names.ldapmanagerdn,
492 "LDAPMANAGERPASS": ldapadminpass,
493 "SERVERPORT": serverport})
495 setup_file(setup_path("fedorads-partitions.ldif"), result.paths.fedoradspartitions,
496 {"CONFIGDN": names.configdn,
497 "SCHEMADN": names.schemadn,
498 "SAMBADN": names.sambadn,
501 setup_file(setup_path("fedorads-sasl.ldif"), result.paths.fedoradssasl,
502 {"SAMBADN": names.sambadn,
505 setup_file(setup_path("fedorads-dna.ldif"), result.paths.fedoradsdna,
506 {"DOMAINDN": names.domaindn,
507 "SAMBADN": names.sambadn,
508 "DOMAINSID": str(domainsid),
511 setup_file(setup_path("fedorads-pam.ldif"), result.paths.fedoradspam)
513 lnkattr = schema.linked_attributes()
515 refint_config = data = open(setup_path("fedorads-refint-delete.ldif"), 'r').read()
520 for attr in lnkattr.keys():
521 if lnkattr[attr] is not None:
522 refint_config += read_and_sub_file(setup_path("fedorads-refint-add.ldif"),
523 { "ARG_NUMBER" : str(argnum) ,
524 "LINK_ATTR" : attr })
525 memberof_config += read_and_sub_file(setup_path("fedorads-linked-attributes.ldif"),
526 { "MEMBER_ATTR" : attr ,
527 "MEMBEROF_ATTR" : lnkattr[attr] })
528 index_config += read_and_sub_file(setup_path("fedorads-index.ldif"),
532 open(result.paths.fedoradsrefint, 'w').write(refint_config)
533 open(result.paths.fedoradslinkedattributes, 'w').write(memberof_config)
535 attrs = ["lDAPDisplayName"]
536 res = schema.ldb.search(expression="(&(objectclass=attributeSchema)(searchFlags:1.2.840.113556.1.4.803:=1))", base=names.schemadn, scope=SCOPE_ONELEVEL, attrs=attrs)
538 for i in range (0, len(res)):
539 attr = res[i]["lDAPDisplayName"][0]
541 if attr == "objectGUID":
544 index_config += read_and_sub_file(setup_path("fedorads-index.ldif"),
547 open(result.paths.fedoradsindex, 'w').write(index_config)
549 setup_file(setup_path("fedorads-samba.ldif"), result.paths.fedoradssamba,
550 {"SAMBADN": names.sambadn,
551 "LDAPADMINPASS": ldapadminpass
554 mapping = "schema-map-fedora-ds-1.0"
555 backend_schema = "99_ad.ldif"
557 # Build a schema file in Fedora DS format
558 backend_schema_data = schema.ldb.convert_schema_to_openldap("fedora-ds", open(setup_path(mapping), 'r').read())
559 assert backend_schema_data is not None
560 open(os.path.join(result.paths.ldapdir, backend_schema), 'w').write(backend_schema_data)
562 result.credentials.set_bind_dn(names.ldapmanagerdn)
564 # Destory the target directory, or else setup-ds.pl will complain
565 fedora_ds_dir = os.path.join(result.paths.ldapdir, "slapd-samba4")
566 shutil.rmtree(fedora_ds_dir, True)
568 result.slapd_provision_command = [slapd_path, "-D", fedora_ds_dir, "-i", result.paths.slapdpid];
569 #In the 'provision' command line, stay in the foreground so we can easily kill it
570 result.slapd_provision_command.append("-d0")
572 #the command for the final run is the normal script
573 result.slapd_command = [os.path.join(result.paths.ldapdir, "slapd-samba4", "start-slapd")]
575 # If we were just looking for crashes up to this point, it's a
576 # good time to exit before we realise we don't have Fedora DS on
580 # Try to print helpful messages when the user has not specified the path to the setup-ds tool
581 if setup_ds_path is None:
582 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\"!")
583 if not os.path.exists(setup_ds_path):
584 message (setup_ds_path)
585 raise ProvisioningError("Warning: Given Path to slapd does not exist!")
587 # Run the Fedora DS setup utility
588 retcode = subprocess.call([setup_ds_path, "--silent", "--file", result.paths.fedoradsinf], close_fds=True, shell=False)
590 raise ProvisioningError("setup-ds failed")
593 retcode = subprocess.call([
594 os.path.join(result.paths.ldapdir, "slapd-samba4", "ldif2db"), "-s", names.sambadn, "-i", result.paths.fedoradssamba],
595 close_fds=True, shell=False)
597 raise("ldib2db failed")
600 class FDSBackend(LDAPBackend):
601 def post_setup(self):
602 ldapi_db = Ldb(self.ldapi_uri, credentials=self.credentials)
604 # delete default SASL mappings
605 res = ldapi_db.search(expression="(!(cn=samba-admin mapping))", base="cn=mapping,cn=sasl,cn=config", scope=SCOPE_ONELEVEL, attrs=["dn"])
607 # configure in-directory access control on Fedora DS via the aci attribute (over a direct ldapi:// socket)
608 for i in range (0, len(res)):
609 dn = str(res[i]["dn"])
612 aci = """(targetattr = "*") (version 3.0;acl "full access to all by samba-admin";allow (all)(userdn = "ldap:///CN=samba-admin,%s");)""" % self.names.sambadn
615 m["aci"] = ldb.MessageElement([aci], ldb.FLAG_MOD_REPLACE, "aci")
617 m.dn = ldb.Dn(1, self.names.domaindn)
620 m.dn = ldb.Dn(1, self.names.configdn)
623 m.dn = ldb.Dn(1, self.names.schemadn)