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 <saml/exceptions.h>
35 # include <saml/SAMLConfig.h>
36 # include <saml/binding/ArtifactMap.h>
37 # include <saml/binding/MessageEncoder.h>
38 # include <saml/binding/MessageDecoder.h>
39 # include <saml/binding/SAMLArtifact.h>
40 # include <saml/saml2/core/Assertions.h>
41 # include <saml/saml2/core/Protocols.h>
42 # include <saml/saml2/metadata/Metadata.h>
43 using namespace opensaml::saml2md;
44 using namespace opensaml::saml2p;
45 using namespace opensaml::saml2;
46 using namespace opensaml;
47 using namespace samlconstants;
50 #include <xmltooling/soap/SOAP.h>
52 using namespace shibspconstants;
53 using namespace shibsp;
54 using namespace soap11;
55 using namespace xmltooling;
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 const char* getType() const {
76 return "ArtifactResolutionService";
79 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
80 // Initial guess at index to use.
81 pair<bool,unsigned int> ix = pair<bool,unsigned int>(false,0);
82 if (!strncmp(handlerURL, "https", 5))
83 ix = getUnsignedInt("sslIndex", shibspconstants::ASCII_SHIB2SPCONFIG_NS);
85 ix = getUnsignedInt("index");
89 // Find maximum index in use and go one higher.
90 const vector<ArtifactResolutionService*>& services = const_cast<const SPSSODescriptor&>(role).getArtifactResolutionServices();
91 if (!services.empty() && ix.second <= services.back()->getIndex().second)
92 ix.second = services.back()->getIndex().second + 1;
94 const char* loc = getString("Location").second;
95 string hurl(handlerURL);
99 auto_ptr_XMLCh widen(hurl.c_str());
101 ArtifactResolutionService* ep = ArtifactResolutionServiceBuilder::buildArtifactResolutionService();
102 ep->setLocation(widen.get());
103 ep->setBinding(getXMLString("Binding").second);
104 ep->setIndex(ix.second);
105 role.getArtifactResolutionServices().push_back(ep);
110 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
112 pair<bool,long> emptyResponse(
113 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
116 MessageEncoder* m_encoder;
117 MessageDecoder* m_decoder;
118 xmltooling::QName m_role;
122 #if defined (_MSC_VER)
123 #pragma warning( pop )
126 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
128 return new SAML2ArtifactResolution(p.first, p.second);
133 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
134 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
136 ,m_encoder(nullptr), m_decoder(nullptr), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
140 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
142 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
143 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
145 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
146 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,nullptr)
150 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
157 string address(appId);
158 address += getString("Location").second;
159 address += "::run::SAML2Artifact";
160 setAddress(address.c_str());
163 SAML2ArtifactResolution::~SAML2ArtifactResolution()
171 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
174 SPConfig& conf = SPConfig::getConfig();
177 if (conf.isEnabled(SPConfig::OutOfProcess)) {
178 // When out of process, we run natively and directly process the message.
179 return processMessage(request.getApplication(), request, request);
182 // When not out of process, we remote all the message processing.
183 DDF out,in = wrap(request, nullptr, true);
184 DDFJanitor jin(in), jout(out);
186 out=request.getServiceProvider().getListenerService()->send(in);
187 return unwrap(request, out);
190 catch (exception& ex) {
191 m_log.error("error while processing request: %s", ex.what());
193 // Build a SOAP fault around the error.
194 auto_ptr<Fault> fault(FaultBuilder::buildFault());
195 Faultcode* code = FaultcodeBuilder::buildFaultcode();
196 fault->setFaultcode(code);
197 code->setCode(&Faultcode::SERVER);
198 Faultstring* fs = FaultstringBuilder::buildFaultstring();
199 fault->setFaultstring(fs);
200 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
201 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
202 fs->setString(msg.get());
204 // Use MessageEncoder to send back the fault.
205 long ret = m_encoder->encode(request, fault.get(), nullptr);
207 return make_pair(true, ret);
209 // Brute force the fault to avoid library dependency.
210 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
211 Body* body = BodyBuilder::buildBody();
213 body->getUnknownXMLObjects().push_back(fault.release());
215 XMLHelper::serialize(env->marshall(), xmlbuf);
216 istringstream s(xmlbuf);
217 request.setContentType("text/xml");
218 return make_pair(true, request.sendError(s));
223 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
226 const char* aid=in["application_id"].string();
227 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
229 // Something's horribly wrong.
230 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
231 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
234 // Unpack the request.
235 auto_ptr<HTTPRequest> req(getRequest(in));
236 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
238 // Wrap a response shim.
240 DDFJanitor jout(ret);
241 auto_ptr<HTTPResponse> resp(getResponse(ret));
244 // Since we're remoted, the result should either be a throw, a false/0 return,
245 // which we just return as an empty structure, or a response/redirect,
246 // which we capture in the facade and send back.
247 processMessage(*app, *req.get(), *resp.get());
250 catch (exception& ex) {
252 m_log.error("error while processing request: %s", ex.what());
254 // Use MessageEncoder to send back a SOAP fault.
255 auto_ptr<Fault> fault(FaultBuilder::buildFault());
256 Faultcode* code = FaultcodeBuilder::buildFaultcode();
257 fault->setFaultcode(code);
258 code->setCode(&Faultcode::SERVER);
259 Faultstring* fs = FaultstringBuilder::buildFaultstring();
260 fault->setFaultstring(fs);
261 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
262 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
263 fs->setString(msg.get());
264 m_encoder->encode(*resp.get(), fault.get(), nullptr);
268 throw; // should never happen anyway
273 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
276 m_log.debug("processing SAML 2.0 ArtifactResolve request");
278 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
280 throw ConfigurationException("No ArtifactMap instance installed.");
282 // Locate policy key.
283 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
285 policyId = application.getString("policyId"); // unqualified in Application(s) element
287 // Access policy properties.
288 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
289 pair<bool,bool> validate = settings->getBool("validate");
291 // Lock metadata for use by policy.
292 Locker metadataLocker(application.getMetadataProvider());
294 // Create the policy.
295 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
297 // Decode the message and verify that it's a secured ArtifactResolve request.
299 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
301 throw BindingException("Failed to decode a SAML request.");
302 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
304 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
306 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
309 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : nullptr);
310 if (!artifact.get() || !*artifact.get())
311 return emptyResponse(application, *req, httpResponse, entity);
312 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : nullptr);
314 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
316 // Parse the artifact and retrieve the object.
317 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
318 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
320 if (!policy.isAuthenticated()) {
321 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
322 return emptyResponse(application, *req, httpResponse, entity);
325 m_log.debug("artifact resolved, preparing response");
327 // Wrap it in a response.
328 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
329 resp->setInResponseTo(req->getID());
330 Issuer* me = IssuerBuilder::buildIssuer();
331 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
332 resp->setPayload(payload.release());
334 long ret = sendMessage(
335 *m_encoder, resp.get(), relayState.c_str(), nullptr, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
337 resp.release(); // freed by encoder
338 return make_pair(true,ret);
340 catch (exception& ex) {
341 // Trap localized errors.
342 m_log.error("error processing artifact request: %s", ex.what());
343 return emptyResponse(application, *req, httpResponse, entity);
346 return make_pair(false,0L);
351 pair<bool,long> SAML2ArtifactResolution::emptyResponse(
352 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const EntityDescriptor* recipient
355 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
356 resp->setInResponseTo(request.getID());
357 Issuer* me = IssuerBuilder::buildIssuer();
358 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
359 fillStatus(*resp.get(), StatusCode::SUCCESS);
360 long ret = m_encoder->encode(httpResponse, resp.get(), nullptr);
361 resp.release(); // freed by encoder
362 return make_pair(true,ret);