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