use of com.tremolosecurity.config.xml.TrustType in project OpenUnison by TremoloSecurity.
the class LoadApplicationsFromK8s method createIdpOnUrl.
private void createIdpOnUrl(JSONObject jsonUrl, UrlType url) throws ProvisioningException, Exception {
IdpType idp = new IdpType();
JSONObject jsonIdp = (JSONObject) jsonUrl.get("idp");
url.setIdp(idp);
idp.setClassName((String) jsonIdp.get("className"));
JSONObject params = (JSONObject) jsonIdp.get("params");
if (params != null) {
for (Object x : params.keySet()) {
String paramName = (String) x;
Object z = params.get(paramName);
if (z instanceof String) {
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue((String) z);
idp.getParams().add(pt);
} else {
JSONArray values = (JSONArray) z;
for (Object y : values) {
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue((String) y);
idp.getParams().add(pt);
}
}
}
}
JSONArray secretParams = (JSONArray) jsonIdp.get("secretParams");
if (secretParams != null) {
HttpCon nonwatchHttp = this.k8sWatch.getK8s().createClient();
String token = this.k8sWatch.getK8s().getAuthToken();
try {
for (Object ox : secretParams) {
JSONObject secretParam = (JSONObject) ox;
String paramName = (String) secretParam.get("name");
String secretName = (String) secretParam.get("secretName");
String secretKey = (String) secretParam.get("secretKey");
String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue(secretValue);
idp.getParams().add(pt);
}
} finally {
nonwatchHttp.getHttp().close();
nonwatchHttp.getBcm().close();
}
}
JSONObject mappings = (JSONObject) jsonIdp.get("mappings");
if (mappings != null) {
IdpMappingType idpMappingType = new IdpMappingType();
idpMappingType.setStrict(getBoolValue(mappings.get("strict"), true));
JSONArray jsonMap = (JSONArray) mappings.get("map");
if (jsonMap != null) {
for (Object x : jsonMap) {
JSONObject map = (JSONObject) x;
ProvisionMappingType pmt = new ProvisionMappingType();
pmt.setTargetAttributeName((String) map.get("targetAttributeName"));
pmt.setTargetAttributeSource((String) map.get("targetAttributeSource"));
pmt.setSourceType((String) map.get("sourceType"));
idpMappingType.getMapping().add(pmt);
}
}
idp.setMappings(idpMappingType);
}
JSONArray jsonTrusts = (JSONArray) jsonIdp.get("trusts");
if (jsonTrusts != null) {
TrustsType tt = new TrustsType();
for (Object o : jsonTrusts) {
JSONObject jsonTrust = (JSONObject) o;
TrustType trust = new TrustType();
trust.setName((String) jsonTrust.get("name"));
params = (JSONObject) jsonTrust.get("params");
if (params != null) {
for (Object x : params.keySet()) {
String paramName = (String) x;
Object z = params.get(paramName);
if (z instanceof String) {
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue((String) z);
trust.getParam().add(pt);
} else {
JSONArray values = (JSONArray) z;
for (Object y : values) {
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue((String) y);
trust.getParam().add(pt);
}
}
}
}
secretParams = (JSONArray) jsonTrust.get("secretParams");
if (secretParams != null) {
HttpCon nonwatchHttp = this.k8sWatch.getK8s().createClient();
String token = this.k8sWatch.getK8s().getAuthToken();
try {
for (Object ox : secretParams) {
JSONObject secretParam = (JSONObject) ox;
String paramName = (String) secretParam.get("name");
String secretName = (String) secretParam.get("secretName");
String secretKey = (String) secretParam.get("secretKey");
String secretValue = this.k8sWatch.getSecretValue(secretName, secretKey, token, nonwatchHttp);
ParamType pt = new ParamType();
pt.setName(paramName);
pt.setValue(secretValue);
trust.getParam().add(pt);
}
} finally {
nonwatchHttp.getHttp().close();
nonwatchHttp.getBcm().close();
}
}
tt.getTrust().add(trust);
}
idp.setTrusts(tt);
}
}
use of com.tremolosecurity.config.xml.TrustType in project OpenUnison by TremoloSecurity.
the class OpenUnisonUtils method importIdpMetadata.
private static void importIdpMetadata(Options options, CommandLine cmd, String unisonXMLFile, TremoloType ttRead, TremoloType ttWrite, String ksPath, KeyStore ks) throws ParserConfigurationException, SAXException, IOException, FileNotFoundException, UnmarshallingException, Exception, Base64DecodingException, CertificateException, KeyStoreException, NoSuchAlgorithmException, JAXBException, PropertyException {
logger.info("Import SP Metadata into the IdP");
logger.info("Loading Metadata...");
String metadataFile = loadOption(cmd, "pathToMetaData", options);
InitializationService.initialize();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Element root = builder.parse(new InputSource(new InputStreamReader(new FileInputStream(metadataFile)))).getDocumentElement();
EntityDescriptor ed = (EntityDescriptor) XMLObjectSupport.getUnmarshaller(root).unmarshall(root);
logger.info("Loading IdP...");
String idpName = loadOption(cmd, "idpName", options);
ApplicationType idp = null;
for (ApplicationType app : ttWrite.getApplications().getApplication()) {
if (app.getName().equalsIgnoreCase(idpName)) {
idp = app;
}
}
if (idp == null) {
throw new Exception("IdP '" + idpName + "' not found");
}
SPSSODescriptor sp = ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
TrustType trust = null;
trust = new TrustType();
if (sp.getID() == null) {
trust.setName(ed.getEntityID());
} else {
trust.setName(sp.getID());
}
for (AssertionConsumerService svc : sp.getAssertionConsumerServices()) {
if (svc.getBinding().equalsIgnoreCase("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")) {
ParamType pt = new ParamType();
pt.setName("httpPostRespURL");
pt.setValue(svc.getLocation());
trust.getParam().add(pt);
}
}
ParamType pt = new ParamType();
pt.setName("signAssertion");
pt.setValue(Boolean.toString(sp.getWantAssertionsSigned().booleanValue()));
trust.getParam().add(pt);
if (pt.getValue().equalsIgnoreCase("false")) {
pt = new ParamType();
pt.setName("signResponse");
pt.setValue("true");
trust.getParam().add(pt);
} else {
pt = new ParamType();
pt.setName("signResponse");
pt.setValue("false");
trust.getParam().add(pt);
}
boolean first = true;
for (NameIDFormat nameid : sp.getNameIDFormats()) {
if (first) {
pt = new ParamType();
pt.setName("defaultNameId");
pt.setValue(nameid.getFormat());
trust.getParam().add(pt);
first = false;
}
pt = new ParamType();
pt.setName("nameIdMap");
pt.setValue(nameid.getFormat() + "=");
trust.getParam().add(pt);
}
boolean encryptAssertion = false;
boolean signAssertion = false;
for (KeyDescriptor kd : sp.getKeyDescriptors()) {
if (kd.getUse().equals(UsageType.SIGNING)) {
String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
String name = "verify-" + ed.getEntityID() + "-sp-sig";
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> c = cf.generateCertificates(bais);
if (c.size() > 1) {
int j = 0;
Iterator<? extends Certificate> i = c.iterator();
while (i.hasNext()) {
Certificate certificate = (Certificate) i.next();
ks.setCertificateEntry(name + "-" + j, certificate);
}
} else {
ks.setCertificateEntry(name, c.iterator().next());
}
pt = new ParamType();
pt.setName("spSigKey");
pt.setValue(name);
trust.getParam().add(pt);
signAssertion = true;
}
if (kd.getUse().equals(UsageType.ENCRYPTION)) {
String base64 = kd.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0).getValue();
String name = "verify-" + ed.getEntityID() + "-sp-enc";
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(base64));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> c = cf.generateCertificates(bais);
if (c.size() > 1) {
int j = 0;
Iterator<? extends Certificate> i = c.iterator();
while (i.hasNext()) {
Certificate certificate = (Certificate) i.next();
ks.setCertificateEntry(name + "-" + j, certificate);
}
} else {
ks.setCertificateEntry(name, c.iterator().next());
}
pt = new ParamType();
pt.setName("spEncKey");
pt.setValue(name);
trust.getParam().add(pt);
encryptAssertion = true;
}
}
pt = new ParamType();
pt.setName("encAssertion");
pt.setValue(encryptAssertion ? "true" : "false");
trust.getParam().add(pt);
if (!signAssertion) {
pt = new ParamType();
pt.setName("spSigKey");
pt.setValue("");
trust.getParam().add(pt);
}
if (!encryptAssertion) {
pt = new ParamType();
pt.setName("spEncKey");
pt.setValue("");
trust.getParam().add(pt);
}
pt = new ParamType();
pt.setName("defaultAuthCtx");
pt.setValue("");
trust.getParam().add(pt);
TrustType cur = null;
for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
if (trustType.getName().equals(trust.getName())) {
cur = trustType;
break;
}
}
if (cur != null) {
idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().remove(cur);
}
idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust().add(trust);
OpenUnisonUtils.storeMethod(unisonXMLFile, ttWrite, ksPath, ks);
}
use of com.tremolosecurity.config.xml.TrustType in project OpenUnison by TremoloSecurity.
the class PreAuthFilter method initFilter.
@Override
public void initFilter(HttpFilterConfig config) throws Exception {
this.postSAML = config.getAttribute("postSAML") != null && config.getAttribute("postSAML").getValues().get(0).equalsIgnoreCase("true");
if (postSAML) {
String idpName = config.getAttribute("idpName").getValues().get(0);
ApplicationType app = config.getConfigManager().getApp(idpName);
IdpType idp = app.getUrls().getUrl().get(0).getIdp();
for (ParamType pt : idp.getParams()) {
if (pt.getName().equalsIgnoreCase("sigKey")) {
this.keyAlias = pt.getValue();
}
}
TrustType tt = idp.getTrusts().getTrust().get(0);
for (ParamType pt : tt.getParam()) {
if (pt.getName().equalsIgnoreCase("signResponse")) {
this.signResponse = pt.getValue().equalsIgnoreCase("true");
} else if (pt.getName().equalsIgnoreCase("signAssertion")) {
this.signAssertion = pt.getValue().equalsIgnoreCase("true");
} else if (pt.getName().equalsIgnoreCase("httpPostRespURL")) {
this.assertionConsumerURL = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("defaultNameId")) {
this.nameIDType = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("nameIdMap")) {
this.nameIDAttribute = pt.getValue().substring(pt.getValue().indexOf('=') + 1);
} else if (pt.getName().equalsIgnoreCase("defaultAuthCtx")) {
this.authnCtxClassRef = pt.getValue();
}
}
String issuerHost = config.getAttribute("issuerHost").getValues().get(0);
String issuerPort = config.getAttribute("issuerPort").getValues().get(0);
boolean issuerSSL = config.getAttribute("issuerSSL").getValues().get(0).equalsIgnoreCase("true");
StringBuffer b = new StringBuffer();
if (issuerSSL) {
b.append("https://");
} else {
b.append("http://");
}
b.append(issuerHost);
if (!issuerPort.isEmpty()) {
b.append(':').append(issuerPort);
}
b.append("/auth/idp/").append(idpName);
this.issuer = b.toString();
// this.issuer = config.getAttribute("issuer").getValues().get(0);
this.audience = tt.getName();
this.relayState = config.getAttribute("relayState").getValues().get(0);
InitializationService.initialize();
this.url = this.assertionConsumerURL;
} else {
this.url = config.getAttribute("url").getValues().get(0);
}
URL nurl = new URL(this.url);
this.uri = nurl.getPath();
UrlType urlCfg = config.getConfigManager().findURL(this.url).getUrl();
for (FilterConfigType filterCfg : urlCfg.getFilterChain().getFilter()) {
if (filterCfg.getClazz().equalsIgnoreCase("com.tremolosecurity.proxy.filters.LastMile")) {
for (ParamWithValueType pt : filterCfg.getParam()) {
if (pt.getName().equalsIgnoreCase("encKeyAlias")) {
this.lastMileKeyAlias = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("headerName")) {
this.headerName = pt.getValue();
} else if (pt.getName().equalsIgnoreCase("userAttribute")) {
this.loginAttribute = pt.getValue();
}
}
for (ParamWithValueType pt : filterCfg.getParam()) {
if (pt.getName().equalsIgnoreCase("attribs")) {
String param = pt.getValue();
String fromUser = param.substring(0, param.indexOf('='));
String toApp = param.substring(param.indexOf('=') + 1);
if (fromUser.equalsIgnoreCase(this.headerName)) {
this.headerName = toApp;
}
}
}
}
}
logger.info("URL : '" + this.url + "'");
logger.info("Key Alias : '" + this.lastMileKeyAlias + "'");
logger.info("Login ID Attribute : '" + this.loginAttribute + "'");
logger.info("Header Attribute : '" + this.headerName + "'");
if (this.postSAML) {
logger.info("Saml : true");
logger.info("Issuer : " + this.issuer);
}
}
use of com.tremolosecurity.config.xml.TrustType in project OpenUnison by TremoloSecurity.
the class OpenUnisonUtils method exportIdPMetadata.
private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException, UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {
InitializationService.initialize();
logger.info("Finding IdP...");
String idpName = loadOption(cmd, "idpName", options);
ApplicationType idp = null;
for (ApplicationType app : tt.getApplications().getApplication()) {
if (app.getName().equalsIgnoreCase(idpName)) {
idp = app;
}
}
if (idp == null) {
throw new Exception("IdP '" + idpName + "' not found");
}
logger.info("Loading the base URL");
String baseURL = loadOption(cmd, "urlBase", options);
String url = baseURL + idp.getUrls().getUrl().get(0).getUri();
SecureRandom random = new SecureRandom();
byte[] idBytes = new byte[20];
random.nextBytes(idBytes);
StringBuffer b = new StringBuffer();
b.append('f').append(Hex.encodeHexString(idBytes));
String id = b.toString();
EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
EntityDescriptor ed = edb.buildObject();
ed.setID(id);
ed.setEntityID(url);
IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
// ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
IDPSSODescriptor sd = idpssdb.buildObject();
sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
ed.getRoleDescriptors().add(sd);
HashMap<String, List<String>> params = new HashMap<String, List<String>>();
for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
List<String> vals = params.get(pt.getName());
if (vals == null) {
vals = new ArrayList<String>();
params.put(pt.getName(), vals);
}
vals.add(pt.getValue());
}
sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn") && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));
KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();
if (params.get("encKey") != null && !params.get("encKey").isEmpty() && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
KeyDescriptor kd = kdb.buildObject();
kd.setUse(UsageType.ENCRYPTION);
KeyInfoBuilder kib = new KeyInfoBuilder();
KeyInfo ki = kib.buildObject();
X509DataBuilder x509b = new X509DataBuilder();
X509Data x509 = x509b.buildObject();
X509CertificateBuilder certb = new X509CertificateBuilder();
org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
x509.getX509Certificates().add(cert);
ki.getX509Datas().add(x509);
kd.setKeyInfo(ki);
sd.getKeyDescriptors().add(kd);
}
if (params.get("sigKey") != null && !params.get("sigKey").isEmpty() && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
KeyDescriptor kd = kdb.buildObject();
kd.setUse(UsageType.SIGNING);
KeyInfoBuilder kib = new KeyInfoBuilder();
KeyInfo ki = kib.buildObject();
X509DataBuilder x509b = new X509DataBuilder();
X509Data x509 = x509b.buildObject();
X509CertificateBuilder certb = new X509CertificateBuilder();
org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
x509.getX509Certificates().add(cert);
ki.getX509Datas().add(x509);
kd.setKeyInfo(ki);
sd.getKeyDescriptors().add(kd);
}
HashSet<String> nameids = new HashSet<String>();
for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
for (ParamType pt : trustType.getParam()) {
if (pt.getName().equalsIgnoreCase("nameIdMap")) {
String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
if (!nameids.contains(val)) {
nameids.add(val);
}
}
}
}
NameIDFormatBuilder nifb = new NameIDFormatBuilder();
for (String nidf : nameids) {
NameIDFormat nif = nifb.buildObject();
nif.setFormat(nidf);
sd.getNameIDFormats().add(nif);
}
SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
SingleSignOnService sso = ssosb.buildObject();
sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
sso.setLocation(url + "/httpPost");
sd.getSingleSignOnServices().add(sso);
sso = ssosb.buildObject();
sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
sso.setLocation(url + "/httpRedirect");
sd.getSingleSignOnServices().add(sso);
String signingKey = loadOptional(cmd, "signMetadataWithKey", options);
if (signingKey != null && ks.getCertificate(signingKey) != null) {
BasicX509Credential signingCredential = new BasicX509Credential((X509Certificate) ks.getCertificate(signingKey), (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));
Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);
signature.setSigningCredential(signingCredential);
signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
ed.setSignature(signature);
try {
XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
} catch (MarshallingException e) {
throw new RuntimeException(e);
}
Signer.signObject(signature);
}
// Get the Subject marshaller
EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
// Marshall the Subject
Element assertionElement = marshaller.marshall(ed);
logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}
use of com.tremolosecurity.config.xml.TrustType in project OpenUnison by TremoloSecurity.
the class IdpHolder method configIdp.
public void configIdp(ApplicationType app, UrlType url, IdpType idp, ServletConfig config) throws ServletException {
String idpName = app.getName();
String className = idp.getClassName();
IdentityProvider identityProvider = null;
try {
identityProvider = (IdentityProvider) Class.forName(className).newInstance();
} catch (Exception e) {
StringBuffer b = new StringBuffer();
b.append("Could not instanciate identity provider '").append(idpName).append("'");
logger.error(b.toString(), e);
throw new ServletException(b.toString(), e);
}
HashMap<String, Attribute> initParams = new HashMap<String, Attribute>();
for (ParamType param : idp.getParams()) {
Attribute attr = initParams.get(param.getName());
if (attr == null) {
attr = new Attribute(param.getName());
initParams.put(attr.getName(), attr);
}
attr.getValues().add(param.getValue());
}
HashMap<String, HashMap<String, Attribute>> trusts = new HashMap<String, HashMap<String, Attribute>>();
for (TrustType trust : idp.getTrusts().getTrust()) {
HashMap<String, Attribute> trustCfg = new HashMap<String, Attribute>();
for (ParamType param : trust.getParam()) {
Attribute attr = trustCfg.get(param.getName());
if (attr == null) {
attr = new Attribute(param.getName());
trustCfg.put(attr.getName(), attr);
}
attr.getValues().add(param.getValue());
}
// System.out.println(trust.getName());
trusts.put(trust.getName(), trustCfg);
}
try {
identityProvider.init(app.getName(), config.getServletContext(), initParams, trusts, new MapIdentity(idp.getMappings()));
} catch (ProvisioningException e) {
throw new ServletException("Could not initiate IDP", e);
}
IdpHolder holder = new IdpHolder();
holder.idp = identityProvider;
holder.idpConfig = idp;
this.idps.put(idpName.toLowerCase(), holder);
}
Aggregations