Stop defaulting in xercesc namespace.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2SessionInitiator.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  * SAML2SessionInitiator.cpp
19  * 
20  * SAML 2.0 AuthnRequest support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "handler/SessionInitiator.h"
31 #include "util/SPConstants.h"
32
33 #include <saml/SAMLConfig.h>
34 #include <saml/binding/MessageEncoder.h>
35 #include <saml/saml2/core/Protocols.h>
36 #include <saml/saml2/metadata/EndpointManager.h>
37 #include <saml/saml2/metadata/Metadata.h>
38 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
39
40 using namespace shibsp;
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
45 using namespace xmltooling;
46 using namespace log4cpp;
47 using namespace std;
48
49 namespace shibsp {
50
51 #if defined (_MSC_VER)
52     #pragma warning( push )
53     #pragma warning( disable : 4250 )
54 #endif
55
56     class SHIBSP_DLLLOCAL SAML2SessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
57     {
58     public:
59         SAML2SessionInitiator(const DOMElement* e, const char* appId);
60         virtual ~SAML2SessionInitiator() {
61             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
62                 XMLString::release(&m_outgoing);
63                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
64             }
65         }
66         
67         void setParent(const PropertySet* parent);
68         void receive(DDF& in, ostream& out);
69         pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
70
71     private:
72         pair<bool,long> doRequest(
73             const Application& application,
74             HTTPResponse& httpResponse,
75             const char* entityID,
76             const XMLCh* acsIndex,
77             const char* acsLocation,
78             const XMLCh* acsBinding,
79             bool isPassive,
80             bool forceAuthn,
81             string& relayState
82             ) const;
83
84         string m_appId;
85         XMLCh* m_outgoing;
86         vector<const XMLCh*> m_bindings;
87         map<const XMLCh*,MessageEncoder*> m_encoders;
88     };
89
90 #if defined (_MSC_VER)
91     #pragma warning( pop )
92 #endif
93
94     SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
95     {
96         return new SAML2SessionInitiator(p.first, p.second);
97     }
98
99 };
100
101 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
102     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator")), m_appId(appId), m_outgoing(NULL)
103 {
104     // If Location isn't set, defer address registration until the setParent call.
105     pair<bool,const char*> loc = getString("Location");
106     if (loc.first) {
107         string address = m_appId + loc.second + "::run::SAML2SI";
108         setAddress(address.c_str());
109     }
110
111     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
112         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
113         if (outgoing.first) {
114             m_outgoing = XMLString::replicate(outgoing.second);
115         }
116         else {
117             // No override, so we'll install a default binding precedence.
118             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
119                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
120             m_outgoing = XMLString::transcode(prec.c_str());
121             XMLString::trim(m_outgoing);
122         }
123
124         int pos;
125         XMLCh* start = m_outgoing;
126         while (start && *start) {
127             pos = XMLString::indexOf(start,chSpace);
128             if (pos != -1)
129                 *(start + pos)=chNull;
130             m_bindings.push_back(start);
131             try {
132                 auto_ptr_char b(start);
133                 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(b.get(),e);
134                 m_encoders[start] = encoder;
135                 m_log.info("supporting outgoing binding (%s)", b.get());
136             }
137             catch (exception& ex) {
138                 m_log.error("error building MessageEncoder: %s", ex.what());
139             }
140             if (pos != -1)
141                 start = start + pos + 1;
142             else
143                 break;
144         }
145     }
146 }
147
148 void SAML2SessionInitiator::setParent(const PropertySet* parent)
149 {
150     DOMPropertySet::setParent(parent);
151     pair<bool,const char*> loc = getString("Location");
152     if (loc.first) {
153         string address = m_appId + loc.second + "::run::SAML2SI";
154         setAddress(address.c_str());
155     }
156     else {
157         m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
158     }
159 }
160
161 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
162 {
163     // We have to know the IdP to function.
164     if (!entityID || !*entityID)
165         return make_pair(false,0);
166
167     string target;
168     const Handler* ACS=NULL;
169     const char* option;
170     pair<bool,const char*> acClass;
171     pair<bool,const char*> acComp;
172     bool isPassive=false,forceAuthn=false;
173     const Application& app=request.getApplication();
174     pair<bool,bool> acsByIndex = getBool("acsByIndex");
175
176     if (isHandler) {
177         option=request.getParameter("acsIndex");
178         if (option)
179             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
180
181         option = request.getParameter("target");
182         if (option)
183             target = option;
184         if (!acsByIndex.first || !acsByIndex.second) {
185             // Since we're passing the ACS by value, we need to compute the return URL,
186             // so we'll need the target resource for real.
187             recoverRelayState(request.getApplication(), request, target, false);
188         }
189
190         option = request.getParameter("isPassive");
191         isPassive = (option && (*option=='1' || *option=='t'));
192         if (!isPassive) {
193             option = request.getParameter("forceAuthn");
194             forceAuthn = (option && (*option=='1' || *option=='t'));
195         }
196
197         acClass.second = request.getParameter("authnContextClassRef");
198         acClass.first = (acClass.second!=NULL);
199         acComp.second = request.getParameter("authnContextComparison");
200         acComp.first = (acComp.second!=NULL);
201     }
202     else {
203         // We're running as a "virtual handler" from within the filter.
204         // The target resource is the current one and everything else is defaulted.
205         target=request.getRequestURL();
206         const PropertySet* settings = request.getRequestSettings().first;
207
208         pair<bool,bool> flag = settings->getBool("isPassive");
209         isPassive = flag.first && flag.second;
210         if (!isPassive) {
211             flag = settings->getBool("forceAuthn");
212             forceAuthn = flag.first && flag.second;
213         }
214
215         acClass = settings->getString("authnContextClassRef");
216         acComp = settings->getString("authnContextComparison");
217     }
218
219     m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
220
221     // To invoke the request builder, the key requirement is to figure out how and whether
222     // to express the ACS, by index or value, and if by value, where.
223
224     SPConfig& conf = SPConfig::getConfig();
225     if (conf.isEnabled(SPConfig::OutOfProcess)) {
226         if (acsByIndex.first && acsByIndex.second) {
227             // Pass by Index. This also allows for defaulting it entirely and sending nothing.
228             if (isHandler) {
229                 // We may already have RelayState set if we looped back here,
230                 // but just in case target is a resource, we reset it back.
231                 target.erase();
232                 option = request.getParameter("target");
233                 if (option)
234                     target = option;
235             }
236             return doRequest(
237                 app, request, entityID, ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL, isPassive, forceAuthn, target
238                 );
239         }
240
241         // Since we're not passing by index, we need to fully compute the return URL and binding.
242         if (!ACS)
243             ACS = app.getDefaultAssertionConsumerService();
244
245         // Compute the ACS URL. We add the ACS location to the base handlerURL.
246         string ACSloc=request.getHandlerURL(target.c_str());
247         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
248         if (loc.first) ACSloc+=loc.second;
249
250         if (isHandler) {
251             // We may already have RelayState set if we looped back here,
252             // but just in case target is a resource, we reset it back.
253             target.erase();
254             option = request.getParameter("target");
255             if (option)
256                 target = option;
257         }
258
259         return doRequest(
260             app, request, entityID, NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL, isPassive, forceAuthn, target
261             );
262     }
263
264     // Remote the call.
265     DDF out,in = DDF(m_address.c_str()).structure();
266     DDFJanitor jin(in), jout(out);
267     in.addmember("application_id").string(app.getId());
268     in.addmember("entity_id").string(entityID);
269     if (isPassive)
270         in.addmember("isPassive").integer(1);
271     else if (forceAuthn)
272         in.addmember("forceAuthn").integer(1);
273     if (acClass.first)
274         in.addmember("authnContextClassRef").string(acClass.second);
275     if (acComp.first)
276         in.addmember("authnContextComparison").string(acComp.second);
277     if (acsByIndex.first && acsByIndex.second) {
278         if (ACS)
279             in.addmember("acsIndex").string(ACS->getString("index").second);
280     }
281     else {
282         // Since we're not passing by index, we need to fully compute the return URL and binding.
283         if (!ACS)
284             ACS = app.getDefaultAssertionConsumerService();
285
286         // Compute the ACS URL. We add the ACS location to the base handlerURL.
287         string ACSloc=request.getHandlerURL(target.c_str());
288         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
289         if (loc.first) ACSloc+=loc.second;
290         in.addmember("acsLocation").string(ACSloc.c_str());
291         if (ACS)
292             in.addmember("acsBinding").string(ACS->getString("Binding").second);
293     }
294
295     if (isHandler) {
296         // We may already have RelayState set if we looped back here,
297         // but just in case target is a resource, we reset it back.
298         target.erase();
299         option = request.getParameter("target");
300         if (option)
301             target = option;
302     }
303     if (!target.empty())
304         in.addmember("RelayState").string(target.c_str());
305
306     // Remote the processing.
307     out = request.getServiceProvider().getListenerService()->send(in);
308     return unwrap(request, out);
309 }
310
311 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
312 {
313     // Find application.
314     const char* aid=in["application_id"].string();
315     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
316     if (!app) {
317         // Something's horribly wrong.
318         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
319         throw ConfigurationException("Unable to locate application for new session, deleted?");
320     }
321
322     const char* entityID = in["entity_id"].string();
323     if (!entityID)
324         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
325
326     DDF ret(NULL);
327     DDFJanitor jout(ret);
328
329     // Wrap the outgoing object with a Response facade.
330     auto_ptr<HTTPResponse> http(getResponse(ret));
331
332     auto_ptr_XMLCh index(in["acsIndex"].string());
333     auto_ptr_XMLCh bind(in["acsBinding"].string());
334
335     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
336
337     // Since we're remoted, the result should either be a throw, which we pass on,
338     // a false/0 return, which we just return as an empty structure, or a response/redirect,
339     // which we capture in the facade and send back.
340     doRequest(
341         *app, *http.get(), entityID,
342         index.get(), in["acsLocation"].string(), bind.get(),
343         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
344         relayState
345         );
346     out << ret;
347 }
348
349 pair<bool,long> SAML2SessionInitiator::doRequest(
350     const Application& app,
351     HTTPResponse& httpResponse,
352     const char* entityID,
353     const XMLCh* acsIndex,
354     const char* acsLocation,
355     const XMLCh* acsBinding,
356     bool isPassive,
357     bool forceAuthn,
358     string& relayState
359     ) const
360 {
361     // Use metadata to locate the IdP's SSO service.
362     MetadataProvider* m=app.getMetadataProvider();
363     Locker locker(m);
364     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
365     if (!entity) {
366         m_log.error("unable to locate metadata for provider (%s)", entityID);
367         return make_pair(false,0);
368     }
369     const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
370     if (!role) {
371         m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
372         return make_pair(false,0);
373     }
374
375     // Loop over the supportable outgoing bindings.
376     const EndpointType* ep=NULL;
377     const MessageEncoder* encoder=NULL;
378     vector<const XMLCh*>::const_iterator b;
379     for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
380         if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
381             map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
382             if (enc!=m_encoders.end())
383                 encoder = enc->second;
384             break;
385         }
386     }
387     if (!ep || !encoder) {
388         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
389         return make_pair(false,0);
390     }
391
392     preserveRelayState(app, httpResponse, relayState);
393
394     // For now just build a dummy AuthnRequest.
395     auto_ptr<AuthnRequest> req(AuthnRequestBuilder::buildAuthnRequest());
396     req->setDestination(ep->getLocation());
397     if (acsIndex)
398         req->setAssertionConsumerServiceIndex(acsIndex);
399     if (acsLocation) {
400         auto_ptr_XMLCh wideloc(acsLocation);
401         req->setAssertionConsumerServiceURL(wideloc.get());
402     }
403     if (acsBinding)
404         req->setProtocolBinding(acsBinding);
405     if (isPassive)
406         req->IsPassive(isPassive);
407     else if (forceAuthn)
408         req->ForceAuthn(forceAuthn);
409     Issuer* issuer = IssuerBuilder::buildIssuer();
410     req->setIssuer(issuer);
411     issuer->setName(app.getXMLString("providerId").second);
412
413     auto_ptr_char dest(ep->getLocation());
414
415     // Check for signing.
416     const PropertySet* relyingParty = app.getRelyingParty(entity);
417     pair<bool,bool> flag = relyingParty->getBool("signRequests");
418     if ((flag.first && flag.second) || role->WantAuthnRequestsSigned()) {
419         CredentialResolver* credResolver=app.getCredentialResolver();
420         if (credResolver) {
421             Locker credLocker(credResolver);
422             // Fill in criteria to use.
423             MetadataCredentialCriteria mcc(*role);
424             mcc.setUsage(CredentialCriteria::SIGNING_CREDENTIAL);
425             pair<bool,const XMLCh*> sigalg = relyingParty->getXMLString("signatureAlg");
426             if (sigalg.first)
427                 mcc.setXMLAlgorithm(sigalg.second);
428             const Credential* cred = credResolver->resolve(&mcc);
429             if (cred) {
430                 // Signed request.
431                 long ret = encoder->encode(
432                     httpResponse,
433                     req.get(),
434                     dest.get(),
435                     entityID,
436                     relayState.c_str(),
437                     cred,
438                     sigalg.second,
439                     relyingParty->getXMLString("digestAlg").second
440                     );
441                 req.release();  // freed by encoder
442                 return make_pair(true,ret);
443             }
444             else {
445                 m_log.warn("no signing credential resolved, leaving AuthnRequest unsigned");
446             }
447         }
448     }
449
450     // Unsigned request.
451     long ret = encoder->encode(httpResponse, req.get(), dest.get(), entityID, relayState.c_str());
452     req.release();  // freed by encoder
453     return make_pair(true,ret);
454 }