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