use of com.sun.identity.saml2.protocol.RequestAbstract in project OpenAM by OpenRock.
the class XACMLAuthzDecisionQueryHandler method handleQuery.
/**
* Processes an XACMLAuthzDecisionQuery and retruns a SAML2 Response.
*
* @param pdpEntityId EntityID of PDP
* @param pepEntityId EntityID of PEP
* @param samlpRequest SAML2 Request, an XAMLAuthzDecisionQuery
* @param soapMessage SOAPMessage that carried the SAML2 Request
* @return SAML2 Response with an XAMLAuthzDecisionStatement
* @exception SAML2Exception if the query can not be handled
*/
public com.sun.identity.saml2.protocol.Response handleQuery(String pdpEntityId, String pepEntityId, RequestAbstract samlpRequest, SOAPMessage soapMessage) throws SAML2Exception {
//TODO: logging, i18n
//TODO: long term, allow different mapper impls for different
//combination of pdp, pep
SubjectMapper subjectMapper = new FMSubjectMapper();
subjectMapper.initialize(pdpEntityId, pepEntityId, null);
ResourceMapper resourceMapper = new FMResourceMapper();
resourceMapper.initialize(pdpEntityId, pepEntityId, null);
ActionMapper actionMapper = new FMActionMapper();
actionMapper.initialize(pdpEntityId, pepEntityId, null);
EnvironmentMapper environmentMapper = new FMEnvironmentMapper();
environmentMapper.initialize(pdpEntityId, pepEntityId, null);
ResultMapper resultMapper = new FMResultMapper();
resultMapper.initialize(pdpEntityId, pepEntityId, null);
boolean evaluationFailed = false;
String statusCodeValue = null;
if (XACMLSDKUtils.debug.messageEnabled()) {
XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), entering" + ":pdpEntityId=" + pdpEntityId + ":pepEntityId=" + pepEntityId + ":samlpRequest=\n" + samlpRequest.toXMLString(true, true) + ":soapMessage=\n" + soapMessage);
}
Request xacmlRequest = ((XACMLAuthzDecisionQuery) samlpRequest).getRequest();
boolean returnContext = ((XACMLAuthzDecisionQuery) samlpRequest).getReturnContext();
SSOToken ssoToken = null;
String resourceName = null;
String serviceName = null;
String actionName = null;
Map environment = null;
boolean booleanDecision = false;
try {
//get native sso token
ssoToken = (SSOToken) subjectMapper.mapToNativeSubject(xacmlRequest.getSubjects());
if (ssoToken == null) {
//TODO: log message and fill missing attribute details
statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
evaluationFailed = true;
} else {
if (XACMLSDKUtils.debug.messageEnabled()) {
XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery()," + "created ssoToken");
}
}
if (ssoToken != null) {
//get native service name, resource name
List resources = xacmlRequest.getResources();
Resource resource = null;
if (!resources.isEmpty()) {
//We deal with only one resource for now
resource = (Resource) resources.get(0);
}
if (resource != null) {
String[] resourceService = resourceMapper.mapToNativeResource(resource);
if (resourceService != null) {
if (resourceService.length > 0) {
resourceName = resourceService[0];
}
if (resourceService.length > 1) {
serviceName = resourceService[1];
}
}
}
if (resourceName == null) {
//TODO: log message and fill missing attribute details
statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
evaluationFailed = true;
}
if (serviceName == null) {
//TODO: log message and fill missing attribute details
throw new SAML2Exception(XACMLSDKUtils.xacmlResourceBundle.getString("missing_attribute"));
}
}
if (serviceName != null) {
//get native action name
if (serviceName != null) {
actionName = actionMapper.mapToNativeAction(xacmlRequest.getAction(), serviceName);
}
if (actionName == null) {
//TODO: log message and fill missing attribute details
statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
evaluationFailed = true;
}
}
//get environment map
/*
environment = environmentMapper.mapToNativeEnvironment(
xacmlRequest.getEnvironment(),
xacmlRequest.getSubjects());
*/
} catch (XACMLException xe) {
statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
evaluationFailed = true;
if (XACMLSDKUtils.debug.warningEnabled()) {
XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", xe);
}
}
//get native policy deicison using native policy evaluator
if (!evaluationFailed) {
try {
PolicyEvaluator pe = new PolicyEvaluator(serviceName);
booleanDecision = pe.isAllowed(ssoToken, resourceName, actionName, environment);
} catch (SSOException ssoe) {
if (XACMLSDKUtils.debug.warningEnabled()) {
XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", ssoe);
}
evaluationFailed = true;
} catch (PolicyException pe) {
if (XACMLSDKUtils.debug.warningEnabled()) {
XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", pe);
}
evaluationFailed = true;
}
}
//decision: Indeterminate, Deny, Permit, NotApplicable
//status code: missing_attribute, syntax_error, processing_error, ok
Decision decision = ContextFactory.getInstance().createDecision();
Status status = ContextFactory.getInstance().createStatus();
StatusCode code = ContextFactory.getInstance().createStatusCode();
StatusMessage message = ContextFactory.getInstance().createStatusMessage();
StatusDetail detail = ContextFactory.getInstance().createStatusDetail();
detail.getElement().insertBefore(detail.getElement().cloneNode(true), null);
if (evaluationFailed) {
decision.setValue(XACMLConstants.INDETERMINATE);
if (statusCodeValue == null) {
statusCodeValue = XACMLConstants.STATUS_CODE_PROCESSING_ERROR;
}
code.setValue(statusCodeValue);
//TODO: i18n
message.setValue("processing_error");
} else if (booleanDecision) {
decision.setValue(XACMLConstants.PERMIT);
code.setValue(XACMLConstants.STATUS_CODE_OK);
//TODO: i18n
message.setValue("ok");
} else {
decision.setValue(XACMLConstants.DENY);
code.setValue(XACMLConstants.STATUS_CODE_OK);
//TODO: i18n
message.setValue("ok");
}
Result result = ContextFactory.getInstance().createResult();
String resourceId = resourceName;
List resources = xacmlRequest.getResources();
Resource resource = null;
if (!resources.isEmpty()) {
//We deal with only one resource for now
resource = (Resource) resources.get(0);
if (resource != null) {
List attributes = resource.getAttributes();
if (attributes != null) {
for (int count = 0; count < attributes.size(); count++) {
Attribute attr = (Attribute) attributes.get(count);
if (attr != null) {
URI tmpURI = attr.getAttributeId();
if (tmpURI.toString().equals(XACMLConstants.RESOURCE_ID)) {
Element element = (Element) attr.getAttributeValues().get(0);
resourceId = XMLUtils.getElementValue(element);
break;
}
}
}
}
}
}
result.setResourceId(resourceId);
result.setDecision(decision);
status.setStatusCode(code);
status.setStatusMessage(message);
status.setStatusDetail(detail);
result.setStatus(status);
Response response = ContextFactory.getInstance().createResponse();
response.addResult(result);
XACMLAuthzDecisionStatement statement = ContextFactory.getInstance().createXACMLAuthzDecisionStatement();
statement.setResponse(response);
if (returnContext) {
statement.setRequest(xacmlRequest);
}
com.sun.identity.saml2.protocol.Response samlpResponse = createSamlpResponse(statement, status.getStatusCode().getValue());
if (XACMLSDKUtils.debug.messageEnabled()) {
XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), returning" + ":samlResponse=\n" + samlpResponse.toXMLString(true, true));
}
return samlpResponse;
}
use of com.sun.identity.saml2.protocol.RequestAbstract in project OpenAM by OpenRock.
the class QueryHandlerServlet method processXACMLResponse.
/**
* Returns the received Response to the Requester.
* Validates the message signature if signed and invokes the
* Request Handler to pass the request for futher processing.
*
* @param realm realm of the entity.
* @param pdpEntityID entity identifier of Policy Decision Point (PDP).
* @param samlRequest the <code>RequestAbstract</code> object.
* @param request the <code>HttpServletRequest</code> object.
* @param soapMsg the <code>SOAPMessage</code> object.
* @exception <code>SAML2Exception</code> if there is an error processing
* the request and returning a response.
*/
Response processXACMLResponse(String realm, String pdpEntityID, RequestAbstract samlRequest, HttpServletRequest request, SOAPMessage soapMsg) throws SAML2Exception {
String classMethod = "QueryHandlerServlet:processXACMLResponse";
Response samlResponse = null;
String path = request.getPathInfo();
String key = path.substring(path.indexOf(METAALIAS_KEY) + 10);
String pepEntityID = samlRequest.getIssuer().getValue();
if (debug.messageEnabled()) {
debug.message(classMethod + "SOAPMessage KEY . :" + key);
debug.message(classMethod + "pepEntityID is :" + pepEntityID);
}
//Retreive metadata
boolean pdpWantAuthzQuerySigned = SAML2Utils.getWantXACMLAuthzDecisionQuerySigned(realm, pdpEntityID, SAML2Constants.PDP_ROLE);
if (debug.messageEnabled()) {
debug.message(classMethod + "PDP wantAuthzQuerySigned:" + pdpWantAuthzQuerySigned);
}
if (pdpWantAuthzQuerySigned) {
if (samlRequest.isSigned()) {
XACMLAuthzDecisionQueryDescriptorElement pep = SAML2Utils.getSAML2MetaManager().getPolicyEnforcementPointDescriptor(realm, pepEntityID);
Set<X509Certificate> verificationCerts = KeyUtil.getPEPVerificationCerts(pep, pepEntityID);
if (verificationCerts.isEmpty() || !samlRequest.isSignatureValid(verificationCerts)) {
// error
debug.error(classMethod + "Invalid signature in message");
throw new SAML2Exception("invalidQuerySignature");
} else {
debug.message(classMethod + "Valid signature found");
}
} else {
debug.error("Request not signed");
throw new SAML2Exception("nullSig");
}
}
//getRequestHandlerClass
RequestHandler handler = (RequestHandler) SOAPBindingService.handlers.get(key);
if (handler != null) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Found handler");
}
samlResponse = handler.handleQuery(pdpEntityID, pepEntityID, samlRequest, soapMsg);
// set response attributes
samlResponse.setID(SAML2Utils.generateID());
samlResponse.setVersion(SAML2Constants.VERSION_2_0);
samlResponse.setIssueInstant(new Date());
Issuer issuer = AssertionFactory.getInstance().createIssuer();
issuer.setValue(pdpEntityID);
samlResponse.setIssuer(issuer);
// end set Response Attributes
//set Assertion attributes
List assertionList = samlResponse.getAssertion();
Assertion assertion = (Assertion) assertionList.get(0);
assertion.setID(SAML2Utils.generateID());
assertion.setVersion(SAML2Constants.VERSION_2_0);
assertion.setIssueInstant(new Date());
assertion.setIssuer(issuer);
// end assertion set attributes
// check if assertion needs to be encrypted,signed.
String wantAssertionEncrypted = SAML2Utils.getAttributeValueFromXACMLConfig(realm, SAML2Constants.PEP_ROLE, pepEntityID, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
XACMLAuthzDecisionQueryDescriptorElement pepDescriptor = SAML2Utils.getSAML2MetaManager().getPolicyEnforcementPointDescriptor(realm, pepEntityID);
EncInfo encInfo = null;
boolean wantAssertionSigned = pepDescriptor.isWantAssertionsSigned();
if (debug.messageEnabled()) {
debug.message(classMethod + " wantAssertionSigned :" + wantAssertionSigned);
}
if (wantAssertionSigned) {
signAssertion(realm, pdpEntityID, assertion);
}
if (wantAssertionEncrypted != null && wantAssertionEncrypted.equalsIgnoreCase(SAML2Constants.TRUE)) {
encInfo = KeyUtil.getPEPEncInfo(pepDescriptor, pepEntityID);
// encrypt the Assertion
EncryptedAssertion encryptedAssertion = assertion.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), pepEntityID);
if (encryptedAssertion == null) {
debug.error(classMethod + "Assertion encryption failed.");
throw new SAML2Exception("FailedToEncryptAssertion");
}
assertionList = new ArrayList();
assertionList.add(encryptedAssertion);
samlResponse.setEncryptedAssertion(assertionList);
//reset Assertion list
samlResponse.setAssertion(new ArrayList());
if (debug.messageEnabled()) {
debug.message(classMethod + "Assertion encrypted.");
}
} else {
List assertionsList = new ArrayList();
assertionsList.add(assertion);
samlResponse.setAssertion(assertionsList);
}
signResponse(samlResponse, realm, pepEntityID, pdpEntityID);
} else {
// error - missing request handler.
debug.error(classMethod + "RequestHandler not found");
throw new SAML2Exception("missingRequestHandler");
}
return samlResponse;
}
use of com.sun.identity.saml2.protocol.RequestAbstract in project OpenAM by OpenRock.
the class SAML2Utils method getErrorResponse.
/**
* Returns a <code>SAML Response</code> object containing error status
*
* @param request the <code>RequestAbstract</code> object
* @param code the error code
* @param subCode teh second-level error code
* @param statusMsg the error message
* @param issuerEntityID the entity id of the issuer
* @return the <code>SAML Response</code> object containing error status
* @throws SAML2Exception if the operation is not successful
*/
public static Response getErrorResponse(RequestAbstract request, String code, String subCode, String statusMsg, String issuerEntityID) throws SAML2Exception {
String classMethod = "IDPSSOUtil.getErrorResponse: ";
Response errResp = ProtocolFactory.getInstance().createResponse();
errResp.setStatus(generateStatus(code, subCode, statusMsg));
String responseID = SAML2Utils.generateID();
if (responseID == null) {
debug.error("Unable to generate response ID.");
return null;
}
errResp.setID(responseID);
if (request != null) {
// sp initiated case, need to set InResponseTo attribute
errResp.setInResponseTo(request.getID());
}
errResp.setVersion(SAML2Constants.VERSION_2_0);
errResp.setIssueInstant(new Date());
// set the idp entity id as the response issuer
if (issuerEntityID != null) {
Issuer issuer = AssertionFactory.getInstance().createIssuer();
issuer.setValue(issuerEntityID);
errResp.setIssuer(issuer);
}
if (debug.messageEnabled()) {
debug.message(classMethod + "Error Response is : " + errResp.toXMLString());
}
return errResp;
}
use of com.sun.identity.saml2.protocol.RequestAbstract in project OpenAM by OpenRock.
the class QueryClient method processXACMLQuery.
/**
* Returns SAMLv2 <code>Response</code>.
* SAMLv2 request is sent enclosed in the body of a SOAP Message
* to a SOAP endpoint.
* Prior to sending the request query, attributes required for completeness
* of the SAMLv2 Request will be set (eg. Issuer) if not already set.
* Message will be signed if signing is enabled.
* SAMLv2 Query Request will be enclosed in the SOAP Body to create a SOAP
* message to send to the server.
*
* @param request the SAMLv2 <code>RequestAbstract</code> object.
* @param pepEntityID entity identifier of the hosted query requester.
* @param pdpEntityID entity identifier of the remote server.
* @return SAMLv2 <code>Response</code> received from the
* Query Responder.
* @throws SAML2Exception if there is an error processing the query.
*/
public static Response processXACMLQuery(RequestAbstract request, String pepEntityID, String pdpEntityID) throws SAML2Exception {
String classMethod = "QueryClient:processXACMLQuery";
String realm = "/";
Response samlResponse = null;
Response response = null;
// retreive pepEntityID metadata
if (pepEntityID == null || pepEntityID.length() == 0) {
debug.error(classMethod + "PEP Identifier is null");
String[] data = { pepEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_PEP_ID, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullPEP"));
}
// retreive pdpEntityID metadata
if (pdpEntityID == null || pdpEntityID.length() == 0) {
debug.error(classMethod + "PDP Identifier is null");
String[] data = { pdpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_PDP_ID, data);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullPDP"));
}
if (request != null) {
// set properties in the request.
XACMLAuthzDecisionQuery xacmlQuery = (XACMLAuthzDecisionQuery) request;
if (xacmlQuery != null) {
// set Issuer
Issuer issuer = createIssuer(pepEntityID);
xacmlQuery.setIssuer(issuer);
//generate ID
String requestID = SAML2SDKUtils.generateID();
xacmlQuery.setID(requestID);
xacmlQuery.setVersion(SAML2Constants.VERSION_2_0);
xacmlQuery.setIssueInstant(new Date());
XACMLPDPConfigElement pdpConfig = getPDPConfig(realm, pdpEntityID);
if (pdpConfig != null) {
String wantQuerySigned = getAttributeValueFromPDPConfig(pdpConfig, "wantXACMLAuthzDecisionQuerySigned");
if (wantQuerySigned != null && wantQuerySigned.equals("true")) {
signAttributeQuery(xacmlQuery, realm, pepEntityID, false);
}
}
String xmlString = xacmlQuery.toXMLString(true, true);
if (debug.messageEnabled()) {
debug.message(classMethod + "XACML Query XML String :" + xmlString);
}
// retrieve endpoint from meta data
String endPoint = null;
XACMLAuthzDecisionQueryConfigElement pepConfig = getPEPConfig(realm, pepEntityID);
endPoint = getPDPEndPoint(pdpEntityID);
if (debug.messageEnabled()) {
debug.message(classMethod + " ResponseLocation is :" + endPoint);
}
// create SOAP message
try {
String soapMessage = SAML2SDKUtils.createSOAPMessageString(xmlString);
endPoint = SAML2SDKUtils.fillInBasicAuthInfo(pepConfig, endPoint);
String[] urls = { endPoint };
SOAPClient soapClient = new SOAPClient(urls);
if (debug.messageEnabled()) {
debug.message(classMethod + "soapMessage :" + soapMessage);
}
InputStream soapIn = soapClient.call(soapMessage, null, null);
StringBuffer reply = new StringBuffer();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(soapIn, "UTF-8"));
while ((line = reader.readLine()) != null) {
reply.append(line).append("\n");
}
// check the SOAP message for any SOAP related errors
// before passing control to SAML processor
xmlString = reply.toString();
if (debug.messageEnabled()) {
debug.message("Response Message:\n" + xmlString);
}
samlResponse = getSAMLResponse(xmlString);
issuer = samlResponse.getIssuer();
String issuerID = null;
if (issuer != null) {
issuerID = issuer.getValue().trim();
}
boolean isTrusted = verifyResponseIssuer(realm, pepEntityID, issuerID);
if (!isTrusted) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Issuer in Request is not valid.");
}
String[] args = { realm, pepEntityID, pdpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_IN_PEP_REQUEST, args);
throw new SAML2Exception("invalidIssuerInRequest");
}
if (samlResponse != null) {
xmlString = samlResponse.toXMLString(true, true);
if (debug.messageEnabled()) {
debug.message(classMethod + "Response: " + xmlString);
}
response = verifyResponse(realm, pepEntityID, samlResponse);
if (debug.messageEnabled()) {
debug.message(classMethod + "Response with decrypted Assertion: " + response.toXMLString(true, true));
}
}
} catch (SOAPException soae) {
if (debug.messageEnabled()) {
debug.message(classMethod + "SOAPException :", soae);
}
throw new SAML2Exception(soae.getMessage());
} catch (Exception e) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Exception ", e);
}
throw new SAML2Exception(e.getMessage());
}
}
}
return response;
}
use of com.sun.identity.saml2.protocol.RequestAbstract in project OpenAM by OpenRock.
the class QueryHandlerServlet method processSAMLRequest.
/**
* Returns the SAMLv2 <code>Response</code> received in response to
* the Request.
*
* @param realm the realm of the entity.
* @param pdpEntityID entity identifier of the Policy Decision Point.
* @param reqAbs the Document Element object.
* @param request the <code>HttpServletRequest</code> object.
* @param soapMsg the <code>SOAPMessage</code> object
* @return the <code>Response</code> object.
* @exception <code>SAML2Exception</code> if there is an error processing
* the request.
*/
Response processSAMLRequest(String realm, String pdpEntityID, Element reqAbs, HttpServletRequest request, SOAPMessage soapMsg) throws SAML2Exception {
String classMethod = "QueryHandlerServlet:processSAMLRequest";
Response samlResponse = null;
if (reqAbs != null) {
String xsiType = reqAbs.getAttribute(XSI_TYPE_ATTR);
if (debug.messageEnabled()) {
debug.message(classMethod + "xsi type is : " + xsiType);
}
if (xsiType != null && xsiType.indexOf(XACML_AUTHZ_QUERY) != -1) {
RequestAbstract samlRequest = ContextFactory.getInstance().createXACMLAuthzDecisionQuery(reqAbs);
String requestStr = samlRequest.toXMLString(true, true);
String[] data = { requestStr, pdpEntityID };
LogUtil.access(Level.FINE, LogUtil.REQUEST_MESSAGE, data);
Issuer issuer = samlRequest.getIssuer();
String pepEntityID = null;
if (issuer != null) {
pepEntityID = issuer.getValue().trim();
}
if (debug.messageEnabled()) {
debug.message(classMethod + "Issuer is:" + pepEntityID);
}
boolean isTrusted = false;
try {
isTrusted = SAML2Utils.getSAML2MetaManager().isTrustedXACMLProvider(realm, pdpEntityID, pepEntityID, SAML2Constants.PDP_ROLE);
} catch (SAML2MetaException sme) {
debug.error("Error retreiving meta", sme);
}
if (!isTrusted) {
if (debug.messageEnabled()) {
debug.message(classMethod + "Issuer in Request is not valid." + pepEntityID);
}
String[] args = { realm, pepEntityID, pdpEntityID };
LogUtil.error(Level.INFO, LogUtil.INVALID_ISSUER_IN_PEP_REQUEST, args);
throw new SAML2Exception("invalidIssuerInRequest");
}
samlResponse = processXACMLResponse(realm, pdpEntityID, samlRequest, request, soapMsg);
}
}
return samlResponse;
}
Aggregations