2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * SAML2ArtifactResolution.cpp
24 * Handler for resolving SAML 2.0 artifacts.
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "util/SPConstants.h"
37 # include "security/SecurityPolicy.h"
38 # include "security/SecurityPolicyProvider.h"
39 # include <saml/exceptions.h>
40 # include <saml/SAMLConfig.h>
41 # include <saml/binding/ArtifactMap.h>
42 # include <saml/binding/MessageEncoder.h>
43 # include <saml/binding/MessageDecoder.h>
44 # include <saml/binding/SAMLArtifact.h>
45 # include <saml/saml2/core/Assertions.h>
46 # include <saml/saml2/core/Protocols.h>
47 # include <saml/saml2/metadata/Metadata.h>
48 using namespace opensaml::saml2md;
49 using namespace opensaml::saml2p;
50 using namespace opensaml::saml2;
51 using namespace opensaml;
53 # include "lite/SAMLConstants.h"
56 #include <xmltooling/soap/SOAP.h>
58 using namespace shibspconstants;
59 using namespace shibsp;
60 using namespace soap11;
61 using namespace xmltooling;
66 #if defined (_MSC_VER)
67 #pragma warning( push )
68 #pragma warning( disable : 4250 )
71 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
74 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
75 virtual ~SAML2ArtifactResolution();
77 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
78 void receive(DDF& in, ostream& out);
81 const char* getType() const {
82 return "ArtifactResolutionService";
85 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
86 // Initial guess at index to use.
87 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
88 if (!strncmp(handlerURL, "https", 5))
89 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
91 ix = getUnsignedInt("index");
95 // Find maximum index in use and go one higher.
96 const vector<ArtifactResolutionService*>& services = const_cast<const SPSSODescriptor&>(role).getArtifactResolutionServices();
97 if (!services.empty() && ix.second <= services.back()->getIndex().second)
98 ix.second = services.back()->getIndex().second + 1;
100 const char* loc = getString("Location").second;
101 string hurl(handlerURL);
105 auto_ptr_XMLCh widen(hurl.c_str());
107 ArtifactResolutionService* ep = ArtifactResolutionServiceBuilder::buildArtifactResolutionService();
108 ep->setLocation(widen.get());
109 ep->setBinding(getXMLString("Binding").second);
110 ep->setIndex(ix.second);
111 role.getArtifactResolutionServices().push_back(ep);
114 const XMLCh* getProtocolFamily() const {
115 return samlconstants::SAML20P_NS;
119 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
121 pair<bool,long> emptyResponse(
122 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
125 MessageEncoder* m_encoder;
126 MessageDecoder* m_decoder;
127 xmltooling::QName m_role;
131 #if defined (_MSC_VER)
132 #pragma warning( pop )
135 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
137 return new SAML2ArtifactResolution(p.first, p.second);
142 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
143 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
145 ,m_encoder(nullptr), m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
149 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
151 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
152 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
154 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
155 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
159 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
166 string address(appId);
167 address += getString("Location").second;
168 address += "::run::SAML2Artifact";
169 setAddress(address.c_str());
172 SAML2ArtifactResolution::~SAML2ArtifactResolution()
180 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
183 SPConfig& conf = SPConfig::getConfig();
186 if (conf.isEnabled(SPConfig::OutOfProcess)) {
187 // When out of process, we run natively and directly process the message.
188 return processMessage(request.getApplication(), request, request);
191 // When not out of process, we remote all the message processing.
192 DDF out,in = wrap(request, nullptr, true);
193 DDFJanitor jin(in), jout(out);
195 out=request.getServiceProvider().getListenerService()->send(in);
196 return unwrap(request, out);
199 catch (exception& ex) {
200 m_log.error("error while processing request: %s", ex.what());
202 // Build a SOAP fault around the error.
203 auto_ptr<Fault> fault(FaultBuilder::buildFault());
204 Faultcode* code = FaultcodeBuilder::buildFaultcode();
205 fault->setFaultcode(code);
206 code->setCode(&Faultcode::SERVER);
207 Faultstring* fs = FaultstringBuilder::buildFaultstring();
208 fault->setFaultstring(fs);
209 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
210 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
211 fs->setString(msg.get());
213 // Use MessageEncoder to send back the fault.
214 long ret = m_encoder->encode(request, fault.get(), nullptr);
216 return make_pair(true, ret);
218 // Brute force the fault to avoid library dependency.
219 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
220 Body* body = BodyBuilder::buildBody();
222 body->getUnknownXMLObjects().push_back(fault.release());
224 XMLHelper::serialize(env->marshall(), xmlbuf);
225 istringstream s(xmlbuf);
226 request.setContentType("text/xml");
227 return make_pair(true, request.sendError(s));
232 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
235 const char* aid=in["application_id"].string();
236 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
238 // Something's horribly wrong.
239 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
240 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
243 // Unpack the request.
244 auto_ptr<HTTPRequest> req(getRequest(in));
245 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
247 // Wrap a response shim.
249 DDFJanitor jout(ret);
250 auto_ptr<HTTPResponse> resp(getResponse(ret));
253 // Since we're remoted, the result should either be a throw, a false/0 return,
254 // which we just return as an empty structure, or a response/redirect,
255 // which we capture in the facade and send back.
256 processMessage(*app, *req.get(), *resp.get());
259 catch (exception& ex) {
261 m_log.error("error while processing request: %s", ex.what());
263 // Use MessageEncoder to send back a SOAP fault.
264 auto_ptr<Fault> fault(FaultBuilder::buildFault());
265 Faultcode* code = FaultcodeBuilder::buildFaultcode();
266 fault->setFaultcode(code);
267 code->setCode(&Faultcode::SERVER);
268 Faultstring* fs = FaultstringBuilder::buildFaultstring();
269 fault->setFaultstring(fs);
270 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
271 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
272 fs->setString(msg.get());
273 m_encoder->encode(*resp.get(), fault.get(), nullptr);
277 throw; // should never happen anyway
282 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
285 m_log.debug("processing SAML 2.0 ArtifactResolve request");
287 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
289 throw ConfigurationException("No ArtifactMap instance installed.");
291 // Locate policy key.
292 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
294 policyId = application.getString("policyId"); // unqualified in Application(s) element
296 // Lock metadata for use by policy.
297 Locker metadataLocker(application.getMetadataProvider());
299 // Create the policy.
300 auto_ptr<SecurityPolicy> policy(
301 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
304 // Decode the message and verify that it's a secured ArtifactResolve request.
306 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *policy.get()));
308 throw BindingException("Failed to decode a SAML request.");
309 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
311 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
313 const EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
316 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : nullptr);
317 if (!artifact.get() || !*artifact.get())
318 return emptyResponse(application, *req, httpResponse, entity);
319 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
321 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
323 // Parse the artifact and retrieve the object.
324 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
325 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
327 if (!policy->isAuthenticated()) {
328 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
329 return emptyResponse(application, *req, httpResponse, entity);
332 m_log.debug("artifact resolved, preparing response");
334 // Wrap it in a response.
335 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
336 resp->setInResponseTo(req->getID());
337 Issuer* me = IssuerBuilder::buildIssuer();
338 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
339 resp->setPayload(payload.release());
341 long ret = sendMessage(
342 *m_encoder, resp.get(), relayState.c_str(), nullptr, policy->getIssuerMetadata(), application, httpResponse, "signResponses"
344 resp.release(); // freed by encoder
345 return make_pair(true,ret);
347 catch (exception& ex) {
348 // Trap localized errors.
349 m_log.error("error processing artifact request: %s", ex.what());
350 return emptyResponse(application, *req, httpResponse, entity);
353 return make_pair(false,0L);
358 pair<bool,long> SAML2ArtifactResolution::emptyResponse(
359 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
362 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
363 resp->setInResponseTo(request.getID());
364 Issuer* me = IssuerBuilder::buildIssuer();
365 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
366 fillStatus(*resp.get(), StatusCode::SUCCESS);
367 long ret = m_encoder->encode(httpResponse, resp.get(), nullptr);
368 resp.release(); // freed by encoder
369 return make_pair(true,ret);