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