Boost changes
[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());  // namespace-qualified if inside handler element
251     if (!policyId.first)
252         policyId = application.getString("policyId");   // unqualified in Application(s) element
253
254     // Lock metadata for use by policy.
255     Locker metadataLocker(application.getMetadataProvider());
256
257     // Create the policy.
258     scoped_ptr<SecurityPolicy> policy(
259         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &IDPSSODescriptor::ELEMENT_QNAME, policyId.second)
260         );
261
262     // Decode the message.
263     string relayState;
264     scoped_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy));
265     const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
266     if (mgmtRequest) {
267         if (!policy->isAuthenticated())
268             throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
269
270         // Message from IdP to change or terminate a NameID.
271
272         // If this is front-channel, we have to have a session_id to use already.
273         string session_id = cache->active(application, request);
274         if (m_decoder->isUserAgentPresent() && session_id.empty()) {
275             m_log.error("no active session");
276             return sendResponse(
277                 mgmtRequest->getID(),
278                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
279                 relayState.c_str(),
280                 policy->getIssuerMetadata(),
281                 application,
282                 response,
283                 true
284                 );
285         }
286
287         EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
288
289         scoped_ptr<XMLObject> decryptedID;
290         NameID* nameid = mgmtRequest->getNameID();
291         if (!nameid) {
292             // Check for EncryptedID.
293             EncryptedID* encname = mgmtRequest->getEncryptedID();
294             if (encname) {
295                 CredentialResolver* cr=application.getCredentialResolver();
296                 if (!cr)
297                     m_log.warn("found encrypted NameID, but no decryption credential was available");
298                 else {
299                     Locker credlocker(cr);
300                     scoped_ptr<MetadataCredentialCriteria> mcc(
301                         policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
302                         );
303                     try {
304                         decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
305                         nameid = dynamic_cast<NameID*>(decryptedID.get());
306                     }
307                     catch (std::exception& ex) {
308                         m_log.error(ex.what());
309                     }
310                 }
311             }
312         }
313         if (!nameid) {
314             // No NameID, so must respond with an error.
315             m_log.error("NameID not found in request");
316             return sendResponse(
317                 mgmtRequest->getID(),
318                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
319                 relayState.c_str(),
320                 policy->getIssuerMetadata(),
321                 application,
322                 response,
323                 m_decoder->isUserAgentPresent()
324                 );
325         }
326
327         // For a front-channel request, we have to match the information in the request
328         // against the current session.
329         if (!session_id.empty()) {
330             if (!cache->matches(application, request, entity, *nameid, nullptr)) {
331                 return sendResponse(
332                     mgmtRequest->getID(),
333                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
334                     relayState.c_str(),
335                     policy->getIssuerMetadata(),
336                     application,
337                     response,
338                     true
339                     );
340             }
341
342         }
343
344         // Determine what's happening...
345         scoped_ptr<XMLObject> newDecryptedID;
346         NewID* newid = nullptr;
347         if (!mgmtRequest->getTerminate()) {
348             // Better be a NewID in there.
349             newid = mgmtRequest->getNewID();
350             if (!newid) {
351                 // Check for NewEncryptedID.
352                 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
353                 if (encnewid) {
354                     CredentialResolver* cr=application.getCredentialResolver();
355                     if (!cr)
356                         m_log.warn("found encrypted NewID, but no decryption credential was available");
357                     else {
358                         Locker credlocker(cr);
359                         scoped_ptr<MetadataCredentialCriteria> mcc(
360                             policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
361                             );
362                         try {
363                             newDecryptedID.reset(encnewid->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
364                             newid = dynamic_cast<NewID*>(newDecryptedID.get());
365                         }
366                         catch (std::exception& ex) {
367                             m_log.error(ex.what());
368                         }
369                     }
370                 }
371             }
372
373             if (!newid) {
374                 // No NewID, so must respond with an error.
375                 m_log.error("NewID not found in request");
376                 return sendResponse(
377                     mgmtRequest->getID(),
378                     StatusCode::REQUESTER, nullptr, "NewID not found in request.",
379                     relayState.c_str(),
380                     policy->getIssuerMetadata(),
381                     application,
382                     response,
383                     m_decoder->isUserAgentPresent()
384                     );
385             }
386         }
387
388         // TODO: maybe support in-place modification of sessions?
389         /*
390         vector<string> sessions;
391         try {
392             time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
393             cache->logout(entity, *nameid, &indexes, expires, application, sessions);
394
395             // Now we actually terminate everything except for the active session,
396             // if this is front-channel, for notification purposes.
397             for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
398                 if (session_id && strcmp(sit->c_str(), session_id))
399                     cache->remove(sit->c_str(), application);
400         }
401         catch (exception& ex) {
402             m_log.error("error while logging out matching sessions: %s", ex.what());
403             return sendResponse(
404                 logoutRequest->getID(),
405                 StatusCode::RESPONDER, nullptr, ex.what(),
406                 relayState.c_str(),
407                 policy.getIssuerMetadata(),
408                 application,
409                 response,
410                 m_decoder->isUserAgentPresent()
411                 );
412         }
413         */
414
415         // Do back-channel app notifications.
416         // Not supporting front-channel due to privacy concerns.
417         bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
418
419         return sendResponse(
420             mgmtRequest->getID(),
421             worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
422             nullptr,
423             nullptr,
424             relayState.c_str(),
425             policy->getIssuerMetadata(),
426             application,
427             response,
428             m_decoder->isUserAgentPresent()
429             );
430     }
431
432     // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
433     /*
434     const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
435     if (mgmtResponse) {
436         if (!policy.isAuthenticated()) {
437             SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
438             if (policy.getIssuerMetadata())
439                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
440             ex.raise();
441         }
442         checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
443
444         // Return template for completion.
445         return sendLogoutPage(application, response, false, "Global logout completed.");
446     }
447     */
448
449     FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
450     if (policy->getIssuerMetadata())
451         annotateException(&ex, policy->getIssuerMetadata()); // throws it
452     ex.raise();
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