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 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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.auth.ldap.server;
  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.handlers.sasl.MechanismHandler;
  47. import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
  48. import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
  49. import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler;
  50. import org.apache.directory.server.ldap.handlers.sasl.plain.PlainMechanismHandler;
  51. import org.apache.directory.server.protocol.shared.transport.TcpTransport;
  52. import org.apache.directory.server.protocol.shared.transport.UdpTransport;
  53. import org.apache.directory.server.xdbm.impl.avl.AvlIndex;
  54. import org.apache.mina.util.AvailablePortFinder;
  55. import org.slf4j.Logger;
  56. import org.slf4j.LoggerFactory;
  57. public final class ApacheDS {
  58. private static final Logger LOG = LoggerFactory.getLogger(ApacheDS.class);
  59. private final String realm;
  60. private final String baseDn;
  61. private DirectoryService directoryService;
  62. private org.apache.directory.server.ldap.LdapServer ldapServer;
  63. private KdcServer kdcServer;
  64. private ApacheDS(String realm, String baseDn) {
  65. this.realm = realm;
  66. this.baseDn = baseDn;
  67. ldapServer = new org.apache.directory.server.ldap.LdapServer();
  68. }
  69. public static ApacheDS start(String realm, String baseDn, String workDir) throws Exception {
  70. return start(realm, baseDn, workDir + realm, null);
  71. }
  72. static ApacheDS start(String realm, String baseDn) throws Exception {
  73. return start(realm, baseDn, "target/ldap-work/" + realm, null);
  74. }
  75. private static ApacheDS start(String realm, String baseDn, String workDir, Integer port) throws Exception {
  76. return new ApacheDS(realm, baseDn)
  77. .startDirectoryService(workDir)
  78. .startKdcServer()
  79. .startLdapServer(port == null ? AvailablePortFinder.getNextAvailable(1024) : port)
  80. .activateNis();
  81. }
  82. void stop() throws Exception {
  83. kdcServer.stop();
  84. kdcServer = null;
  85. ldapServer.stop();
  86. ldapServer = null;
  87. directoryService.shutdown();
  88. directoryService = null;
  89. }
  90. public String getUrl() {
  91. return "ldap://localhost:" + ldapServer.getPort();
  92. }
  93. /**
  94. * Stream will be closed automatically.
  95. */
  96. public void importLdif(InputStream is) throws Exception {
  97. try (LdifReader reader = new LdifReader(is)) {
  98. CoreSession coreSession = directoryService.getAdminSession();
  99. // see LdifFileLoader
  100. for (LdifEntry ldifEntry : reader) {
  101. String ldif = ldifEntry.toString();
  102. LOG.info(ldif);
  103. if (ChangeType.Add == ldifEntry.getChangeType() || /* assume "add" by default */ ChangeType.None == ldifEntry.getChangeType()) {
  104. coreSession.add(new DefaultEntry(coreSession.getDirectoryService().getSchemaManager(), ldifEntry.getEntry()));
  105. } else if (ChangeType.Modify == ldifEntry.getChangeType()) {
  106. coreSession.modify(ldifEntry.getDn(), ldifEntry.getModifications());
  107. } else if (ChangeType.Delete == ldifEntry.getChangeType()) {
  108. coreSession.delete(ldifEntry.getDn());
  109. } else {
  110. throw new IllegalStateException();
  111. }
  112. }
  113. }
  114. }
  115. void disableAnonymousAccess() {
  116. directoryService.setAllowAnonymousAccess(false);
  117. }
  118. void enableAnonymousAccess() {
  119. directoryService.setAllowAnonymousAccess(true);
  120. }
  121. private ApacheDS startDirectoryService(String workDirStr) throws Exception {
  122. DefaultDirectoryServiceFactory factory = new DefaultDirectoryServiceFactory();
  123. factory.init(realm);
  124. directoryService = factory.getDirectoryService();
  125. directoryService.getChangeLog().setEnabled(false);
  126. directoryService.setShutdownHookEnabled(false);
  127. directoryService.setAllowAnonymousAccess(true);
  128. File workDir = new File(workDirStr);
  129. if (workDir.exists()) {
  130. FileUtils.deleteDirectory(workDir);
  131. }
  132. InstanceLayout instanceLayout = new InstanceLayout(workDir);
  133. directoryService.setInstanceLayout(instanceLayout);
  134. AvlPartition partition = new AvlPartition(directoryService.getSchemaManager());
  135. partition.setId("Test");
  136. partition.setSuffixDn(new Dn(directoryService.getSchemaManager(), baseDn));
  137. partition.addIndexedAttributes(
  138. new AvlIndex<>("ou"),
  139. new AvlIndex<>("uid"),
  140. new AvlIndex<>("dc"),
  141. new AvlIndex<>("objectClass"));
  142. partition.initialize();
  143. directoryService.addPartition(partition);
  144. directoryService.addLast(new KeyDerivationInterceptor());
  145. directoryService.shutdown();
  146. directoryService.startup();
  147. return this;
  148. }
  149. private ApacheDS startLdapServer(int port) throws Exception {
  150. ldapServer.setTransports(new TcpTransport(port));
  151. ldapServer.setDirectoryService(directoryService);
  152. // Setup SASL mechanisms
  153. Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<>();
  154. mechanismHandlerMap.put(SupportedSaslMechanisms.PLAIN, new PlainMechanismHandler());
  155. mechanismHandlerMap.put(SupportedSaslMechanisms.CRAM_MD5, new CramMd5MechanismHandler());
  156. mechanismHandlerMap.put(SupportedSaslMechanisms.DIGEST_MD5, new DigestMd5MechanismHandler());
  157. mechanismHandlerMap.put(SupportedSaslMechanisms.GSSAPI, new GssapiMechanismHandler());
  158. ldapServer.setSaslMechanismHandlers(mechanismHandlerMap);
  159. ldapServer.setSaslHost("localhost");
  160. ldapServer.setSaslRealms(Collections.singletonList(realm));
  161. // TODO ldapServer.setSaslPrincipal();
  162. // The base DN containing users that can be SASL authenticated.
  163. ldapServer.setSearchBaseDn(baseDn);
  164. ldapServer.start();
  165. return this;
  166. }
  167. private ApacheDS startKdcServer() throws IOException, LdapOperationException {
  168. int port = AvailablePortFinder.getNextAvailable(6088);
  169. KerberosConfig kdcConfig = new KerberosConfig();
  170. kdcConfig.setServicePrincipal("krbtgt/EXAMPLE.ORG@EXAMPLE.ORG");
  171. kdcConfig.setPrimaryRealm("EXAMPLE.ORG");
  172. kdcConfig.setPaEncTimestampRequired(false);
  173. kdcServer = new KdcServer(kdcConfig);
  174. kdcServer.setSearchBaseDn("dc=example,dc=org");
  175. kdcServer.addTransports(new UdpTransport("localhost", port));
  176. kdcServer.setDirectoryService(directoryService);
  177. kdcServer.start();
  178. FileUtils.writeStringToFile(new File("target/krb5.conf"), ""
  179. + "[libdefaults]\n"
  180. + " default_realm = EXAMPLE.ORG\n"
  181. + "\n"
  182. + "[realms]\n"
  183. + " EXAMPLE.ORG = {\n"
  184. + " kdc = localhost:" + port + "\n"
  185. + " }\n"
  186. + "\n"
  187. + "[domain_realm]\n"
  188. + " .example.org = EXAMPLE.ORG\n"
  189. + " example.org = EXAMPLE.ORG\n",
  190. StandardCharsets.UTF_8.name());
  191. return this;
  192. }
  193. /**
  194. * This seems to be required for objectClass posixGroup.
  195. */
  196. private ApacheDS activateNis() throws Exception {
  197. directoryService.getAdminSession().modify(
  198. new Dn("cn=nis,ou=schema"),
  199. new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "m-disabled", "FALSE"));
  200. return this;
  201. }
  202. }