Simplify/rename signing and encryption properties.
[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 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 #ifndef SHIBSP_LITE
62             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
63                 XMLString::release(&m_outgoing);
64                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
65                 delete m_requestTemplate;
66             }
67 #endif
68         }
69         
70         void setParent(const PropertySet* parent);
71         void receive(DDF& in, ostream& out);
72         pair<bool,long> run(SPRequest& request, const char* entityID=NULL, bool isHandler=true) const;
73
74     private:
75         pair<bool,long> doRequest(
76             const Application& application,
77             HTTPResponse& httpResponse,
78             const char* entityID,
79             const XMLCh* acsIndex,
80             const char* acsLocation,
81             const XMLCh* acsBinding,
82             bool isPassive,
83             bool forceAuthn,
84             const char* authnContextClassRef,
85             const char* authnContextComparison,
86             string& relayState
87             ) const;
88
89         string m_appId;
90 #ifndef SHIBSP_LITE
91         XMLCh* m_outgoing;
92         vector<const XMLCh*> m_bindings;
93         map<const XMLCh*,MessageEncoder*> m_encoders;
94         AuthnRequest* m_requestTemplate;
95 #endif
96     };
97
98 #if defined (_MSC_VER)
99     #pragma warning( pop )
100 #endif
101
102     SessionInitiator* SHIBSP_DLLLOCAL SAML2SessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
103     {
104         return new SAML2SessionInitiator(p.first, p.second);
105     }
106
107 };
108
109 SAML2SessionInitiator::SAML2SessionInitiator(const DOMElement* e, const char* appId)
110     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAML2")), m_appId(appId)
111 {
112 #ifndef SHIBSP_LITE
113     m_outgoing=NULL;
114     m_requestTemplate=NULL;
115     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
116         // Check for a template AuthnRequest to build from.
117         DOMElement* child = XMLHelper::getFirstChildElement(e, samlconstants::SAML20P_NS, AuthnRequest::LOCAL_NAME);
118         if (child)
119             m_requestTemplate = dynamic_cast<AuthnRequest*>(AuthnRequestBuilder::buildOneFromElement(child));
120
121         // Handle outgoing binding setup.
122         pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings");
123         if (outgoing.first) {
124             m_outgoing = XMLString::replicate(outgoing.second);
125             XMLString::trim(m_outgoing);
126         }
127         else {
128             // No override, so we'll install a default binding precedence.
129             string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
130                 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
131             m_outgoing = XMLString::transcode(prec.c_str());
132         }
133
134         int pos;
135         XMLCh* start = m_outgoing;
136         while (start && *start) {
137             pos = XMLString::indexOf(start,chSpace);
138             if (pos != -1)
139                 *(start + pos)=chNull;
140             m_bindings.push_back(start);
141             try {
142                 auto_ptr_char b(start);
143                 MessageEncoder * encoder = SAMLConfig::getConfig().MessageEncoderManager.newPlugin(
144                     b.get(),pair<const DOMElement*,const XMLCh*>(e,NULL)
145                     );
146                 m_encoders[start] = encoder;
147                 m_log.debug("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                 request.log(SPRequest::SPWarn, "invalid acsIndex specified in request, using default ACS location");
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     if (!ACS) {
245         pair<bool,unsigned int> index = getUnsignedInt("defaultACSIndex");
246         if (index.first) {
247             ACS = app.getAssertionConsumerServiceByIndex(index.second);
248             if (!ACS)
249                 request.log(SPRequest::SPWarn, "invalid defaultACSIndex, using default ACS location");
250         }
251         if (!ACS)
252             ACS = app.getDefaultAssertionConsumerService();
253     }
254
255     // To invoke the request builder, the key requirement is to figure out how
256     // to express the ACS, by index or value, and if by value, where.
257
258     SPConfig& conf = SPConfig::getConfig();
259     if (conf.isEnabled(SPConfig::OutOfProcess)) {
260         if (!acsByIndex.first || acsByIndex.second) {
261             // Pass by Index.
262             if (isHandler) {
263                 // We may already have RelayState set if we looped back here,
264                 // but just in case target is a resource, we reset it back.
265                 target.erase();
266                 option = request.getParameter("target");
267                 if (option)
268                     target = option;
269             }
270             return doRequest(
271                 app, request, entityID,
272                 ACS ? ACS->getXMLString("index").second : NULL, NULL, NULL,
273                 isPassive, forceAuthn,
274                 acClass.first ? acClass.second : NULL,
275                 acComp.first ? acComp.second : NULL,
276                 target
277                 );
278         }
279
280         // Since we're not passing by index, we need to fully compute the return URL and binding.
281         // Compute the ACS URL. We add the ACS location to the base handlerURL.
282         string ACSloc=request.getHandlerURL(target.c_str());
283         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
284         if (loc.first) ACSloc+=loc.second;
285
286         if (isHandler) {
287             // We may already have RelayState set if we looped back here,
288             // but just in case target is a resource, we reset it back.
289             target.erase();
290             option = request.getParameter("target");
291             if (option)
292                 target = option;
293         }
294
295         return doRequest(
296             app, request, entityID,
297             NULL, ACSloc.c_str(), ACS ? ACS->getXMLString("Binding").second : NULL,
298             isPassive, forceAuthn,
299             acClass.first ? acClass.second : NULL,
300             acComp.first ? acComp.second : NULL,
301             target
302             );
303     }
304
305     // Remote the call.
306     DDF out,in = DDF(m_address.c_str()).structure();
307     DDFJanitor jin(in), jout(out);
308     in.addmember("application_id").string(app.getId());
309     in.addmember("entity_id").string(entityID);
310     if (isPassive)
311         in.addmember("isPassive").integer(1);
312     else if (forceAuthn)
313         in.addmember("forceAuthn").integer(1);
314     if (acClass.first)
315         in.addmember("authnContextClassRef").string(acClass.second);
316     if (acComp.first)
317         in.addmember("authnContextComparison").string(acComp.second);
318     if (!acsByIndex.first || acsByIndex.second) {
319         if (ACS)
320             in.addmember("acsIndex").string(ACS->getString("index").second);
321     }
322     else {
323         // Since we're not passing by index, we need to fully compute the return URL and binding.
324         // Compute the ACS URL. We add the ACS location to the base handlerURL.
325         string ACSloc=request.getHandlerURL(target.c_str());
326         pair<bool,const char*> loc=ACS ? ACS->getString("Location") : pair<bool,const char*>(false,NULL);
327         if (loc.first) ACSloc+=loc.second;
328         in.addmember("acsLocation").string(ACSloc.c_str());
329         if (ACS)
330             in.addmember("acsBinding").string(ACS->getString("Binding").second);
331     }
332
333     if (isHandler) {
334         // We may already have RelayState set if we looped back here,
335         // but just in case target is a resource, we reset it back.
336         target.erase();
337         option = request.getParameter("target");
338         if (option)
339             target = option;
340     }
341     if (!target.empty())
342         in.addmember("RelayState").string(target.c_str());
343
344     // Remote the processing.
345     out = request.getServiceProvider().getListenerService()->send(in);
346     return unwrap(request, out);
347 }
348
349 void SAML2SessionInitiator::receive(DDF& in, ostream& out)
350 {
351     // Find application.
352     const char* aid=in["application_id"].string();
353     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
354     if (!app) {
355         // Something's horribly wrong.
356         m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
357         throw ConfigurationException("Unable to locate application for new session, deleted?");
358     }
359
360     const char* entityID = in["entity_id"].string();
361     if (!entityID)
362         throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
363
364     DDF ret(NULL);
365     DDFJanitor jout(ret);
366
367     // Wrap the outgoing object with a Response facade.
368     auto_ptr<HTTPResponse> http(getResponse(ret));
369
370     auto_ptr_XMLCh index(in["acsIndex"].string());
371     auto_ptr_XMLCh bind(in["acsBinding"].string());
372
373     string relayState(in["RelayState"].string() ? in["RelayState"].string() : "");
374
375     // Since we're remoted, the result should either be a throw, which we pass on,
376     // a false/0 return, which we just return as an empty structure, or a response/redirect,
377     // which we capture in the facade and send back.
378     doRequest(
379         *app, *http.get(), entityID,
380         index.get(), in["acsLocation"].string(), bind.get(),
381         in["isPassive"].integer()==1, in["forceAuthn"].integer()==1,
382         in["authnContextClassRef"].string(), in["authnContextComparison"].string(),
383         relayState
384         );
385     out << ret;
386 }
387
388 pair<bool,long> SAML2SessionInitiator::doRequest(
389     const Application& app,
390     HTTPResponse& httpResponse,
391     const char* entityID,
392     const XMLCh* acsIndex,
393     const char* acsLocation,
394     const XMLCh* acsBinding,
395     bool isPassive,
396     bool forceAuthn,
397     const char* authnContextClassRef,
398     const char* authnContextComparison,
399     string& relayState
400     ) const
401 {
402 #ifndef SHIBSP_LITE
403     // Use metadata to locate the IdP's SSO service.
404     MetadataProvider* m=app.getMetadataProvider();
405     Locker locker(m);
406     const EntityDescriptor* entity=m->getEntityDescriptor(entityID);
407     if (!entity) {
408         m_log.error("unable to locate metadata for provider (%s)", entityID);
409         throw MetadataException("Unable to locate metadata for identity provider ($entityID)",
410             namedparams(1, "entityID", entityID));
411     }
412     const IDPSSODescriptor* role=entity->getIDPSSODescriptor(samlconstants::SAML20P_NS);
413     if (!role) {
414         m_log.error("unable to locate SAML 2.0 identity provider role for provider (%s)", entityID);
415         return make_pair(false,0);
416     }
417
418     // Loop over the supportable outgoing bindings.
419     const EndpointType* ep=NULL;
420     const MessageEncoder* encoder=NULL;
421     vector<const XMLCh*>::const_iterator b;
422     for (b = m_bindings.begin(); b!=m_bindings.end(); ++b) {
423         if (ep=EndpointManager<SingleSignOnService>(role->getSingleSignOnServices()).getByBinding(*b)) {
424             map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
425             if (enc!=m_encoders.end())
426                 encoder = enc->second;
427             break;
428         }
429     }
430     if (!ep || !encoder) {
431         m_log.error("unable to locate compatible SSO service for provider (%s)", entityID);
432         return make_pair(false,0);
433     }
434
435     preserveRelayState(app, httpResponse, relayState);
436
437     auto_ptr<AuthnRequest> req(m_requestTemplate ? m_requestTemplate->cloneAuthnRequest() : AuthnRequestBuilder::buildAuthnRequest());
438     if (m_requestTemplate) {
439         // Freshen TS and ID.
440         req->setID(NULL);
441         req->setIssueInstant(time(NULL));
442     }
443
444     req->setDestination(ep->getLocation());
445     if (acsIndex && *acsIndex)
446         req->setAssertionConsumerServiceIndex(acsIndex);
447     if (acsLocation) {
448         auto_ptr_XMLCh wideloc(acsLocation);
449         req->setAssertionConsumerServiceURL(wideloc.get());
450     }
451     if (acsBinding && *acsBinding)
452         req->setProtocolBinding(acsBinding);
453     if (isPassive)
454         req->IsPassive(isPassive);
455     else if (forceAuthn)
456         req->ForceAuthn(forceAuthn);
457     if (!req->getIssuer()) {
458         Issuer* issuer = IssuerBuilder::buildIssuer();
459         req->setIssuer(issuer);
460         issuer->setName(app.getXMLString("entityID").second);
461     }
462     if (!req->getNameIDPolicy()) {
463         NameIDPolicy* namepol = NameIDPolicyBuilder::buildNameIDPolicy();
464         req->setNameIDPolicy(namepol);
465         namepol->AllowCreate(true);
466     }
467     if (authnContextClassRef || authnContextComparison) {
468         RequestedAuthnContext* reqContext = req->getRequestedAuthnContext();
469         if (!reqContext) {
470             reqContext = RequestedAuthnContextBuilder::buildRequestedAuthnContext();
471             req->setRequestedAuthnContext(reqContext);
472         }
473         if (authnContextClassRef) {
474             reqContext->getAuthnContextDeclRefs().clear();
475             auto_ptr_XMLCh wideclass(authnContextClassRef);
476             AuthnContextClassRef* cref = AuthnContextClassRefBuilder::buildAuthnContextClassRef();
477             cref->setReference(wideclass.get());
478             reqContext->getAuthnContextClassRefs().push_back(cref);
479         }
480         if (authnContextComparison &&
481                 (!reqContext->getAuthnContextClassRefs().empty() || !reqContext->getAuthnContextDeclRefs().empty())) {
482             auto_ptr_XMLCh widecomp(authnContextComparison);
483             reqContext->setComparison(widecomp.get());
484         }
485     }
486
487     auto_ptr_char dest(ep->getLocation());
488
489     long ret = sendMessage(
490         *encoder, req.get(), relayState.c_str(), dest.get(), role, app, httpResponse, role->WantAuthnRequestsSigned()
491         );
492     req.release();  // freed by encoder
493     return make_pair(true,ret);
494 #else
495     return make_pair(false,0);
496 #endif
497 }