Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander-Kreutz committed Jun 15, 2024
1 parent c173176 commit f7816da
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@

@Slf4j
@Component
public class ScSAMLRenewSecurityTokenBuilder {
public class SAMLRenewSecurityTokenBuilder {

private String renewEndpointUrl = "https://samlservices.test.epr.fed.hin.ch/saml/2.0/renewassertion";
//private String renewEndpointUrl = "https://test.ahdis.ch/eprik-cara/camel/hin/ahdis/saml/2.0/renewassertion";
Expand All @@ -144,10 +144,7 @@ public class ScSAMLRenewSecurityTokenBuilder {

@Autowired
SAMLProcessor processor;

//@Autowired
//private HttpClient httpClient;


@Value("${mag.iua.idp.key-alias}")
private String keyAlias;

Expand Down Expand Up @@ -214,11 +211,7 @@ public String requestRenewToken(@Body ch.bfh.ti.i4mi.mag.xua.AssertionRequest re
expires.setDateTime(created.getDateTime().plusSeconds(5*60));
timestamp.setExpires(expires);
security.getUnknownXMLObjects().add(timestamp);

// Binary security token is the base64 encoded representation of an X.509 public certificate.
//KeyStore.PrivateKeyEntry privateKeyEntry = securityModule.findPrivateKey();
//X509Certificate publicCertificate = (X509Certificate) privateKeyEntry.getCertificate();


X509Certificate publicCertificate = keyManager.getCertificate(keyAlias);
log.info("CERT NOT NULL:"+publicCertificate.toString());

Expand Down Expand Up @@ -262,22 +255,13 @@ public String requestRenewToken(@Body ch.bfh.ti.i4mi.mag.xua.AssertionRequest re
security.getUnknownXMLObjects().add(signature);

marshall(envelope);
sign(signature);
//securityModule.signObject(envelope, signature);
sign(signature);

// Build the W3C DOM representing the SOAP message.
Element elem = marshall(envelope);

//context.setOutboundSAMLMessage(null);
//HTTPSOAP11Encoder encode = new HTTPSOAP11Encoder();
//encode.encode(context);

Element elem = marshall(envelope);

log.info(StaxUtils.toString(elem));

//XMLObject result = send2(renewEndpointUrl, context, envelope);
//NodeList lst = result.getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion","Assertion");


Envelope result = send(renewEndpointUrl, context, envelope);
NodeList lst = result.getBody().getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion","Assertion");

Expand Down Expand Up @@ -366,7 +350,7 @@ public static String randomId() {
private Envelope send(String targetUrl, SAMLMessageContext context, Envelope envelope) throws SOAPException, CertificateEncodingException,
MarshallingException, SignatureException, IllegalAccessException, org.opensaml.xml.security.SecurityException, URIException, MessageEncodingException {
HttpClientBuilder clientBuilder = new HttpClientBuilder();
//clientBuilder.setHttpsProtocolSocketFactory(SSLProtocolSocketFactory.getSocketFactory());

CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new EntityIDCriteria(context.getPeerEntityId()));
criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
Expand All @@ -380,111 +364,19 @@ private Envelope send(String targetUrl, SAMLMessageContext context, Envelope env
new TLSProtocolSocketFactory(manager, trustManager));


HttpClient httpClient = clientBuilder.buildClient();
httpClient.setHostConfiguration(getHostConfiguration(new URI(targetUrl, true, "UTF-8"), context, httpClient));


HttpClient httpClient = clientBuilder.buildClient();
HttpSOAPClient soapClient = new HttpSOAPClient(httpClient, new BasicParserPool());

BasicSOAPMessageContext soapContext = new BasicSOAPMessageContext();
soapContext.setOutboundMessage(envelope);
log.info("ISSUER="+soapContext.getOutboundMessageIssuer());
//soapContext.setOutboundMessageIssuer("https://test.ahdis.ch");
log.info("SEND!");

soapClient.send(targetUrl, soapContext);
log.info("POST-SEND!");


Envelope soapResponse = (Envelope)soapContext.getInboundMessage();

return soapResponse;
}

protected HostConfiguration getHostConfiguration(URI uri, SAMLMessageContext context, HttpClient httpClient) throws MessageEncodingException {

try {

HostConfiguration hc = httpClient.getHostConfiguration();

if (hc != null) {
// Clone configuration from the HTTP Client object
log.info("EXIST");
hc = new HostConfiguration(hc);
} else {
// Create brand new configuration when there are no defaults
log.info("NOT EXIST");
hc = new HostConfiguration();
}

if (uri.getScheme().equalsIgnoreCase("http")) {

log.info("Using HTTP configuration");
hc.setHost(uri);

} else {

log.info("Using HTTPS configuration");
log.info("PEER="+context.getPeerEntityId());
CriteriaSet criteriaSet = new CriteriaSet();
criteriaSet.add(new EntityIDCriteria(context.getPeerEntityId()));
criteriaSet.add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
criteriaSet.add(new UsageCriteria(UsageType.UNSPECIFIED));

X509TrustManager trustManager = new X509TrustManager(criteriaSet, context.getLocalSSLTrustEngine());

//X509KeyManager manager1 = new X509KeyManager(context.getLocalSSLCredential());
//log.info("TLS NOT NULL:"+keyManager.getCredential("hintls").toString());

X509KeyManager manager = new X509KeyManager((X509Credential) keyManager.getCredential("hintls"));

HostnameVerifier hostnameVerifier = context.getLocalSSLHostnameVerifier();

ProtocolSocketFactory socketFactory = getSSLSocketFactory(context, manager, trustManager, hostnameVerifier);
Protocol protocol = new Protocol("https", socketFactory, 443);
hc.setHost(uri.getHost(), uri.getPort(), protocol);

log.info("SET-HOST: "+uri.getHost()+" proto="+protocol.toString());
}

return hc;

} catch (URIException e) {
throw new MessageEncodingException("Error parsing remote location URI", e);
}

}

/**
* Method returns SecureProtocolSocketFactory used to connect to create SSL connections for artifact resolution.
* By default we create instance of org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.
*
* @param context current SAML context
* @param manager keys used for client authentication
* @param trustManager trust manager for server verification
* @param hostnameVerifier verifier for server hostname, or null
* @return socket factory
*/
protected SecureProtocolSocketFactory getSSLSocketFactory(SAMLMessageContext context, X509KeyManager manager, X509TrustManager trustManager, HostnameVerifier hostnameVerifier) {
if (isHostnameVerificationSupported()) {
return new TLSProtocolSocketFactory(manager, trustManager, hostnameVerifier);
} else {
return new TLSProtocolSocketFactory(manager, trustManager);
}
}

/**
* Check for the latest OpenSAML library. Support for HostnameVerification was added in openws-1.5.1 and
* customers might use previous versions of OpenSAML.
*
* @return true when OpenSAML library support hostname verification
*/
protected boolean isHostnameVerificationSupported() {
try {
TLSProtocolSocketFactory.class.getConstructor(javax.net.ssl.X509KeyManager.class, javax.net.ssl.X509TrustManager.class, javax.net.ssl.HostnameVerifier.class);
return true;
} catch (NoSuchMethodException e) {
log.warn("HostnameVerification is not supported, update your OpenSAML libraries");
return false;
}
}


}
50 changes: 1 addition & 49 deletions src/main/java/ch/bfh/ti/i4mi/mag/xua/TokenRenew.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,55 +41,7 @@
@Slf4j
public class TokenRenew {

private String BASE_MSG() { return """
<?xml version="1.0" ?>
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap12:Body>
<wst:RequestSecurityToken xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<wst:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew</wst:RequestType>
<wst:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</wst:TokenType>
<wst:RenewTarget></wst:RenewTarget>
</wst:RequestSecurityToken>
</soap12:Body>
</soap12:Envelope>
"""; }

public Element addSecurityHeader(String input) throws XMLStreamException {
return (Element) StaxUtils.read(new StringReader(input)).getDocumentElement();
}

public SOAPMessage buildRenewRequest(@Body AssertionRequest request) throws SOAPException, IOException, XMLStreamException, AuthException {

Object token = request.getSamlToken();
if (token == null) throw new AuthException(400, "server_error", "No SAML token found");
log.info(token.getClass().getSimpleName());
if (token instanceof String && token.toString().startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")) token = token.toString().substring("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".length());
log.info("Decoded IDP Token:"+token);

MessageFactory factory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
SOAPMessage message = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(BASE_MSG().getBytes(Charset.forName("UTF-8"))));
log.info("BASE MSG");
// message.getSOAPHeader().addChildElement("MessageID","wsa","http://www.w3.org/2005/08/addressing").addTextNode(UUID.randomUUID().toString());

SOAPElement renewTarget = (SOAPElement) message.getSOAPBody().getElementsByTagNameNS("http://docs.oasis-open.org/ws-sx/ws-trust/200512", "RenewTarget").item(0);
log.info("RENEW TG");
Element elem;
if (token instanceof String) {
elem = addSecurityHeader(token.toString());
} else {
elem = ((Element) token);
}
Node node = message.getSOAPBody().getOwnerDocument().importNode(elem, true);
log.info("RENEW NODE");
renewTarget.appendChild(node);

log.info("Sending IDP Renew Request: "+message.toString());

message.saveChanges();

return message;
}


public AssertionRequest buildAssertionRequest(@Header("assertionRequest") AssertionRequest assertionRequest, @Body String renewedIdpAssertion) {
assertionRequest.setSamlToken(renewedIdpAssertion);
return assertionRequest;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ public void configure() throws Exception {

from(String.format("servlet://%s?httpMethodRestrict=POST&matchOnUriPrefix=true", RENEW_PATH))
.routeId("renewEndpoint")
.process(ScSAMLRenewSecurityTokenBuilder.keepRequest())
.process(SAMLRenewSecurityTokenBuilder.keepRequest())
.setProperty("oauthrequest").method(TokenRenew.class, "emptyAuthRequest")
.doTry()
.bean(AuthRequestConverter.class, "buildAssertionRequestFromToken")
.setHeader("assertionRequest", body())
.bean(ScSAMLRenewSecurityTokenBuilder.class, "requestRenewToken")
.bean(SAMLRenewSecurityTokenBuilder.class, "requestRenewToken")

.bean(TokenRenew.class, "buildAssertionRequest")
.bean(TokenRenew.class, "keepIdpAssertion")
Expand Down

0 comments on commit f7816da

Please sign in to comment.