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