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(getString("Binding").second,e);
112 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
114 catch (exception& ex) {
115 m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
122 string address(appId);
123 address += getString("Location").second;
124 address += "::run::SAML2Artifact";
125 setAddress(address.c_str());
128 SAML2ArtifactResolution::~SAML2ArtifactResolution()
136 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
139 SPConfig& conf = SPConfig::getConfig();
142 if (conf.isEnabled(SPConfig::OutOfProcess)) {
143 // When out of process, we run natively and directly process the message.
144 return processMessage(request.getApplication(), request, request);
147 // When not out of process, we remote all the message processing.
148 DDF out,in = wrap(request, NULL, true);
149 DDFJanitor jin(in), jout(out);
151 out=request.getServiceProvider().getListenerService()->send(in);
152 return unwrap(request, out);
155 catch (exception& ex) {
156 m_log.error("error while processing request: %s", ex.what());
158 // Build a SOAP fault around the error.
159 auto_ptr<Fault> fault(FaultBuilder::buildFault());
160 Faultcode* code = FaultcodeBuilder::buildFaultcode();
161 fault->setFaultcode(code);
162 code->setCode(&Faultcode::SERVER);
163 Faultstring* fs = FaultstringBuilder::buildFaultstring();
164 fault->setFaultstring(fs);
165 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
166 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
167 fs->setString(msg.get());
169 // Use MessageEncoder to send back the fault.
170 long ret = m_encoder->encode(request, fault.get(), NULL);
172 return make_pair(true, ret);
174 // Brute force the fault to avoid library dependency.
175 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
176 Body* body = BodyBuilder::buildBody();
178 body->getUnknownXMLObjects().push_back(fault.release());
180 XMLHelper::serialize(env->marshall(), xmlbuf);
181 istringstream s(xmlbuf);
182 request.setContentType("text/xml");
183 return make_pair(true, request.sendError(s));
188 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
191 const char* aid=in["application_id"].string();
192 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
194 // Something's horribly wrong.
195 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
196 throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
199 // Unpack the request.
200 auto_ptr<HTTPRequest> req(getRequest(in));
201 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
203 // Wrap a response shim.
205 DDFJanitor jout(ret);
206 auto_ptr<HTTPResponse> resp(getResponse(ret));
209 // Since we're remoted, the result should either be a throw, a false/0 return,
210 // which we just return as an empty structure, or a response/redirect,
211 // which we capture in the facade and send back.
212 processMessage(*app, *req.get(), *resp.get());
215 catch (exception& ex) {
217 m_log.error("error while processing request: %s", ex.what());
219 // Use MessageEncoder to send back a SOAP fault.
220 auto_ptr<Fault> fault(FaultBuilder::buildFault());
221 Faultcode* code = FaultcodeBuilder::buildFaultcode();
222 fault->setFaultcode(code);
223 code->setCode(&Faultcode::SERVER);
224 Faultstring* fs = FaultstringBuilder::buildFaultstring();
225 fault->setFaultstring(fs);
226 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
227 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
228 fs->setString(msg.get());
229 m_encoder->encode(*resp.get(), fault.get(), NULL);
233 throw; // should never happen anyway
238 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
241 m_log.debug("processing SAML 2.0 ArtifactResolve request");
243 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
245 throw ConfigurationException("No ArtifactMap instance installed.");
247 // Locate policy key.
248 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
250 policyId = application.getString("policyId"); // unqualified in Application(s) element
252 // Access policy properties.
253 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
254 pair<bool,bool> validate = settings->getBool("validate");
256 // Lock metadata for use by policy.
257 Locker metadataLocker(application.getMetadataProvider());
259 // Create the policy.
260 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
262 // Decode the message and verify that it's a secured ArtifactResolve request.
264 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
266 throw BindingException("Failed to decode a SAML request.");
267 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
269 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
272 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
273 if (!artifact.get() || !*artifact.get())
274 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
275 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
277 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
279 // Parse the artifact and retrieve the object.
280 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
281 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
283 if (!policy.isSecure()) {
284 m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
285 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
288 m_log.debug("artifact resolved, preparing response");
290 // Wrap it in a response.
291 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
292 resp->setInResponseTo(req->getID());
293 Issuer* me = IssuerBuilder::buildIssuer();
294 me->setName(application.getXMLString("entityID").second);
295 resp->setPayload(payload.release());
297 long ret = sendMessage(
298 *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
300 resp.release(); // freed by encoder
301 return make_pair(true,ret);
303 catch (exception& ex) {
304 // Trap localized errors in a SAML Response.
305 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
306 return samlError(application, *req, httpResponse, StatusCode::RESPONDER, NULL, ex.what());
309 return make_pair(false,0);
314 pair<bool,long> SAML2ArtifactResolution::samlError(
315 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
318 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
319 resp->setInResponseTo(request.getID());
320 Issuer* me = IssuerBuilder::buildIssuer();
321 me->setName(app.getXMLString("entityID").second);
322 fillStatus(*resp.get(), code, subcode, msg);
323 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
324 resp.release(); // freed by encoder
325 return make_pair(true,ret);