2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 * SAML2ArtifactResolution.cpp
20 * Handler for resolving SAML 2.0 artifacts.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "util/SPConstants.h"
32 # include "security/SecurityPolicy.h"
33 # include <saml/SAMLConfig.h>
34 # include <saml/binding/ArtifactMap.h>
35 # include <saml/binding/MessageEncoder.h>
36 # include <saml/binding/MessageDecoder.h>
37 # include <saml/binding/SAMLArtifact.h>
38 # include <saml/saml2/core/Assertions.h>
39 # include <saml/saml2/core/Protocols.h>
40 # include <saml/saml2/metadata/Metadata.h>
41 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2;
45 using namespace samlconstants;
48 #include <xmltooling/soap/SOAP.h>
50 using namespace shibspconstants;
51 using namespace shibsp;
52 using namespace opensaml;
53 using namespace soap11;
54 using namespace xmltooling;
55 using namespace log4cpp;
60 #if defined (_MSC_VER)
61 #pragma warning( push )
62 #pragma warning( disable : 4250 )
65 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
68 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
69 virtual ~SAML2ArtifactResolution();
71 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
72 void receive(DDF& in, ostream& out);
75 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
77 pair<bool,long> samlError(
78 const Application& app,
79 const ArtifactResolve& request,
80 HTTPResponse& httpResponse,
82 const XMLCh* subcode=NULL,
86 MessageEncoder* m_encoder;
87 MessageDecoder* m_decoder;
92 #if defined (_MSC_VER)
93 #pragma warning( pop )
96 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
98 return new SAML2ArtifactResolution(p.first, p.second);
103 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
104 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2ArtifactResolution"))
106 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
110 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
112 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(getString("Binding").second,e);
113 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
115 catch (exception& ex) {
116 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
123 string address(appId);
124 address += getString("Location").second;
125 address += "::run::SAML2Artifact";
126 setAddress(address.c_str());
129 SAML2ArtifactResolution::~SAML2ArtifactResolution()
137 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
140 SPConfig& conf = SPConfig::getConfig();
143 if (conf.isEnabled(SPConfig::OutOfProcess)) {
144 // When out of process, we run natively and directly process the message.
145 return processMessage(request.getApplication(), request, request);
148 // When not out of process, we remote all the message processing.
149 DDF out,in = wrap(request, NULL, true);
150 DDFJanitor jin(in), jout(out);
152 out=request.getServiceProvider().getListenerService()->send(in);
153 return unwrap(request, out);
156 catch (exception& ex) {
157 m_log.error("error while processing request: %s", ex.what());
159 // Build a SOAP fault around the error.
160 auto_ptr<Fault> fault(FaultBuilder::buildFault());
161 Faultcode* code = FaultcodeBuilder::buildFaultcode();
162 fault->setFaultcode(code);
163 code->setCode(&Faultcode::SERVER);
164 Faultstring* fs = FaultstringBuilder::buildFaultstring();
165 fault->setFaultstring(fs);
166 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
167 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
168 fs->setString(msg.get());
170 // Use MessageEncoder to send back the fault.
171 long ret = m_encoder->encode(request, fault.get(), NULL);
173 return make_pair(true, ret);
175 // Brute force the fault to avoid library dependency.
176 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
177 Body* body = BodyBuilder::buildBody();
179 body->getUnknownXMLObjects().push_back(fault.release());
181 XMLHelper::serialize(env->marshall(), xmlbuf);
182 istringstream s(xmlbuf);
183 request.setContentType("text/xml");
184 return make_pair(true, request.sendError(s));
189 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
192 const char* aid=in["application_id"].string();
193 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
195 // Something's horribly wrong.
196 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
197 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
200 // Unpack the request.
201 auto_ptr<HTTPRequest> req(getRequest(in));
202 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
204 // Wrap a response shim.
206 DDFJanitor jout(ret);
207 auto_ptr<HTTPResponse> resp(getResponse(ret));
210 // Since we're remoted, the result should either be a throw, a false/0 return,
211 // which we just return as an empty structure, or a response/redirect,
212 // which we capture in the facade and send back.
213 processMessage(*app, *req.get(), *resp.get());
216 catch (exception& ex) {
218 m_log.error("error while processing request: %s", ex.what());
220 // Use MessageEncoder to send back a SOAP fault.
221 auto_ptr<Fault> fault(FaultBuilder::buildFault());
222 Faultcode* code = FaultcodeBuilder::buildFaultcode();
223 fault->setFaultcode(code);
224 code->setCode(&Faultcode::SERVER);
225 Faultstring* fs = FaultstringBuilder::buildFaultstring();
226 fault->setFaultstring(fs);
227 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
228 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
229 fs->setString(msg.get());
230 m_encoder->encode(*resp.get(), fault.get(), NULL);
234 throw; // should never happen anyway
239 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
242 m_log.debug("processing SAML 2.0 ArtifactResolve request");
244 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
246 throw ConfigurationException("No ArtifactMap instance installed.");
248 // Locate policy key.
249 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
251 policyId = application.getString("policyId"); // unqualified in Application(s) element
253 // Access policy properties.
254 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
255 pair<bool,bool> validate = settings->getBool("validate");
257 // Lock metadata for use by policy.
258 Locker metadataLocker(application.getMetadataProvider());
260 // Create the policy.
261 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
263 // Decode the message and verify that it's a secured ArtifactResolve request.
265 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
267 throw BindingException("Failed to decode a SAML request.");
268 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
270 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
273 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
274 if (!artifact.get() || !*artifact.get())
275 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
276 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
278 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
280 // Parse the artifact and retrieve the object.
281 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
282 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
284 if (!policy.isSecure()) {
285 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
286 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
289 m_log.debug("artifact resolved, preparing response");
291 // Wrap it in a response.
292 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
293 resp->setInResponseTo(req->getID());
294 Issuer* me = IssuerBuilder::buildIssuer();
295 me->setName(application.getXMLString("entityID").second);
296 resp->setPayload(payload.release());
298 const EntityDescriptor* entity =
299 policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
300 const PropertySet* relyingParty = application.getRelyingParty(entity);
301 pair<bool,const char*> flag = relyingParty->getString("signResponses");
302 if (policy.getIssuerMetadata() && flag.first && (!strcmp(flag.second, "true") || !strcmp(flag.second, "back"))) {
303 CredentialResolver* credResolver=application.getCredentialResolver();
305 Locker credLocker(credResolver);
306 // Fill in criteria to use.
307 MetadataCredentialCriteria mcc(*policy.getIssuerMetadata());
308 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
309 pair<bool,const char*> keyName = relyingParty->getString("keyName");
311 mcc.getKeyNames().insert(keyName.second);
312 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
314 mcc.setXMLAlgorithm(sigalg.second);
315 const Credential* cred = credResolver->resolve(&mcc);
318 long ret = m_encoder->encode(
327 relyingParty->getXMLString("digestAlg").second
329 resp.release(); // freed by encoder
330 return make_pair(true,ret);
333 m_log.warn("no signing credential resolved, leaving response unsigned");
338 long ret = m_encoder->encode(httpResponse, resp.get(), NULL, entity, relayState.c_str());
339 resp.release(); // freed by encoder
340 return make_pair(true,ret);
342 catch (exception& ex) {
343 // Trap localized errors in a SAML Response.
344 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
345 return samlError(application, *req, httpResponse, StatusCode::RESPONDER, NULL, ex.what());
348 return make_pair(false,0);
353 pair<bool,long> SAML2ArtifactResolution::samlError(
354 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
357 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
358 resp->setInResponseTo(request.getID());
359 Issuer* me = IssuerBuilder::buildIssuer();
360 me->setName(app.getXMLString("entityID").second);
361 prepareResponse(*resp.get(), code, subcode, msg);
362 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
363 resp.release(); // freed by encoder
364 return make_pair(true,ret);