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";
81 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
83 pair<bool,long> samlError(
84 const Application& app,
85 const ArtifactResolve& request,
86 HTTPResponse& httpResponse,
87 const EntityDescriptor* recipient,
89 const XMLCh* subcode=NULL,
93 MessageEncoder* m_encoder;
94 MessageDecoder* m_decoder;
95 xmltooling::QName m_role;
99 #if defined (_MSC_VER)
100 #pragma warning( pop )
103 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
105 return new SAML2ArtifactResolution(p.first, p.second);
110 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
111 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
113 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
117 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
119 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
120 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
122 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
123 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
127 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
134 string address(appId);
135 address += getString("Location").second;
136 address += "::run::SAML2Artifact";
137 setAddress(address.c_str());
140 SAML2ArtifactResolution::~SAML2ArtifactResolution()
148 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
151 SPConfig& conf = SPConfig::getConfig();
154 if (conf.isEnabled(SPConfig::OutOfProcess)) {
155 // When out of process, we run natively and directly process the message.
156 return processMessage(request.getApplication(), request, request);
159 // When not out of process, we remote all the message processing.
160 DDF out,in = wrap(request, NULL, true);
161 DDFJanitor jin(in), jout(out);
163 out=request.getServiceProvider().getListenerService()->send(in);
164 return unwrap(request, out);
167 catch (exception& ex) {
168 m_log.error("error while processing request: %s", ex.what());
170 // Build a SOAP fault around the error.
171 auto_ptr<Fault> fault(FaultBuilder::buildFault());
172 Faultcode* code = FaultcodeBuilder::buildFaultcode();
173 fault->setFaultcode(code);
174 code->setCode(&Faultcode::SERVER);
175 Faultstring* fs = FaultstringBuilder::buildFaultstring();
176 fault->setFaultstring(fs);
177 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
178 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
179 fs->setString(msg.get());
181 // Use MessageEncoder to send back the fault.
182 long ret = m_encoder->encode(request, fault.get(), NULL);
184 return make_pair(true, ret);
186 // Brute force the fault to avoid library dependency.
187 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
188 Body* body = BodyBuilder::buildBody();
190 body->getUnknownXMLObjects().push_back(fault.release());
192 XMLHelper::serialize(env->marshall(), xmlbuf);
193 istringstream s(xmlbuf);
194 request.setContentType("text/xml");
195 return make_pair(true, request.sendError(s));
200 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
203 const char* aid=in["application_id"].string();
204 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
206 // Something's horribly wrong.
207 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
208 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
211 // Unpack the request.
212 auto_ptr<HTTPRequest> req(getRequest(in));
213 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
215 // Wrap a response shim.
217 DDFJanitor jout(ret);
218 auto_ptr<HTTPResponse> resp(getResponse(ret));
221 // Since we're remoted, the result should either be a throw, a false/0 return,
222 // which we just return as an empty structure, or a response/redirect,
223 // which we capture in the facade and send back.
224 processMessage(*app, *req.get(), *resp.get());
227 catch (exception& ex) {
229 m_log.error("error while processing request: %s", ex.what());
231 // Use MessageEncoder to send back a SOAP fault.
232 auto_ptr<Fault> fault(FaultBuilder::buildFault());
233 Faultcode* code = FaultcodeBuilder::buildFaultcode();
234 fault->setFaultcode(code);
235 code->setCode(&Faultcode::SERVER);
236 Faultstring* fs = FaultstringBuilder::buildFaultstring();
237 fault->setFaultstring(fs);
238 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
239 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
240 fs->setString(msg.get());
241 m_encoder->encode(*resp.get(), fault.get(), NULL);
245 throw; // should never happen anyway
250 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
253 m_log.debug("processing SAML 2.0 ArtifactResolve request");
255 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
257 throw ConfigurationException("No ArtifactMap instance installed.");
259 // Locate policy key.
260 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
262 policyId = application.getString("policyId"); // unqualified in Application(s) element
264 // Access policy properties.
265 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
266 pair<bool,bool> validate = settings->getBool("validate");
268 // Lock metadata for use by policy.
269 Locker metadataLocker(application.getMetadataProvider());
271 // Create the policy.
272 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
274 // Decode the message and verify that it's a secured ArtifactResolve request.
276 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
278 throw BindingException("Failed to decode a SAML request.");
279 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
281 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
283 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
286 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
287 if (!artifact.get() || !*artifact.get())
288 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
289 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
291 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
293 // Parse the artifact and retrieve the object.
294 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
295 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
297 if (!policy.isAuthenticated()) {
298 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
299 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
302 m_log.debug("artifact resolved, preparing response");
304 // Wrap it in a response.
305 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
306 resp->setInResponseTo(req->getID());
307 Issuer* me = IssuerBuilder::buildIssuer();
308 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
309 resp->setPayload(payload.release());
311 long ret = sendMessage(
312 *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
314 resp.release(); // freed by encoder
315 return make_pair(true,ret);
317 catch (exception& ex) {
318 // Trap localized errors in a SAML Response.
319 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
320 return samlError(application, *req, httpResponse, entity, StatusCode::RESPONDER, NULL, ex.what());
323 return make_pair(false,0L);
328 pair<bool,long> SAML2ArtifactResolution::samlError(
329 const Application& app,
330 const ArtifactResolve& request,
331 HTTPResponse& httpResponse,
332 const EntityDescriptor* recipient,
334 const XMLCh* subcode,
338 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
339 resp->setInResponseTo(request.getID());
340 Issuer* me = IssuerBuilder::buildIssuer();
341 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
342 fillStatus(*resp.get(), code, subcode, msg);
343 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
344 resp.release(); // freed by encoder
345 return make_pair(true,ret);