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