Parameterize config namespace for message plugins.
[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 #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(
145                     b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
146                     );
147                 m_encoders[start] = encoder;
148                 m_log.debug("supporting outgoing binding (%s)", b.get());
149             }
150             catch (exception& ex) {
151                 m_log.error("error building MessageEncoder: %s", ex.what());
152             }
153             if (pos != -1)
154                 start = start + pos + 1;
155             else
156                 break;
157         }
158     }
159 #endif
160
161     // If Location isn't set, defer address registration until the setParent call.
162     pair<bool,const char*> loc = getString("Location");
163     if (loc.first) {
164         string address = m_appId + loc.second + "::run::SAML2SI";
165         setAddress(address.c_str());
166     }
167 }
168
169 void SAML2SessionInitiator::setParent(const PropertySet* parent)
170 {
171     DOMPropertySet::setParent(parent);
172     pair<bool,const char*> loc = getString("Location");
173     if (loc.first) {
174         string address = m_appId + loc.second + "::run::SAML2SI";
175         setAddress(address.c_str());
176     }
177     else {
178         m_log.warn("no Location property in SAML2 SessionInitiator (or parent), can't register as remoted handler");
179     }
180 }
181
182 pair<bool,long> SAML2SessionInitiator::run(SPRequest& request, const char* entityID, bool isHandler) const
183 {
184     // We have to know the IdP to function.
185     if (!entityID || !*entityID)
186         return make_pair(false,0);
187
188     string target;
189     const Handler* ACS=NULL;
190     const char* option;
191     pair<bool,const char*> acClass;
192     pair<bool,const char*> acComp;
193     bool isPassive=false,forceAuthn=false;
194     const Application& app=request.getApplication();
195     pair<bool,bool> acsByIndex = getBool("acsByIndex");
196
197     if (isHandler) {
198         option=request.getParameter("acsIndex");
199         if (option) {
200             ACS = app.getAssertionConsumerServiceByIndex(atoi(option));
201             if (!ACS)
202                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
203         }
204
205         option = request.getParameter("target");
206         if (option)
207             target = option;
208         if (acsByIndex.first && !acsByIndex.second) {
209             // Since we're passing the ACS by value, we need to compute the return URL,
210             // so we'll need the target resource for real.
211             recoverRelayState(request.getApplication(), request, target, false);
212         }
213
214         option = request.getParameter("isPassive");
215         isPassive = (option && (*option=='1' || *option=='t'));
216         if (!isPassive) {
217             option = request.getParameter("forceAuthn");
218             forceAuthn = (option && (*option=='1' || *option=='t'));
219         }
220
221         acClass.second = request.getParameter("authnContextClassRef");
222         acClass.first = (acClass.second!=NULL);
223         acComp.second = request.getParameter("authnContextComparison");
224         acComp.first = (acComp.second!=NULL);
225     }
226     else {
227         // We're running as a "virtual handler" from within the filter.
228         // The target resource is the current one and everything else is defaulted.
229         target=request.getRequestURL();
230         const PropertySet* settings = request.getRequestSettings().first;
231
232         pair<bool,bool> flag = settings->getBool("isPassive");
233         isPassive = flag.first && flag.second;
234         if (!isPassive) {
235             flag = settings->getBool("forceAuthn");
236             forceAuthn = flag.first && flag.second;
237         }
238
239         acClass = settings->getString("authnContextClassRef");
240         acComp = settings->getString("authnContextComparison");
241     }
242
243     m_log.debug("attempting to initiate session using SAML 2.0 with provider (%s)", entityID);
244
245     if (!ACS) {
246         pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
247         if (index.first) {
248             ACS = app.getAssertionConsumerServiceByIndex(index.second);
249             if (!ACS)
250                 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
251         }
252         if (!ACS)
253             ACS = app.getDefaultAssertionConsumerService();
254     }
255
256     // To invoke the request builder, the key requirement is to figure out how
257     // to express the ACS, by index or value, and if by value, where.
258
259     SPConfig& conf = SPConfig::getConfig();
260     if (conf.isEnabled(SPConfig::OutOfProcess)) {
261         if (!acsByIndex.first || acsByIndex.second) {
262             // Pass by Index.
263             if (isHandler) {
264                 // We may already have RelayState set if we looped back here,
265                 // but just in case target is a resource, we reset it back.
266                 target.erase();
267                 option = request.getParameter("target");
268                 if (option)
269                     target = option;
270             }
271             return doRequest(
272                 app, request, entityID,
273                 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
274                 isPassive, forceAuthn,
275                 acClass.first ? acClass.second : NULL,
276                 acComp.first ? acComp.second : NULL,
277                 target
278                 );
279         }
280
281         // Since we're not passing by index, we need to fully compute the return URL and binding.
282         // Compute the ACS URL. We add the ACS location to the base handlerURL.
283         string ACSloc=request.getHandlerURL(target.c_str());
284         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
285         if (loc.first) ACSloc+=loc.second;
286
287         if (isHandler) {
288             // We may already have RelayState set if we looped back here,
289             // but just in case target is a resource, we reset it back.
290             target.erase();
291             option = request.getParameter("target");
292             if (option)
293                 target = option;
294         }
295
296         return doRequest(
297             app, request, entityID,
298             NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
299             isPassive, forceAuthn,
300             acClass.first ? acClass.second : NULL,
301             acComp.first ? acComp.second : NULL,
302             target
303             );
304     }
305
306     // Remote the call.
307     DDF out,in = DDF(m_address.c_str()).structure();
308     DDFJanitor jin(in), jout(out);
309     in.addmember("application_id").string(app.getId());
310     in.addmember("entity_id").string(entityID);
311     if (isPassive)
312         in.addmember("isPassive").integer(1);
313     else if (forceAuthn)
314         in.addmember("forceAuthn").integer(1);
315     if (acClass.first)
316         in.addmember("authnContextClassRef").string(acClass.second);
317     if (acComp.first)
318         in.addmember("authnContextComparison").string(acComp.second);
319     if (!acsByIndex.first || acsByIndex.second) {
320         if (ACS)
321             in.addmember("acsIndex").string(ACS->getString("index").second);
322     }
323     else {
324         // Since we're not passing by index, we need to fully compute the return URL and binding.
325         // Compute the ACS URL. We add the ACS location to the base handlerURL.
326         string ACSloc=request.getHandlerURL(target.c_str());
327         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
328         if (loc.first) ACSloc+=loc.second;
329         in.addmember("acsLocation").string(ACSloc.c_str());
330         if (ACS)
331             in.addmember("acsBinding").string(ACS->getString("Binding").second);
332     }
333
334     if (isHandler) {
335         // We may already have RelayState set if we looped back here,
336         // but just in case target is a resource, we reset it back.
337         target.erase();
338         option = request.getParameter("target");
339         if (option)
340             target = option;
341     }
342     if (!target.empty())
343         in.addmember("RelayState").string(target.c_str());
344
345     // Remote the processing.
346     out = request.getServiceProvider().getListenerService()->send(in);
347     return unwrap(request, out);
348 }
349
350 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
351 {
352     // Find application.
353     const char* aid=in["application_id"].string();
354     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
355     if (!app) {
356         // Something's horribly wrong.
357         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
358         throw ConfigurationException("Unable to locate application for new session, deleted?");
359     }
360
361     const char* entityID = in["entity_id"].string();
362     if (!entityID)
363         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
364
365     DDF ret(NULL);
366     DDFJanitor jout(ret);
367
368     // Wrap the outgoing object with a Response facade.
369     auto_ptr<HTTPResponse> http(getResponse(ret));
370
371     auto_ptr_XMLCh index(in["acsIndex"].string());
372     auto_ptr_XMLCh bind(in["acsBinding"].string());
373
374     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
375
376     // Since we're remoted, the result should either be a throw, which we pass on,
377     // a false/0 return, which we just return as an empty structure, or a response/redirect,
378     // which we capture in the facade and send back.
379     doRequest(
380         *app, *http.get(), entityID,
381         index.get(), in["acsLocation"].string(), bind.get(),
382         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
383         in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
384         relayState
385         );
386     out << ret;
387 }
388
389 pair<bool,long> SAML2SessionInitiator::doRequest(
390     const Application& app,
391     HTTPResponse& httpResponse,
392     const char* entityID,
393     const XMLCh* acsIndex,
394     const char* acsLocation,
395     const XMLCh* acsBinding,
396     bool isPassive,
397     bool forceAuthn,
398     const char* authnContextClassRef,
399     const char* authnContextComparison,
400     string& relayState
401     ) const
402 {
403 #ifndef SHIBSP_LITE
404     // Use metadata to locate the IdP's SSO service.
405     MetadataProvider* m=app.getMetadataProvider();
406     Locker locker(m);
407     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
408     if (!entity) {
409         m_log.error("unable to locate metadata for provider (%s)", entityID);
410         throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
411             namedparams(1, "entityID", entityID));
412     }
413     const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
414     if (!role) {
415         m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
416         return make_pair(false,0);
417     }
418
419     // Loop over the supportable outgoing bindings.
420     const EndpointType* ep=NULL;
421     const MessageEncoder* encoder=NULL;
422     vector<const XMLCh*>::const_iterator b;
423     for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
424         if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
425             map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
426             if (enc!=m_encoders.end())
427                 encoder = enc->second;
428             break;
429         }
430     }
431     if (!ep || !encoder) {
432         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
433         return make_pair(false,0);
434     }
435
436     preserveRelayState(app, httpResponse, relayState);
437
438     auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
439     if (m_requestTemplate) {
440         // Freshen TS and ID.
441         req->setID(NULL);
442         req->setIssueInstant(time(NULL));
443     }
444
445     req->setDestination(ep->getLocation());
446     if (acsIndex && *acsIndex)
447         req->setAssertionConsumerServiceIndex(acsIndex);
448     if (acsLocation) {
449         auto_ptr_XMLCh wideloc(acsLocation);
450         req->setAssertionConsumerServiceURL(wideloc.get());
451     }
452     if (acsBinding && *acsBinding)
453         req->setProtocolBinding(acsBinding);
454     if (isPassive)
455         req->IsPassive(isPassive);
456     else if (forceAuthn)
457         req->ForceAuthn(forceAuthn);
458     if (!req->getIssuer()) {
459         Issuer* issuer = IssuerBuilder::buildIssuer();
460         req->setIssuer(issuer);
461         issuer->setName(app.getXMLString("entityID").second);
462     }
463     if (!req->getNameIDPolicy()) {
464         NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
465         req->setNameIDPolicy(namepol);
466         namepol->AllowCreate(true);
467     }
468     if (authnContextClassRef || authnContextComparison) {
469         RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
470         if (!reqContext) {
471             reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
472             req->setRequestedAuthnContext(reqContext);
473         }
474         if (authnContextClassRef) {
475             reqContext->getAuthnContextDeclRefs().clear();
476             auto_ptr_XMLCh wideclass(authnContextClassRef);
477             AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
478             cref->setReference(wideclass.get());
479             reqContext->getAuthnContextClassRefs().push_back(cref);
480         }
481         if (authnContextComparison &&
482                 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
483             auto_ptr_XMLCh widecomp(authnContextComparison);
484             reqContext->setComparison(widecomp.get());
485         }
486     }
487
488     auto_ptr_char dest(ep->getLocation());
489
490     long ret = sendMessage(
491         *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, "signRequests", role->WantAuthnRequestsSigned()
492         );
493     req.release();  // freed by encoder
494     return make_pair(true,ret);
495 #else
496     return make_pair(false,0);
497 #endif
498 }