use of com.sun.identity.saml2.assertion.EncryptedAssertion in project OpenAM by OpenRock.
the class AuthnQueryUtil method verifyResponse.
private static void verifyResponse(Response response, AuthnQuery authnQuery, String authnAuthorityEntityID, String realm, AuthnAuthorityDescriptorElement aad) throws SAML2Exception {
String authnQueryID = authnQuery.getID();
if ((authnQueryID != null) && (!authnQueryID.equals(response.getInResponseTo()))) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseToAuthnQuery"));
}
Issuer respIssuer = response.getIssuer();
if (respIssuer == null) {
return;
}
if (!authnAuthorityEntityID.equals(respIssuer.getValue())) {
throw new SAML2Exception(SAML2Utils.bundle.getString("responseIssuerMismatch"));
}
if (!response.isSigned()) {
throw new SAML2Exception(SAML2Utils.bundle.getString("responseNotSigned"));
}
Set<X509Certificate> signingCerts = KeyUtil.getVerificationCerts(aad, authnAuthorityEntityID, SAML2Constants.AUTHN_AUTH_ROLE);
if (signingCerts.isEmpty()) {
throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
}
boolean valid = response.isSignatureValid(signingCerts);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AuthnQueryUtil.verifyResponse: " + "Signature validity is : " + valid);
}
if (!valid) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignatureOnResponse"));
}
String spEntityID = authnQuery.getIssuer().getValue();
List<Assertion> assertions = response.getAssertion();
if (assertions == null) {
List<EncryptedAssertion> encAssertions = response.getEncryptedAssertion();
if (encAssertions != null && !encAssertions.isEmpty()) {
Set<PrivateKey> privateKeys = KeyUtil.getDecryptionKeys(realm, spEntityID, SAML2Constants.SP_ROLE);
for (EncryptedAssertion eAssertion : encAssertions) {
Assertion assertion = eAssertion.decrypt(privateKeys);
if (assertions == null) {
assertions = new ArrayList<>();
}
assertions.add(assertion);
}
}
}
if ((assertions == null) || (assertions.isEmpty())) {
return;
}
signingCerts = KeyUtil.getVerificationCerts(aad, authnAuthorityEntityID, SAML2Constants.IDP_ROLE);
for (Iterator iter = assertions.iterator(); iter.hasNext(); ) {
Assertion assertion = (Assertion) iter.next();
if (assertion.isSigned()) {
if (signingCerts.isEmpty()) {
throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
}
valid = assertion.isSignatureValid(signingCerts);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("AuthnQueryUtil.verifyResponse: " + "Signature validity is : " + valid);
}
if (!valid) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignatureOnAssertion"));
}
}
}
}
use of com.sun.identity.saml2.assertion.EncryptedAssertion in project OpenAM by OpenRock.
the class SAML2TokenGenerationImpl method generate.
public String generate(SSOToken subjectToken, STSInstanceState stsInstanceState, TokenGenerationServiceInvocationState invocationState) throws TokenCreationException {
final SAML2Config saml2Config = stsInstanceState.getConfig().getSaml2Config();
if (saml2Config == null) {
throw new TokenCreationException(ResourceException.BAD_REQUEST, "Invocation targets a SAML2 token, but no SAML2Config was specified in the published sts!");
}
final String subjectId = ssoTokenIdentity.validateAndGetTokenPrincipal(subjectToken);
final Assertion assertion = AssertionFactory.getInstance().createAssertion();
setVersionAndId(assertion);
setIssuer(assertion, saml2Config);
final Date issueInstant = new Date();
setIssueInstant(assertion, issueInstant);
final SAML2TokenGenerationState tokenGenerationState = invocationState.getSaml2TokenGenerationState();
setConditions(assertion, saml2Config, issueInstant, tokenGenerationState.getSaml2SubjectConfirmation());
setSubject(assertion, subjectId, saml2Config.getSpAcsUrl(), saml2Config, invocationState.getSaml2TokenGenerationState().getSaml2SubjectConfirmation(), issueInstant, tokenGenerationState.getProofTokenState());
setAuthenticationStatements(assertion, saml2Config, tokenGenerationState.getAuthnContextClassRef());
setAttributeStatements(assertion, subjectToken, saml2Config);
setAuthzDecisionStatements(assertion, subjectToken, saml2Config);
/*
entering this branch handles both encryption and signing, as the encryption of the entire assertion must be
proceeded by signing.
*/
String assertionString;
if (saml2Config.encryptAssertion()) {
EncryptedAssertion encryptedAssertion = handleSingingAndEncryptionOfEntireAssertion(assertion, saml2Config, stsInstanceState);
try {
assertionString = encryptedAssertion.toXMLString(ASSERTION_TO_STRING_INCLUDE_NAMESPACE_PREFIX, ASSERTION_TO_STRING_DECLARE_NAMESPACE_PREFIX);
} catch (SAML2Exception e) {
throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught calling Assertion.toXMLString: " + e, e);
}
} else {
if (saml2Config.encryptAttributes()) {
encryptAttributeStatement(assertion, saml2Config, stsInstanceState);
}
if (saml2Config.encryptNameID()) {
encryptNameID(assertion, saml2Config, stsInstanceState);
}
if (saml2Config.signAssertion()) {
signAssertion(assertion, stsInstanceState);
}
try {
assertionString = assertion.toXMLString(ASSERTION_TO_STRING_INCLUDE_NAMESPACE_PREFIX, ASSERTION_TO_STRING_DECLARE_NAMESPACE_PREFIX);
} catch (SAML2Exception e) {
throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught calling Assertion.toXMLString: " + e, e);
}
}
if (stsInstanceState.getConfig().persistIssuedTokensInCTS()) {
try {
ctsTokenPersistence.persistToken(invocationState.getStsInstanceId(), TokenType.SAML2, assertionString, subjectId, issueInstant.getTime(), saml2Config.getTokenLifetimeInSeconds());
} catch (CTSTokenPersistenceException e) {
throw new TokenCreationException(e.getCode(), e.getMessage(), e);
}
}
return assertionString;
}
use of com.sun.identity.saml2.assertion.EncryptedAssertion in project OpenAM by OpenRock.
the class ResponseImpl method parseElement.
private void parseElement(Element element) throws SAML2Exception {
// make sure that the input xml block is not null
if (element == null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parseElement: " + "element input is null.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
// Make sure this is an Response.
String tag = null;
tag = element.getLocalName();
if ((tag == null) || (!tag.equals("Response"))) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parseElement: " + "not Response.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
}
// handle the attributes of <Response> element
NamedNodeMap atts = ((Node) element).getAttributes();
if (atts != null) {
int length = atts.getLength();
for (int i = 0; i < length; i++) {
Attr attr = (Attr) atts.item(i);
String attrName = attr.getName();
String attrValue = attr.getValue().trim();
if (attrName.equals("ID")) {
responseId = attrValue;
} else if (attrName.equals("InResponseTo")) {
inResponseTo = attrValue;
} else if (attrName.equals("Version")) {
version = attrValue;
} else if (attrName.equals("IssueInstant")) {
try {
issueInstant = DateUtils.stringToDate(attrValue);
} catch (ParseException pe) {
throw new SAML2Exception(pe.getMessage());
}
} else if (attrName.equals("Destination")) {
destination = attrValue;
} else if (attrName.equals("Consent")) {
consent = attrValue;
}
}
}
// handle child elements
NodeList nl = element.getChildNodes();
Node child;
String childName;
int length = nl.getLength();
for (int i = 0; i < length; i++) {
child = nl.item(i);
if ((childName = child.getLocalName()) != null) {
if (childName.equals("Issuer")) {
if (issuer != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: included more than one Issuer.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (signatureString != null || extensions != null || status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
issuer = AssertionFactory.getInstance().createIssuer((Element) child);
} else if (childName.equals("Signature")) {
if (signatureString != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:included more than one Signature.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (extensions != null || status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
signatureString = XMLUtils.print((Element) child, "UTF-8");
isSigned = true;
} else if (childName.equals("Extensions")) {
if (extensions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:included more than one Extensions.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (status != null || assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
extensions = ProtocolFactory.getInstance().createExtensions((Element) child);
} else if (childName.equals("Status")) {
if (status != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: included more than one Status.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
}
if (assertions != null || encAssertions != null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element:wrong sequence.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
}
status = ProtocolFactory.getInstance().createStatus((Element) child);
} else if (childName.equals("Assertion")) {
if (assertions == null) {
assertions = new ArrayList();
}
Element canoEle = SAMLUtils.getCanonicalElement(child);
if (canoEle == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorCanonical"));
}
assertions.add(AssertionFactory.getInstance().createAssertion(canoEle));
} else if (childName.equals("EncryptedAssertion")) {
if (encAssertions == null) {
encAssertions = new ArrayList();
}
encAssertions.add(AssertionFactory.getInstance().createEncryptedAssertion((Element) child));
} else {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ResponseImpl.parse" + "Element: Invalid element:" + childName);
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
}
}
}
super.validateData();
if (assertions != null) {
Iterator iter = assertions.iterator();
while (iter.hasNext()) {
((Assertion) iter.next()).makeImmutable();
}
assertions = Collections.unmodifiableList(assertions);
}
if (encAssertions != null) {
encAssertions = Collections.unmodifiableList(encAssertions);
}
isMutable = false;
}
use of com.sun.identity.saml2.assertion.EncryptedAssertion in project OpenAM by OpenRock.
the class ManageNameIDResponseImpl method parseElement.
private void parseElement(Element element) throws SAML2Exception {
AssertionFactory af = AssertionFactory.getInstance();
ProtocolFactory pf = ProtocolFactory.getInstance();
// make sure that the input xml block is not null
if (element == null) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ManageNameIDResponseImpl.parseElement: Input is null.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
}
// Make sure this is an EncryptedAssertion.
String tag = null;
tag = element.getLocalName();
if ((tag == null) || (!tag.equals(elementName))) {
if (SAML2SDKUtils.debug.messageEnabled()) {
SAML2SDKUtils.debug.message("ManageNameIDResponseImpl.parseElement:" + "not ManageNameIDResponse.");
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
}
responseId = element.getAttribute("ID");
validateID(responseId);
version = element.getAttribute("Version");
validateVersion(version);
String issueInstantStr = element.getAttribute("IssueInstant");
validateIssueInstant(issueInstantStr);
destination = element.getAttribute("Destination");
consent = element.getAttribute("Consent");
inResponseTo = element.getAttribute("InResponseTo");
NodeList nList = element.getChildNodes();
if ((nList != null) && (nList.getLength() > 0)) {
for (int i = 0; i < nList.getLength(); i++) {
Node childNode = nList.item(i);
String cName = childNode.getLocalName();
if (cName != null) {
if (cName.equals("Issuer")) {
issuer = af.createIssuer((Element) childNode);
} else if (cName.equals("Signature")) {
signatureString = XMLUtils.getElementString((Element) childNode);
isSigned = true;
} else if (cName.equals("Extensions")) {
extensions = pf.createExtensions((Element) childNode);
} else if (cName.equals("Status")) {
status = pf.createStatus((Element) childNode);
}
}
}
}
}
use of com.sun.identity.saml2.assertion.EncryptedAssertion in project OpenAM by OpenRock.
the class QueryClient method verifyResponse.
/**
* Returns SAMLv2 <code>Response</code> after validation of the
* response. A new <code>Response</code> object is created which
* contains decrypted assertion if the assertions were encrypted.
*
* @param realm the realm of the entity.
* @param pepEntityID entity identifier of the PEP.
* @param samlResponse the <code>Response</code>.
* @exception <code>SAML2Exception</code> if there is an error.
*/
private static Response verifyResponse(String realm, String pepEntityID, Response samlResponse) throws SAML2Exception {
Response response = samlResponse;
String classMethod = "QueryClient:verifyResponse";
if (samlResponse != null) {
//validate issuer trust.
Issuer issuer = samlResponse.getIssuer();
String issuerID = null;
if (issuer != null) {
issuerID = issuer.getValue().trim();
}
String pdpEntityID = issuerID;
boolean isTrusted = verifyResponseIssuer(realm, pepEntityID, issuerID);
if (!isTrusted) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Issuer in Request is not valid.");
}
String[] args = { realm, pepEntityID, issuerID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_IN_PEP_REQUEST, args);
throw new SAML2Exception(SAML2SDKUtils.BUNDLE_NAME, "invalidIssuer", args);
}
// verify signed response
verifySignedResponse(pepEntityID, pdpEntityID, samlResponse);
try {
// check if assertion needs to be encrypted,signed.
XACMLAuthzDecisionQueryConfigElement pepConfig = saml2MetaManager.getPolicyEnforcementPointConfig(realm, pepEntityID);
String assertionEncrypted = getAttributeValueFromPEPConfig(pepConfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
boolean wantAssertionEncrypted = (assertionEncrypted != null && assertionEncrypted.equalsIgnoreCase("true")) ? true : false;
boolean wantAssertionSigned = wantAssertionSigned(realm, pepEntityID);
String respID = samlResponse.getID();
List assertions = samlResponse.getAssertion();
if (wantAssertionEncrypted && (assertions != null && (assertions.size() != 0))) {
String[] data = { issuerID, respID };
LogUtil.error(Level.INFO, LogUtil.ASSERTION_FROM_PDP_NOT_ENCRYPTED, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("assertionNotEncrypted"));
}
Set<PrivateKey> decryptionKeys;
List<EncryptedAssertion> encAssertions = samlResponse.getEncryptedAssertion();
if (encAssertions != null) {
decryptionKeys = KeyUtil.getDecryptionKeys(pepConfig);
for (EncryptedAssertion encAssertion : encAssertions) {
Assertion assertion = encAssertion.decrypt(decryptionKeys);
if (assertions == null) {
assertions = new ArrayList<>();
}
assertions.add(assertion);
}
}
if (assertions == null || assertions.size() == 0) {
if (debug.messageEnabled()) {
debug.message(classMethod + "no assertion in the Response.");
}
String[] data = { issuerID, respID };
LogUtil.error(Level.INFO, LogUtil.MISSING_ASSERTION_IN_PDP_RESPONSE, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingAssertion"));
}
// validate Issuer in Assertion
Iterator assertionIter = assertions.iterator();
Set<X509Certificate> verificationCerts = null;
XACMLPDPDescriptorElement pdpDesc = null;
if (wantAssertionSigned) {
pdpDesc = saml2MetaManager.getPolicyDecisionPointDescriptor(realm, pdpEntityID);
verificationCerts = KeyUtil.getPDPVerificationCerts(pdpDesc, pdpEntityID);
}
while (assertionIter.hasNext()) {
Assertion assertion = (Assertion) assertionIter.next();
String assertionID = assertion.getID();
String assertionIssuer = assertion.getIssuer().getValue().trim();
isTrusted = verifyResponseIssuer(realm, pepEntityID, assertionIssuer);
if (!isTrusted) {
debug.error(classMethod + "Assertion's source site is not valid.");
String[] data = { assertionIssuer, assertionID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_IN_ASSERTION_FROM_PDP, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidIssuerInAssertion"));
}
String respIssuer = samlResponse.getIssuer().getValue().trim();
if (!respIssuer.equals(assertionIssuer)) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Issuer in Assertion " + assertionIssuer + "doesn't match the Issuer in Response." + respIssuer);
}
String[] data = { pdpEntityID, assertionIssuer };
LogUtil.error(Level.INFO, LogUtil.MISMATCH_ISSUER_IN_ASSERTION_FROM_PDP, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("mismatchIssuer"));
}
if (wantAssertionSigned) {
if (debug.messageEnabled()) {
debug.message(classMethod + "wantAssertionSigned " + wantAssertionSigned);
}
if (!assertion.isSigned() || !assertion.isSignatureValid(verificationCerts)) {
debug.error(classMethod + "Assertion is not signed or signature " + "is not valid.");
String[] data = { assertionIssuer, assertionID };
LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION_FROM_PDP, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidSignatureOnAssertion"));
}
}
}
//end while
if (wantAssertionEncrypted) {
response = createResponse(samlResponse, assertions);
}
if (debug.messageEnabled()) {
debug.message(classMethod + " Response : " + response.toXMLString(true, true));
}
} catch (SAML2MetaException sme) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Error retreiving meta", sme);
}
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
}
}
return response;
}
Aggregations