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