2 * Copyright 2001-2007 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 "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "util/SPConstants.h"
32 # include "security/SecurityPolicy.h"
33 # include <saml/SAMLConfig.h>
34 # include <saml/binding/ArtifactMap.h>
35 # include <saml/binding/MessageEncoder.h>
36 # include <saml/binding/MessageDecoder.h>
37 # include <saml/binding/SAMLArtifact.h>
38 # include <saml/saml2/core/Assertions.h>
39 # include <saml/saml2/core/Protocols.h>
40 # include <saml/saml2/metadata/Metadata.h>
41 using namespace opensaml::saml2md;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2;
44 using namespace samlconstants;
47 #include <xmltooling/soap/SOAP.h>
49 using namespace shibspconstants;
50 using namespace shibsp;
51 using namespace opensaml;
52 using namespace soap11;
53 using namespace xmltooling;
58 #if defined (_MSC_VER)
59 #pragma warning( push )
60 #pragma warning( disable : 4250 )
63 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
66 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
67 virtual ~SAML2ArtifactResolution();
69 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
70 void receive(DDF& in, ostream& out);
73 const char* getType() const {
74 return "ArtifactResolutionService";
79 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
81 pair<bool,long> samlError(
82 const Application& app,
83 const ArtifactResolve& request,
84 HTTPResponse& httpResponse,
85 const EntityDescriptor* recipient,
87 const XMLCh* subcode=NULL,
91 MessageEncoder* m_encoder;
92 MessageDecoder* m_decoder;
97 #if defined (_MSC_VER)
98 #pragma warning( pop )
101 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
103 return new SAML2ArtifactResolution(p.first, p.second);
108 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
109 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
111 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
115 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
117 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
118 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
120 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
121 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
124 catch (exception& ex) {
125 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
132 string address(appId);
133 address += getString("Location").second;
134 address += "::run::SAML2Artifact";
135 setAddress(address.c_str());
138 SAML2ArtifactResolution::~SAML2ArtifactResolution()
146 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
149 SPConfig& conf = SPConfig::getConfig();
152 if (conf.isEnabled(SPConfig::OutOfProcess)) {
153 // When out of process, we run natively and directly process the message.
154 return processMessage(request.getApplication(), request, request);
157 // When not out of process, we remote all the message processing.
158 DDF out,in = wrap(request, NULL, true);
159 DDFJanitor jin(in), jout(out);
161 out=request.getServiceProvider().getListenerService()->send(in);
162 return unwrap(request, out);
165 catch (exception& ex) {
166 m_log.error("error while processing request: %s", ex.what());
168 // Build a SOAP fault around the error.
169 auto_ptr<Fault> fault(FaultBuilder::buildFault());
170 Faultcode* code = FaultcodeBuilder::buildFaultcode();
171 fault->setFaultcode(code);
172 code->setCode(&Faultcode::SERVER);
173 Faultstring* fs = FaultstringBuilder::buildFaultstring();
174 fault->setFaultstring(fs);
175 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
176 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
177 fs->setString(msg.get());
179 // Use MessageEncoder to send back the fault.
180 long ret = m_encoder->encode(request, fault.get(), NULL);
182 return make_pair(true, ret);
184 // Brute force the fault to avoid library dependency.
185 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
186 Body* body = BodyBuilder::buildBody();
188 body->getUnknownXMLObjects().push_back(fault.release());
190 XMLHelper::serialize(env->marshall(), xmlbuf);
191 istringstream s(xmlbuf);
192 request.setContentType("text/xml");
193 return make_pair(true, request.sendError(s));
198 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
201 const char* aid=in["application_id"].string();
202 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
204 // Something's horribly wrong.
205 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
206 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
209 // Unpack the request.
210 auto_ptr<HTTPRequest> req(getRequest(in));
211 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
213 // Wrap a response shim.
215 DDFJanitor jout(ret);
216 auto_ptr<HTTPResponse> resp(getResponse(ret));
219 // Since we're remoted, the result should either be a throw, a false/0 return,
220 // which we just return as an empty structure, or a response/redirect,
221 // which we capture in the facade and send back.
222 processMessage(*app, *req.get(), *resp.get());
225 catch (exception& ex) {
227 m_log.error("error while processing request: %s", ex.what());
229 // Use MessageEncoder to send back a SOAP fault.
230 auto_ptr<Fault> fault(FaultBuilder::buildFault());
231 Faultcode* code = FaultcodeBuilder::buildFaultcode();
232 fault->setFaultcode(code);
233 code->setCode(&Faultcode::SERVER);
234 Faultstring* fs = FaultstringBuilder::buildFaultstring();
235 fault->setFaultstring(fs);
236 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
237 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
238 fs->setString(msg.get());
239 m_encoder->encode(*resp.get(), fault.get(), NULL);
243 throw; // should never happen anyway
248 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
251 m_log.debug("processing SAML 2.0 ArtifactResolve request");
253 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
255 throw ConfigurationException("No ArtifactMap instance installed.");
257 // Locate policy key.
258 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
260 policyId = application.getString("policyId"); // unqualified in Application(s) element
262 // Access policy properties.
263 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
264 pair<bool,bool> validate = settings->getBool("validate");
266 // Lock metadata for use by policy.
267 Locker metadataLocker(application.getMetadataProvider());
269 // Create the policy.
270 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
272 // Decode the message and verify that it's a secured ArtifactResolve request.
274 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
276 throw BindingException("Failed to decode a SAML request.");
277 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
279 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
281 const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
284 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
285 if (!artifact.get() || !*artifact.get())
286 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
287 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
289 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
291 // Parse the artifact and retrieve the object.
292 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
293 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
295 if (!policy.isAuthenticated()) {
296 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
297 return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
300 m_log.debug("artifact resolved, preparing response");
302 // Wrap it in a response.
303 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
304 resp->setInResponseTo(req->getID());
305 Issuer* me = IssuerBuilder::buildIssuer();
306 me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
307 resp->setPayload(payload.release());
309 long ret = sendMessage(
310 *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
312 resp.release(); // freed by encoder
313 return make_pair(true,ret);
315 catch (exception& ex) {
316 // Trap localized errors in a SAML Response.
317 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
318 return samlError(application, *req, httpResponse, entity, StatusCode::RESPONDER, NULL, ex.what());
321 return make_pair(false,0L);
326 pair<bool,long> SAML2ArtifactResolution::samlError(
327 const Application& app,
328 const ArtifactResolve& request,
329 HTTPResponse& httpResponse,
330 const EntityDescriptor* recipient,
332 const XMLCh* subcode,
336 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
337 resp->setInResponseTo(request.getID());
338 Issuer* me = IssuerBuilder::buildIssuer();
339 me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
340 fillStatus(*resp.get(), code, subcode, msg);
341 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
342 resp.release(); // freed by encoder
343 return make_pair(true,ret);