use of org.opensaml.saml.saml1.core.Response in project ddf by codice.
the class LoginFilter method handleAuthenticationToken.
private Subject handleAuthenticationToken(HttpServletRequest httpRequest, SAMLAuthenticationToken token) throws ServletException {
Subject subject;
try {
LOGGER.debug("Validating received SAML assertion.");
boolean wasReference = false;
boolean firstLogin = true;
if (token.isReference()) {
wasReference = true;
LOGGER.trace("Converting SAML reference to assertion");
Object sessionToken = httpRequest.getSession(false).getAttribute(SecurityConstants.SAML_ASSERTION);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Http Session assertion - class: {} loader: {}", sessionToken.getClass().getName(), sessionToken.getClass().getClassLoader());
LOGGER.trace("SecurityToken class: {} loader: {}", SecurityToken.class.getName(), SecurityToken.class.getClassLoader());
}
SecurityToken savedToken = null;
try {
savedToken = ((SecurityTokenHolder) sessionToken).getSecurityToken(token.getRealm());
} catch (ClassCastException e) {
httpRequest.getSession(false).invalidate();
}
if (savedToken != null) {
firstLogin = false;
token.replaceReferenece(savedToken);
}
if (token.isReference()) {
String msg = "Missing or invalid SAML assertion for provided reference.";
LOGGER.debug(msg);
throw new InvalidSAMLReceivedException(msg);
}
}
SAMLAuthenticationToken newToken = renewSecurityToken(httpRequest.getSession(false), token);
SecurityToken securityToken;
if (newToken != null) {
firstLogin = false;
securityToken = (SecurityToken) newToken.getCredentials();
} else {
securityToken = (SecurityToken) token.getCredentials();
}
if (!wasReference) {
// wrap the token
SamlAssertionWrapper assertion = new SamlAssertionWrapper(securityToken.getToken());
// get the crypto junk
Crypto crypto = getSignatureCrypto();
Response samlResponse = createSamlResponse(httpRequest.getRequestURI(), assertion.getIssuerString(), createStatus(SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null));
BUILDER.get().reset();
Document doc = BUILDER.get().newDocument();
Element policyElement = OpenSAMLUtil.toDom(samlResponse, doc);
doc.appendChild(policyElement);
Credential credential = new Credential();
credential.setSamlAssertion(assertion);
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(crypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
X509Certificate[] x509Certs = (X509Certificate[]) httpRequest.getAttribute("javax.servlet.request.X509Certificate");
requestData.setTlsCerts(x509Certs);
validateHolderOfKeyConfirmation(assertion, x509Certs);
if (assertion.isSigned()) {
// Verify the signature
WSSSAMLKeyInfoProcessor wsssamlKeyInfoProcessor = new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument()));
assertion.verifySignature(wsssamlKeyInfoProcessor, crypto);
assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(samlResponse.getDOM().getOwnerDocument())), requestData.getSigVerCrypto(), requestData.getCallbackHandler());
}
// Validate the Assertion & verify trust in the signature
assertionValidator.validate(credential, requestData);
}
// if it is all good, then we'll create our subject
subject = securityManager.getSubject(securityToken);
if (firstLogin) {
boolean hasSecurityAuditRole = Arrays.stream(System.getProperty("security.audit.roles").split(",")).filter(subject::hasRole).findFirst().isPresent();
if (hasSecurityAuditRole) {
SecurityLogger.audit("Subject has logged in with admin privileges", subject);
}
}
if (!wasReference && firstLogin) {
addSamlToSession(httpRequest, token.getRealm(), securityToken);
}
} catch (SecurityServiceException e) {
LOGGER.debug("Unable to get subject from SAML request.", e);
throw new ServletException(e);
} catch (WSSecurityException e) {
LOGGER.debug("Unable to read/validate security token from request.", e);
throw new ServletException(e);
}
return subject;
}
use of org.opensaml.saml.saml1.core.Response in project ddf by codice.
the class AttributeQueryClient method retrieveResponse.
/**
* Retrieves the response and returns its SAML Assertion.
*
* @param requestDocument of the request.
* @return Assertion of the response or null if the response is empty.
* @throws AttributeQueryException
*/
private Assertion retrieveResponse(Document requestDocument) throws AttributeQueryException {
Assertion assertion = null;
try {
Document responseDocument = sendRequest(requestDocument);
if (responseDocument == null) {
return null;
}
// Print Response
if (LOGGER.isTraceEnabled()) {
printXML("SAML Response:\n {}", responseDocument);
}
// Extract Response from Soap message.
NodeList elementsByTagNameNS = responseDocument.getElementsByTagNameNS(SAML2_PROTOCOL, "Response");
if (elementsByTagNameNS == null) {
throw new AttributeQueryException("Unable to find SAML Response.");
}
Node responseNode = elementsByTagNameNS.item(0);
Element responseElement = (Element) responseNode;
Unmarshaller unmarshaller = XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(responseElement);
Response response = (Response) unmarshaller.unmarshall(responseElement);
LOGGER.debug("Successfully marshalled Element to SAML Response.");
if (response.getStatus().getStatusCode().getValue().equals(SAML2_SUCCESS)) {
LOGGER.debug("Successful response, retrieved attributes.");
// Should only have one assertion.
assertion = response.getAssertions().get(0);
} else {
reportError(response.getStatus());
}
return assertion;
} catch (UnmarshallingException e) {
throw new AttributeQueryException("Unable to marshall Element to SAML Response.", e);
}
}
use of org.opensaml.saml.saml1.core.Response in project ddf by codice.
the class SamlProtocol method createResponse.
public static Response createResponse(Issuer issuer, Status status, String requestId, Element samlAssertion) throws WSSecurityException {
Response response = responseSAMLObjectBuilder.buildObject();
response.setIssuer(issuer);
response.setStatus(status);
response.setID("_" + UUID.randomUUID().toString());
response.setIssueInstant(new DateTime());
response.setInResponseTo(requestId);
response.setVersion(SAMLVersion.VERSION_20);
if (samlAssertion != null) {
SamlAssertionWrapper samlAssertionWrapper = new SamlAssertionWrapper(samlAssertion);
response.getAssertions().add(samlAssertionWrapper.getSaml2());
}
return response;
}
use of org.opensaml.saml.saml1.core.Response in project ddf by codice.
the class SimpleSign method signSamlObject.
public void signSamlObject(SignableSAMLObject samlObject) throws SignatureException {
X509Certificate[] certificates = getSignatureCertificates();
String sigAlgo = getSignatureAlgorithm(certificates[0]);
PrivateKey privateKey = getSignaturePrivateKey();
// Create the signature
Signature signature = OpenSAMLUtil.buildSignature();
if (signature == null) {
throw new SignatureException("Unable to build signature.");
}
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
signature.setSignatureAlgorithm(sigAlgo);
BasicX509Credential signingCredential = new BasicX509Credential(certificates[0]);
signingCredential.setPrivateKey(privateKey);
signature.setSigningCredential(signingCredential);
X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true);
try {
KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential);
signature.setKeyInfo(keyInfo);
} catch (org.opensaml.security.SecurityException e) {
throw new SignatureException("Error generating KeyInfo from signing credential", e);
}
if (samlObject instanceof Response) {
List<Assertion> assertions = ((Response) samlObject).getAssertions();
for (Assertion assertion : assertions) {
assertion.getSignature().setSigningCredential(signingCredential);
}
}
samlObject.setSignature(signature);
SAMLObjectContentReference contentRef = (SAMLObjectContentReference) signature.getContentReferences().get(0);
contentRef.setDigestAlgorithm(SignatureConstants.ALGO_ID_DIGEST_SHA1);
samlObject.releaseDOM();
samlObject.releaseChildrenDOM(true);
}
use of org.opensaml.saml.saml1.core.Response in project ddf by codice.
the class AuthnResponseValidator method validate.
public void validate(XMLObject xmlObject) throws ValidationException {
if (!(xmlObject instanceof Response)) {
throw new ValidationException("Invalid AuthN response XML.");
}
Response authnResponse = (Response) xmlObject;
String status = authnResponse.getStatus().getStatusCode().getValue();
if (!StatusCode.SUCCESS.equals(status)) {
throw new ValidationException("AuthN request was unsuccessful. Received status: " + status);
}
if (authnResponse.getAssertions().size() < 1) {
throw new ValidationException("Assertion missing in AuthN response.");
}
if (authnResponse.getAssertions().size() > 1) {
LOGGER.info("Received multiple assertions in AuthN response. Only using the first assertion.");
}
if (authnResponse.getSignature() != null) {
try {
simpleSign.validateSignature(authnResponse.getSignature(), authnResponse.getDOM().getOwnerDocument());
} catch (SimpleSign.SignatureException e) {
throw new ValidationException("Invalid or untrusted signature.");
}
}
}
Aggregations