use of com.sun.identity.saml2.profile.AuthnRequestInfoCopy in project OpenAM by OpenRock.
the class SPSSOFederate method initiateECPRequest.
/**
* Parses the request parameters and builds ECP Request to sent to the IDP.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
*
* @throws SAML2Exception if error creating AuthnRequest.
* @throws IOException if error sending AuthnRequest to ECP.
*/
public static void initiateECPRequest(HttpServletRequest request, HttpServletResponse response) throws SAML2Exception, IOException {
if (!isFromECP(request)) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "invalid HTTP request from ECP.");
SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "invalidHttpRequestFromECP", SAML2Utils.bundle.getString("invalidHttpRequestFromECP"));
return;
}
String metaAlias = request.getParameter("metaAlias");
Map paramsMap = SAML2Utils.getParamsMap(request);
// get the sp entity ID from the metaAlias
String spEntityID = sm.getEntityByMetaAlias(metaAlias);
String realm = getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest: " + "spEntityID is " + spEntityID + ", realm is " + realm);
}
try {
// Retreive MetaData
if (sm == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
}
SPSSOConfigElement spEntityCfg = sm.getSPSSOConfig(realm, spEntityID);
Map spConfigAttrsMap = null;
if (spEntityCfg != null) {
spConfigAttrsMap = SAML2MetaUtils.getAttributes(spEntityCfg);
}
// get SPSSODescriptor
SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
if (spsso == null) {
String[] data = { spEntityID };
LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
String[] data = { spEntityID, realm };
LogUtil.access(Level.INFO, LogUtil.RECEIVED_HTTP_REQUEST_ECP, data, null);
List extensionsList = getExtensionsList(spEntityID, realm);
// create AuthnRequest
AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, null, null, true);
// invoke SP Adapter class if registered
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realm);
if (spAdapter != null) {
spAdapter.preSingleSignOnRequest(spEntityID, realm, null, request, response, authnRequest);
}
String alias = SAML2Utils.getSigningCertAlias(realm, spEntityID, SAML2Constants.SP_ROLE);
PrivateKey signingKey = KeyUtil.getKeyProviderInstance().getPrivateKey(alias);
if (signingKey != null) {
authnRequest.sign(signingKey, null);
} else {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "Unable to find signing key.");
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
ECPFactory ecpFactory = ECPFactory.getInstance();
// Default URL if relayState not present? in providerConfig?
// TODO get Default URL from metadata
String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
String ecpRelayStateXmlStr = "";
if (relayState != null && relayState.length() > 0) {
String relayStateID = getRelayStateID(relayState, authnRequest.getID());
ECPRelayState ecpRelayState = ecpFactory.createECPRelayState();
ecpRelayState.setValue(relayStateID);
ecpRelayState.setMustUnderstand(Boolean.TRUE);
ecpRelayState.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
ecpRelayStateXmlStr = ecpRelayState.toXMLString(true, true);
}
ECPRequest ecpRequest = ecpFactory.createECPRequest();
ecpRequest.setIssuer(createIssuer(spEntityID));
ecpRequest.setMustUnderstand(Boolean.TRUE);
ecpRequest.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
ecpRequest.setIsPassive(authnRequest.isPassive());
SAML2IDPFinder ecpIDPFinder = SAML2Utils.getECPIDPFinder(realm, spEntityID);
if (ecpIDPFinder != null) {
List idps = ecpIDPFinder.getPreferredIDP(authnRequest, spEntityID, realm, request, response);
if ((idps != null) && (!idps.isEmpty())) {
SAML2MetaManager saml2MetaManager = SAML2Utils.getSAML2MetaManager();
List idpEntries = null;
for (Iterator iter = idps.iterator(); iter.hasNext(); ) {
String idpEntityID = (String) iter.next();
IDPSSODescriptorElement idpDesc = saml2MetaManager.getIDPSSODescriptor(realm, idpEntityID);
if (idpDesc != null) {
IDPEntry idpEntry = ProtocolFactory.getInstance().createIDPEntry();
idpEntry.setProviderID(idpEntityID);
String description = SAML2Utils.getAttributeValueFromSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.ENTITY_DESCRIPTION);
idpEntry.setName(description);
List ssoServiceList = idpDesc.getSingleSignOnService();
String ssoURL = getSSOURL(ssoServiceList, SAML2Constants.SOAP);
idpEntry.setLoc(ssoURL);
if (idpEntries == null) {
idpEntries = new ArrayList();
}
idpEntries.add(idpEntry);
}
}
if (idpEntries != null) {
IDPList idpList = ProtocolFactory.getInstance().createIDPList();
idpList.setIDPEntries(idpEntries);
ecpRequest.setIDPList(idpList);
Map attrs = SAML2MetaUtils.getAttributes(spEntityCfg);
List values = (List) attrs.get(SAML2Constants.ECP_REQUEST_IDP_LIST_GET_COMPLETE);
if ((values != null) && (!values.isEmpty())) {
GetComplete getComplete = ProtocolFactory.getInstance().createGetComplete();
getComplete.setValue((String) values.get(0));
idpList.setGetComplete(getComplete);
}
}
}
}
String paosRequestXmlStr = "";
try {
PAOSRequest paosRequest = new PAOSRequest(authnRequest.getAssertionConsumerServiceURL(), SAML2Constants.PAOS_ECP_SERVICE, null, Boolean.TRUE, SAML2Constants.SOAP_ACTOR_NEXT);
paosRequestXmlStr = paosRequest.toXMLString(true, true);
} catch (PAOSException paosex) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest:", paosex);
throw new SAML2Exception(paosex.getMessage());
}
String header = paosRequestXmlStr + ecpRequest.toXMLString(true, true) + ecpRelayStateXmlStr;
String body = authnRequest.toXMLString(true, true);
try {
SOAPMessage reply = SOAPCommunicator.getInstance().createSOAPMessage(header, body, false);
String[] data2 = { spEntityID, realm, "" };
if (LogUtil.isAccessLoggable(Level.FINE)) {
data2[2] = SOAPCommunicator.getInstance().soapMessageToString(reply);
}
LogUtil.access(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST, data2, null);
// are generated as part of the save.
if (reply.saveRequired()) {
reply.saveChanges();
}
response.setStatus(HttpServletResponse.SC_OK);
SAML2Utils.putHeaders(reply.getMimeHeaders(), response);
response.setContentType(PAOSConstants.PAOS_MIME_TYPE);
// Write out the message on the response stream
OutputStream os = response.getOutputStream();
reply.writeTo(os);
os.flush();
} catch (SOAPException soapex) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest", soapex);
String[] data3 = { spEntityID, realm };
LogUtil.error(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST_FAILED, data3, null);
SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "soapError", soapex.getMessage());
return;
}
AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, null, authnRequest, relayState, paramsMap);
synchronized (SPCache.requestHash) {
SPCache.requestHash.put(authnRequest.getID(), reqInfo);
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// sessionExpireTime is counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
String key = authnRequest.getID();
try {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
}
} catch (SAML2TokenRepositoryException e) {
SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
}
}
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
use of com.sun.identity.saml2.profile.AuthnRequestInfoCopy in project OpenAM by OpenRock.
the class SAML2 method saveAuthnRequest.
private void saveAuthnRequest(final AuthnRequest authnRequest, final AuthnRequestInfo reqInfo) throws SAML2Exception {
final long sessionExpireTimeInSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + SPCache.interval;
final String key = authnRequest.getID();
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTimeInSeconds);
DEBUG.message("SAML2.saveAuthnRequestIfFailoverEnabled : " + "SAVE AuthnRequestInfoCopy for requestID {}", key);
} catch (SAML2TokenRepositoryException e) {
DEBUG.error("SAML2.saveAuthnRequestIfFailoverEnabled : There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID {}", key, e);
throw new SAML2Exception(BUNDLE_NAME, "samlFailover", null);
}
} else {
SAML2Store.saveTokenWithKey(key, new AuthnRequestInfoCopy(reqInfo));
DEBUG.message("SAML2.saveAuthnRequestIfFailoverDisabled : " + "SAVE AuthnRequestInfoCopy for requestID {}", key);
}
}
use of com.sun.identity.saml2.profile.AuthnRequestInfoCopy in project OpenAM by OpenRock.
the class IDPProxyUtil method sendProxyAuthnRequest.
/**
* Sends a new AuthnRequest to the authenticating provider.
* @param authnRequest original AuthnRequest sent by the service provider.
* @param preferredIDP IDP to be proxied.
* @param spSSODescriptor SPSSO Descriptor Element
* @param hostedEntityId hosted provider ID
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param realm Realm
* @param relayState the Relay State
* @param originalBinding The binding used to send the original AuthnRequest.
* @exception SAML2Exception for any SAML2 failure.
* @exception IOException if there is a failure in redirection.
*/
public static void sendProxyAuthnRequest(AuthnRequest authnRequest, String preferredIDP, SPSSODescriptorElement spSSODescriptor, String hostedEntityId, HttpServletRequest request, HttpServletResponse response, String realm, String relayState, String originalBinding) throws SAML2Exception, IOException {
String classMethod = "IDPProxyUtil.sendProxyAuthnRequest: ";
String destination = null;
SPSSODescriptorElement localDescriptor = null;
SPSSOConfigElement localDescriptorConfig = null;
IDPSSODescriptorElement idpDescriptor = null;
String binding;
try {
idpDescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(realm, preferredIDP);
List<SingleSignOnServiceElement> ssoServiceList = idpDescriptor.getSingleSignOnService();
SingleSignOnServiceElement endpoint = getMatchingSSOEndpoint(ssoServiceList, originalBinding);
if (endpoint == null) {
SAML2Utils.debug.error(classMethod + "Single Sign-on service is not found for the proxying IDP.");
throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotFoundIDPProxy"));
}
binding = endpoint.getBinding();
destination = endpoint.getLocation();
localDescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, hostedEntityId);
localDescriptorConfig = IDPSSOUtil.metaManager.getSPSSOConfig(realm, hostedEntityId);
} catch (SAML2MetaException e) {
SAML2Utils.debug.error(classMethod, e);
throw new SAML2Exception(e.getMessage());
}
AuthnRequest newAuthnRequest = getNewAuthnRequest(hostedEntityId, destination, realm, authnRequest);
// invoke SP Adapter class if registered
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostedEntityId, realm);
if (spAdapter != null) {
spAdapter.preSingleSignOnRequest(hostedEntityId, preferredIDP, realm, request, response, newAuthnRequest);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "New Authentication request:" + newAuthnRequest.toXMLString());
}
String requestID = newAuthnRequest.getID();
// save the AuthnRequest in the IDPCache so that it can be
// retrieved later when the user successfully authenticates
IDPCache.authnRequestCache.put(requestID, newAuthnRequest);
// save the original AuthnRequest
IDPCache.proxySPAuthnReqCache.put(requestID, authnRequest);
boolean signingNeeded = idpDescriptor.isWantAuthnRequestsSigned() || localDescriptor.isAuthnRequestsSigned();
// check if relayState is present and get the unique
// id which will be appended to the SSO URL before
// redirecting
String relayStateID = null;
if (relayState != null && relayState.length() > 0) {
relayStateID = SPSSOFederate.getRelayStateID(relayState, authnRequest.getID());
}
if (binding.equals(SAML2Constants.HTTP_POST)) {
if (signingNeeded) {
String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
SPSSOFederate.signAuthnRequest(certAlias, newAuthnRequest);
}
String authXMLString = newAuthnRequest.toXMLString(true, true);
String encodedReqMsg = SAML2Utils.encodeForPOST(authXMLString);
SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, destination);
} else {
String authReqXMLString = newAuthnRequest.toXMLString(true, true);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + " AuthnRequest: " + authReqXMLString);
}
String encodedXML = SAML2Utils.encodeForRedirect(authReqXMLString);
StringBuffer queryString = new StringBuffer().append(SAML2Constants.SAML_REQUEST).append(SAML2Constants.EQUAL).append(encodedXML);
//TODO: should it be newAuthnRequest???
if (relayStateID != null && relayStateID.length() > 0) {
queryString.append("&").append(SAML2Constants.RELAY_STATE).append("=").append(URLEncDec.encode(relayStateID));
}
StringBuffer redirectURL = new StringBuffer().append(destination).append(destination.contains("?") ? "&" : "?");
if (signingNeeded) {
String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
String signedQueryStr = SPSSOFederate.signQueryString(queryString.toString(), certAlias);
redirectURL.append(signedQueryStr);
} else {
redirectURL.append(queryString);
}
response.sendRedirect(redirectURL.toString());
}
String[] data = { destination };
LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_SP, data, null);
AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, hostedEntityId, preferredIDP, newAuthnRequest, relayState, null);
synchronized (SPCache.requestHash) {
SPCache.requestHash.put(requestID, reqInfo);
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
// sessionExpireTime is counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(requestID, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID + ", failed!", se);
}
}
}
use of com.sun.identity.saml2.profile.AuthnRequestInfoCopy in project OpenAM by OpenRock.
the class SAML2Utils method verifyResponse.
/**
* Verifies single sign on <code>Response</code> and returns information
* to SAML2 auth module for further processing. This method is used by
* SAML2 auth module only.
*
* @param httpRequest HttpServletRequest
* @param httpResponse HttpServletResponse
* @param response Single Sign On <code>Response</code>.
* @param orgName name of the realm or organization the provider is in.
* @param hostEntityId Entity ID of the hosted provider.
* @param profileBinding Profile binding used.
* @return A Map of information extracted from the Response. The keys of
* map are:
* <code>SAML2Constants.SUBJECT</code>,
* <code>SAML2Constants.POST_ASSERTION</code>,
* <code>SAML2Constants.ASSERTIONS</code>,
* <code>SAML2Constants.SESSION_INDEX</code>,
* <code>SAML2Constants.AUTH_LEVEL</code>,
* <code>SAML2Constants.MAX_SESSION_TIME</code>.
* @throws SAML2Exception if the Response is not valid according to the
* processing rules.
*/
public static Map verifyResponse(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final Response response, final String orgName, final String hostEntityId, final String profileBinding) throws SAML2Exception {
final String method = "SAML2Utils.verifyResponse:";
if (response == null || orgName == null || orgName.length() == 0) {
if (debug.messageEnabled()) {
debug.message(method + "response or orgName is null.");
}
throw new SAML2Exception(bundle.getString("nullInput"));
}
String respID = response.getID();
AuthnRequestInfo reqInfo = null;
String inRespToResp = response.getInResponseTo();
if (inRespToResp != null && inRespToResp.length() != 0) {
reqInfo = (AuthnRequestInfo) SPCache.requestHash.get(inRespToResp);
if (reqInfo == null) {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// Attempt to read AuthnRequestInfoCopy from SAML2 repository
AuthnRequestInfoCopy reqInfoCopy = null;
try {
reqInfoCopy = (AuthnRequestInfoCopy) SAML2FailoverUtils.retrieveSAML2Token(inRespToResp);
} catch (SAML2TokenRepositoryException se) {
debug.error(method + "AuthnRequestInfoCopy" + " unable to retrieve from SAML2 repository for inResponseTo: " + inRespToResp);
}
if (reqInfoCopy != null) {
// Get back the AuthnRequestInfo
reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
if (debug.messageEnabled()) {
debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
}
} else {
debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
String[] data = { respID };
LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
}
} else {
AuthnRequestInfoCopy reqInfoCopy = (AuthnRequestInfoCopy) SAML2Store.getTokenFromStore(inRespToResp);
if (reqInfoCopy != null) {
// Get back the AuthnRequestInfo
reqInfo = reqInfoCopy.getAuthnRequestInfo(httpRequest, httpResponse);
if (debug.messageEnabled()) {
debug.message(method + "AuthnRequestInfoCopy" + " retrieved from SAML2 repository for inResponseTo: " + inRespToResp);
}
} else {
debug.error(method + "InResponseTo attribute in Response" + " is invalid: " + inRespToResp + ", SAML2 failover is enabled");
String[] data = { respID };
LogUtil.error(Level.INFO, LogUtil.INVALID_INRESPONSETO_RESPONSE, data, null);
throw new SAML2Exception(bundle.getString("invalidInResponseToInResponse"));
}
}
}
}
// reqInfo can remain null and will do for IDP initiated SSO requests
// invoke SP Adapter
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, orgName);
if (spAdapter != null) {
AuthnRequest authnRequest = null;
if (reqInfo != null) {
authnRequest = reqInfo.getAuthnRequest();
}
spAdapter.preSingleSignOnProcess(hostEntityId, orgName, httpRequest, httpResponse, authnRequest, response, profileBinding);
}
String idpEntityId = null;
Issuer respIssuer = response.getIssuer();
if (respIssuer != null) {
// optional
if (!isSourceSiteValid(respIssuer, orgName, hostEntityId)) {
if (debug.messageEnabled()) {
debug.message(method + "Issuer in Response is not valid.");
}
String[] data = { hostEntityId, orgName, respID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_RESPONSE, data, null);
throw new SAML2Exception(bundle.getString("invalidIssuerInResponse"));
} else {
idpEntityId = respIssuer.getValue();
}
}
Status status = response.getStatus();
if (status == null || !status.getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
String statusCode = (status == null) ? "" : status.getStatusCode().getValue();
if (debug.messageEnabled()) {
debug.message(method + "Response's status code is not success: " + statusCode);
}
String[] data = { respID, "" };
if (LogUtil.isErrorLoggable(Level.FINE)) {
data[1] = statusCode;
}
LogUtil.error(Level.INFO, LogUtil.WRONG_STATUS_CODE, data, null);
if (SAML2Constants.RESPONDER.equals(statusCode)) {
//In case of passive authentication the NoPassive response will be sent using two StatusCode nodes:
//the outer StatusCode will be Responder and the inner StatusCode will contain the NoPassive URN
StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
if (secondLevelStatusCode != null && SAML2Constants.NOPASSIVE.equals(secondLevelStatusCode.getValue())) {
throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "noPassiveResponse", null);
}
} else if (SAML2Constants.REQUESTER.equals(statusCode)) {
// when is AllowCreate=false mode the auth module gets here with a
// statusCode of urn:oasis:names:tc:SAML:2.0:status:Requester
StatusCode secondLevelStatusCode = status.getStatusCode().getStatusCode();
if (secondLevelStatusCode != null && SAML2Constants.INVALID_NAME_ID_POLICY.equals(secondLevelStatusCode.getValue())) {
throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "nameIDMReqInvalidNameIDPolicy", null);
}
}
throw new SAML2Exception(bundle.getString("invalidStatusCodeInResponse"));
}
if (saml2MetaManager == null) {
throw new SAML2Exception(bundle.getString("nullMetaManager"));
}
SPSSOConfigElement spConfig = null;
SPSSODescriptorElement spDesc = null;
spConfig = saml2MetaManager.getSPSSOConfig(orgName, hostEntityId);
spDesc = saml2MetaManager.getSPSSODescriptor(orgName, hostEntityId);
if (debug.messageEnabled()) {
debug.message(method + "binding is :" + profileBinding);
}
// SAML spec processing
// 4.1.4.3 Verify any signatures present on the assertion(s) or the response
boolean responseIsSigned = false;
if (response.isSigned()) {
IDPSSODescriptorElement idpSSODescriptor = null;
try {
idpSSODescriptor = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
} catch (SAML2MetaException sme) {
String[] data = { orgName, idpEntityId };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
throw new SAML2Exception(sme);
}
if (idpSSODescriptor != null) {
Set<X509Certificate> verificationCerts = KeyUtil.getVerificationCerts(idpSSODescriptor, idpEntityId, SAML2Constants.IDP_ROLE);
if (CollectionUtils.isEmpty(verificationCerts) || !response.isSignatureValid(verificationCerts)) {
debug.error(method + "Response is not signed or signature is not valid.");
String[] data = { orgName, hostEntityId, idpEntityId };
LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
throw new SAML2Exception(bundle.getString("invalidSignInResponse"));
}
} else {
String[] data = { idpEntityId };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
responseIsSigned = true;
}
if (debug.messageEnabled()) {
debug.message(method + "responseIsSigned is :" + responseIsSigned);
}
// assertion encryption check
boolean needAssertionEncrypted = false;
String assertionEncryptedAttr = getAttributeValueFromSPSSOConfig(spConfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
needAssertionEncrypted = Boolean.parseBoolean(assertionEncryptedAttr);
if (debug.messageEnabled()) {
debug.message(method + "NeedAssertionEncrypted is :" + needAssertionEncrypted);
}
List<Assertion> assertions = response.getAssertion();
if (needAssertionEncrypted && !CollectionUtils.isEmpty(assertions)) {
String[] data = { respID };
LogUtil.error(Level.INFO, LogUtil.ASSERTION_NOT_ENCRYPTED, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("assertionNotEncrypted"));
}
Set<PrivateKey> decryptionKeys;
List<EncryptedAssertion> encAssertions = response.getEncryptedAssertion();
if (encAssertions != null) {
decryptionKeys = KeyUtil.getDecryptionKeys(spConfig);
for (EncryptedAssertion encAssertion : encAssertions) {
Assertion assertion = encAssertion.decrypt(decryptionKeys);
if (assertions == null) {
assertions = new ArrayList<>();
}
assertions.add(assertion);
}
}
if (CollectionUtils.isEmpty(assertions)) {
if (debug.messageEnabled()) {
debug.message(method + "no assertion in the Response.");
}
String[] data = { respID };
LogUtil.error(Level.INFO, LogUtil.MISSING_ASSERTION, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("missingAssertion"));
}
boolean wantAssertionsSigned = spDesc.isWantAssertionsSigned();
if (debug.messageEnabled()) {
debug.message(method + "wantAssertionsSigned is :" + wantAssertionsSigned);
}
// validate the assertions
Map smap = null;
Map bearerMap = null;
IDPSSODescriptorElement idp = null;
Set<X509Certificate> verificationCerts = null;
boolean allAssertionsSigned = true;
for (Assertion assertion : assertions) {
String assertionID = assertion.getID();
Issuer issuer = assertion.getIssuer();
if (!isSourceSiteValid(issuer, orgName, hostEntityId)) {
debug.error("assertion's source site is not valid.");
String[] data = { assertionID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_ASSERTION, data, null);
throw new SAML2Exception(bundle.getString("invalidIssuerInAssertion"));
}
if (idpEntityId == null) {
idpEntityId = issuer.getValue();
} else {
if (!idpEntityId.equals(issuer.getValue())) {
if (debug.messageEnabled()) {
debug.message(method + "Issuer in Assertion doesn't " + "match the Issuer in Response or other " + "Assertions in the Response.");
}
String[] data = { assertionID };
LogUtil.error(Level.INFO, LogUtil.MISMATCH_ISSUER_ASSERTION, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("mismatchIssuer"));
}
}
if (assertion.isSigned()) {
if (verificationCerts == null) {
idp = saml2MetaManager.getIDPSSODescriptor(orgName, idpEntityId);
verificationCerts = KeyUtil.getVerificationCerts(idp, idpEntityId, SAML2Constants.IDP_ROLE);
}
if (CollectionUtils.isEmpty(verificationCerts) || !assertion.isSignatureValid(verificationCerts)) {
debug.error(method + "Assertion is not signed or signature is not valid.");
String[] data = { assertionID };
LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
throw new SAML2Exception(bundle.getString("invalidSignatureOnAssertion"));
}
} else {
allAssertionsSigned = false;
}
List authnStmts = assertion.getAuthnStatements();
if (authnStmts != null && !authnStmts.isEmpty()) {
Subject subject = assertion.getSubject();
if (subject == null) {
continue;
}
List subjectConfirms = subject.getSubjectConfirmation();
if (subjectConfirms == null || subjectConfirms.isEmpty()) {
continue;
}
bearerMap = isBearerSubjectConfirmation(subjectConfirms, inRespToResp, spDesc, spConfig, assertionID);
if (!((Boolean) bearerMap.get(SAML2Constants.IS_BEARER))) {
continue;
}
boolean foundAssertion = false;
if ((SPCache.assertionByIDCache != null) && (SPCache.assertionByIDCache.containsKey(assertionID))) {
foundAssertion = true;
}
if ((!foundAssertion) && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
try {
if (SAML2FailoverUtils.retrieveSAML2Token(assertionID) != null) {
foundAssertion = true;
}
} catch (SAML2TokenRepositoryException e) {
if (debug.messageEnabled()) {
debug.message("Session not found in AMTokenSAML2Repository.", e);
}
}
}
if (foundAssertion) {
debug.error("Bearer Assertion is one time use only!");
throw new SAML2Exception(bundle.getString("usedBearAssertion"));
}
checkAudience(assertion.getConditions(), hostEntityId, assertionID);
if (smap == null) {
smap = fillMap(authnStmts, subject, assertion, assertions, reqInfo, inRespToResp, orgName, hostEntityId, idpEntityId, spConfig, (Date) bearerMap.get(SAML2Constants.NOTONORAFTER));
}
}
// end of having authnStmt
}
if (smap == null) {
debug.error("No Authentication Assertion in Response.");
throw new SAML2Exception(bundle.getString("missingAuthnAssertion"));
}
// the enclosing element
if (wantAssertionsSigned && !(responseIsSigned || allAssertionsSigned)) {
debug.error(method + "WantAssertionsSigned is true and response or all assertions are not signed");
String[] data = { orgName, hostEntityId, idpEntityId };
LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
throw new SAML2Exception(bundle.getString("assertionNotSigned"));
}
// signing each individual <Assertion> element or by signing the <Response> element.
if (profileBinding.equals(SAML2Constants.HTTP_POST)) {
boolean wantPostResponseSigned = SAML2Utils.wantPOSTResponseSigned(orgName, hostEntityId, SAML2Constants.SP_ROLE);
if (debug.messageEnabled()) {
debug.message(method + "wantPostResponseSigned is :" + wantPostResponseSigned);
}
if (wantPostResponseSigned && !responseIsSigned) {
debug.error(method + "wantPostResponseSigned is true but response is not signed");
String[] data = { orgName, hostEntityId, idpEntityId };
LogUtil.error(Level.INFO, LogUtil.POST_RESPONSE_INVALID_SIGNATURE, data, null);
throw new SAML2Exception(bundle.getString("responseNotSigned"));
}
if (!responseIsSigned && !allAssertionsSigned) {
debug.error(method + "WantAssertionsSigned is true but some or all assertions are not signed");
String[] data = { orgName, hostEntityId, idpEntityId };
LogUtil.error(Level.INFO, LogUtil.INVALID_SIGNATURE_ASSERTION, data, null);
throw new SAML2Exception(bundle.getString("assertionNotSigned"));
}
}
return smap;
}
use of com.sun.identity.saml2.profile.AuthnRequestInfoCopy in project OpenAM by OpenRock.
the class SPSSOFederate method initiateAuthnRequest.
/**
* Parses the request parameters and builds the Authentication
* Request to sent to the IDP.
*
* @param request the HttpServletRequest.
* @param response the HttpServletResponse.
* @param spEntityID entityID of Service Provider.
* @param idpEntityID entityID of Identity Provider.
* @param paramsMap Map of all other parameters.The key in the
* map are the parameter names of the type String.
* The values in the paramsMap are of the type List.
* Some of the possible keys are:RelayState,NameIDFormat,
* reqBinding, binding, AssertionConsumerServiceIndex,
* AttributeConsumingServiceIndex (currently not supported),
* isPassive, ForceAuthN, AllowCreate, Destination,
* AuthnContextDeclRef, AuthnContextClassRef,
* AuthComparison, Consent (currently not supported),
* AuthLevel, and sunamcompositeadvice.
* @param auditor the auditor for logging SAML2 Events - may be null
* @throws SAML2Exception if error initiating request to IDP.
*/
private static void initiateAuthnRequest(final HttpServletRequest request, final HttpServletResponse response, final String spEntityID, final String idpEntityID, final String realmName, final Map paramsMap, final SAML2EventLogger auditor) throws SAML2Exception {
if (FSUtils.needSetLBCookieAndRedirect(request, response, false)) {
return;
}
if (spEntityID == null) {
SAML2Utils.debug.error("SPSSOFederate:Service Provider ID is missing.");
String[] data = { spEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_SP, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
}
if (idpEntityID == null) {
SAML2Utils.debug.error("SPSSOFederate: Identity Provider ID is missing .");
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_IDP, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPEntityID"));
}
String binding = getParameter(paramsMap, SAML2Constants.REQ_BINDING);
if (binding == null) {
binding = SAML2Constants.HTTP_REDIRECT;
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate: in initiateSSOFed");
SAML2Utils.debug.message("SPSSOFederate: spEntityID is : " + spEntityID);
SAML2Utils.debug.message("SPSSOFederate: idpEntityID : " + idpEntityID);
}
String realm = getRealm(realmName);
try {
// Retreive MetaData
if (sm == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
}
Map spConfigAttrsMap = getAttrsMapForAuthnReq(realm, spEntityID);
// get SPSSODescriptor
SPSSODescriptorElement spsso = getSPSSOForAuthnReq(realm, spEntityID);
if (spsso == null) {
String[] data = { spEntityID };
LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
List extensionsList = getExtensionsList(spEntityID, realm);
// get IDP Descriptor
IDPSSODescriptorElement idpsso = getIDPSSOForAuthnReq(realm, idpEntityID);
if (idpsso == null) {
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
List ssoServiceList = idpsso.getSingleSignOnService();
String ssoURL = getSSOURL(ssoServiceList, binding);
if (ssoURL == null || ssoURL.length() == 0) {
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.SSO_NOT_FOUND, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotfound"));
}
// create AuthnRequest
AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, idpsso, ssoURL, false);
if (null != auditor && null != authnRequest) {
auditor.setRequestId(authnRequest.getID());
}
// invoke SP Adapter class if registered
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realmName);
if (spAdapter != null) {
spAdapter.preSingleSignOnRequest(spEntityID, idpEntityID, realmName, request, response, authnRequest);
}
String authReqXMLString = authnRequest.toXMLString(true, true);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate: AuthnRequest:" + authReqXMLString);
}
// Default URL if relayState not present? in providerConfig?
// TODO get Default URL from metadata
String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
// Validate the RelayState URL.
SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
// check if relayState is present and get the unique
// id which will be appended to the SSO URL before
// redirecting.
String relayStateID = null;
if (relayState != null && relayState.length() > 0) {
relayStateID = getRelayStateID(relayState, authnRequest.getID());
}
if (binding.equals(SAML2Constants.HTTP_POST)) {
String encodedReqMsg = getPostBindingMsg(idpsso, spsso, spConfigAttrsMap, authnRequest);
SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, ssoURL);
} else {
String redirect = getRedirect(authReqXMLString, relayStateID, ssoURL, idpsso, spsso, spConfigAttrsMap);
response.sendRedirect(redirect);
}
String[] data = { ssoURL };
LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_IDP, data, null);
AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, idpEntityID, authnRequest, relayState, paramsMap);
synchronized (SPCache.requestHash) {
SPCache.requestHash.put(authnRequest.getID(), reqInfo);
}
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
// sessionExpireTime is counted in seconds
long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
String key = authnRequest.getID();
try {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSSOFederate.initiateAuthnRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
}
} catch (SAML2TokenRepositoryException e) {
SAML2Utils.debug.error("SPSSOFederate.initiateAuthnRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
} catch (IOException ioe) {
SAML2Utils.debug.error("SPSSOFederate: Exception :", ioe);
throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingAuthnRequest"));
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
Aggregations