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