6e609a39b2efe14549cbdffb385a1d744dfe0fd4
[shibboleth/sp.git] / shibsp / handler / impl / SAML2ArtifactResolution.cpp
1 /*
2  *  Copyright 2001-2009 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 "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "util/SPConstants.h"
31
32 #ifndef SHIBSP_LITE
33 # include "security/SecurityPolicy.h"
34 # include <saml/exceptions.h>
35 # include <saml/SAMLConfig.h>
36 # include <saml/binding/ArtifactMap.h>
37 # include <saml/binding/MessageEncoder.h>
38 # include <saml/binding/MessageDecoder.h>
39 # include <saml/binding/SAMLArtifact.h>
40 # include <saml/saml2/core/Assertions.h>
41 # include <saml/saml2/core/Protocols.h>
42 # include <saml/saml2/metadata/Metadata.h>
43 using namespace opensaml::saml2md;
44 using namespace opensaml::saml2p;
45 using namespace opensaml::saml2;
46 using namespace opensaml;
47 using namespace samlconstants;
48 #endif
49
50 #include <xmltooling/soap/SOAP.h>
51
52 using namespace shibspconstants;
53 using namespace shibsp;
54 using namespace soap11;
55 using namespace xmltooling;
56 using namespace std;
57
58 namespace shibsp {
59
60 #if defined (_MSC_VER)
61     #pragma warning( push )
62     #pragma warning( disable : 4250 )
63 #endif
64
65     class SHIBSP_API SAML2ArtifactResolution : public AbstractHandler, public RemotedHandler 
66     {
67     public:
68         SAML2ArtifactResolution(const DOMElement* e, const char* appId);
69         virtual ~SAML2ArtifactResolution();
70
71         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
72         void receive(DDF& in, ostream& out);
73
74 #ifndef SHIBSP_LITE
75         const char* getType() const {
76             return "ArtifactResolutionService";
77         }
78 #endif
79
80     private:
81         pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
82 #ifndef SHIBSP_LITE
83         pair<bool,long> samlError(
84             const Application& app,
85             const ArtifactResolve& request,
86             HTTPResponse& httpResponse,
87             const EntityDescriptor* recipient,
88             const XMLCh* code,
89             const XMLCh* subcode=NULL,
90             const char* msg=NULL
91             ) const;
92
93         MessageEncoder* m_encoder;
94         MessageDecoder* m_decoder;
95         xmltooling::QName m_role;
96 #endif
97     };
98
99 #if defined (_MSC_VER)
100     #pragma warning( pop )
101 #endif
102
103     Handler* SHIBSP_DLLLOCAL SAML2ArtifactResolutionFactory(const pair<const DOMElement*,const char*>& p)
104     {
105         return new SAML2ArtifactResolution(p.first, p.second);
106     }
107
108 };
109
110 SAML2ArtifactResolution::SAML2ArtifactResolution(const DOMElement* e, const char* appId)
111     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".ArtifactResolution.SAML2"))
112 #ifndef SHIBSP_LITE
113         ,m_encoder(NULL), m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
114 #endif
115 {
116 #ifndef SHIBSP_LITE
117     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
118         try {
119             m_encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
120                 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
121                 );
122             m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
123                 getString("Binding").second,pair<const DOMElement*,const XMLCh*>(e,NULL)
124                 );
125         }
126         catch (exception&) {
127             m_log.error("error building MessageEncoder/Decoder pair for binding (%s)", getString("Binding").second);
128             delete m_encoder;
129             delete m_decoder;
130             throw;
131         }
132     }
133 #endif
134     string address(appId);
135     address += getString("Location").second;
136     address += "::run::SAML2Artifact";
137     setAddress(address.c_str());
138 }
139
140 SAML2ArtifactResolution::~SAML2ArtifactResolution()
141 {
142 #ifndef SHIBSP_LITE
143     delete m_encoder;
144     delete m_decoder;
145 #endif
146 }
147
148 pair<bool,long> SAML2ArtifactResolution::run(SPRequest& request, bool isHandler) const
149 {
150     string relayState;
151     SPConfig& conf = SPConfig::getConfig();
152     
153     try {
154         if (conf.isEnabled(SPConfig::OutOfProcess)) {
155             // When out of process, we run natively and directly process the message.
156             return processMessage(request.getApplication(), request, request);
157         }
158         else {
159             // When not out of process, we remote all the message processing.
160             DDF out,in = wrap(request, NULL, true);
161             DDFJanitor jin(in), jout(out);
162             
163             out=request.getServiceProvider().getListenerService()->send(in);
164             return unwrap(request, out);
165         }
166     }
167     catch (exception& ex) {
168         m_log.error("error while processing request: %s", ex.what());
169
170         // Build a SOAP fault around the error.
171         auto_ptr<Fault> fault(FaultBuilder::buildFault());
172         Faultcode* code = FaultcodeBuilder::buildFaultcode();
173         fault->setFaultcode(code);
174         code->setCode(&Faultcode::SERVER);
175         Faultstring* fs = FaultstringBuilder::buildFaultstring();
176         fault->setFaultstring(fs);
177         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
178         auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
179         fs->setString(msg.get());
180 #ifndef SHIBSP_LITE
181         // Use MessageEncoder to send back the fault.
182         long ret = m_encoder->encode(request, fault.get(), NULL);
183         fault.release();
184         return make_pair(true, ret);
185 #else
186         // Brute force the fault to avoid library dependency.
187         auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
188         Body* body = BodyBuilder::buildBody();
189         env->setBody(body);
190         body->getUnknownXMLObjects().push_back(fault.release());
191         string xmlbuf;
192         XMLHelper::serialize(env->marshall(), xmlbuf);
193         istringstream s(xmlbuf);
194         request.setContentType("text/xml");
195         return make_pair(true, request.sendError(s));
196 #endif
197     }
198 }
199
200 void SAML2ArtifactResolution::receive(DDF& in, ostream& out)
201 {
202     // Find application.
203     const char* aid=in["application_id"].string();
204     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
205     if (!app) {
206         // Something's horribly wrong.
207         m_log.error("couldn't find application (%s) for artifact resolution", aid ? aid : "(missing)");
208         throw ConfigurationException("Unable to locate application for artifact resolution, deleted?");
209     }
210     
211     // Unpack the request.
212     auto_ptr<HTTPRequest> req(getRequest(in));
213     //m_log.debug("found %d client certificates", req->getClientCertificates().size());
214
215     // Wrap a response shim.
216     DDF ret(NULL);
217     DDFJanitor jout(ret);
218     auto_ptr<HTTPResponse> resp(getResponse(ret));
219         
220     try {
221         // Since we're remoted, the result should either be a throw, a false/0 return,
222         // which we just return as an empty structure, or a response/redirect,
223         // which we capture in the facade and send back.
224         processMessage(*app, *req.get(), *resp.get());
225         out << ret;
226     }
227     catch (exception& ex) {
228 #ifndef SHIBSP_LITE
229         m_log.error("error while processing request: %s", ex.what());
230
231         // Use MessageEncoder to send back a SOAP fault.
232         auto_ptr<Fault> fault(FaultBuilder::buildFault());
233         Faultcode* code = FaultcodeBuilder::buildFaultcode();
234         fault->setFaultcode(code);
235         code->setCode(&Faultcode::SERVER);
236         Faultstring* fs = FaultstringBuilder::buildFaultstring();
237         fault->setFaultstring(fs);
238         pair<bool,bool> flag = getBool("detailedErrors", m_configNS.get());
239         auto_ptr_XMLCh msg((flag.first && flag.second) ? ex.what() : "Error processing request.");
240         fs->setString(msg.get());
241         m_encoder->encode(*resp.get(), fault.get(), NULL);
242         fault.release();
243         out << ret;
244 #else
245         throw;  // should never happen anyway
246 #endif
247     }
248 }
249
250 pair<bool,long> SAML2ArtifactResolution::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
251 {
252 #ifndef SHIBSP_LITE
253     m_log.debug("processing SAML 2.0 ArtifactResolve request");
254
255     ArtifactMap* artmap = SAMLConfig::getConfig().getArtifactMap();
256     if (!artmap)
257         throw ConfigurationException("No ArtifactMap instance installed.");
258
259     // Locate policy key.
260     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
261     if (!policyId.first)
262         policyId = application.getString("policyId");   // unqualified in Application(s) element
263         
264     // Access policy properties.
265     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
266     pair<bool,bool> validate = settings->getBool("validate");
267
268     // Lock metadata for use by policy.
269     Locker metadataLocker(application.getMetadataProvider());
270
271     // Create the policy.
272     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
273     
274     // Decode the message and verify that it's a secured ArtifactResolve request.
275     string relayState;
276     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
277     if (!msg.get())
278         throw BindingException("Failed to decode a SAML request.");
279     const ArtifactResolve* req = dynamic_cast<const ArtifactResolve*>(msg.get());
280     if (!req)
281         throw FatalProfileException("Decoded message was not a samlp::ArtifactResolve request.");
282
283     const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
284
285     try {
286         auto_ptr_char artifact(req->getArtifact() ? req->getArtifact()->getArtifact() : NULL);
287         if (!artifact.get() || !*artifact.get())
288             return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, NULL, "Request did not contain an artifact to resolve.");
289         auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
290
291         m_log.info("resolving artifact (%s) for (%s)", artifact.get(), issuer.get() ? issuer.get() : "unknown");
292
293         // Parse the artifact and retrieve the object.
294         auto_ptr<SAMLArtifact> artobj(SAMLArtifact::parse(artifact.get()));
295         auto_ptr<XMLObject> payload(artmap->retrieveContent(artobj.get(), issuer.get()));
296
297         if (!policy.isAuthenticated()) {
298             m_log.error("request for artifact was unauthenticated, purging the artifact mapping");
299             return samlError(application, *req, httpResponse, entity, StatusCode::REQUESTER, StatusCode::AUTHN_FAILED, "Unable to authenticate request.");
300         }
301
302         m_log.debug("artifact resolved, preparing response");
303
304         // Wrap it in a response.
305         auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
306         resp->setInResponseTo(req->getID());
307         Issuer* me = IssuerBuilder::buildIssuer();
308         me->setName(application.getRelyingParty(entity)->getXMLString("entityID").second);
309         resp->setPayload(payload.release());
310
311         long ret = sendMessage(
312             *m_encoder, resp.get(), relayState.c_str(), NULL, policy.getIssuerMetadata(), application, httpResponse, "signResponses"
313             );
314         resp.release();  // freed by encoder
315         return make_pair(true,ret);
316     }
317     catch (exception& ex) {
318         // Trap localized errors in a SAML Response.
319         m_log.error("error processing artifact request, returning SAML error: %s", ex.what());
320         return samlError(application, *req, httpResponse, entity, StatusCode::RESPONDER, NULL, ex.what());
321     }
322 #else
323     return make_pair(false,0L);
324 #endif
325 }
326
327 #ifndef SHIBSP_LITE
328 pair<bool,long> SAML2ArtifactResolution::samlError(
329     const Application& app,
330     const ArtifactResolve& request,
331     HTTPResponse& httpResponse,
332     const EntityDescriptor* recipient,
333     const XMLCh* code,
334     const XMLCh* subcode,
335     const char* msg
336     ) const
337 {
338     auto_ptr<ArtifactResponse> resp(ArtifactResponseBuilder::buildArtifactResponse());
339     resp->setInResponseTo(request.getID());
340     Issuer* me = IssuerBuilder::buildIssuer();
341     me->setName(app.getRelyingParty(recipient)->getXMLString("entityID").second);
342     fillStatus(*resp.get(), code, subcode, msg);
343     long ret = m_encoder->encode(httpResponse, resp.get(), NULL);
344     resp.release();  // freed by encoder
345     return make_pair(true,ret);
346 }
347 #endif