2 * Copyright 2001-2009 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 for (vector<ArtifactResolutionService*>::const_iterator i = services.begin(); i != services.end(); ++i) {
92 if (ix.second <= (*i)->getIndex().second)
93 ix.second = (*i)->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);
112 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
114 pair<bool,long> samlError(
115 const Application& app,
116 const ArtifactResolve& request,
117 HTTPResponse& httpResponse,
118 const EntityDescriptor* recipient,
120 const XMLCh* subcode=NULL,
124 MessageEncoder* m_encoder;
125 MessageDecoder* m_decoder;
126 xmltooling::QName m_role;
130 #if defined (_MSC_VER)
131 #pragma warning( pop )
134 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
136 return new SAML2ArtifactResolution(p.first, p.second);
141 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
142 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
144 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
148 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
150 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
151 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
153 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
154 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
158 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
165 string address(appId);
166 address += getString("Location").second;
167 address += "::run::SAML2Artifact";
168 setAddress(address.c_str());
171 SAML2ArtifactResolution::~SAML2ArtifactResolution()
179 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
182 SPConfig& conf = SPConfig::getConfig();
185 if (conf.isEnabled(SPConfig::OutOfProcess)) {
186 // When out of process, we run natively and directly process the message.
187 return processMessage(request.getApplication(), request, request);
190 // When not out of process, we remote all the message processing.
191 DDF out,in = wrap(request, NULL, true);
192 DDFJanitor jin(in), jout(out);
194 out=request.getServiceProvider().getListenerService()->send(in);
195 return unwrap(request, out);
198 catch (exception& ex) {
199 m_log.error("error while processing request: %s", ex.what());
201 // Build a SOAP fault around the error.
202 auto_ptr<Fault> fault(FaultBuilder::buildFault());
203 Faultcode* code = FaultcodeBuilder::buildFaultcode();
204 fault->setFaultcode(code);
205 code->setCode(&Faultcode::SERVER);
206 Faultstring* fs = FaultstringBuilder::buildFaultstring();
207 fault->setFaultstring(fs);
208 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
209 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
210 fs->setString(msg.get());
212 // Use MessageEncoder to send back the fault.
213 long ret = m_encoder->encode(request, fault.get(), NULL);
215 return make_pair(true, ret);
217 // Brute force the fault to avoid library dependency.
218 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
219 Body* body = BodyBuilder::buildBody();
221 body->getUnknownXMLObjects().push_back(fault.release());
223 XMLHelper::serialize(env->marshall(), xmlbuf);
224 istringstream s(xmlbuf);
225 request.setContentType("text/xml");
226 return make_pair(true, request.sendError(s));
231 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
234 const char* aid=in["application_id"].string();
235 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
237 // Something's horribly wrong.
238 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
239 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
242 // Unpack the request.
243 auto_ptr<HTTPRequest> req(getRequest(in));
244 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
246 // Wrap a response shim.
248 DDFJanitor jout(ret);
249 auto_ptr<HTTPResponse> resp(getResponse(ret));
252 // Since we're remoted, the result should either be a throw, a false/0 return,
253 // which we just return as an empty structure, or a response/redirect,
254 // which we capture in the facade and send back.
255 processMessage(*app, *req.get(), *resp.get());
258 catch (exception& ex) {
260 m_log.error("error while processing request: %s", ex.what());
262 // Use MessageEncoder to send back a SOAP fault.
263 auto_ptr<Fault> fault(FaultBuilder::buildFault());
264 Faultcode* code = FaultcodeBuilder::buildFaultcode();
265 fault->setFaultcode(code);
266 code->setCode(&Faultcode::SERVER);
267 Faultstring* fs = FaultstringBuilder::buildFaultstring();
268 fault->setFaultstring(fs);
269 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
270 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
271 fs->setString(msg.get());
272 m_encoder->encode(*resp.get(), fault.get(), NULL);
276 throw; // should never happen anyway
281 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
284 m_log.debug("processing SAML 2.0 ArtifactResolve request");
286 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
288 throw ConfigurationException("No ArtifactMap instance installed.");
290 // Locate policy key.
291 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
293 policyId = application.getString("policyId"); // unqualified in Application(s) element
295 // Access policy properties.
296 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
297 pair<bool,bool> validate = settings->getBool("validate");
299 // Lock metadata for use by policy.
300 Locker metadataLocker(application.getMetadataProvider());
302 // Create the policy.
303 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
305 // Decode the message and verify that it's a secured ArtifactResolve request.
307 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
309 throw BindingException("Failed to decode a SAML request.");
310 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
312 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
314 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
317 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
318 if (!artifact.get() || !*artifact.get())
319 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
320 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
322 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
324 // Parse the artifact and retrieve the object.
325 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
326 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
328 if (!policy.isAuthenticated()) {
329 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
330 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
333 m_log.debug("artifact resolved, preparing response");
335 // Wrap it in a response.
336 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
337 resp->setInResponseTo(req->getID());
338 Issuer* me = IssuerBuilder::buildIssuer();
339 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
340 resp->setPayload(payload.release());
342 long ret = sendMessage(
343 *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
345 resp.release(); // freed by encoder
346 return make_pair(true,ret);
348 catch (exception& ex) {
349 // Trap localized errors in a SAML Response.
350 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
351 return samlError(application, *req, httpResponse, entity, StatusCode::RESPONDER, NULL, ex.what());
354 return make_pair(false,0L);
359 pair<bool,long> SAML2ArtifactResolution::samlError(
360 const Application& app,
361 const ArtifactResolve& request,
362 HTTPResponse& httpResponse,
363 const EntityDescriptor* recipient,
365 const XMLCh* subcode,
369 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
370 resp->setInResponseTo(request.getID());
371 Issuer* me = IssuerBuilder::buildIssuer();
372 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
373 fillStatus(*resp.get(), code, subcode, msg);
374 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
375 resp.release(); // freed by encoder
376 return make_pair(true,ret);