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 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
42 using namespace opensaml::saml2md;
43 using namespace opensaml::saml2p;
44 using namespace opensaml::saml2;
45 using namespace samlconstants;
48 #include <xmltooling/soap/SOAP.h>
50 using namespace shibspconstants;
51 using namespace shibsp;
52 using namespace opensaml;
53 using namespace soap11;
54 using namespace xmltooling;
55 using namespace log4cpp;
60 class SHIBSP_API Attribute;
61 class SHIBSP_API ResolutionContext;
63 #if defined (_MSC_VER)
64 #pragma warning( push )
65 #pragma warning( disable : 4250 )
68 class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler
71 SAML2ArtifactResolution(const DOMElement* e, const char* appId);
72 virtual ~SAML2ArtifactResolution();
74 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
75 void receive(DDF& in, ostream& out);
78 pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
80 pair<bool,long> samlError(
81 const Application& app,
82 const ArtifactResolve& request,
83 HTTPResponse& httpResponse,
85 const XMLCh* subcode=NULL,
89 MessageEncoder* m_encoder;
90 MessageDecoder* m_decoder;
95 #if defined (_MSC_VER)
96 #pragma warning( pop )
99 Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
101 return new SAML2ArtifactResolution(p.first, p.second);
106 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
107 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2ArtifactResolution"))
109 ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
113 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
115 m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(getString("Binding").second,e);
116 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
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.
149 return processMessage(request.getApplication(), request, request);
152 // When not out of process, we remote all the message processing.
153 DDF out,in = wrap(request, NULL, true);
154 DDFJanitor jin(in), jout(out);
156 in.addmember("application_id").string(request.getApplication().getId());
157 out=request.getServiceProvider().getListenerService()->send(in);
158 return unwrap(request, out);
161 catch (exception& ex) {
162 m_log.error("error while processing request: %s", ex.what());
164 // Build a SOAP fault around the error.
165 auto_ptr<Fault> fault(FaultBuilder::buildFault());
166 Faultcode* code = FaultcodeBuilder::buildFaultcode();
167 fault->setFaultcode(code);
168 code->setCode(&Faultcode::SERVER);
169 Faultstring* fs = FaultstringBuilder::buildFaultstring();
170 fault->setFaultstring(fs);
171 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
172 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
173 fs->setString(msg.get());
175 // Use MessageEncoder to send back the fault.
176 long ret = m_encoder->encode(request, fault.get(), NULL);
178 return make_pair(true, ret);
180 // Brute force the fault to avoid library dependency.
181 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
182 Body* body = BodyBuilder::buildBody();
184 body->getUnknownXMLObjects().push_back(fault.release());
186 XMLHelper::serialize(env->marshall(), xmlbuf);
187 istringstream s(xmlbuf);
188 request.setContentType("text/xml");
189 return make_pair(true, request.sendError(s));
194 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
197 const char* aid=in["application_id"].string();
198 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
200 // Something's horribly wrong.
201 m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
202 throw ConfigurationException("Unable to locate application for new session, deleted?");
205 // Unpack the request.
206 auto_ptr<HTTPRequest> req(getRequest(in));
207 //m_log.debug("found %d client certificates", req->getClientCertificates().size());
209 // Wrap a response shim.
211 DDFJanitor jout(ret);
212 auto_ptr<HTTPResponse> resp(getResponse(ret));
215 // Since we're remoted, the result should either be a throw, a false/0 return,
216 // which we just return as an empty structure, or a response/redirect,
217 // which we capture in the facade and send back.
218 processMessage(*app, *req.get(), *resp.get());
221 catch (exception& ex) {
223 m_log.error("error while processing request: %s", ex.what());
225 // Use MessageEncoder to send back a SOAP fault.
226 auto_ptr<Fault> fault(FaultBuilder::buildFault());
227 Faultcode* code = FaultcodeBuilder::buildFaultcode();
228 fault->setFaultcode(code);
229 code->setCode(&Faultcode::SERVER);
230 Faultstring* fs = FaultstringBuilder::buildFaultstring();
231 fault->setFaultstring(fs);
232 pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
233 auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
234 fs->setString(msg.get());
235 m_encoder->encode(*resp.get(), fault.get(), NULL);
239 throw; // should never happen anyway
244 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
247 m_log.debug("processing SAML 2.0 ArtifactResolve request");
249 ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
251 throw ConfigurationException("No ArtifactMap instance installed.");
253 // Locate policy key.
254 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
256 policyId = application.getString("policyId"); // unqualified in Application(s) element
258 // Access policy properties.
259 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
260 pair<bool,bool> validate = settings->getBool("validate");
262 // Lock metadata for use by policy.
263 Locker metadataLocker(application.getMetadataProvider());
265 // Create the policy.
266 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
268 // Decode the message and verify that it's a secured ArtifactResolve request.
270 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
272 throw BindingException("Failed to decode a SAML request.");
273 const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
275 throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
278 if (!policy.isSecure())
279 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
281 auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
282 if (!artifact.get() || !*artifact.get())
283 return samlError(application, *req, httpResponse, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
284 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
286 m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
288 // Parse the artifact and retrieve the object.
289 auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
290 auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
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 const EntityDescriptor* entity =
302 policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
303 const PropertySet* relyingParty = application.getRelyingParty(entity);
304 pair<bool,bool> flag = relyingParty->getBool("signResponses");
305 if (flag.first && flag.second && policy.getIssuerMetadata()) {
306 CredentialResolver* credResolver=application.getCredentialResolver();
308 Locker credLocker(credResolver);
309 // Fill in criteria to use.
310 MetadataCredentialCriteria mcc(*policy.getIssuerMetadata());
311 mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
312 pair<bool,const char*> keyName = relyingParty->getString("keyName");
314 mcc.getKeyNames().insert(keyName.second);
315 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
317 mcc.setXMLAlgorithm(sigalg.second);
318 const Credential* cred = credResolver->resolve(&mcc);
321 long ret = m_encoder->encode(
330 relyingParty->getXMLString("digestAlg").second
332 resp.release(); // freed by encoder
333 return make_pair(true,ret);
336 m_log.warn("no signing credential resolved, leaving response unsigned");
341 long ret = m_encoder->encode(httpResponse, resp.get(), NULL, entity, relayState.c_str());
342 resp.release(); // freed by encoder
343 return make_pair(true,ret);
345 catch (exception& ex) {
346 // Trap localized errors in a SAML Response.
347 m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
348 return samlError(application, *req, httpResponse, StatusCode::RESPONDER, NULL, ex.what());
351 return make_pair(false,0);
356 pair<bool,long> SAML2ArtifactResolution::samlError(
357 const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
360 auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
361 resp->setInResponseTo(request.getID());
362 Issuer* me = IssuerBuilder::buildIssuer();
363 me->setName(app.getXMLString("entityID").second);
364 prepareResponse(*resp.get(), code, subcode, msg);
365 long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
366 resp.release(); // freed by encoder
367 return make_pair(true,ret);