2 * Copyright 2001-2010 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 "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "util/SPConstants.h"
33 # include "security/SecurityPolicy.h"
34 # include "security/SecurityPolicyProvider.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/binding/ArtifactMap.h>
38 # include <saml/binding/MessageEncoder.h>
39 # include <saml/binding/MessageDecoder.h>
40 # include <saml/binding/SAMLArtifact.h>
41 # include <saml/saml2/core/Assertions.h>
42 # include <saml/saml2/core/Protocols.h>
43 # include <saml/saml2/metadata/Metadata.h>
44 using namespace opensaml::saml2md;
45 using namespace opensaml::saml2p;
46 using namespace opensaml::saml2;
47 using namespace opensaml;
49 # include "lite/SAMLConstants.h"
52 #include <xmltooling/soap/SOAP.h>
54 using namespace shibspconstants;
55 using namespace shibsp;
56 using namespace soap11;
57 using namespace xmltooling;
62 #if defined (_MSC_VER)
63 #pragma warning( push )
64 #pragma warning( disable : 4250 )
67 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
70 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
71 virtual ~SAML2ArtifactResolution();
73 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
74 void receive(DDF& in, ostream& out);
77 const char* getType() const {
78 return "ArtifactResolutionService";
81 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
82 // Initial guess at index to use.
83 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
84 if (!strncmp(handlerURL, "https", 5))
85 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
87 ix = getUnsignedInt("index");
91 // Find maximum index in use and go one higher.
92 const vector<ArtifactResolutionService*>& services = const_cast<const SPSSODescriptor&>(role).getArtifactResolutionServices();
93 if (!services.empty() && ix.second <= services.back()->getIndex().second)
94 ix.second = services.back()->getIndex().second + 1;
96 const char* loc = getString("Location").second;
97 string hurl(handlerURL);
101 auto_ptr_XMLCh widen(hurl.c_str());
103 ArtifactResolutionService* ep = ArtifactResolutionServiceBuilder::buildArtifactResolutionService();
104 ep->setLocation(widen.get());
105 ep->setBinding(getXMLString("Binding").second);
106 ep->setIndex(ix.second);
107 role.getArtifactResolutionServices().push_back(ep);
110 const XMLCh* getProtocolFamily() const {
111 return samlconstants::SAML20P_NS;
115 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
117 pair<bool,long> emptyResponse(
118 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
121 MessageEncoder* m_encoder;
122 MessageDecoder* m_decoder;
123 xmltooling::QName m_role;
127 #if defined (_MSC_VER)
128 #pragma warning( pop )
131 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
133 return new SAML2ArtifactResolution(p.first, p.second);
138 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
139 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
141 ,m_encoder(nullptr), m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
145 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
147 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
148 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
150 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
151 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
155 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
162 string address(appId);
163 address += getString("Location").second;
164 address += "::run::SAML2Artifact";
165 setAddress(address.c_str());
168 SAML2ArtifactResolution::~SAML2ArtifactResolution()
176 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
179 SPConfig& conf = SPConfig::getConfig();
182 if (conf.isEnabled(SPConfig::OutOfProcess)) {
183 // When out of process, we run natively and directly process the message.
184 return processMessage(request.getApplication(), request, request);
187 // When not out of process, we remote all the message processing.
188 DDF out,in = wrap(request, nullptr, true);
189 DDFJanitor jin(in), jout(out);
191 out=request.getServiceProvider().getListenerService()->send(in);
192 return unwrap(request, out);
195 catch (exception& ex) {
196 m_log.error("error while processing request: %s", ex.what());
198 // Build a SOAP fault around the error.
199 auto_ptr<Fault> fault(FaultBuilder::buildFault());
200 Faultcode* code = FaultcodeBuilder::buildFaultcode();
201 fault->setFaultcode(code);
202 code->setCode(&Faultcode::SERVER);
203 Faultstring* fs = FaultstringBuilder::buildFaultstring();
204 fault->setFaultstring(fs);
205 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
206 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
207 fs->setString(msg.get());
209 // Use MessageEncoder to send back the fault.
210 long ret = m_encoder->encode(request, fault.get(), nullptr);
212 return make_pair(true, ret);
214 // Brute force the fault to avoid library dependency.
215 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
216 Body* body = BodyBuilder::buildBody();
218 body->getUnknownXMLObjects().push_back(fault.release());
220 XMLHelper::serialize(env->marshall(), xmlbuf);
221 istringstream s(xmlbuf);
222 request.setContentType("text/xml");
223 return make_pair(true, request.sendError(s));
228 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
231 const char* aid=in["application_id"].string();
232 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
234 // Something's horribly wrong.
235 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
236 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
239 // Unpack the request.
240 auto_ptr<HTTPRequest> req(getRequest(in));
241 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
243 // Wrap a response shim.
245 DDFJanitor jout(ret);
246 auto_ptr<HTTPResponse> resp(getResponse(ret));
249 // Since we're remoted, the result should either be a throw, a false/0 return,
250 // which we just return as an empty structure, or a response/redirect,
251 // which we capture in the facade and send back.
252 processMessage(*app, *req.get(), *resp.get());
255 catch (exception& ex) {
257 m_log.error("error while processing request: %s", ex.what());
259 // Use MessageEncoder to send back a SOAP fault.
260 auto_ptr<Fault> fault(FaultBuilder::buildFault());
261 Faultcode* code = FaultcodeBuilder::buildFaultcode();
262 fault->setFaultcode(code);
263 code->setCode(&Faultcode::SERVER);
264 Faultstring* fs = FaultstringBuilder::buildFaultstring();
265 fault->setFaultstring(fs);
266 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
267 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
268 fs->setString(msg.get());
269 m_encoder->encode(*resp.get(), fault.get(), nullptr);
273 throw; // should never happen anyway
278 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
281 m_log.debug("processing SAML 2.0 ArtifactResolve request");
283 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
285 throw ConfigurationException("No ArtifactMap instance installed.");
287 // Locate policy key.
288 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
290 policyId = application.getString("policyId"); // unqualified in Application(s) element
292 // Lock metadata for use by policy.
293 Locker metadataLocker(application.getMetadataProvider());
295 // Create the policy.
296 auto_ptr<SecurityPolicy> policy(
297 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
300 // Decode the message and verify that it's a secured ArtifactResolve request.
302 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *policy.get()));
304 throw BindingException("Failed to decode a SAML request.");
305 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
307 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
309 const EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
312 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : nullptr);
313 if (!artifact.get() || !*artifact.get())
314 return emptyResponse(application, *req, httpResponse, entity);
315 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
317 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
319 // Parse the artifact and retrieve the object.
320 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
321 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
323 if (!policy->isAuthenticated()) {
324 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
325 return emptyResponse(application, *req, httpResponse, entity);
328 m_log.debug("artifact resolved, preparing response");
330 // Wrap it in a response.
331 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
332 resp->setInResponseTo(req->getID());
333 Issuer* me = IssuerBuilder::buildIssuer();
334 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
335 resp->setPayload(payload.release());
337 long ret = sendMessage(
338 *m_encoder, resp.get(), relayState.c_str(), nullptr, policy->getIssuerMetadata(), application, httpResponse, "signResponses"
340 resp.release(); // freed by encoder
341 return make_pair(true,ret);
343 catch (exception& ex) {
344 // Trap localized errors.
345 m_log.error("error processing artifact request: %s", ex.what());
346 return emptyResponse(application, *req, httpResponse, entity);
349 return make_pair(false,0L);
354 pair<bool,long> SAML2ArtifactResolution::emptyResponse(
355 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
358 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
359 resp->setInResponseTo(request.getID());
360 Issuer* me = IssuerBuilder::buildIssuer();
361 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
362 fillStatus(*resp.get(), StatusCode::SUCCESS);
363 long ret = m_encoder->encode(httpResponse, resp.get(), nullptr);
364 resp.release(); // freed by encoder
365 return make_pair(true,ret);