Commit d0abe699 authored by benjamin.ertl's avatar benjamin.ertl
Browse files

refactoring

parent 63b3a03d
......@@ -23,6 +23,47 @@
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>edu.kit.scc.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
${project.build.directory}/lib
</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
......@@ -37,7 +78,7 @@
<artifactId>httpclient</artifactId>
<version>4.1</version>
</dependency>
<!-- OpenID Connect -->
<dependency>
<groupId>com.nimbusds</groupId>
......@@ -45,5 +86,22 @@
<version>5.1</version>
</dependency>
<!-- Utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package edu.kit.scc;
import java.net.URISyntaxException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nimbusds.oauth2.sdk.ParseException;
import edu.kit.scc.oidc.OidcClient;
import edu.kit.scc.dei.adsecp.EcpAuthenticator;
import edu.kit.scc.http.HttpClient;
import edu.kit.scc.http.HttpResponse;
public class Main {
private static String authorizationCode = "4/RRRRiWO4Avp1olNeXv2NyJUljPD4_5NqMHQQg0WY_-w";
private static String accessToken = "ya29.YAJ0rCj_mZbvfXKtqYSDYjwZE-vc0MNqEpQcT931T3vWv-5tdXKD85iVC2lxIq1HYHG8";
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
OidcClient oidcClient = new OidcClient();
// private static String authorizationCode =
// "997fc6c123b3224b3ade247ea8376164";
// private static String accessToken = "88e3bd6a549e385926378129b330c";
try {
oidcClient.requestUserInfo(accessToken);
} catch (URISyntaxException | ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void main(String[] args) {
// OidcClient oidcClient = new OidcClient(clientId, clientSecret,
// redirectUri, oidcTokenEndpoint,
// oidcUserInfoEndpoint);
//
// Tokens tokens = oidcClient.requestTokens(authorizationCode);
//
// oidcClient.requestUserInfo(tokens.getAccessToken().getValue());
// Utils.printProperties();
// ScimClient scimClient = new ScimClient();
// scimClient.getUsers("admin", "admin");
// scimClient.getGroups("admin", "admin");
// HttpClient client = new HttpClient();
// HttpResponse response =
// client.makeHTTPPOSTRequest("password=password",
// "http://localhost:50070");
// log.debug(response.toString());
// client.makePOST("localhost", 50070, "user", "password",
// "http://localhost:50070");
// EcpAuthenticator auth = new EcpAuthenticator();
// try {
// auth.authenticate(null);
// } catch (LdapException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
package edu.kit.scc;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Utils {
private static final Logger log = LoggerFactory.getLogger(Utils.class);
private Utils() {
}
public static Properties loadProperties() {
InputStream in = null;
Properties properties = new Properties();
try {
// load properties from configuration.properties file
in = Main.class.getClassLoader().getResourceAsStream("config.properties");
if (in != null) {
properties.load(in);
log.debug("loaded properties from {} file", "config.properties");
}
// load properties from System.getProperty, overwrite
// configuration.properties
if (System.getProperty("registerApp.serviceUrl") != null)
properties.put("regapp.serviceUrl", System.getProperty("registerApp.serviceUrl"));
if (System.getProperty("registerApp.serviceUsername") != null)
properties.put("regapp.serviceUsername", System.getProperty("registerApp.serviceUsername"));
if (System.getProperty("registerApp.servicePassword") != null)
properties.put("regapp.servicePassword", System.getProperty("registerApp.servicePassword"));
if (System.getProperty("registerApp.checkCert") != null)
properties.put("regapp.checkCert", System.getProperty("registerApp.serviceUrl"));
} catch (IOException e) {
// e.printStackTrace();
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// e.printStackTrace();
log.error(e.getMessage());
}
}
}
return properties;
}
public static void printProperties() {
Properties properties = loadProperties();
for (Entry<Object, Object> e : properties.entrySet())
log.info("{}: {}", new Object[] { e.getKey(), e.getValue() });
}
}
package edu.kit.scc.dei.adsecp;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.util.Properties;
import org.apache.directory.api.ldap.model.constants.AuthenticationLevel;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
......@@ -31,68 +20,70 @@ import org.apache.directory.server.core.api.interceptor.context.BindOperationCon
import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext;
import org.apache.directory.server.core.authn.SimpleAuthenticator;
import org.apache.directory.server.i18n.I18n;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.kit.scc.Utils;
import edu.kit.scc.http.HttpClient;
import edu.kit.scc.http.HttpResponse;
import edu.kit.scc.http.HttpsClient;
public class EcpAuthenticator extends SimpleAuthenticator {
private static final Logger logger = LoggerFactory.getLogger(EcpAuthenticator.class);
// Reg-App connection properties, overwritten by system properties
// registerApp.serviceUrl
private static String serviceUrl = "https://localhost/rest/ecp/regid/";
// registerApp.serviceUsername
private static String serviceUsername = "ldaprest";
// registerApp.servicePassword
private static String servicePassword = "qwertz";
//
// config.properties regapp.serviceUrl or registerApp.serviceUrl
private String serviceUrl;
// config.properties regapp.serviceUsername or registerApp.serviceUsername
private String serviceUsername;
// config.properties regapp.servicePassword or registerApp.servicePassword
private String servicePassword;
// config.properties regapp.checkCert or registerApp.checkCert
private Boolean checkCert;
// from registerApp.serviceUrl
private static String serviceHost = "localhost";
private String serviceHost;
// from registerApp.serviceUrl
private static int servicePort = 443;
private int servicePort;
// from registerApp.serviceUrl
private static String serviceProtocol = "http";
// registerApp.checkCert
private static Boolean checkCert = Boolean.TRUE;
private String serviceProtocol;
public EcpAuthenticator() {
super();
Properties properties = Utils.loadProperties();
this.serviceUrl = properties.getProperty("regapp.serviceUrl");
this.serviceUsername = properties.getProperty("regapp.serviceUsername");
this.servicePassword = properties.getProperty("regapp.servicePassword");
this.checkCert = Boolean.valueOf(properties.getProperty("regapp.checkCert"));
logger.info("Constructing EcpAuthenticator");
logger.debug("RegApp service url {}", serviceUrl);
logger.debug("RegApp service username {}", serviceUsername);
logger.debug("RegApp service password {}", servicePassword);
logger.debug("RegApp check certificate {}", checkCert);
}
@Override
public LdapPrincipal authenticate(BindOperationContext bindContext) throws LdapException {
logger.debug("Starting ECP Auth routine for {}", bindContext.getDn());
try {
logger.debug("Starting ECP Auth routine for {}", bindContext.getDn());
LdapPrincipal principal = super.authenticate(bindContext);
logger.debug("SimpleAuthentication succeded, no ECP auth");
return principal;
} catch (NullPointerException e) {
logger.warn(e.getMessage());
} catch (LdapException e) {
logger.warn("LdapException", e);
}
logger.debug("ECP Authenticate called");
logger.debug("ECP authenticate called");
// TODO - needs to be reconsidered
//
......@@ -104,7 +95,7 @@ public class EcpAuthenticator extends SimpleAuthenticator {
// bindContext.getEntry().get("description") == null)
// lookupUserPassword(bindContext);
String regId = "";
String regId = "007";
try {
regId = (String) bindContext.getEntry().get("description").get().getValue();
......@@ -116,26 +107,20 @@ public class EcpAuthenticator extends SimpleAuthenticator {
throw new IllegalStateException("description not of type String");
}
byte[] credentials = bindContext.getCredentials();
String password;
String password = "";
try {
byte[] credentials = bindContext.getCredentials();
password = new String(credentials, "UTF-8");
} catch (NullPointerException e) {
logger.error("Context has no password", e);
// throw new IllegalStateException("entry has no description");
} catch (UnsupportedEncodingException e) {
logger.error("Unsupported encoding: UTF-8");
logger.error("Unsupported encoding: UTF-8", e);
throw new LdapAuthenticationException("Internal server error");
}
logger.debug("trying login for regId {}", regId);
if (System.getProperty("registerApp.serviceUrl") != null)
serviceUrl = System.getProperty("registerApp.serviceUrl");
if (System.getProperty("registerApp.serviceUsername") != null)
serviceUsername = System.getProperty("registerApp.serviceUsername");
if (System.getProperty("registerApp.servicePassword") != null)
servicePassword = System.getProperty("registerApp.servicePassword");
if (System.getProperty("registerApp.checkCert") != null)
checkCert = Boolean.parseBoolean(System.getProperty("registerApp.checkCert"));
try {
serviceHost = new URI(serviceUrl).getHost();
servicePort = new URI(serviceUrl).getPort();
......@@ -148,43 +133,36 @@ public class EcpAuthenticator extends SimpleAuthenticator {
logger.debug("ECPAuth Config: url {}, user {}, pass {}, host {}, port {}, protocol {}, cert {}", new Object[] {
serviceUrl, serviceUsername, servicePassword, serviceHost, servicePort, serviceProtocol, checkCert });
DefaultHttpClient httpClient = getHttpClient(serviceProtocol, checkCert);
serviceUrl = serviceUrl.replaceAll("/$", "");
serviceUrl += "/" + regId;
httpClient.getCredentialsProvider().setCredentials(new AuthScope(serviceHost, servicePort),
new UsernamePasswordCredentials(serviceUsername, servicePassword));
HttpResponse response = null;
if (serviceProtocol.toLowerCase().equals("http")) {
HttpClient httpClient = new HttpClient();
response = httpClient.makeHTTPPostRequest(serviceUsername, servicePassword, "password=" + password,
serviceUrl);
logger.debug(String.valueOf(response.toString()));
} else if (serviceProtocol.toLowerCase().equals("https")) {
HttpsClient httpsClient = new HttpsClient();
response = httpsClient.makeHTTPSPostRequest(serviceUsername, servicePassword, "password=" + password,
serviceUrl);
logger.debug(String.valueOf(response.toString()));
} else {
logger.error("Unsupported protocol: {}", serviceProtocol.toLowerCase());
throw new LdapAuthenticationException("Internal server error");
}
HttpPost post;
try {
post = new HttpPost(serviceUrl + URLEncoder.encode(regId, "UTF-8"));
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
logger.debug(post.getEntity().toString());
HttpResponse response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String responseString = EntityUtils.toString(response.getEntity());
logger.debug(responseString);
return new LdapPrincipal(getDirectoryService().getSchemaManager(), bindContext.getDn(),
AuthenticationLevel.SIMPLE);
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
logger.info("User {} is not authorized by idp", regId);
} else {
logger.warn("Statuscode bad: {}", response.getStatusLine());
String responseString = EntityUtils.toString(response.getEntity());
logger.debug(responseString);
}
} catch (UnsupportedEncodingException e) {
logger.warn("UnsupportedEncodingException", e);
} catch (ClientProtocolException e) {
logger.warn("ClientProtocolException", e);
} catch (ParseException e) {
logger.warn("ParseException", e);
} catch (IOException e) {
logger.warn("IOException", e);
if (response.getStatusCode() == HttpStatus.SC_OK) {
return new LdapPrincipal(getDirectoryService().getSchemaManager(), bindContext.getDn(),
AuthenticationLevel.SIMPLE);
} else if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
logger.info("User {} is not authorized by idp", regId);
} else {
logger.warn("Statuscode bad: {}", response.getStatusCode());
String responseString = response.getResponseString();
logger.debug(responseString);
}
String message = I18n.err(I18n.ERR_230, bindContext.getDn().getName());
......@@ -193,48 +171,6 @@ public class EcpAuthenticator extends SimpleAuthenticator {
}
private DefaultHttpClient getHttpClient(String serviceProtocol, Boolean checkCert) {
// TODO - remove in production
// HTTP support for testing
if (serviceProtocol.toLowerCase().equals("http")) {
return new DefaultHttpClient();
}
if (checkCert) {
return new DefaultHttpClient();
} else {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} }, new SecureRandom());
SSLSocketFactory sf = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
Scheme httpsScheme = new Scheme("https", 443, sf);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(httpsScheme);
// apache HttpClient version >4.2 should use
// BasicClientConnectionManager
ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
return new DefaultHttpClient(cm);
} catch (KeyManagementException e) {
logger.warn("Problem while createing no cert check http client", e);
return new DefaultHttpClient();
} catch (NoSuchAlgorithmException e) {
logger.warn("Problem while createing no cert check http client", e);
return new DefaultHttpClient();
}
}
}
@SuppressWarnings("unused")
private byte[] lookupUserPassword(BindOperationContext bindContext) throws LdapException {
// ---- lookup the principal entry's userPassword attribute
......
package edu.kit.scc.http;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public final class CustomSSLContext {
private static final String cert = "-----BEGIN CERTIFICATE-----\n"
+ "MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJV"
+ "UzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoM"
+ "BFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAy"
+ "MTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwN"
+ "TW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0"
+ "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzO"
+ "M4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe"
+ "0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXn"
+ "RS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcN"
+ "AQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTm"
+ "xbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogR"
+ "Kv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=" + "-----END CERTIFICATE-----";
private CustomSSLContext() {
}
public static SSLContext initSslContextWithCertificate(String cert) {
SSLContext sslContext = null;
InputStream in = null;
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
in = new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8));
// in = new FileInputStream("saml-delegation.data.kit.edu");
Certificate ca = cf.generateCertificate(in);
String keyStoreType = KeyStore.getDefaultType();
KeyStore keystore = KeyStore.getInstance(keyStoreType);
keystore.load(null, null);
keystore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keystore);
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sslContext;
}
public static SSLContext initEmptySslContext() {
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
} }, null);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}