http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/configurer/SslConfigurer.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/configurer/SslConfigurer.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/configurer/SslConfigurer.java new file mode 100644 index 0000000..f4e2947 --- /dev/null +++ b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/configurer/SslConfigurer.java @@ -0,0 +1,363 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.ambari.logsearch.configurer; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.net.ssl.SSLContext; + +import org.apache.ambari.logsearch.conf.LogSearchSslConfig; +import org.apache.ambari.logsearch.util.FileUtil; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.hadoop.conf.Configuration; +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.ContentSigner; +import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; +import org.bouncycastle.operator.OperatorCreationException; +import org.bouncycastle.operator.bc.BcContentSignerBuilder; +import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.X509v3CertificateBuilder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.crypto.params.RSAKeyParameters; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetAddress; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.Security; +import java.security.SignatureException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Date; + +import static org.apache.ambari.logsearch.conf.LogSearchSslConfig.CREDENTIAL_STORE_PROVIDER_PATH; +import static org.apache.ambari.logsearch.conf.LogSearchSslConfig.LOGSEARCH_CERT_DEFAULT_FOLDER; + +@Named +public class SslConfigurer { + private static final Logger LOG = LoggerFactory.getLogger(SslConfigurer.class); + + private static final String KEYSTORE_LOCATION_ARG = "javax.net.ssl.keyStore"; + private static final String KEYSTORE_PASSWORD_ARG = "javax.net.ssl.keyStorePassword"; + private static final String KEYSTORE_TYPE_ARG = "javax.net.ssl.keyStoreType"; + private static final String DEFAULT_KEYSTORE_TYPE = "JKS"; + private static final String TRUSTSTORE_LOCATION_ARG = "javax.net.ssl.trustStore"; + private static final String TRUSTSTORE_PASSWORD_ARG = "javax.net.ssl.trustStorePassword"; + private static final String TRUSTSTORE_TYPE_ARG = "javax.net.ssl.trustStoreType"; + private static final String DEFAULT_TRUSTSTORE_TYPE = "JKS"; + private static final String KEYSTORE_PASSWORD_PROPERTY_NAME = "logsearch_keystore_password"; + private static final String TRUSTSTORE_PASSWORD_PROPERTY_NAME = "logsearch_truststore_password"; + private static final String KEYSTORE_PASSWORD_FILE = "ks_pass.txt"; + private static final String TRUSTSTORE_PASSWORD_FILE = "ts_pass.txt"; + + private static final String LOGSEARCH_CERT_FILENAME = "logsearch.crt"; + private static final String LOGSEARCH_KEYSTORE_FILENAME = "logsearch.jks"; + private static final String LOGSEARCH_KEYSTORE_PRIVATE_KEY = "logsearch.private.key"; + private static final String LOGSEARCH_KEYSTORE_PUBLIC_KEY = "logsearch.public.key"; + + private static final String LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD = "bigdata"; + + @Inject + private LogSearchSslConfig logSearchSslConfig; + + private String getKeyStoreLocation() { + return System.getProperty(KEYSTORE_LOCATION_ARG); + } + + private String getKeyStorePassword() { + return System.getProperty(KEYSTORE_PASSWORD_ARG); + } + + private String getKeyStoreType() { + return System.getProperty(KEYSTORE_TYPE_ARG, DEFAULT_KEYSTORE_TYPE); + } + + private String getTrustStoreLocation() { + return System.getProperty(TRUSTSTORE_LOCATION_ARG); + } + + private String getTrustStorePassword() { + return System.getProperty(TRUSTSTORE_PASSWORD_ARG); + } + + private String getTrustStoreType() { + return System.getProperty(TRUSTSTORE_TYPE_ARG, DEFAULT_TRUSTSTORE_TYPE); + } + + public boolean isKeyStoreSpecified() { + return StringUtils.isNotEmpty(getKeyStoreLocation()); + } + + private boolean isTrustStoreSpecified() { + return StringUtils.isNotEmpty(getTrustStoreLocation()); + } + + public SslContextFactory getSslContextFactory() { + SslContextFactory sslContextFactory = new SslContextFactory(); + sslContextFactory.setKeyStorePath(getKeyStoreLocation()); + sslContextFactory.setKeyStorePassword(getKeyStorePassword()); + sslContextFactory.setKeyStoreType(getKeyStoreType()); + if (isTrustStoreSpecified()) { + sslContextFactory.setTrustStorePath(getTrustStoreLocation()); + sslContextFactory.setTrustStorePassword(getTrustStorePassword()); + sslContextFactory.setTrustStoreType(getTrustStoreType()); + } + + return sslContextFactory; + } + + public SSLContext getSSLContext() { + SslContextFactory sslContextFactory = getSslContextFactory(); + + try { + sslContextFactory.start(); + return sslContextFactory.getSslContext(); + } catch (Exception e) { + LOG.error("Could not create SSL Context", e); + return null; + } finally { + try { + sslContextFactory.stop(); + } catch (Exception e) { + LOG.error("Could not stop sslContextFactory", e); + } + } + } + + private String getPasswordFromFile(String fileName) { + try { + File pwdFile = new File(LOGSEARCH_CERT_DEFAULT_FOLDER, fileName); + if (!pwdFile.exists()) { + FileUtils.writeStringToFile(pwdFile, LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD); + return LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD; + } else { + return FileUtils.readFileToString(pwdFile); + } + } catch (Exception e) { + LOG.warn("Exception occurred during read/write password file for keystore/truststore.", e); + return null; + } + } + + private String getPasswordFromCredentialStore(String propertyName) { + try { + String providerPath = logSearchSslConfig.getCredentialStoreProviderPath(); + if (StringUtils.isEmpty(providerPath)) { + return null; + } + + Configuration config = new Configuration(); + config.set(CREDENTIAL_STORE_PROVIDER_PATH, providerPath); + char[] passwordChars = config.getPassword(propertyName); + return (ArrayUtils.isNotEmpty(passwordChars)) ? new String(passwordChars) : null; + } catch (Exception e) { + LOG.warn(String.format("Could not load password %s from credential store, using default password", propertyName), e); + return null; + } + } + + private String getPassword(String propertyName, String fileName) { + String credentialStorePassword = getPasswordFromCredentialStore(propertyName); + if (credentialStorePassword != null) { + return credentialStorePassword; + } + + String filePassword = getPasswordFromFile(fileName); + if (filePassword != null) { + return filePassword; + } + + return LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD; + } + + /** + * Put private key into in-memory keystore and write it to a file (JKS file) + */ + private void setKeyAndCertInKeystore(X509Certificate cert, KeyPair keyPair, KeyStore keyStore, String keyStoreLocation, char[] password) + throws Exception { + Certificate[] certChain = new Certificate[1]; + certChain[0] = cert; + try (FileOutputStream fos = new FileOutputStream(keyStoreLocation)) { + keyStore.setKeyEntry("logsearch.alias", keyPair.getPrivate(), password, certChain); + keyStore.store(fos, password); + } catch (Exception e) { + LOG.error("Could not write certificate to Keystore", e); + throw e; + } + } + + /** + * Create in-memory keypair with bouncy castle + */ + private KeyPair createKeyPair(String encryptionType, int byteCount) + throws NoSuchProviderException, NoSuchAlgorithmException { + Security.addProvider(new BouncyCastleProvider()); + KeyPairGenerator keyPairGenerator = createKeyPairGenerator(encryptionType, byteCount); + return keyPairGenerator.genKeyPair(); + } + + /** + * Generate X509 certificate if it does not exist + */ + private X509Certificate generateCertificate(String certificateLocation, KeyPair keyPair, String algorithm) throws Exception { + try { + File certFile = new File(certificateLocation); + if (certFile.exists()) { + LOG.info("Certificate file exists ({}), skip the generation.", certificateLocation); + return getCertFile(certificateLocation); + } else { + Security.addProvider(new BouncyCastleProvider()); + X509Certificate cert = createCert(keyPair, algorithm, InetAddress.getLocalHost().getCanonicalHostName()); + FileUtils.writeByteArrayToFile(certFile, cert.getEncoded()); + return cert; + } + } catch (Exception e) { + LOG.error("Could not create certificate.", e); + throw e; + } + } + + private void ensureStorePassword(String locationArg, String pwdArg, String propertyName, String fileName) { + if (StringUtils.isNotEmpty(System.getProperty(locationArg)) && StringUtils.isEmpty(System.getProperty(pwdArg))) { + String password = getPassword(propertyName, fileName); + System.setProperty(pwdArg, password); + } + } + + public void ensureStorePasswords() { + ensureStorePassword(KEYSTORE_LOCATION_ARG, KEYSTORE_PASSWORD_ARG, KEYSTORE_PASSWORD_PROPERTY_NAME, KEYSTORE_PASSWORD_FILE); + ensureStorePassword(TRUSTSTORE_LOCATION_ARG, TRUSTSTORE_PASSWORD_ARG, TRUSTSTORE_PASSWORD_PROPERTY_NAME, TRUSTSTORE_PASSWORD_FILE); + } + + private X509Certificate getCertFile(String location) throws Exception { + try (FileInputStream fos = new FileInputStream(location)) { + CertificateFactory factory = CertificateFactory.getInstance("X.509"); + return (X509Certificate) factory.generateCertificate(fos); + } catch (Exception e) { + LOG.error("Cannot read cert file. ('" + location + "')", e); + throw e; + } + } + + private X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName) + throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException { + + RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); + RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); + + AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm); + AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); + BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); + + ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded()); + SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject()); + publicKeyStream.close(); + + X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder( + new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"), + BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), + new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), + new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)), + new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"), + pubKey); + + RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()); + ContentSigner contentSigner = sigGen.build(keyParams); + + X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner); + + JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC"); + return certConverter.getCertificate(certificateHolder); + } + + private KeyPairGenerator createKeyPairGenerator(String algorithmIdentifier, int bitCount) + throws NoSuchProviderException, NoSuchAlgorithmException { + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithmIdentifier, BouncyCastleProvider.PROVIDER_NAME); + kpg.initialize(bitCount); + return kpg; + } + + /** + * Create keystore with keys and certificate (only if the keystore does not exist or if you have no permissions on the keystore file) + */ + public void loadKeystore() { + try { + String certFolder = logSearchSslConfig.getCertFolder(); + String certAlgorithm = logSearchSslConfig.getCertAlgorithm(); + String certLocation = String.format("%s/%s", LOGSEARCH_CERT_DEFAULT_FOLDER, LOGSEARCH_CERT_FILENAME); + String keyStoreLocation = StringUtils.isNotEmpty(getKeyStoreLocation()) ? getKeyStoreLocation() + : String.format("%s/%s", LOGSEARCH_CERT_DEFAULT_FOLDER, LOGSEARCH_KEYSTORE_FILENAME); + char[] password = StringUtils.isNotEmpty(getKeyStorePassword()) ? + getKeyStorePassword().toCharArray() : LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD.toCharArray(); + boolean keyStoreFileExists = new File(keyStoreLocation).exists(); + if (!keyStoreFileExists) { + FileUtil.createDirectory(certFolder); + LOG.warn("Keystore file ('{}') does not exist, creating new one. " + + "If the file exists, make sure you have proper permissions on that.", keyStoreLocation); + if (isKeyStoreSpecified() && !"JKS".equalsIgnoreCase(getKeyStoreType())) { + throw new RuntimeException(String.format("Keystore does not exist. Only JKS keystore can be auto generated. (%s)", keyStoreLocation)); + } + LOG.info("SSL keystore is not specified. Generating it with certificate ... (using default format: JKS)"); + Security.addProvider(new BouncyCastleProvider()); + KeyPair keyPair = createKeyPair("RSA", 2048); + File privateKeyFile = new File(String.format("%s/%s", certFolder, LOGSEARCH_KEYSTORE_PRIVATE_KEY)); + if (!privateKeyFile.exists()) { + FileUtils.writeByteArrayToFile(privateKeyFile, keyPair.getPrivate().getEncoded()); + } + File file = new File(String.format("%s/%s", certFolder, LOGSEARCH_KEYSTORE_PUBLIC_KEY)); + if (!file.exists()) { + FileUtils.writeByteArrayToFile(file, keyPair.getPublic().getEncoded()); + } + X509Certificate cert = generateCertificate(certLocation, keyPair, certAlgorithm); + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + setKeyAndCertInKeystore(cert, keyPair, keyStore, keyStoreLocation, password); + FileUtil.setPermissionOnDirectory(certFolder, "600"); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +}
http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/SSLUtil.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/SSLUtil.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/SSLUtil.java deleted file mode 100644 index b0b893f..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/SSLUtil.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.ambari.logsearch.util; - -import javax.net.ssl.SSLContext; - -import org.apache.ambari.logsearch.common.PropertiesHelper; -import org.apache.ambari.logsearch.config.api.LogSearchPropertyDescription; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.hadoop.conf.Configuration; -import org.bouncycastle.asn1.ASN1InputStream; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x509.AlgorithmIdentifier; -import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; -import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.bouncycastle.operator.ContentSigner; -import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; -import org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder; -import org.bouncycastle.operator.OperatorCreationException; -import org.bouncycastle.operator.bc.BcContentSignerBuilder; -import org.bouncycastle.operator.bc.BcRSAContentSignerBuilder; -import org.bouncycastle.cert.X509CertificateHolder; -import org.bouncycastle.cert.X509v3CertificateBuilder; -import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.bouncycastle.crypto.params.RSAKeyParameters; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigInteger; -import java.net.InetAddress; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.KeyStore; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.SecureRandom; -import java.security.Security; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.interfaces.RSAPublicKey; -import java.util.Date; - -import static org.apache.ambari.logsearch.common.LogSearchConstants.LOGSEARCH_PROPERTIES_FILE; - -public class SSLUtil { - private static final Logger LOG = LoggerFactory.getLogger(SSLUtil.class); - - private static final String KEYSTORE_LOCATION_ARG = "javax.net.ssl.keyStore"; - private static final String KEYSTORE_PASSWORD_ARG = "javax.net.ssl.keyStorePassword"; - private static final String KEYSTORE_TYPE_ARG = "javax.net.ssl.keyStoreType"; - private static final String DEFAULT_KEYSTORE_TYPE = "JKS"; - private static final String TRUSTSTORE_LOCATION_ARG = "javax.net.ssl.trustStore"; - private static final String TRUSTSTORE_PASSWORD_ARG = "javax.net.ssl.trustStorePassword"; - private static final String TRUSTSTORE_TYPE_ARG = "javax.net.ssl.trustStoreType"; - private static final String DEFAULT_TRUSTSTORE_TYPE = "JKS"; - private static final String KEYSTORE_PASSWORD_PROPERTY_NAME = "logsearch_keystore_password"; - private static final String TRUSTSTORE_PASSWORD_PROPERTY_NAME = "logsearch_truststore_password"; - private static final String KEYSTORE_PASSWORD_FILE = "ks_pass.txt"; - private static final String TRUSTSTORE_PASSWORD_FILE = "ts_pass.txt"; - - @LogSearchPropertyDescription( - name = "hadoop.security.credential.provider.path", - description = "Path to interrogate for protected credentials. (see: https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-common/CredentialProviderAPI.html)", - examples = {"localjceks://file/home/mypath/my.jceks"}, - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String CREDENTIAL_STORE_PROVIDER_PATH = "hadoop.security.credential.provider.path"; - - @LogSearchPropertyDescription( - name = "logsearch.cert.folder.location", - description = "Folder where the generated certificates (SSL) will be located. Make sure the user of Log Search Server can access it.", - examples = {"/etc/mypath/keys"}, - defaultValue = "/etc/ambari-logsearch-portal/conf/keys", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String LOGSEARCH_CERT_FOLDER_LOCATION = "logsearch.cert.folder.location"; - - @LogSearchPropertyDescription( - name = "logsearch.cert.algorithm", - description = "Algorithm to generate certificates for SSL (if needed).", - examples = {"sha256WithRSA"}, - defaultValue = "sha256WithRSA", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String LOGSEARCH_CERT_ALGORITHM = "logsearch.cert.algorithm"; - - private static final String LOGSEARCH_CERT_FILENAME = "logsearch.crt"; - private static final String LOGSEARCH_KEYSTORE_FILENAME = "logsearch.jks"; - private static final String LOGSEARCH_KEYSTORE_PRIVATE_KEY = "logsearch.private.key"; - private static final String LOGSEARCH_KEYSTORE_PUBLIC_KEY = "logsearch.public.key"; - private static final String LOGSEARCH_CERT_DEFAULT_ALGORITHM = "sha256WithRSA"; - - private static final String LOGSEARCH_CERT_DEFAULT_FOLDER = "/etc/ambari-logsearch-portal/conf/keys"; - private static final String LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD = "bigdata"; - - private SSLUtil() { - throw new UnsupportedOperationException(); - } - - public static String getKeyStoreLocation() { - return System.getProperty(KEYSTORE_LOCATION_ARG); - } - - public static String getKeyStorePassword() { - return System.getProperty(KEYSTORE_PASSWORD_ARG); - } - - public static String getKeyStoreType() { - return System.getProperty(KEYSTORE_TYPE_ARG, DEFAULT_KEYSTORE_TYPE); - } - - public static String getTrustStoreLocation() { - return System.getProperty(TRUSTSTORE_LOCATION_ARG); - } - - public static String getTrustStorePassword() { - return System.getProperty(TRUSTSTORE_PASSWORD_ARG); - } - - public static String getTrustStoreType() { - return System.getProperty(TRUSTSTORE_TYPE_ARG, DEFAULT_TRUSTSTORE_TYPE); - } - - public static boolean isKeyStoreSpecified() { - return StringUtils.isNotEmpty(getKeyStoreLocation()); - } - - private static boolean isTrustStoreSpecified() { - return StringUtils.isNotEmpty(getTrustStoreLocation()); - } - - public static SslContextFactory getSslContextFactory() { - SslContextFactory sslContextFactory = new SslContextFactory(); - sslContextFactory.setKeyStorePath(getKeyStoreLocation()); - sslContextFactory.setKeyStorePassword(getKeyStorePassword()); - sslContextFactory.setKeyStoreType(getKeyStoreType()); - if (isTrustStoreSpecified()) { - sslContextFactory.setTrustStorePath(getTrustStoreLocation()); - sslContextFactory.setTrustStorePassword(getTrustStorePassword()); - sslContextFactory.setTrustStoreType(getTrustStoreType()); - } - - return sslContextFactory; - } - - public static SSLContext getSSLContext() { - SslContextFactory sslContextFactory = getSslContextFactory(); - - try { - sslContextFactory.start(); - return sslContextFactory.getSslContext(); - } catch (Exception e) { - LOG.error("Could not create SSL Context", e); - return null; - } finally { - try { - sslContextFactory.stop(); - } catch (Exception e) { - LOG.error("Could not stop sslContextFactory", e); - } - } - } - - private static String getPasswordFromFile(String fileName) { - try { - File pwdFile = new File(LOGSEARCH_CERT_DEFAULT_FOLDER, fileName); - if (!pwdFile.exists()) { - FileUtils.writeStringToFile(pwdFile, LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD); - return LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD; - } else { - return FileUtils.readFileToString(pwdFile); - } - } catch (Exception e) { - LOG.warn("Exception occurred during read/write password file for keystore/truststore.", e); - return null; - } - } - - private static String getPasswordFromCredentialStore(String propertyName) { - try { - String providerPath = PropertiesHelper.getProperty(CREDENTIAL_STORE_PROVIDER_PATH); - if (providerPath == null) { - return null; - } - - Configuration config = new Configuration(); - config.set(CREDENTIAL_STORE_PROVIDER_PATH, providerPath); - char[] passwordChars = config.getPassword(propertyName); - return (ArrayUtils.isNotEmpty(passwordChars)) ? new String(passwordChars) : null; - } catch (Exception e) { - LOG.warn(String.format("Could not load password %s from credential store, using default password", propertyName), e); - return null; - } - } - - private static String getPassword(String propertyName, String fileName) { - String credentialStorePassword = getPasswordFromCredentialStore(propertyName); - if (credentialStorePassword != null) { - return credentialStorePassword; - } - - String filePassword = getPasswordFromFile(fileName); - if (filePassword != null) { - return filePassword; - } - - return LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD; - } - - /** - * Put private key into in-memory keystore and write it to a file (JKS file) - */ - private static void setKeyAndCertInKeystore(X509Certificate cert, KeyPair keyPair, KeyStore keyStore, String keyStoreLocation, char[] password) - throws Exception { - Certificate[] certChain = new Certificate[1]; - certChain[0] = cert; - try (FileOutputStream fos = new FileOutputStream(keyStoreLocation)) { - keyStore.setKeyEntry("logsearch.alias", keyPair.getPrivate(), password, certChain); - keyStore.store(fos, password); - } catch (Exception e) { - LOG.error("Could not write certificate to Keystore", e); - throw e; - } - } - - /** - * Create in-memory keypair with bouncy castle - */ - private static KeyPair createKeyPair(String encryptionType, int byteCount) - throws NoSuchProviderException, NoSuchAlgorithmException { - Security.addProvider(new BouncyCastleProvider()); - KeyPairGenerator keyPairGenerator = createKeyPairGenerator(encryptionType, byteCount); - return keyPairGenerator.genKeyPair(); - } - - /** - * Generate X509 certificate if it does not exist - */ - private static X509Certificate generateCertificate(String certificateLocation, KeyPair keyPair, String algorithm) throws Exception { - try { - File certFile = new File(certificateLocation); - if (certFile.exists()) { - LOG.info("Certificate file exists ({}), skip the generation.", certificateLocation); - return getCertFile(certificateLocation); - } else { - Security.addProvider(new BouncyCastleProvider()); - X509Certificate cert = createCert(keyPair, algorithm, InetAddress.getLocalHost().getCanonicalHostName()); - FileUtils.writeByteArrayToFile(certFile, cert.getEncoded()); - return cert; - } - } catch (Exception e) { - LOG.error("Could not create certificate.", e); - throw e; - } - } - - private static void ensureStorePassword(String locationArg, String pwdArg, String propertyName, String fileName) { - if (StringUtils.isNotEmpty(System.getProperty(locationArg)) && StringUtils.isEmpty(System.getProperty(pwdArg))) { - String password = getPassword(propertyName, fileName); - System.setProperty(pwdArg, password); - } - } - - public static void ensureStorePasswords() { - ensureStorePassword(KEYSTORE_LOCATION_ARG, KEYSTORE_PASSWORD_ARG, KEYSTORE_PASSWORD_PROPERTY_NAME, KEYSTORE_PASSWORD_FILE); - ensureStorePassword(TRUSTSTORE_LOCATION_ARG, TRUSTSTORE_PASSWORD_ARG, TRUSTSTORE_PASSWORD_PROPERTY_NAME, TRUSTSTORE_PASSWORD_FILE); - } - - private static X509Certificate getCertFile(String location) throws Exception { - try (FileInputStream fos = new FileInputStream(location)) { - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - return (X509Certificate) factory.generateCertificate(fos); - } catch (Exception e) { - LOG.error("Cannot read cert file. ('" + location + "')", e); - throw e; - } - } - - private static X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName) - throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException { - - RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); - RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate(); - - AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm); - AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); - BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); - - ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded()); - SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject()); - publicKeyStream.close(); - - X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder( - new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"), - BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())), - new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), - new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)), - new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"), - pubKey); - - RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus()); - ContentSigner contentSigner = sigGen.build(keyParams); - - X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner); - - JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC"); - return certConverter.getCertificate(certificateHolder); - } - - private static KeyPairGenerator createKeyPairGenerator(String algorithmIdentifier, int bitCount) - throws NoSuchProviderException, NoSuchAlgorithmException { - KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithmIdentifier, BouncyCastleProvider.PROVIDER_NAME); - kpg.initialize(bitCount); - return kpg; - } - - /** - * Create keystore with keys and certificate (only if the keystore does not exist or if you have no permissions on the keystore file) - */ - public static void loadKeystore() { - try { - String certFolder = PropertiesHelper.getProperty(LOGSEARCH_CERT_FOLDER_LOCATION, LOGSEARCH_CERT_DEFAULT_FOLDER); - String certAlgorithm = PropertiesHelper.getProperty(LOGSEARCH_CERT_ALGORITHM, LOGSEARCH_CERT_DEFAULT_ALGORITHM); - String certLocation = String.format("%s/%s", LOGSEARCH_CERT_DEFAULT_FOLDER, LOGSEARCH_CERT_FILENAME); - String keyStoreLocation = StringUtils.isNotEmpty(getKeyStoreLocation()) ? getKeyStoreLocation() - : String.format("%s/%s", LOGSEARCH_CERT_DEFAULT_FOLDER, LOGSEARCH_KEYSTORE_FILENAME); - char[] password = StringUtils.isNotEmpty(getKeyStorePassword()) ? - getKeyStorePassword().toCharArray() : LOGSEARCH_KEYSTORE_DEFAULT_PASSWORD.toCharArray(); - boolean keyStoreFileExists = new File(keyStoreLocation).exists(); - if (!keyStoreFileExists) { - FileUtil.createDirectory(certFolder); - LOG.warn("Keystore file ('{}') does not exist, creating new one. " + - "If the file exists, make sure you have proper permissions on that.", keyStoreLocation); - if (isKeyStoreSpecified() && !"JKS".equalsIgnoreCase(getKeyStoreType())) { - throw new RuntimeException(String.format("Keystore does not exist. Only JKS keystore can be auto generated. (%s)", keyStoreLocation)); - } - LOG.info("SSL keystore is not specified. Generating it with certificate ... (using default format: JKS)"); - Security.addProvider(new BouncyCastleProvider()); - KeyPair keyPair = createKeyPair("RSA", 2048); - File privateKeyFile = new File(String.format("%s/%s", certFolder, LOGSEARCH_KEYSTORE_PRIVATE_KEY)); - if (!privateKeyFile.exists()) { - FileUtils.writeByteArrayToFile(privateKeyFile, keyPair.getPrivate().getEncoded()); - } - File file = new File(String.format("%s/%s", certFolder, LOGSEARCH_KEYSTORE_PUBLIC_KEY)); - if (!file.exists()) { - FileUtils.writeByteArrayToFile(file, keyPair.getPublic().getEncoded()); - } - X509Certificate cert = generateCertificate(certLocation, keyPair, certAlgorithm); - KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - keyStore.load(null, password); - setKeyAndCertInKeystore(cert, keyPair, keyStore, keyStoreLocation, password); - FileUtil.setPermissionOnDirectory(certFolder, "600"); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/WebUtil.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/WebUtil.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/WebUtil.java deleted file mode 100644 index 36865ad..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/util/WebUtil.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.ambari.logsearch.util; - -import java.io.IOException; -import java.net.ServerSocket; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class WebUtil { - private static final Logger LOG = LoggerFactory.getLogger(WebUtil.class); - - private static final String WEB_RESOURCE_FOLDER = "webapps/app"; - - private WebUtil() { - throw new UnsupportedOperationException(); - } - - public static URI findWebResourceBase() { - URL fileCompleteUrl = Thread.currentThread().getContextClassLoader().getResource(WEB_RESOURCE_FOLDER); - String errorMessage = "Web Resource Folder " + WEB_RESOURCE_FOLDER + " not found in classpath"; - if (fileCompleteUrl != null) { - try { - return fileCompleteUrl.toURI().normalize(); - } catch (URISyntaxException e) { - LOG.error(errorMessage, e); - System.exit(1); - } - } else { - LOG.error(errorMessage); - System.exit(1); - } - throw new IllegalStateException(errorMessage); - } - - public static void checkPort(int port) { - try (ServerSocket serverSocket = new ServerSocket(port)) { - } catch (IOException ex) { - LOG.error(ex.getLocalizedMessage() + " PORT :" + port); - System.exit(1); - } - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/filters/LogsearchKRBAuthenticationFilter.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/filters/LogsearchKRBAuthenticationFilter.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/filters/LogsearchKRBAuthenticationFilter.java index ec3075c..e50fab5 100644 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/filters/LogsearchKRBAuthenticationFilter.java +++ b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/filters/LogsearchKRBAuthenticationFilter.java @@ -30,6 +30,8 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import javax.annotation.PostConstruct; +import javax.inject.Inject; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; @@ -40,7 +42,7 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.ambari.logsearch.config.api.LogSearchPropertyDescription; +import org.apache.ambari.logsearch.conf.LogSearchSpnegoConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.AbstractAuthenticationToken; @@ -54,7 +56,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; -import org.apache.ambari.logsearch.common.PropertiesHelper; import org.apache.commons.collections.iterators.IteratorEnumeration; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; @@ -63,83 +64,12 @@ import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHand import org.apache.hadoop.security.authentication.util.KerberosName; import org.springframework.security.web.authentication.WebAuthenticationDetails; -import static org.apache.ambari.logsearch.common.LogSearchConstants.LOGSEARCH_PROPERTIES_FILE; public class LogsearchKRBAuthenticationFilter extends LogsearchKrbFilter { private static final Logger logger = LoggerFactory.getLogger(LogsearchKRBAuthenticationFilter.class); - @LogSearchPropertyDescription( - name = "logsearch.hadoop.security.auth_to_local", - description = "Rules that will be applied on authentication names and map them into local usernames.", - examples = {"RULE:[1:$1@$0](.*@EXAMPLE.COM)s/@.*//", "DEFAULT"}, - defaultValue = "DEFAULT", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String NAME_RULES = "logsearch.hadoop.security.auth_to_local"; - - @LogSearchPropertyDescription( - name = "logsearch.admin.kerberos.token.valid.seconds", - description = "Kerberos token validity in seconds.", - examples = {"30"}, - defaultValue = "30", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String TOKEN_VALID = "logsearch.admin.kerberos.token.valid.seconds"; - - @LogSearchPropertyDescription( - name = "logsearch.admin.kerberos.cookie.domain", - description = "Domain for Kerberos cookie.", - examples = {"c6401.ambari.apache.org", "localhost"}, - defaultValue = "localhost", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String COOKIE_DOMAIN = "logsearch.admin.kerberos.cookie.domain"; - - @LogSearchPropertyDescription( - name = "logsearch.admin.kerberos.cookie.path", - description = "Cookie path of the kerberos cookie", - examples = {"/"}, - defaultValue = "/", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String COOKIE_PATH = "logsearch.admin.kerberos.cookie.path"; - - @LogSearchPropertyDescription( - name = "logsearch.spnego.kerberos.principal", - description = "Principal for SPNEGO authentication for Http requests", - examples = {"myu...@example.com"}, - defaultValue = "", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String PRINCIPAL = "logsearch.spnego.kerberos.principal"; - - @LogSearchPropertyDescription( - name = "logsearch.spnego.kerberos.keytab", - description = "Keytab for SPNEGO authentication for Http requests.", - examples = {"/etc/security/keytabs/mykeytab.keytab"}, - defaultValue = "", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String KEYTAB = "logsearch.spnego.kerberos.keytab"; - - @LogSearchPropertyDescription( - name = "logsearch.spnego.kerberos.host", - description = "", - examples = {"c6401.ambari.apache.org", "localhost"}, - defaultValue = "localhost", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String HOST_NAME = "logsearch.spnego.kerberos.host"; - - @LogSearchPropertyDescription( - name = "logsearch.spnego.kerberos.enabled", - description = "Enable SPNEGO based authentication for Log Search Server.", - examples = {"true", "false"}, - defaultValue = "false", - sources = {LOGSEARCH_PROPERTIES_FILE} - ) - private static final String KERBEROS_ENABLED = "logsearch.spnego.kerberos.enabled"; - + @Inject + private LogSearchSpnegoConfig logSearchSpnegoConfig; private static final String NAME_RULES_PARAM = "kerberos.name.rules"; private static final String TOKEN_VALID_PARAM = "token.validity"; @@ -157,7 +87,8 @@ public class LogsearchKRBAuthenticationFilter extends LogsearchKrbFilter { private String authType = PseudoAuthenticationHandler.TYPE; private static boolean spnegoEnable = false; - public LogsearchKRBAuthenticationFilter() { + @PostConstruct + public void postConstruct() { try { isSpnegoEnable(); init(null); @@ -169,18 +100,18 @@ public class LogsearchKRBAuthenticationFilter extends LogsearchKrbFilter { @Override public void init(FilterConfig conf) throws ServletException { final FilterConfig globalConf = conf; - String hostName = PropertiesHelper.getProperty(HOST_NAME, "localhost"); + String hostName = logSearchSpnegoConfig.getHostName(); final Map<String, String> params = new HashMap<String, String>(); if (spnegoEnable) { authType = KerberosAuthenticationHandler.TYPE; } params.put(AUTH_TYPE,authType); - params.put(NAME_RULES_PARAM,PropertiesHelper.getProperty(NAME_RULES, "DEFAULT")); - params.put(TOKEN_VALID_PARAM, PropertiesHelper.getProperty(TOKEN_VALID, "30")); - params.put(COOKIE_DOMAIN_PARAM, PropertiesHelper.getProperty(COOKIE_DOMAIN, hostName)); - params.put(COOKIE_PATH_PARAM, PropertiesHelper.getProperty(COOKIE_PATH, "/")); - params.put(PRINCIPAL_PARAM,PropertiesHelper.getProperty(PRINCIPAL,"")); - params.put(KEYTAB_PARAM,PropertiesHelper.getProperty(KEYTAB,"")); + params.put(NAME_RULES_PARAM, logSearchSpnegoConfig.getNameRules()); + params.put(TOKEN_VALID_PARAM, logSearchSpnegoConfig.getTokenValid()); + params.put(COOKIE_DOMAIN_PARAM, logSearchSpnegoConfig.getCookieDomain()); + params.put(COOKIE_PATH_PARAM, logSearchSpnegoConfig.getCookiePath()); + params.put(PRINCIPAL_PARAM, logSearchSpnegoConfig.getPrincipal()); + params.put(KEYTAB_PARAM, logSearchSpnegoConfig.getKeyTab()); FilterConfig myConf = new FilterConfig() { @Override public ServletContext getServletContext() { @@ -263,7 +194,7 @@ public class LogsearchKRBAuthenticationFilter extends LogsearchKrbFilter { } if (!isLoginRequest(httpRequest) && spnegoEnable && (existingAuth == null || !existingAuth.isAuthenticated())) { - KerberosName.setRules(PropertiesHelper.getProperty(NAME_RULES, "DEFAULT")); + KerberosName.setRules(logSearchSpnegoConfig.getNameRules()); String userName = getUsernameFromRequest(httpRequest); if ((existingAuth == null || !existingAuth.isAuthenticated()) && (StringUtils.isNotEmpty(userName))) { @@ -297,12 +228,12 @@ public class LogsearchKRBAuthenticationFilter extends LogsearchKrbFilter { } private void isSpnegoEnable() { - spnegoEnable = PropertiesHelper.getBooleanProperty(KERBEROS_ENABLED, false); + spnegoEnable = logSearchSpnegoConfig.isKerberosEnabled(); if (spnegoEnable) { spnegoEnable = false; - String keytab = PropertiesHelper.getProperty(KEYTAB); - String principal = PropertiesHelper.getProperty(PRINCIPAL); - String hostname = PropertiesHelper.getProperty(HOST_NAME); + String keytab = logSearchSpnegoConfig.getKeyTab(); + String principal = logSearchSpnegoConfig.getPrincipal(); + String hostname = logSearchSpnegoConfig.getHostName(); if (StringUtils.isNotEmpty(keytab) && StringUtils.isNotEmpty(principal) && StringUtils.isNotEmpty(hostname)) { spnegoEnable = true; http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/listener/LogSearchSessionListener.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/listener/LogSearchSessionListener.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/listener/LogSearchSessionListener.java index 9fa5c80..55101db 100644 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/listener/LogSearchSessionListener.java +++ b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/listener/LogSearchSessionListener.java @@ -35,7 +35,7 @@ public class LogSearchSessionListener implements HttpSessionListener { synchronized (this) { numberOfSessions++; } - LOG.debug(String.format("New session is created (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions)); + LOG.info(String.format("New session is created (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions)); } @Override @@ -43,6 +43,6 @@ public class LogSearchSessionListener implements HttpSessionListener { synchronized (this) { numberOfSessions--; } - LOG.debug(String.format("Session destroyed (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions)); + LOG.info(String.format("Session destroyed (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions)); } } http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapProperties.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapProperties.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapProperties.java deleted file mode 100644 index 82e71fe..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapProperties.java +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.ambari.logsearch.web.security; - -import org.apache.commons.lang.StringUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Describes LDAP Server connection parameters - */ -public class LdapProperties { - private String primaryUrl; - private String secondaryUrl; - private boolean useSsl; - private boolean anonymousBind; - private String managerDn; - private String managerPassword; - private String baseDN; - private String dnAttribute; - private String referralMethod; - - // LDAP group properties - private String groupBase; - private String groupObjectClass; - private String groupMembershipAttr; - private String groupNamingAttr; - private String adminGroupMappingRules; - private boolean groupMappingEnabled; - - // LDAP user properties - private String userBase; - private String userObjectClass; - private String usernameAttribute; - private String userSearchBase = ""; - - private String groupSearchFilter; - private static final String userSearchFilter = "({attribute}={0})"; - - public List<String> getLdapUrls() { - String protocol = useSsl ? "ldaps://" : "ldap://"; - - if (StringUtils.isEmpty(primaryUrl) || primaryUrl.equalsIgnoreCase("none")) { - return Collections.emptyList(); - } else { - List<String> list = new ArrayList<String>(); - list.add(protocol + primaryUrl); - if (StringUtils.isNotEmpty(secondaryUrl)) { - list.add(protocol + secondaryUrl); - } - return list; - } - } - - public String getPrimaryUrl() { - return primaryUrl; - } - - public void setPrimaryUrl(String primaryUrl) { - this.primaryUrl = primaryUrl; - } - - public String getSecondaryUrl() { - return secondaryUrl; - } - - public void setSecondaryUrl(String secondaryUrl) { - this.secondaryUrl = secondaryUrl; - } - - public boolean isUseSsl() { - return useSsl; - } - - public void setUseSsl(boolean useSsl) { - this.useSsl = useSsl; - } - - public boolean isAnonymousBind() { - return anonymousBind; - } - - public void setAnonymousBind(boolean anonymousBind) { - this.anonymousBind = anonymousBind; - } - - public String getManagerDn() { - return managerDn; - } - - public void setManagerDn(String managerDn) { - this.managerDn = managerDn; - } - - public String getManagerPassword() { - return managerPassword; - } - - public void setManagerPassword(String managerPassword) { - this.managerPassword = managerPassword; - } - - public String getBaseDN() { - return baseDN; - } - - public void setBaseDN(String baseDN) { - this.baseDN = baseDN; - } - - public String getUserSearchBase() { - return userSearchBase; - } - - public void setUserSearchBase(String userSearchBase) { - this.userSearchBase = userSearchBase; - } - - public String getUserSearchFilter() { - return userSearchFilter.replace("{attribute}", usernameAttribute); - } - - public String getUsernameAttribute() { - return usernameAttribute; - } - - public void setUsernameAttribute(String usernameAttribute) { - this.usernameAttribute = usernameAttribute; - } - - public String getGroupBase() { - return groupBase; - } - - public void setGroupBase(String groupBase) { - this.groupBase = groupBase; - } - - public String getGroupObjectClass() { - return groupObjectClass; - } - - public void setGroupObjectClass(String groupObjectClass) { - this.groupObjectClass = groupObjectClass; - } - - public String getGroupMembershipAttr() { - return groupMembershipAttr; - } - - public void setGroupMembershipAttr(String groupMembershipAttr) { - this.groupMembershipAttr = groupMembershipAttr; - } - - public String getGroupNamingAttr() { - return groupNamingAttr; - } - - public void setGroupNamingAttr(String groupNamingAttr) { - this.groupNamingAttr = groupNamingAttr; - } - - public String getAdminGroupMappingRules() { - return adminGroupMappingRules; - } - - public void setAdminGroupMappingRules(String adminGroupMappingRules) { - this.adminGroupMappingRules = adminGroupMappingRules; - } - - public String getGroupSearchFilter() { - return groupSearchFilter; - } - - public void setGroupSearchFilter(String groupSearchFilter) { - this.groupSearchFilter = groupSearchFilter; - } - - public boolean isGroupMappingEnabled() { - return groupMappingEnabled; - } - - public void setGroupMappingEnabled(boolean groupMappingEnabled) { - this.groupMappingEnabled = groupMappingEnabled; - } - - public void setUserBase(String userBase) { - this.userBase = userBase; - } - - public void setUserObjectClass(String userObjectClass) { - this.userObjectClass = userObjectClass; - } - - public String getUserBase() { - return userBase; - } - - public String getUserObjectClass() { - return userObjectClass; - } - - public String getDnAttribute() { - return dnAttribute; - } - - public void setDnAttribute(String dnAttribute) { - this.dnAttribute = dnAttribute; - } - - public void setReferralMethod(String referralMethod) { - this.referralMethod = referralMethod; - } - - public String getReferralMethod() { - return referralMethod; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null || getClass() != obj.getClass()) - return false; - - LdapProperties that = (LdapProperties) obj; - - if (primaryUrl != null ? !primaryUrl.equals(that.primaryUrl) - : that.primaryUrl != null) - return false; - if (secondaryUrl != null ? !secondaryUrl.equals(that.secondaryUrl) - : that.secondaryUrl != null) - return false; - if (useSsl != that.useSsl) - return false; - if (anonymousBind != that.anonymousBind) - return false; - if (managerDn != null ? !managerDn.equals(that.managerDn) - : that.managerDn != null) - return false; - if (managerPassword != null ? !managerPassword - .equals(that.managerPassword) : that.managerPassword != null) - return false; - if (baseDN != null ? !baseDN.equals(that.baseDN) : that.baseDN != null) - return false; - if (userBase != null ? !userBase.equals(that.userBase) - : that.userBase != null) - return false; - if (userObjectClass != null ? !userObjectClass - .equals(that.userObjectClass) : that.userObjectClass != null) - return false; - if (usernameAttribute != null ? !usernameAttribute - .equals(that.usernameAttribute) - : that.usernameAttribute != null) - return false; - if (groupBase != null ? !groupBase.equals(that.groupBase) - : that.groupBase != null) - return false; - if (groupObjectClass != null ? !groupObjectClass - .equals(that.groupObjectClass) : that.groupObjectClass != null) - return false; - if (groupMembershipAttr != null ? !groupMembershipAttr - .equals(that.groupMembershipAttr) - : that.groupMembershipAttr != null) - return false; - if (groupNamingAttr != null ? !groupNamingAttr - .equals(that.groupNamingAttr) : that.groupNamingAttr != null) - return false; - if (adminGroupMappingRules != null ? !adminGroupMappingRules - .equals(that.adminGroupMappingRules) - : that.adminGroupMappingRules != null) - return false; - if (groupSearchFilter != null ? !groupSearchFilter - .equals(that.groupSearchFilter) - : that.groupSearchFilter != null) - return false; - if (dnAttribute != null ? !dnAttribute.equals(that.dnAttribute) - : that.dnAttribute != null) - return false; - if (referralMethod != null ? !referralMethod - .equals(that.referralMethod) : that.referralMethod != null) - return false; - - return true; - } - - @Override - public int hashCode() { - int result = primaryUrl != null ? primaryUrl.hashCode() : 0; - result = 31 * result - + (secondaryUrl != null ? secondaryUrl.hashCode() : 0); - result = 31 * result + (useSsl ? 1 : 0); - result = 31 * result + (anonymousBind ? 1 : 0); - result = 31 * result + (managerDn != null ? managerDn.hashCode() : 0); - result = 31 * result - + (managerPassword != null ? managerPassword.hashCode() : 0); - result = 31 * result + (baseDN != null ? baseDN.hashCode() : 0); - result = 31 * result + (userBase != null ? userBase.hashCode() : 0); - result = 31 * result - + (userObjectClass != null ? userObjectClass.hashCode() : 0); - result = 31 - * result - + (usernameAttribute != null ? usernameAttribute.hashCode() : 0); - result = 31 * result + (groupBase != null ? groupBase.hashCode() : 0); - result = 31 * result - + (groupObjectClass != null ? groupObjectClass.hashCode() : 0); - result = 31 - * result - + (groupMembershipAttr != null ? groupMembershipAttr.hashCode() - : 0); - result = 31 * result - + (groupNamingAttr != null ? groupNamingAttr.hashCode() : 0); - result = 31 - * result - + (adminGroupMappingRules != null ? adminGroupMappingRules - .hashCode() : 0); - result = 31 - * result - + (groupSearchFilter != null ? groupSearchFilter.hashCode() : 0); - result = 31 * result - + (dnAttribute != null ? dnAttribute.hashCode() : 0); - result = 31 * result - + (referralMethod != null ? referralMethod.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return "LdapProperties [primaryUrl=" + primaryUrl + ", secondaryUrl=" - + secondaryUrl + ", useSsl=" + useSsl + ", anonymousBind=" - + anonymousBind + ", managerDn=" + managerDn - + ", managerPassword=" + managerPassword == null ? "null" - : "****" + ", baseDN=" + baseDN + ", dnAttribute=" - + dnAttribute + ", referralMethod=" + referralMethod - + ", groupBase=" + groupBase + ", groupObjectClass=" - + groupObjectClass + ", groupMembershipAttr=" - + groupMembershipAttr + ", groupNamingAttr=" - + groupNamingAttr + ", adminGroupMappingRules=" - + adminGroupMappingRules + ", groupMappingEnabled=" - + groupMappingEnabled + ", userBase=" + userBase - + ", userObjectClass=" + userObjectClass - + ", usernameAttribute=" + usernameAttribute - + ", userSearchBase=" + userSearchBase - + ", groupSearchFilter=" + groupSearchFilter + "]"; - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapPropertyName.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapPropertyName.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapPropertyName.java deleted file mode 100644 index 370c94b..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapPropertyName.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.ambari.logsearch.web.security; - -public class LdapPropertyName { - - public static final String LDAP_USE_SSL_KEY = "authentication.ldap.useSSL"; - public static final String LDAP_PRIMARY_URL_KEY = "authentication.ldap.primaryUrl"; - public static final String LDAP_SECONDARY_URL_KEY = "authentication.ldap.secondaryUrl"; - public static final String LDAP_BASE_DN_KEY = "authentication.ldap.baseDn"; - public static final String LDAP_BIND_ANONYMOUSLY_KEY = "authentication.ldap.bindAnonymously"; - public static final String LDAP_MANAGER_DN_KEY = "authentication.ldap.managerDn"; - public static final String LDAP_MANAGER_PASSWORD_KEY = "authentication.ldap.managerPassword"; - public static final String LDAP_DN_ATTRIBUTE_KEY = "authentication.ldap.dnAttribute"; - public static final String LDAP_USERNAME_ATTRIBUTE_KEY = "authentication.ldap.usernameAttribute"; - public static final String LDAP_USER_BASE_KEY = "authentication.ldap.userBase"; - public static final String LDAP_USER_OBJECT_CLASS_KEY = "authentication.ldap.userObjectClass"; - public static final String LDAP_GROUP_BASE_KEY = "authentication.ldap.groupBase"; - public static final String LDAP_GROUP_OBJECT_CLASS_KEY = "authentication.ldap.groupObjectClass"; - public static final String LDAP_GROUP_NAMING_ATTR_KEY = "authentication.ldap.groupNamingAttr"; - public static final String LDAP_GROUP_MEMEBERSHIP_ATTR_KEY = "authentication.ldap.groupMembershipAttr"; - public static final String LDAP_ADMIN_GROUP_MAPPING_RULES_KEY = "authorization.ldap.adminGroupMappingRules"; - public static final String LDAP_GROUP_SEARCH_FILTER_KEY = "authorization.ldap.groupSearchFilter"; - public static final String LDAP_REFERRAL_KEY = "authentication.ldap.referral"; - - // default - public static final String LDAP_BIND_ANONYMOUSLY_DEFAULT = "true"; - public static final String LDAP_PRIMARY_URL_DEFAULT = "localhost:389"; - public static final String LDAP_BASE_DN_DEFAULT = "dc=example,dc=com"; - public static final String LDAP_USERNAME_ATTRIBUTE_DEFAULT = "uid"; - public static final String LDAP_DN_ATTRIBUTE_DEFAULT = "dn"; - public static final String LDAP_USER_BASE_DEFAULT = "ou=people,dc=example,dc=com"; - public static final String LDAP_USER_OBJECT_CLASS_DEFAULT = "person"; - public static final String LDAP_GROUP_BASE_DEFAULT = "ou=groups,dc=example,dc=com"; - public static final String LDAP_GROUP_OBJECT_CLASS_DEFAULT = "group"; - public static final String LDAP_GROUP_NAMING_ATTR_DEFAULT = "cn"; - public static final String LDAP_GROUP_MEMBERSHIP_ATTR_DEFAULT = "member"; - public static final String LDAP_ADMIN_GROUP_MAPPING_RULES_DEFAULT = "Logsearch Administrators"; - public static final String LDAP_GROUP_SEARCH_FILTER_DEFAULT = ""; - public static final String LDAP_REFERRAL_DEFAULT = "ignore"; - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapUtil.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapUtil.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapUtil.java deleted file mode 100644 index 6248e74..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LdapUtil.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.ambari.logsearch.web.security; - -import java.io.IOException; -import java.util.Properties; - -import org.apache.ambari.logsearch.common.PropertiesHelper; -import org.apache.ambari.logsearch.common.XMLPropertiesHelper; -import org.apache.log4j.Logger; -import org.springframework.core.io.ClassPathResource; - -public class LdapUtil { - - private static Logger logger = Logger.getLogger(LdapUtil.class); - - /** - * Gets parameters of LDAP server to connect to - * - * @return LdapServerProperties object representing connection parameters - */ - public static LdapProperties getLdapServerProperties(Properties properties) { - LdapProperties ldapServerProperties = new LdapProperties(); - - ldapServerProperties.setPrimaryUrl(properties.getProperty(LdapPropertyName.LDAP_PRIMARY_URL_KEY, - LdapPropertyName.LDAP_PRIMARY_URL_DEFAULT)); - ldapServerProperties.setSecondaryUrl(properties.getProperty(LdapPropertyName.LDAP_SECONDARY_URL_KEY)); - ldapServerProperties.setUseSsl("true".equalsIgnoreCase(properties - .getProperty(LdapPropertyName.LDAP_USE_SSL_KEY))); - ldapServerProperties.setAnonymousBind("true".equalsIgnoreCase(properties.getProperty( - LdapPropertyName.LDAP_BIND_ANONYMOUSLY_KEY, LdapPropertyName.LDAP_BIND_ANONYMOUSLY_DEFAULT))); - ldapServerProperties.setManagerDn(properties.getProperty(LdapPropertyName.LDAP_MANAGER_DN_KEY)); - String ldapPasswordProperty = properties.getProperty(LdapPropertyName.LDAP_MANAGER_PASSWORD_KEY); - // TODO read password from password file - ldapServerProperties.setManagerPassword(ldapPasswordProperty); - ldapServerProperties.setBaseDN(properties.getProperty(LdapPropertyName.LDAP_BASE_DN_KEY, - LdapPropertyName.LDAP_BASE_DN_DEFAULT)); - ldapServerProperties.setUsernameAttribute(properties.getProperty(LdapPropertyName.LDAP_USERNAME_ATTRIBUTE_KEY, - LdapPropertyName.LDAP_USERNAME_ATTRIBUTE_DEFAULT)); - - ldapServerProperties.setUserBase(properties.getProperty(LdapPropertyName.LDAP_USER_BASE_KEY, - LdapPropertyName.LDAP_USER_BASE_DEFAULT)); - ldapServerProperties.setUserObjectClass(properties.getProperty(LdapPropertyName.LDAP_USER_OBJECT_CLASS_KEY, - LdapPropertyName.LDAP_USER_OBJECT_CLASS_DEFAULT)); - ldapServerProperties.setDnAttribute(properties.getProperty(LdapPropertyName.LDAP_DN_ATTRIBUTE_KEY, - LdapPropertyName.LDAP_DN_ATTRIBUTE_DEFAULT)); - - ldapServerProperties.setGroupBase(properties.getProperty(LdapPropertyName.LDAP_GROUP_BASE_KEY, - LdapPropertyName.LDAP_GROUP_BASE_DEFAULT)); - ldapServerProperties.setGroupObjectClass(properties.getProperty(LdapPropertyName.LDAP_GROUP_OBJECT_CLASS_KEY, - LdapPropertyName.LDAP_GROUP_OBJECT_CLASS_DEFAULT)); - ldapServerProperties.setGroupMembershipAttr(properties.getProperty( - LdapPropertyName.LDAP_GROUP_MEMEBERSHIP_ATTR_KEY, LdapPropertyName.LDAP_GROUP_MEMBERSHIP_ATTR_DEFAULT)); - ldapServerProperties.setGroupNamingAttr(properties.getProperty(LdapPropertyName.LDAP_GROUP_NAMING_ATTR_KEY, - LdapPropertyName.LDAP_GROUP_NAMING_ATTR_DEFAULT)); - ldapServerProperties.setAdminGroupMappingRules(properties.getProperty( - LdapPropertyName.LDAP_ADMIN_GROUP_MAPPING_RULES_KEY, - LdapPropertyName.LDAP_ADMIN_GROUP_MAPPING_RULES_DEFAULT)); - ldapServerProperties.setGroupSearchFilter(properties.getProperty(LdapPropertyName.LDAP_GROUP_SEARCH_FILTER_KEY, - LdapPropertyName.LDAP_GROUP_SEARCH_FILTER_DEFAULT)); - ldapServerProperties.setReferralMethod(properties.getProperty(LdapPropertyName.LDAP_REFERRAL_KEY, - LdapPropertyName.LDAP_REFERRAL_DEFAULT)); - - if (properties.containsKey(LdapPropertyName.LDAP_GROUP_BASE_KEY) - || properties.containsKey(LdapPropertyName.LDAP_GROUP_OBJECT_CLASS_KEY) - || properties.containsKey(LdapPropertyName.LDAP_GROUP_MEMEBERSHIP_ATTR_KEY) - || properties.containsKey(LdapPropertyName.LDAP_GROUP_NAMING_ATTR_KEY) - || properties.containsKey(LdapPropertyName.LDAP_ADMIN_GROUP_MAPPING_RULES_KEY) - || properties.containsKey(LdapPropertyName.LDAP_GROUP_SEARCH_FILTER_KEY)) { - ldapServerProperties.setGroupMappingEnabled(true); - } - - return ldapServerProperties; - } - - /** - * @return - */ - public static LdapProperties loadLdapProperties() { - LdapProperties ldapServerProperties = null; - String ldapConfigFileName = PropertiesHelper.getProperty("logsearch.login.ldap.config", "logsearch-admin-site.xml"); - Properties props = null; - ClassPathResource resource = new ClassPathResource(ldapConfigFileName); - if (resource != null) { - try { - props = new Properties(); - new XMLPropertiesHelper().loadFromXml(props, resource.getInputStream()); - ldapServerProperties = getLdapServerProperties(props); - } catch (IOException e) { - logger.error("Ldap configudation file loading failed : " + e.getMessage()); - } - } - if (ldapServerProperties == null) { - logger.error("ldapServerProperties object is not created."); - } - return ldapServerProperties; - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAbstractAuthenticationProvider.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAbstractAuthenticationProvider.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAbstractAuthenticationProvider.java index 1c7bf3b..88f8c3b 100644 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAbstractAuthenticationProvider.java +++ b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAbstractAuthenticationProvider.java @@ -29,7 +29,7 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; abstract class LogsearchAbstractAuthenticationProvider implements AuthenticationProvider { protected enum AuthMethod { - LDAP, FILE, EXTERNAL_AUTH, SIMPLE + FILE, EXTERNAL_AUTH, SIMPLE }; @Override http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAuthenticationProvider.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAuthenticationProvider.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAuthenticationProvider.java index 711e3ec..09c05fc 100644 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAuthenticationProvider.java +++ b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchAuthenticationProvider.java @@ -37,9 +37,6 @@ public class LogsearchAuthenticationProvider extends LogsearchAbstractAuthentica private static final Logger auditLogger = Logger.getLogger("org.apache.ambari.logsearch.audit"); @Inject - private LogsearchLdapAuthenticationProvider ldapAuthenticationProvider; - - @Inject private LogsearchFileAuthenticationProvider fileAuthenticationProvider; @Inject @@ -106,7 +103,6 @@ public class LogsearchAuthenticationProvider extends LogsearchAbstractAuthentica private Authentication doAuth(Authentication authentication, AuthMethod authMethod) { switch (authMethod) { - case LDAP: return ldapAuthenticationProvider.authenticate(authentication); case FILE: return fileAuthenticationProvider.authenticate(authentication); case EXTERNAL_AUTH: return externalServerAuthenticationProvider.authenticate(authentication); case SIMPLE: return simpleAuthenticationProvider.authenticate(authentication); http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapAuthenticationProvider.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapAuthenticationProvider.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapAuthenticationProvider.java deleted file mode 100644 index ed4d7ef..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapAuthenticationProvider.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.ambari.logsearch.web.security; - -import java.util.List; - -import org.apache.ambari.logsearch.conf.AuthPropsConfig; -import org.apache.log4j.Logger; -import org.springframework.ldap.CommunicationException; -import org.springframework.ldap.core.support.LdapContextSource; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.ldap.authentication.LdapAuthenticationProvider; -import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; - -import javax.annotation.PostConstruct; -import javax.inject.Inject; -import javax.inject.Named; - -@Named -public class LogsearchLdapAuthenticationProvider extends - LogsearchAbstractAuthenticationProvider { - - private static Logger logger = Logger - .getLogger(LogsearchLdapAuthenticationProvider.class); - - private static LdapProperties ldapServerProperties = null; - private static LdapAuthenticationProvider ldapAuthProvider = null; - private String logStatement = ""; - - @Inject - private AuthPropsConfig authPropsConfig; - - public LogsearchLdapAuthenticationProvider() { - } - - @PostConstruct - public void postConstruct() { - logger.debug("Creating object of ldap auth provider "); - if (authPropsConfig.isAuthLdapEnabled()) { - ldapAuthProvider = loadLdapAuthenticationProvider(); - } else { - logger.info("Ldap auth is disabled"); - } - } - - @Override - public Authentication authenticate(Authentication authentication) - throws AuthenticationException { - if (!authPropsConfig.isAuthLdapEnabled()) { - logger.debug("Ldap auth is disabled"); - return authentication; - } - try { - LdapAuthenticationProvider authProvider = loadLdapAuthenticationProvider(); - if (authProvider != null) { - return authProvider.authenticate(authentication); - } else { - return authentication; - } - } catch (AuthenticationException e) { - logger.info("Got exception during LDAP authentication attempt", e); - // Try to help in troubleshooting - Throwable cause = e.getCause(); - if (cause != null) { - if ((cause != e) - && (cause instanceof org.springframework.ldap.AuthenticationException)) { - logger.warn( - "Looks like LDAP manager credentials (that are used for " - + "connecting to LDAP server) are invalid.", - e); - } - } - } catch (CommunicationException e) { - logger.error(e); - } catch (Exception e) { - logger.error(e, e.getCause()); - } - if (authentication != null && !authentication.isAuthenticated()) { - logger.warn("Ldap authentication failed. username=" - + authentication.getName() + ", details=" - + authentication.getDetails()); - throw new BadCredentialsException("Invalid credentials!!"); - } - return authentication; - } - - /** - * Reloads LDAP Context Source and depending objects if properties were - * changed - * - * @return corresponding LDAP authentication provider - */ - private LdapAuthenticationProvider loadLdapAuthenticationProvider() { - if (reloadLdapServerProperties()) { - logger.info("LDAP Properties changed - rebuilding Context"); - LdapContextSource springSecurityContextSource = new LdapContextSource(); - List<String> ldapUrls = ldapServerProperties.getLdapUrls(); - logStatement = "ldapUrls=" + ldapUrls; - if (ldapUrls == null || ldapUrls.size() == 0) { - logger.info("LDAP URL is empty. So won't initialize LDAP provider"); - return null; - } - - springSecurityContextSource.setUrls(ldapUrls - .toArray(new String[ldapUrls.size()])); - springSecurityContextSource.setBase(ldapServerProperties - .getBaseDN()); - logStatement = logStatement + ", baseDN=" - + ldapServerProperties.getBaseDN(); - - if (!ldapServerProperties.isAnonymousBind()) { - springSecurityContextSource.setUserDn(ldapServerProperties - .getManagerDn()); - logStatement = logStatement + ", managerDN=" - + ldapServerProperties.getManagerDn(); - springSecurityContextSource.setPassword(ldapServerProperties - .getManagerPassword()); - } - - try { - springSecurityContextSource.afterPropertiesSet(); - } catch (Exception e) { - logger.error("LDAP Context Source not loaded ", e); - throw new UsernameNotFoundException( - "LDAP Context Source not loaded. ldapDetails=" - + logStatement, e); - } - - String userSearchBase = ldapServerProperties.getUserSearchBase(); - logStatement = logStatement + ", userSearchBase=" + userSearchBase; - String userSearchFilter = ldapServerProperties - .getUserSearchFilter(); - logStatement = logStatement + ", userSearchFilter=" - + userSearchFilter; - - logger.info("LDAP properties=" + logStatement); - FilterBasedLdapUserSearch userSearch = new FilterBasedLdapUserSearch( - userSearchBase, userSearchFilter, - springSecurityContextSource); - - LogsearchLdapBindAuthenticator bindAuthenticator = new LogsearchLdapBindAuthenticator( - springSecurityContextSource, ldapServerProperties); - bindAuthenticator.setUserSearch(userSearch); - - LdapAuthenticationProvider authenticationProvider = new LdapAuthenticationProvider( - bindAuthenticator); - ldapAuthProvider = authenticationProvider; - - } - return ldapAuthProvider; - } - - /** - * Reloads LDAP Server properties from configuration - * - * @return true if properties were reloaded - */ - private boolean reloadLdapServerProperties() { - LdapProperties properties = LdapUtil.loadLdapProperties(); - if (!properties.equals(ldapServerProperties)) { - logger.info("Reloading properties"); - ldapServerProperties = properties; - return true; - } - return false; - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapBindAuthenticator.java ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapBindAuthenticator.java b/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapBindAuthenticator.java deleted file mode 100644 index 10f7507..0000000 --- a/ambari-logsearch/ambari-logsearch-server/src/main/java/org/apache/ambari/logsearch/web/security/LogsearchLdapBindAuthenticator.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.ambari.logsearch.web.security; - -import org.apache.log4j.Logger; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.support.BaseLdapPathContextSource; -import org.springframework.security.core.Authentication; -import org.springframework.security.ldap.authentication.BindAuthenticator; - -public class LogsearchLdapBindAuthenticator extends BindAuthenticator { - private static Logger logger = Logger - .getLogger(LogsearchLdapBindAuthenticator.class); - - LdapProperties ldapServerProperties; - - public LogsearchLdapBindAuthenticator( - BaseLdapPathContextSource contextSource, - LdapProperties ldapServerProperties) { - super(contextSource); - this.ldapServerProperties = ldapServerProperties; - logger.info("LDAP properties=" + ldapServerProperties); - } - - @Override - public DirContextOperations authenticate(Authentication authentication) { - return super.authenticate(authentication); - } - -} http://git-wip-us.apache.org/repos/asf/ambari/blob/555f241c/ambari-logsearch/ambari-logsearch-server/src/main/resources/default.properties ---------------------------------------------------------------------- diff --git a/ambari-logsearch/ambari-logsearch-server/src/main/resources/default.properties b/ambari-logsearch/ambari-logsearch-server/src/main/resources/default.properties index cd1f22a..4c74142 100644 --- a/ambari-logsearch/ambari-logsearch-server/src/main/resources/default.properties +++ b/ambari-logsearch/ambari-logsearch-server/src/main/resources/default.properties @@ -21,7 +21,6 @@ logsearch.auth.simple.enable=false #login config logsearch.login.credentials.file=user_pass.json -logsearch.login.ldap.config=logsearch-admin-site.xml logsearch.cert.folder.location=/etc/ambari-logsearch-portal/conf/keys logsearch.cert.algorithm=sha256WithRSAEncryption