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