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