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