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