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