6bdfecf80a9212a79ddbf317da68686c66cfbede
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2NameIDMgmt.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2NameIDMgmt.cpp
23  *
24  * Handles SAML 2.0 NameID management protocol messages.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "util/SPConstants.h"
35
36 #ifndef SHIBSP_LITE
37 # include "SessionCache.h"
38 # include "security/SecurityPolicy.h"
39 # include "security/SecurityPolicyProvider.h"
40 # include <fstream>
41 # include <boost/algorithm/string.hpp>
42 # include <boost/iterator/indirect_iterator.hpp>
43 # include <saml/exceptions.h>
44 # include <saml/SAMLConfig.h>
45 # include <saml/saml2/core/Protocols.h>
46 # include <saml/saml2/metadata/EndpointManager.h>
47 # include <saml/saml2/metadata/Metadata.h>
48 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
49 # include <xmltooling/util/URLEncoder.h>
50 using namespace opensaml::saml2;
51 using namespace opensaml::saml2p;
52 using namespace opensaml::saml2md;
53 using namespace opensaml;
54 #else
55 # include "lite/SAMLConstants.h"
56 #endif
57
58 #include <boost/scoped_ptr.hpp>
59
60 using namespace shibsp;
61 using namespace xmltooling;
62 using namespace boost;
63 using namespace std;
64
65 namespace shibsp {
66
67 #if defined (_MSC_VER)
68     #pragma warning( push )
69     #pragma warning( disable : 4250 )
70 #endif
71
72     class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
73     {
74     public:
75         SAML2NameIDMgmt(const DOMElement* e, const char* appId);
76         virtual ~SAML2NameIDMgmt() {}
77
78         void receive(DDF& in, ostream& out);
79         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
80
81 #ifndef SHIBSP_LITE
82         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
83             const char* loc = getString("Location").second;
84             string hurl(handlerURL);
85             if (*loc != '/')
86                 hurl += '/';
87             hurl += loc;
88             auto_ptr_XMLCh widen(hurl.c_str());
89             ManageNameIDService* ep = ManageNameIDServiceBuilder::buildManageNameIDService();
90             ep->setLocation(widen.get());
91             ep->setBinding(getXMLString("Binding").second);
92             role.getManageNameIDServices().push_back(ep);
93             role.addSupport(samlconstants::SAML20P_NS);
94         }
95
96         const char* getType() const {
97             return "ManageNameIDService";
98         }
99 #endif
100         const XMLCh* getProtocolFamily() const {
101             return samlconstants::SAML20P_NS;
102         }
103
104     private:
105         pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
106
107 #ifndef SHIBSP_LITE
108         bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
109
110         pair<bool,long> sendResponse(
111             const XMLCh* requestID,
112             const XMLCh* code,
113             const XMLCh* subcode,
114             const char* msg,
115             const char* relayState,
116             const RoleDescriptor* role,
117             const Application& application,
118             HTTPResponse& httpResponse,
119             bool front
120             ) const;
121
122         scoped_ptr<MessageDecoder> m_decoder;
123         vector<string> m_bindings;
124         map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
125 #endif
126     };
127
128 #if defined (_MSC_VER)
129     #pragma warning( pop )
130 #endif
131
132     Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
133     {
134         return new SAML2NameIDMgmt(p.first, p.second);
135     }
136 };
137
138 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
139     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
140 {
141 #ifndef SHIBSP_LITE
142     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
143         SAMLConfig& conf = SAMLConfig::getConfig();
144
145         // Handle incoming binding.
146         m_decoder.reset(
147             conf.MessageDecoderManager.newPlugin(
148                 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
149                 )
150             );
151         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
152
153         if (m_decoder->isUserAgentPresent()) {
154             // Handle front-channel binding setup.
155             string dupBindings;
156             pair<bool,const char*> outgoing = getString("outgoingBindings", m_configNS.get());
157             if (outgoing.first) {
158                 dupBindings = outgoing.second;
159             }
160             else {
161                 // No override, so we'll install a default binding precedence.
162                 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
163                     samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
164             }
165
166             split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
167             for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
168                 try {
169                     boost::shared_ptr<MessageEncoder> encoder(
170                         conf.MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
171                         );
172                     if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
173                         m_encoders[*b] = encoder;
174                         m_log.debug("supporting outgoing binding (%s)", b->c_str());
175                     }
176                     else {
177                         m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
178                     }
179                 }
180                 catch (std::exception& ex) {
181                     m_log.error("error building MessageEncoder: %s", ex.what());
182                 }
183             }
184         }
185         else {
186             pair<bool,const char*> b = getString("Binding");
187             boost::shared_ptr<MessageEncoder> encoder(
188                 conf.MessageEncoderManager.newPlugin(b.second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
189                 );
190             m_encoders[b.second] = encoder;
191         }
192     }
193 #endif
194
195     string address(appId);
196     address += getString("Location").second;
197     setAddress(address.c_str());
198 }
199
200 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
201 {
202     SPConfig& conf = SPConfig::getConfig();
203     if (conf.isEnabled(SPConfig::OutOfProcess)) {
204         // When out of process, we run natively and directly process the message.
205         return doRequest(request.getApplication(), request, request);
206     }
207     else {
208         // When not out of process, we remote all the message processing.
209         vector<string> headers(1,"Cookie");
210         headers.push_back("User-Agent");
211         DDF out,in = wrap(request, &headers, true);
212         DDFJanitor jin(in), jout(out);
213         out=request.getServiceProvider().getListenerService()->send(in);
214         return unwrap(request, out);
215     }
216 }
217
218 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
219 {
220     // Find application.
221     const char* aid = in["application_id"].string();
222     const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
223     if (!app) {
224         // Something's horribly wrong.
225         m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
226         throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
227     }
228
229     // Unpack the request.
230     scoped_ptr<HTTPRequest> req(getRequest(in));
231
232     // Wrap a response shim.
233     DDF ret(nullptr);
234     DDFJanitor jout(ret);
235     scoped_ptr<HTTPResponse> resp(getResponse(ret));
236
237     // Since we're remoted, the result should either be a throw, which we pass on,
238     // a false/0 return, which we just return as an empty structure, or a response/redirect,
239     // which we capture in the facade and send back.
240     doRequest(*app, *req, *resp);
241     out << ret;
242 }
243
244 pair<bool,long> SAML2NameIDMgmt::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
245 {
246 #ifndef SHIBSP_LITE
247     SessionCache* cache = application.getServiceProvider().getSessionCache();
248
249     // Locate policy key.
250     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // may be namespace-qualified inside handler element
251     if (!policyId.first)
252         policyId = getString("policyId");   // try unqualified
253     if (!policyId.first)
254         policyId = application.getString("policyId");   // unqualified in Application(s) element
255
256     // Lock metadata for use by policy.
257     Locker metadataLocker(application.getMetadataProvider());
258
259     // Create the policy.
260     scoped_ptr<SecurityPolicy> policy(
261         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &IDPSSODescriptor::ELEMENT_QNAME, policyId.second)
262         );
263
264     // Decode the message.
265     string relayState;
266     scoped_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy));
267     const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
268     if (mgmtRequest) {
269         if (!policy->isAuthenticated())
270             throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
271
272         // Message from IdP to change or terminate a NameID.
273
274         // If this is front-channel, we have to have a session_id to use already.
275         string session_id = cache->active(application, request);
276         if (m_decoder->isUserAgentPresent() && session_id.empty()) {
277             m_log.error("no active session");
278             return sendResponse(
279                 mgmtRequest->getID(),
280                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
281                 relayState.c_str(),
282                 policy->getIssuerMetadata(),
283                 application,
284                 response,
285                 true
286                 );
287         }
288
289         EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
290
291         scoped_ptr<XMLObject> decryptedID;
292         NameID* nameid = mgmtRequest->getNameID();
293         if (!nameid) {
294             // Check for EncryptedID.
295             EncryptedID* encname = mgmtRequest->getEncryptedID();
296             if (encname) {
297                 CredentialResolver* cr=application.getCredentialResolver();
298                 if (!cr)
299                     m_log.warn("found encrypted NameID, but no decryption credential was available");
300                 else {
301                     Locker credlocker(cr);
302                     scoped_ptr<MetadataCredentialCriteria> mcc(
303                         policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
304                         );
305                     try {
306                         decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
307                         nameid = dynamic_cast<NameID*>(decryptedID.get());
308                     }
309                     catch (std::exception& ex) {
310                         m_log.error(ex.what());
311                     }
312                 }
313             }
314         }
315         if (!nameid) {
316             // No NameID, so must respond with an error.
317             m_log.error("NameID not found in request");
318             return sendResponse(
319                 mgmtRequest->getID(),
320                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
321                 relayState.c_str(),
322                 policy->getIssuerMetadata(),
323                 application,
324                 response,
325                 m_decoder->isUserAgentPresent()
326                 );
327         }
328
329         // For a front-channel request, we have to match the information in the request
330         // against the current session.
331         if (!session_id.empty()) {
332             if (!cache->matches(application, request, entity, *nameid, nullptr)) {
333                 return sendResponse(
334                     mgmtRequest->getID(),
335                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
336                     relayState.c_str(),
337                     policy->getIssuerMetadata(),
338                     application,
339                     response,
340                     true
341                     );
342             }
343
344         }
345
346         // Determine what's happening...
347         scoped_ptr<XMLObject> newDecryptedID;
348         NewID* newid = nullptr;
349         if (!mgmtRequest->getTerminate()) {
350             // Better be a NewID in there.
351             newid = mgmtRequest->getNewID();
352             if (!newid) {
353                 // Check for NewEncryptedID.
354                 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
355                 if (encnewid) {
356                     CredentialResolver* cr=application.getCredentialResolver();
357                     if (!cr)
358                         m_log.warn("found encrypted NewID, but no decryption credential was available");
359                     else {
360                         Locker credlocker(cr);
361                         scoped_ptr<MetadataCredentialCriteria> mcc(
362                             policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
363                             );
364                         try {
365                             newDecryptedID.reset(encnewid->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
366                             newid = dynamic_cast<NewID*>(newDecryptedID.get());
367                         }
368                         catch (std::exception& ex) {
369                             m_log.error(ex.what());
370                         }
371                     }
372                 }
373             }
374
375             if (!newid) {
376                 // No NewID, so must respond with an error.
377                 m_log.error("NewID not found in request");
378                 return sendResponse(
379                     mgmtRequest->getID(),
380                     StatusCode::REQUESTER, nullptr, "NewID not found in request.",
381                     relayState.c_str(),
382                     policy->getIssuerMetadata(),
383                     application,
384                     response,
385                     m_decoder->isUserAgentPresent()
386                     );
387             }
388         }
389
390         // TODO: maybe support in-place modification of sessions?
391         /*
392         vector<string> sessions;
393         try {
394             time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
395             cache->logout(entity, *nameid, &indexes, expires, application, sessions);
396
397             // Now we actually terminate everything except for the active session,
398             // if this is front-channel, for notification purposes.
399             for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
400                 if (session_id && strcmp(sit->c_str(), session_id))
401                     cache->remove(sit->c_str(), application);
402         }
403         catch (exception& ex) {
404             m_log.error("error while logging out matching sessions: %s", ex.what());
405             return sendResponse(
406                 logoutRequest->getID(),
407                 StatusCode::RESPONDER, nullptr, ex.what(),
408                 relayState.c_str(),
409                 policy.getIssuerMetadata(),
410                 application,
411                 response,
412                 m_decoder->isUserAgentPresent()
413                 );
414         }
415         */
416
417         // Do back-channel app notifications.
418         // Not supporting front-channel due to privacy concerns.
419         bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
420
421         return sendResponse(
422             mgmtRequest->getID(),
423             worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
424             nullptr,
425             nullptr,
426             relayState.c_str(),
427             policy->getIssuerMetadata(),
428             application,
429             response,
430             m_decoder->isUserAgentPresent()
431             );
432     }
433
434     // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
435     /*
436     const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
437     if (mgmtResponse) {
438         if (!policy.isAuthenticated()) {
439             SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
440             if (policy.getIssuerMetadata())
441                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
442             ex.raise();
443         }
444         checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
445
446         // Return template for completion.
447         return sendLogoutPage(application, response, false, "Global logout completed.");
448     }
449     */
450
451     FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
452     annotateException(&ex, policy->getIssuerMetadata()); // throws it
453     return make_pair(false, 0L);  // never happen, satisfies compiler
454 #else
455     throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
456 #endif
457 }
458
459 #ifndef SHIBSP_LITE
460
461 pair<bool,long> SAML2NameIDMgmt::sendResponse(
462     const XMLCh* requestID,
463     const XMLCh* code,
464     const XMLCh* subcode,
465     const char* msg,
466     const char* relayState,
467     const RoleDescriptor* role,
468     const Application& application,
469     HTTPResponse& httpResponse,
470     bool front
471     ) const
472 {
473     // Get endpoint and encoder to use.
474     const EndpointType* ep = nullptr;
475     const MessageEncoder* encoder = nullptr;
476     if (front) {
477         const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
478         for (vector<string>::const_iterator b = m_bindings.begin(); idp && b != m_bindings.end(); ++b) {
479             auto_ptr_XMLCh wideb(b->c_str());
480             if ((ep = EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(wideb.get()))) {
481                 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
482                 if (enc != m_encoders.end())
483                     encoder = enc->second.get();
484                 break;
485             }
486         }
487         if (!ep || !encoder) {
488             auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
489             m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
490             MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
491             annotateException(&ex, role);   // throws it
492         }
493     }
494     else {
495         encoder = m_encoders.begin()->second.get();
496     }
497
498     // Prepare response.
499     auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
500     nim->setInResponseTo(requestID);
501     if (ep) {
502         const XMLCh* loc = ep->getResponseLocation();
503         if (!loc || !*loc)
504             loc = ep->getLocation();
505         nim->setDestination(loc);
506     }
507     Issuer* issuer = IssuerBuilder::buildIssuer();
508     nim->setIssuer(issuer);
509     issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
510     fillStatus(*nim, code, subcode, msg);
511
512     auto_ptr_char dest(nim->getDestination());
513
514     long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
515     nim.release();  // freed by encoder
516     return make_pair(true, ret);
517 }
518
519 #include "util/SPConstants.h"
520 #include <xmltooling/impl/AnyElement.h>
521 #include <xmltooling/soap/SOAP.h>
522 #include <xmltooling/soap/SOAPClient.h>
523 #include <xmltooling/soap/HTTPSOAPTransport.h>
524 using namespace soap11;
525 namespace {
526     static const XMLCh NameIDNotification[] =   UNICODE_LITERAL_18(N,a,m,e,I,D,N,o,t,i,f,i,c,a,t,i,o,n);
527
528     class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
529     {
530     public:
531         SOAPNotifier() {}
532         virtual ~SOAPNotifier() {}
533     private:
534         void prepareTransport(SOAPTransport& transport) {
535             transport.setVerifyHost(false);
536             HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
537             if (http) {
538                 http->useChunkedEncoding(false);
539                 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
540             }
541         }
542     };
543 };
544
545 bool SAML2NameIDMgmt::notifyBackChannel(
546     const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
547     ) const
548 {
549     unsigned int index = 0;
550     string endpoint = application.getNotificationURL(requestURL, false, index++);
551     if (endpoint.empty())
552         return true;
553
554     scoped_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
555     Body* body = BodyBuilder::buildBody();
556     env->setBody(body);
557     ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
558     body->getUnknownXMLObjects().push_back(msg);
559     msg->getUnknownXMLObjects().push_back(nameid.clone());
560     if (newid)
561         msg->getUnknownXMLObjects().push_back(newid->clone());
562     else
563         msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
564
565     bool result = true;
566     SOAPNotifier soaper;
567     while (!endpoint.empty()) {
568         try {
569             soaper.send(*env, SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
570             delete soaper.receive();
571         }
572         catch (std::exception& ex) {
573             m_log.error("error notifying application of logout event: %s", ex.what());
574             result = false;
575         }
576         soaper.reset();
577         endpoint = application.getNotificationURL(requestURL, false, index++);
578     }
579     return result;
580 }
581
582 #endif