Draft artifact resolver.
[shibboleth/sp.git] / shibsp / handler / impl / SAML2ArtifactResolution.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * SAML2ArtifactResolution.cpp
19  * 
20  * Handler for resolving SAML 2.0 artifacts.
21  */
22
23 #include "internal.h"
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"
30
31 #ifndef SHIBSP_LITE
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;
46 #endif
47
48 #include <xmltooling/soap/SOAP.h>
49
50 using namespace shibspconstants;
51 using namespace shibsp;
52 using namespace opensaml;
53 using namespace soap11;
54 using namespace xmltooling;
55 using namespace log4cpp;
56 using namespace std;
57
58 namespace shibsp {
59
60     class SHIBSP_API Attribute;
61     class SHIBSP_API ResolutionContext;
62
63 #if defined (_MSC_VER)
64     #pragma warning( push )
65     #pragma warning( disable : 4250 )
66 #endif
67
68     class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler 
69     {
70     public:
71         SAML2ArtifactResolution(const DOMElement* e, const char* appId);
72         virtual ~SAML2ArtifactResolution();
73
74         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
75         void receive(DDF& in, ostream& out);
76
77     private:
78         pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
79 #ifndef SHIBSP_LITE
80         pair<bool,long> samlError(
81             const Application& app,
82             const ArtifactResolve& request,
83             HTTPResponse& httpResponse,
84             const XMLCh* code,
85             const XMLCh* subcode=NULL,
86             const char* msg=NULL
87             ) const;
88
89         MessageEncoder* m_encoder;
90         MessageDecoder* m_decoder;
91         QName m_role;
92 #endif
93     };
94
95 #if defined (_MSC_VER)
96     #pragma warning( pop )
97 #endif
98
99     Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
100     {
101         return new SAML2ArtifactResolution(p.first, p.second);
102     }
103
104 };
105
106 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
107     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SAML2ArtifactResolution"))
108 #ifndef SHIBSP_LITE
109         ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
110 #endif
111 {
112 #ifndef SHIBSP_LITE
113     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
114         try {
115             m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(getString("Binding").second,e);
116             m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
117         }
118         catch (exception& ex) {
119             m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
120             delete m_encoder;
121             delete m_decoder;
122             throw;
123         }
124     }
125 #endif
126     string address(appId);
127     address += getString("Location").second;
128     address += "::run::SAML2Artifact";
129     setAddress(address.c_str());
130 }
131
132 SAML2ArtifactResolution::~SAML2ArtifactResolution()
133 {
134 #ifndef SHIBSP_LITE
135     delete m_encoder;
136     delete m_decoder;
137 #endif
138 }
139
140 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
141 {
142     string relayState;
143     SPConfig& conf = SPConfig::getConfig();
144     
145     try {
146         if (conf.isEnabled(SPConfig::OutOfProcess)) {
147             // When out of process, we run natively and directly process the message.
148             string entityID;
149             return processMessage(request.getApplication(), request, request);
150         }
151         else {
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);
155             
156             in.addmember("application_id").string(request.getApplication().getId());
157             out=request.getServiceProvider().getListenerService()->send(in);
158             return unwrap(request, out);
159         }
160     }
161     catch (exception& ex) {
162         m_log.error("error while processing request: %s", ex.what());
163
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());
174 #ifndef SHIBSP_LITE
175         // Use MessageEncoder to send back the fault.
176         long ret = m_encoder->encode(request, fault.get(), NULL);
177         fault.release();
178         return make_pair(true, ret);
179 #else
180         // Brute force the fault to avoid library dependency.
181         auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
182         Body* body = BodyBuilder::buildBody();
183         env->setBody(body);
184         body->getUnknownXMLObjects().push_back(fault.release());
185         string xmlbuf;
186         XMLHelper::serialize(env->marshall(), xmlbuf);
187         istringstream s(xmlbuf);
188         request.setContentType("text/xml");
189         return make_pair(true, request.sendError(s));
190 #endif
191     }
192 }
193
194 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
195 {
196     // Find application.
197     const char* aid=in["application_id"].string();
198     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
199     if (!app) {
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?");
203     }
204     
205     // Unpack the request.
206     auto_ptr<HTTPRequest> req(getRequest(in));
207     //m_log.debug("found %d client certificates", req->getClientCertificates().size());
208
209     // Wrap a response shim.
210     DDF ret(NULL);
211     DDFJanitor jout(ret);
212     auto_ptr<HTTPResponse> resp(getResponse(ret));
213         
214     try {
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());
219         out << ret;
220     }
221     catch (exception& ex) {
222 #ifndef SHIBSP_LITE
223         m_log.error("error while processing request: %s", ex.what());
224
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);
236         fault.release();
237         out << ret;
238 #else
239         throw;  // should never happen anyway
240 #endif
241     }
242 }
243
244 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
245 {
246 #ifndef SHIBSP_LITE
247     m_log.debug("processing SAML 2.0 ArtifactResolve request");
248
249     ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
250     if (!artmap)
251         throw ConfigurationException("No ArtifactMap instance installed.");
252
253     // Locate policy key.
254     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
255     if (!policyId.first)
256         policyId = application.getString("policyId");   // unqualified in Application(s) element
257         
258     // Access policy properties.
259     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
260     pair<bool,bool> validate = settings->getBool("validate");
261
262     // Lock metadata for use by policy.
263     Locker metadataLocker(application.getMetadataProvider());
264
265     // Create the policy.
266     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
267     
268     // Decode the message and verify that it's a secured ArtifactResolve request.
269     string relayState;
270     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
271     if (!msg.get())
272         throw BindingException("Failed to decode a SAML request.");
273     const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
274     if (!req)
275         throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
276
277     try {
278         if (!policy.isSecure())
279             return samlError(application, *req, httpResponse, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
280
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);
285
286         m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
287
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()));
291
292         m_log.debug("artifact resolved, preparing response");
293
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());
300
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();
307             if (credResolver) {
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");
313                 if (keyName.first)
314                     mcc.getKeyNames().insert(keyName.second);
315                 pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
316                 if (sigalg.first)
317                     mcc.setXMLAlgorithm(sigalg.second);
318                 const Credential* cred = credResolver->resolve(&mcc);
319                 if (cred) {
320                     // Signed request.
321                     long ret = m_encoder->encode(
322                         httpResponse,
323                         resp.get(),
324                         NULL,
325                         entity,
326                         relayState.c_str(),
327                         NULL,
328                         cred,
329                         sigalg.second,
330                         relyingParty->getXMLString("digestAlg").second
331                         );
332                     resp.release();  // freed by encoder
333                     return make_pair(true,ret);
334                 }
335                 else {
336                     m_log.warn("no signing credential resolved, leaving response unsigned");
337                 }
338             }
339         }
340
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);
344     }
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());
349     }
350 #else
351     return make_pair(false,0);
352 #endif
353 }
354
355 #ifndef SHIBSP_LITE
356 pair<bool,long> SAML2ArtifactResolution::samlError(
357     const Application& app, const ArtifactResolve& request, HTTPResponse& httpResponse, const XMLCh* code, const XMLCh* subcode, const char* msg
358     ) const
359 {
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);
368 }
369 #endif