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