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