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;
54 using namespace log4cpp;
59 #if defined (_MSC_VER)
60 #pragma warning( push )
61 #pragma warning( disable : 4250 )
64 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
67 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
68 virtual ~SAML2ArtifactResolution();
70 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
71 void receive(DDF& in, ostream& out);
74 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
76 pair<bool,long> samlError(
77 const Application& app,
78 const ArtifactResolve& request,
79 HTTPResponse& httpResponse,
81 const XMLCh* subcode=NULL,
85 MessageEncoder* m_encoder;
86 MessageDecoder* m_decoder;
91 #if defined (_MSC_VER)
92 #pragma warning( pop )
95 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
97 return new SAML2ArtifactResolution(p.first, p.second);
102 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
103 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2ArtifactResolution"))
105 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
109 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
111 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
112 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
114 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
115 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
118 catch (exception& ex) {
119 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
126 string address(appId);
127 address += getString("Location").second;
128 address += "::run::SAML2Artifact";
129 setAddress(address.c_str());
132 SAML2ArtifactResolution::~SAML2ArtifactResolution()
140 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
143 SPConfig& conf = SPConfig::getConfig();
146 if (conf.isEnabled(SPConfig::OutOfProcess)) {
147 // When out of process, we run natively and directly process the message.
148 return processMessage(request.getApplication(), request, request);
151 // When not out of process, we remote all the message processing.
152 DDF out,in = wrap(request, NULL, true);
153 DDFJanitor jin(in), jout(out);
155 out=request.getServiceProvider().getListenerService()->send(in);
156 return unwrap(request, out);
159 catch (exception& ex) {
160 m_log.error("error while processing request: %s", ex.what());
162 // Build a SOAP fault around the error.
163 auto_ptr<Fault> fault(FaultBuilder::buildFault());
164 Faultcode* code = FaultcodeBuilder::buildFaultcode();
165 fault->setFaultcode(code);
166 code->setCode(&Faultcode::SERVER);
167 Faultstring* fs = FaultstringBuilder::buildFaultstring();
168 fault->setFaultstring(fs);
169 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
170 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
171 fs->setString(msg.get());
173 // Use MessageEncoder to send back the fault.
174 long ret = m_encoder->encode(request, fault.get(), NULL);
176 return make_pair(true, ret);
178 // Brute force the fault to avoid library dependency.
179 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
180 Body* body = BodyBuilder::buildBody();
182 body->getUnknownXMLObjects().push_back(fault.release());
184 XMLHelper::serialize(env->marshall(), xmlbuf);
185 istringstream s(xmlbuf);
186 request.setContentType("text/xml");
187 return make_pair(true, request.sendError(s));
192 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
195 const char* aid=in["application_id"].string();
196 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
198 // Something's horribly wrong.
199 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
200 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
203 // Unpack the request.
204 auto_ptr<HTTPRequest> req(getRequest(in));
205 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
207 // Wrap a response shim.
209 DDFJanitor jout(ret);
210 auto_ptr<HTTPResponse> resp(getResponse(ret));
213 // Since we're remoted, the result should either be a throw, a false/0 return,
214 // which we just return as an empty structure, or a response/redirect,
215 // which we capture in the facade and send back.
216 processMessage(*app, *req.get(), *resp.get());
219 catch (exception& ex) {
221 m_log.error("error while processing request: %s", ex.what());
223 // Use MessageEncoder to send back a SOAP fault.
224 auto_ptr<Fault> fault(FaultBuilder::buildFault());
225 Faultcode* code = FaultcodeBuilder::buildFaultcode();
226 fault->setFaultcode(code);
227 code->setCode(&Faultcode::SERVER);
228 Faultstring* fs = FaultstringBuilder::buildFaultstring();
229 fault->setFaultstring(fs);
230 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
231 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
232 fs->setString(msg.get());
233 m_encoder->encode(*resp.get(), fault.get(), NULL);
237 throw; // should never happen anyway
242 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
245 m_log.debug("processing SAML 2.0 ArtifactResolve request");
247 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
249 throw ConfigurationException("No ArtifactMap instance installed.");
251 // Locate policy key.
252 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
254 policyId = application.getString("policyId"); // unqualified in Application(s) element
256 // Access policy properties.
257 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
258 pair<bool,bool> validate = settings->getBool("validate");
260 // Lock metadata for use by policy.
261 Locker metadataLocker(application.getMetadataProvider());
263 // Create the policy.
264 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
266 // Decode the message and verify that it's a secured ArtifactResolve request.
268 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
270 throw BindingException("Failed to decode a SAML request.");
271 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
273 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
276 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
277 if (!artifact.get() || !*artifact.get())
278 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
279 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
281 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
283 // Parse the artifact and retrieve the object.
284 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
285 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
287 if (!policy.isSecure()) {
288 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
289 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
292 m_log.debug("artifact resolved, preparing response");
294 // Wrap it in a response.
295 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
296 resp->setInResponseTo(req->getID());
297 Issuer* me = IssuerBuilder::buildIssuer();
298 me->setName(application.getXMLString("entityID").second);
299 resp->setPayload(payload.release());
301 long ret = sendMessage(
302 *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
304 resp.release(); // freed by encoder
305 return make_pair(true,ret);
307 catch (exception& ex) {
308 // Trap localized errors in a SAML Response.
309 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
310 return samlError(application, *req, httpResponse, StatusCode::RESPONDER, NULL, ex.what());
313 return make_pair(false,0);
318 pair<bool,long> SAML2ArtifactResolution::samlError(
319 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
322 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
323 resp->setInResponseTo(request.getID());
324 Issuer* me = IssuerBuilder::buildIssuer();
325 me->setName(app.getXMLString("entityID").second);
326 fillStatus(*resp.get(), code, subcode, msg);
327 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
328 resp.release(); // freed by encoder
329 return make_pair(true,ret);