use of com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement in project OpenAM by OpenRock.
the class SPACSUtils method getResponseFromPostECP.
/**
* Obtains <code>SAML Response</code> from <code>SOAPBody</code>.
* Used by ECP profile.
*/
private static ResponseInfo getResponseFromPostECP(HttpServletRequest request, HttpServletResponse response, String orgName, String hostEntityId, SAML2MetaManager metaManager) throws SAML2Exception, IOException {
Message message = null;
try {
message = new Message(SOAPCommunicator.getInstance().getSOAPMessage(request));
} catch (SOAPException soapex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SOAP_MESSAGE_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", soapex.getMessage());
throw new SAML2Exception(soapex.getMessage());
} catch (SOAPBindingException soapex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SOAP_MESSAGE_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", soapex.getMessage());
throw new SAML2Exception(soapex.getMessage());
} catch (SOAPFaultException sfex) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.RECEIVE_SOAP_FAULT_ECP, data, null);
String faultString = sfex.getSOAPFaultMessage().getSOAPFault().getFaultString();
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateSOAPMessage", faultString);
throw new SAML2Exception(faultString);
}
List soapHeaders = message.getOtherSOAPHeaders();
ECPRelayState ecpRelayState = null;
if ((soapHeaders != null) && (!soapHeaders.isEmpty())) {
for (Iterator iter = soapHeaders.iterator(); iter.hasNext(); ) {
Element headerEle = (Element) iter.next();
try {
ecpRelayState = ECPFactory.getInstance().createECPRelayState(headerEle);
break;
} catch (SAML2Exception saml2ex) {
// not ECP RelayState
}
}
}
String relayState = null;
if (ecpRelayState != null) {
relayState = ecpRelayState.getValue();
}
List soapBodies = message.getBodies();
if ((soapBodies == null) || (soapBodies.isEmpty())) {
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SAML_RESPONSE_FROM_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "missingSAMLResponse", SAML2Utils.bundle.getString("missingSAMLResponse"));
throw new SAML2Exception(SAML2Utils.bundle.getString("missingSAMLResponse"));
}
Element resElem = (Element) soapBodies.get(0);
Response resp = null;
try {
resp = ProtocolFactory.getInstance().createResponse(resElem);
} catch (SAML2Exception se) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP:" + "Couldn't create Response:", se);
}
String[] data = { hostEntityId };
LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_SAML_RESPONSE_FROM_ECP, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToCreateResponse", se.getMessage());
throw se;
}
String idpEntityID = resp.getIssuer().getValue();
IDPSSODescriptorElement idpDesc = null;
try {
idpDesc = metaManager.getIDPSSODescriptor(orgName, idpEntityID);
} catch (SAML2MetaException se) {
String[] data = { orgName, idpEntityID };
LogUtil.error(Level.INFO, LogUtil.IDP_META_NOT_FOUND, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToGetIDPSSODescriptor", se.getMessage());
throw se;
}
Set<X509Certificate> certificates = KeyUtil.getVerificationCerts(idpDesc, idpEntityID, SAML2Constants.IDP_ROLE);
List assertions = resp.getAssertion();
if ((assertions != null) && (!assertions.isEmpty())) {
for (Iterator iter = assertions.iterator(); iter.hasNext(); ) {
Assertion assertion = (Assertion) iter.next();
if (!assertion.isSigned()) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP: " + " Assertion is not signed.");
}
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.ECP_ASSERTION_NOT_SIGNED, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "assertionNotSigned", SAML2Utils.bundle.getString("assertionNotSigned"));
throw new SAML2Exception(SAML2Utils.bundle.getString("assertionNotSigned"));
} else if (!assertion.isSignatureValid(certificates)) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.getResponseFromPostECP: " + " Assertion signature is invalid.");
}
String[] data = { idpEntityID };
LogUtil.error(Level.INFO, LogUtil.ECP_ASSERTION_INVALID_SIGNATURE, data, null);
SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "invalidSignature", SAML2Utils.bundle.getString("invalidSignature"));
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignature"));
}
}
}
return new ResponseInfo(resp, SAML2Constants.PAOS, relayState);
}
use of com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement in project OpenAM by OpenRock.
the class SPSSOFederate method createNameIDPolicy.
/* Create NameIDPolicy Element */
private static NameIDPolicy createNameIDPolicy(String spEntityID, String format, boolean allowCreate, SPSSODescriptorElement spsso, IDPSSODescriptorElement idpsso, String realm, Map paramsMap) throws SAML2Exception {
format = SAML2Utils.verifyNameIDFormat(format, spsso, idpsso);
NameIDPolicy nameIDPolicy = ProtocolFactory.getInstance().createNameIDPolicy();
String affiliationID = getParameter(paramsMap, SAML2Constants.AFFILIATION_ID);
if (affiliationID != null) {
AffiliationDescriptorType affiDesc = sm.getAffiliationDescriptor(realm, affiliationID);
if (affiDesc == null) {
throw new SAML2Exception(SAML2Utils.bundle.getString("affiliationNotFound"));
}
if (!affiDesc.getAffiliateMember().contains(spEntityID)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
}
nameIDPolicy.setSPNameQualifier(affiliationID);
} else {
nameIDPolicy.setSPNameQualifier(spEntityID);
}
nameIDPolicy.setAllowCreate(allowCreate);
nameIDPolicy.setFormat(format);
return nameIDPolicy;
}
use of com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement 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.jaxb.metadata.IDPSSODescriptorElement in project OpenAM by OpenRock.
the class SPSingleLogout method prepareForLogout.
private static String prepareForLogout(String realm, String tokenID, String metaAlias, List extensionsList, String binding, String relayState, HttpServletRequest request, HttpServletResponse response, Map paramsMap, String infoKeyString, LogoutRequest origLogoutRequest, SOAPMessage msg) throws SAML2Exception, SessionException {
NameIDInfoKey nameIdInfoKey = NameIDInfoKey.parse(infoKeyString);
String sessionIndex = null;
NameID nameID = null;
if (SPCache.isFedlet) {
sessionIndex = SAML2Utils.getParameter(paramsMap, SAML2Constants.SESSION_INDEX);
nameID = AssertionFactory.getInstance().createNameID();
nameID.setValue(nameIdInfoKey.getNameIDValue());
nameID.setFormat(SAML2Constants.NAMEID_TRANSIENT_FORMAT);
nameID.setNameQualifier(nameIdInfoKey.getRemoteEntityID());
nameID.setSPNameQualifier(nameIdInfoKey.getHostEntityID());
} else {
SPFedSession fedSession = null;
List list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (list != null) {
synchronized (list) {
ListIterator iter = list.listIterator();
while (iter.hasNext()) {
fedSession = (SPFedSession) iter.next();
if (tokenID.equals(fedSession.spTokenID)) {
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
if (list.size() == 0) {
SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyString);
}
break;
}
fedSession = null;
}
}
}
if (fedSession == null) {
// just do local logout
if (debug.messageEnabled()) {
debug.message("No session partner, just do local logout.");
}
return null;
}
sessionIndex = fedSession.idpSessionIndex;
nameID = fedSession.info.getNameID();
}
// get IDPSSODescriptor
IDPSSODescriptorElement idpsso = sm.getIDPSSODescriptor(realm, nameIdInfoKey.getRemoteEntityID());
if (idpsso == null) {
String[] data = { nameIdInfoKey.getRemoteEntityID() };
LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
List slosList = idpsso.getSingleLogoutService();
if (slosList == null) {
String[] data = { nameIdInfoKey.getRemoteEntityID() };
LogUtil.error(Level.INFO, LogUtil.SLO_NOT_FOUND, data, null);
throw new SAML2Exception(SAML2Utils.bundle.getString("sloServiceListNotfound"));
}
// get IDP entity config in case of SOAP, for basic auth info
IDPSSOConfigElement idpConfig = null;
if (binding.equals(SAML2Constants.SOAP)) {
idpConfig = sm.getIDPSSOConfig(realm, nameIdInfoKey.getRemoteEntityID());
}
StringBuffer requestID = LogoutUtil.doLogout(metaAlias, nameIdInfoKey.getRemoteEntityID(), slosList, extensionsList, binding, relayState, sessionIndex, nameID, request, response, paramsMap, idpConfig);
String requestIDStr = requestID.toString();
if (debug.messageEnabled()) {
debug.message("\nSPSLO.requestIDStr = " + requestIDStr + "\nbinding = " + binding);
}
if ((requestIDStr != null) && (requestIDStr.length() != 0) && (binding.equals(SAML2Constants.HTTP_REDIRECT) || binding.equals(SAML2Constants.HTTP_POST)) && (origLogoutRequest != null)) {
IDPCache.proxySPLogoutReqCache.put(requestIDStr, origLogoutRequest);
} else if ((requestIDStr != null) && (requestIDStr.length() != 0) && binding.equals(SAML2Constants.SOAP) && (msg != null)) {
IDPCache.SOAPMessageByLogoutRequestID.put(requestIDStr, msg);
}
return requestIDStr;
}
use of com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement in project OpenAM by OpenRock.
the class LogoutUtil method verifySLOResponse.
/**
* Verify the signature in LogoutResponse.
*
* @param sloResponse SLO response will be verified.
* @param realm realm of host entity.
* @param remoteEntity entity ID of remote host entity.
* @param hostEntity entity ID of host entity.
* @param hostEntityRole role of host entity.
* @return returns true if signature is valid.
* @throws SAML2Exception if error in verifying the signature.
* @throws SessionException if error in verifying the signature.
*/
public static boolean verifySLOResponse(LogoutResponse sloResponse, String realm, String remoteEntity, String hostEntity, String hostEntityRole) throws SAML2Exception, SessionException {
String method = "verifySLOResponse : ";
boolean needVerifySignature = SAML2Utils.getWantLogoutResponseSigned(realm, hostEntity, hostEntityRole);
if (needVerifySignature == false) {
if (debug.messageEnabled()) {
debug.message(method + "SLOResponse doesn't need to be verified.");
}
return true;
}
Set<X509Certificate> signingCerts;
if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
SPSSODescriptorElement spSSODesc = metaManager.getSPSSODescriptor(realm, remoteEntity);
signingCerts = KeyUtil.getVerificationCerts(spSSODesc, remoteEntity, SAML2Constants.SP_ROLE);
} else {
IDPSSODescriptorElement idpSSODesc = metaManager.getIDPSSODescriptor(realm, remoteEntity);
signingCerts = KeyUtil.getVerificationCerts(idpSSODesc, remoteEntity, SAML2Constants.IDP_ROLE);
}
if (!signingCerts.isEmpty()) {
boolean valid = sloResponse.isSignatureValid(signingCerts);
if (debug.messageEnabled()) {
debug.message(method + "Signature is : " + valid);
}
return valid;
} else {
debug.error("Incorrect configuration for Signing Certificate.");
throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
}
}
Aggregations