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