You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ApacheDS.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.ldap;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.nio.charset.StandardCharsets;
  25. import java.util.Collections;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
  29. import org.apache.directory.api.ldap.model.entry.DefaultEntry;
  30. import org.apache.directory.api.ldap.model.entry.DefaultModification;
  31. import org.apache.directory.api.ldap.model.entry.ModificationOperation;
  32. import org.apache.directory.api.ldap.model.exception.LdapOperationException;
  33. import org.apache.directory.api.ldap.model.ldif.ChangeType;
  34. import org.apache.directory.api.ldap.model.ldif.LdifEntry;
  35. import org.apache.directory.api.ldap.model.ldif.LdifReader;
  36. import org.apache.directory.api.ldap.model.name.Dn;
  37. import org.apache.directory.api.util.FileUtils;
  38. import org.apache.directory.server.core.api.CoreSession;
  39. import org.apache.directory.server.core.api.DirectoryService;
  40. import org.apache.directory.server.core.api.InstanceLayout;
  41. import org.apache.directory.server.core.factory.DefaultDirectoryServiceFactory;
  42. import org.apache.directory.server.core.kerberos.KeyDerivationInterceptor;
  43. import org.apache.directory.server.core.partition.impl.avl.AvlPartition;
  44. import org.apache.directory.server.kerberos.KerberosConfig;
  45. import org.apache.directory.server.kerberos.kdc.KdcServer;
  46. import org.apache.directory.server.ldap.LdapServer;
  47. import org.apache.directory.server.ldap.handlers.sasl.MechanismHandler;
  48. import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
  49. import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
  50. import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler;
  51. import org.apache.directory.server.ldap.handlers.sasl.plain.PlainMechanismHandler;
  52. import org.apache.directory.server.protocol.shared.transport.TcpTransport;
  53. import org.apache.directory.server.protocol.shared.transport.UdpTransport;
  54. import org.apache.directory.server.xdbm.impl.avl.AvlIndex;
  55. import org.apache.mina.util.AvailablePortFinder;
  56. import org.slf4j.Logger;
  57. import org.slf4j.LoggerFactory;
  58. public final class ApacheDS {
  59. private static final Logger LOG = LoggerFactory.getLogger(ApacheDS.class);
  60. private final String realm;
  61. private final String baseDn;
  62. private DirectoryService directoryService;
  63. private LdapServer ldapServer;
  64. private KdcServer kdcServer;
  65. private ApacheDS(String realm, String baseDn) {
  66. this.realm = realm;
  67. this.baseDn = baseDn;
  68. ldapServer = new LdapServer();
  69. }
  70. public static ApacheDS start(String realm, String baseDn, String workDir, Integer port) throws Exception {
  71. return new ApacheDS(realm, baseDn)
  72. .startDirectoryService(workDir)
  73. .startKdcServer()
  74. .startLdapServer(port == null ? AvailablePortFinder.getNextAvailable(1024) : port)
  75. .activateNis();
  76. }
  77. public static ApacheDS start(String realm, String baseDn, String workDir) throws Exception {
  78. return start(realm, baseDn, workDir + realm, null);
  79. }
  80. public static ApacheDS start(String realm, String baseDn) throws Exception {
  81. return start(realm, baseDn, "target/ldap-work/" + realm, null);
  82. }
  83. public void stop() {
  84. try {
  85. kdcServer.stop();
  86. kdcServer = null;
  87. ldapServer.stop();
  88. ldapServer = null;
  89. directoryService.shutdown();
  90. directoryService = null;
  91. } catch (Exception e) {
  92. throw new IllegalStateException(e);
  93. }
  94. }
  95. public String getUrl() {
  96. return "ldap://localhost:" + ldapServer.getPort();
  97. }
  98. /**
  99. * Stream will be closed automatically.
  100. */
  101. public void importLdif(InputStream is) throws Exception {
  102. try (LdifReader reader = new LdifReader(is)) {
  103. CoreSession coreSession = directoryService.getAdminSession();
  104. // see LdifFileLoader
  105. for (LdifEntry ldifEntry : reader) {
  106. String ldif = ldifEntry.toString();
  107. LOG.info(ldif);
  108. if (ChangeType.Add == ldifEntry.getChangeType() || /* assume "add" by default */ ChangeType.None == ldifEntry.getChangeType()) {
  109. coreSession.add(new DefaultEntry(coreSession.getDirectoryService().getSchemaManager(), ldifEntry.getEntry()));
  110. } else if (ChangeType.Modify == ldifEntry.getChangeType()) {
  111. coreSession.modify(ldifEntry.getDn(), ldifEntry.getModifications());
  112. } else if (ChangeType.Delete == ldifEntry.getChangeType()) {
  113. coreSession.delete(ldifEntry.getDn());
  114. } else {
  115. throw new IllegalStateException();
  116. }
  117. }
  118. }
  119. }
  120. public void disableAnonymousAccess() {
  121. directoryService.setAllowAnonymousAccess(false);
  122. }
  123. public void enableAnonymousAccess() {
  124. directoryService.setAllowAnonymousAccess(true);
  125. }
  126. private ApacheDS startDirectoryService(String workDirStr) throws Exception {
  127. DefaultDirectoryServiceFactory factory = new DefaultDirectoryServiceFactory();
  128. factory.init(realm);
  129. directoryService = factory.getDirectoryService();
  130. directoryService.getChangeLog().setEnabled(false);
  131. directoryService.setShutdownHookEnabled(false);
  132. directoryService.setAllowAnonymousAccess(true);
  133. File workDir = new File(workDirStr);
  134. if (workDir.exists()) {
  135. FileUtils.deleteDirectory(workDir);
  136. }
  137. InstanceLayout instanceLayout = new InstanceLayout(workDir);
  138. directoryService.setInstanceLayout(instanceLayout);
  139. AvlPartition partition = new AvlPartition(directoryService.getSchemaManager());
  140. partition.setId("Test");
  141. partition.setSuffixDn(new Dn(directoryService.getSchemaManager(), baseDn));
  142. partition.addIndexedAttributes(
  143. new AvlIndex<>("ou"),
  144. new AvlIndex<>("uid"),
  145. new AvlIndex<>("dc"),
  146. new AvlIndex<>("objectClass"));
  147. partition.initialize();
  148. directoryService.addPartition(partition);
  149. directoryService.addLast(new KeyDerivationInterceptor());
  150. directoryService.shutdown();
  151. directoryService.startup();
  152. return this;
  153. }
  154. private ApacheDS startLdapServer(int port) throws Exception {
  155. ldapServer.setTransports(new TcpTransport(port));
  156. ldapServer.setDirectoryService(directoryService);
  157. // Setup SASL mechanisms
  158. Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<>();
  159. mechanismHandlerMap.put(SupportedSaslMechanisms.PLAIN, new PlainMechanismHandler());
  160. mechanismHandlerMap.put(SupportedSaslMechanisms.CRAM_MD5, new CramMd5MechanismHandler());
  161. mechanismHandlerMap.put(SupportedSaslMechanisms.DIGEST_MD5, new DigestMd5MechanismHandler());
  162. mechanismHandlerMap.put(SupportedSaslMechanisms.GSSAPI, new GssapiMechanismHandler());
  163. ldapServer.setSaslMechanismHandlers(mechanismHandlerMap);
  164. ldapServer.setSaslHost("localhost");
  165. ldapServer.setSaslRealms(Collections.singletonList(realm));
  166. // TODO ldapServer.setSaslPrincipal();
  167. // The base DN containing users that can be SASL authenticated.
  168. ldapServer.setSearchBaseDn(baseDn);
  169. ldapServer.start();
  170. return this;
  171. }
  172. private ApacheDS startKdcServer() throws IOException, LdapOperationException {
  173. int port = AvailablePortFinder.getNextAvailable(6088);
  174. KerberosConfig kdcConfig = new KerberosConfig();
  175. kdcConfig.setServicePrincipal("krbtgt/EXAMPLE.ORG@EXAMPLE.ORG");
  176. kdcConfig.setPrimaryRealm("EXAMPLE.ORG");
  177. kdcConfig.setPaEncTimestampRequired(false);
  178. kdcServer = new KdcServer(kdcConfig);
  179. kdcServer.setSearchBaseDn("dc=example,dc=org");
  180. kdcServer.addTransports(new UdpTransport("localhost", port));
  181. kdcServer.setDirectoryService(directoryService);
  182. kdcServer.start();
  183. FileUtils.writeStringToFile(new File("target/krb5.conf"), ""
  184. + "[libdefaults]\n"
  185. + " default_realm = EXAMPLE.ORG\n"
  186. + "\n"
  187. + "[realms]\n"
  188. + " EXAMPLE.ORG = {\n"
  189. + " kdc = localhost:" + port + "\n"
  190. + " }\n"
  191. + "\n"
  192. + "[domain_realm]\n"
  193. + " .example.org = EXAMPLE.ORG\n"
  194. + " example.org = EXAMPLE.ORG\n",
  195. StandardCharsets.UTF_8.name());
  196. return this;
  197. }
  198. /**
  199. * This seems to be required for objectClass posixGroup.
  200. */
  201. private ApacheDS activateNis() throws Exception {
  202. directoryService.getAdminSession().modify(
  203. new Dn("cn=nis,ou=schema"),
  204. new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "m-disabled", "FALSE"));
  205. return this;
  206. }
  207. }