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;
48 using namespace samlconstants;
51 #include <xmltooling/soap/SOAP.h>
53 using namespace shibspconstants;
54 using namespace shibsp;
55 using namespace soap11;
56 using namespace xmltooling;
61 #if defined (_MSC_VER)
62 #pragma warning( push )
63 #pragma warning( disable : 4250 )
66 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
69 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
70 virtual ~SAML2ArtifactResolution();
72 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
73 void receive(DDF& in, ostream& out);
76 const char* getType() const {
77 return "ArtifactResolutionService";
80 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
81 // Initial guess at index to use.
82 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
83 if (!strncmp(handlerURL, "https", 5))
84 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
86 ix = getUnsignedInt("index");
90 // Find maximum index in use and go one higher.
91 const vector<ArtifactResolutionService*>& services = const_cast<const SPSSODescriptor&>(role).getArtifactResolutionServices();
92 if (!services.empty() && ix.second <= services.back()->getIndex().second)
93 ix.second = services.back()->getIndex().second + 1;
95 const char* loc = getString("Location").second;
96 string hurl(handlerURL);
100 auto_ptr_XMLCh widen(hurl.c_str());
102 ArtifactResolutionService* ep = ArtifactResolutionServiceBuilder::buildArtifactResolutionService();
103 ep->setLocation(widen.get());
104 ep->setBinding(getXMLString("Binding").second);
105 ep->setIndex(ix.second);
106 role.getArtifactResolutionServices().push_back(ep);
111 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
113 pair<bool,long> emptyResponse(
114 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
117 MessageEncoder* m_encoder;
118 MessageDecoder* m_decoder;
119 xmltooling::QName m_role;
123 #if defined (_MSC_VER)
124 #pragma warning( pop )
127 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
129 return new SAML2ArtifactResolution(p.first, p.second);
134 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
135 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
137 ,m_encoder(nullptr), m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
141 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
143 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
144 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
146 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
147 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
151 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
158 string address(appId);
159 address += getString("Location").second;
160 address += "::run::SAML2Artifact";
161 setAddress(address.c_str());
164 SAML2ArtifactResolution::~SAML2ArtifactResolution()
172 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
175 SPConfig& conf = SPConfig::getConfig();
178 if (conf.isEnabled(SPConfig::OutOfProcess)) {
179 // When out of process, we run natively and directly process the message.
180 return processMessage(request.getApplication(), request, request);
183 // When not out of process, we remote all the message processing.
184 DDF out,in = wrap(request, nullptr, true);
185 DDFJanitor jin(in), jout(out);
187 out=request.getServiceProvider().getListenerService()->send(in);
188 return unwrap(request, out);
191 catch (exception& ex) {
192 m_log.error("error while processing request: %s", ex.what());
194 // Build a SOAP fault around the error.
195 auto_ptr<Fault> fault(FaultBuilder::buildFault());
196 Faultcode* code = FaultcodeBuilder::buildFaultcode();
197 fault->setFaultcode(code);
198 code->setCode(&Faultcode::SERVER);
199 Faultstring* fs = FaultstringBuilder::buildFaultstring();
200 fault->setFaultstring(fs);
201 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
202 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
203 fs->setString(msg.get());
205 // Use MessageEncoder to send back the fault.
206 long ret = m_encoder->encode(request, fault.get(), nullptr);
208 return make_pair(true, ret);
210 // Brute force the fault to avoid library dependency.
211 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
212 Body* body = BodyBuilder::buildBody();
214 body->getUnknownXMLObjects().push_back(fault.release());
216 XMLHelper::serialize(env->marshall(), xmlbuf);
217 istringstream s(xmlbuf);
218 request.setContentType("text/xml");
219 return make_pair(true, request.sendError(s));
224 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
227 const char* aid=in["application_id"].string();
228 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
230 // Something's horribly wrong.
231 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
232 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
235 // Unpack the request.
236 auto_ptr<HTTPRequest> req(getRequest(in));
237 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
239 // Wrap a response shim.
241 DDFJanitor jout(ret);
242 auto_ptr<HTTPResponse> resp(getResponse(ret));
245 // Since we're remoted, the result should either be a throw, a false/0 return,
246 // which we just return as an empty structure, or a response/redirect,
247 // which we capture in the facade and send back.
248 processMessage(*app, *req.get(), *resp.get());
251 catch (exception& ex) {
253 m_log.error("error while processing request: %s", ex.what());
255 // Use MessageEncoder to send back a SOAP fault.
256 auto_ptr<Fault> fault(FaultBuilder::buildFault());
257 Faultcode* code = FaultcodeBuilder::buildFaultcode();
258 fault->setFaultcode(code);
259 code->setCode(&Faultcode::SERVER);
260 Faultstring* fs = FaultstringBuilder::buildFaultstring();
261 fault->setFaultstring(fs);
262 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
263 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
264 fs->setString(msg.get());
265 m_encoder->encode(*resp.get(), fault.get(), nullptr);
269 throw; // should never happen anyway
274 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
277 m_log.debug("processing SAML 2.0 ArtifactResolve request");
279 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
281 throw ConfigurationException("No ArtifactMap instance installed.");
283 // Locate policy key.
284 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
286 policyId = application.getString("policyId"); // unqualified in Application(s) element
288 // Lock metadata for use by policy.
289 Locker metadataLocker(application.getMetadataProvider());
291 // Create the policy.
292 auto_ptr<SecurityPolicy> policy(
293 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
296 // Decode the message and verify that it's a secured ArtifactResolve request.
298 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, *policy.get()));
300 throw BindingException("Failed to decode a SAML request.");
301 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
303 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
305 const EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
308 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : nullptr);
309 if (!artifact.get() || !*artifact.get())
310 return emptyResponse(application, *req, httpResponse, entity);
311 auto_ptr_char issuer(policy->getIssuer() ? policy->getIssuer()->getName() : nullptr);
313 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
315 // Parse the artifact and retrieve the object.
316 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
317 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
319 if (!policy->isAuthenticated()) {
320 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
321 return emptyResponse(application, *req, httpResponse, entity);
324 m_log.debug("artifact resolved, preparing response");
326 // Wrap it in a response.
327 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
328 resp->setInResponseTo(req->getID());
329 Issuer* me = IssuerBuilder::buildIssuer();
330 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
331 resp->setPayload(payload.release());
333 long ret = sendMessage(
334 *m_encoder, resp.get(), relayState.c_str(), nullptr, policy->getIssuerMetadata(), application, httpResponse, "signResponses"
336 resp.release(); // freed by encoder
337 return make_pair(true,ret);
339 catch (exception& ex) {
340 // Trap localized errors.
341 m_log.error("error processing artifact request: %s", ex.what());
342 return emptyResponse(application, *req, httpResponse, entity);
345 return make_pair(false,0L);
350 pair<bool,long> SAML2ArtifactResolution::emptyResponse(
351 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
354 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
355 resp->setInResponseTo(request.getID());
356 Issuer* me = IssuerBuilder::buildIssuer();
357 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
358 fillStatus(*resp.get(), StatusCode::SUCCESS);
359 long ret = m_encoder->encode(httpResponse, resp.get(), nullptr);
360 resp.release(); // freed by encoder
361 return make_pair(true,ret);