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