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