Change license header.
[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         DDF out,in = wrap(request, &headers, true);
229         DDFJanitor jin(in), jout(out);
230         out=request.getServiceProvider().getListenerService()->send(in);
231         return unwrap(request, out);
232     }
233 }
234
235 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
236 {
237     // Find application.
238     const char* aid=in["application_id"].string();
239     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
240     if (!app) {
241         // Something's horribly wrong.
242         m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
243         throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
244     }
245
246     // Unpack the request.
247     auto_ptr<HTTPRequest> req(getRequest(in));
248
249     // Wrap a response shim.
250     DDF ret(nullptr);
251     DDFJanitor jout(ret);
252     auto_ptr<HTTPResponse> resp(getResponse(ret));
253
254     // Since we're remoted, the result should either be a throw, which we pass on,
255     // a false/0 return, which we just return as an empty structure, or a response/redirect,
256     // which we capture in the facade and send back.
257     doRequest(*app, *req.get(), *resp.get());
258     out << ret;
259 }
260
261 pair<bool,long> SAML2NameIDMgmt::doRequest(
262     const Application& application, const HTTPRequest& request, HTTPResponse& response
263     ) const
264 {
265 #ifndef SHIBSP_LITE
266     SessionCache* cache = application.getServiceProvider().getSessionCache();
267
268     // Locate policy key.
269     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
270     if (!policyId.first)
271         policyId = application.getString("policyId");   // unqualified in Application(s) element
272
273     // Lock metadata for use by policy.
274     Locker metadataLocker(application.getMetadataProvider());
275
276     // Create the policy.
277     auto_ptr<SecurityPolicy> policy(
278         application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
279         );
280
281     // Decode the message.
282     string relayState;
283     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy.get()));
284     const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
285     if (mgmtRequest) {
286         if (!policy->isAuthenticated())
287             throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
288
289         // Message from IdP to change or terminate a NameID.
290
291         // If this is front-channel, we have to have a session_id to use already.
292         string session_id = cache->active(application, request);
293         if (m_decoder->isUserAgentPresent() && session_id.empty()) {
294             m_log.error("no active session");
295             return sendResponse(
296                 mgmtRequest->getID(),
297                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
298                 relayState.c_str(),
299                 policy->getIssuerMetadata(),
300                 application,
301                 response,
302                 true
303                 );
304         }
305
306         EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
307
308         bool ownedName = false;
309         NameID* nameid = mgmtRequest->getNameID();
310         if (!nameid) {
311             // Check for EncryptedID.
312             EncryptedID* encname = mgmtRequest->getEncryptedID();
313             if (encname) {
314                 CredentialResolver* cr=application.getCredentialResolver();
315                 if (!cr)
316                     m_log.warn("found encrypted NameID, but no decryption credential was available");
317                 else {
318                     Locker credlocker(cr);
319                     auto_ptr<MetadataCredentialCriteria> mcc(
320                         policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
321                         );
322                     try {
323                         auto_ptr<XMLObject> decryptedID(
324                             encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
325                             );
326                         nameid = dynamic_cast<NameID*>(decryptedID.get());
327                         if (nameid) {
328                             ownedName = true;
329                             decryptedID.release();
330                         }
331                     }
332                     catch (exception& ex) {
333                         m_log.error(ex.what());
334                     }
335                 }
336             }
337         }
338         if (!nameid) {
339             // No NameID, so must respond with an error.
340             m_log.error("NameID not found in request");
341             return sendResponse(
342                 mgmtRequest->getID(),
343                 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
344                 relayState.c_str(),
345                 policy->getIssuerMetadata(),
346                 application,
347                 response,
348                 m_decoder->isUserAgentPresent()
349                 );
350         }
351
352         auto_ptr<NameID> namewrapper(ownedName ? nameid : nullptr);
353
354         // For a front-channel request, we have to match the information in the request
355         // against the current session.
356         if (!session_id.empty()) {
357             if (!cache->matches(application, request, entity, *nameid, nullptr)) {
358                 return sendResponse(
359                     mgmtRequest->getID(),
360                     StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
361                     relayState.c_str(),
362                     policy->getIssuerMetadata(),
363                     application,
364                     response,
365                     true
366                     );
367             }
368
369         }
370
371         // Determine what's happening...
372         bool ownedNewID = false;
373         NewID* newid = nullptr;
374         if (!mgmtRequest->getTerminate()) {
375             // Better be a NewID in there.
376             newid = mgmtRequest->getNewID();
377             if (!newid) {
378                 // Check for NewEncryptedID.
379                 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
380                 if (encnewid) {
381                     CredentialResolver* cr=application.getCredentialResolver();
382                     if (!cr)
383                         m_log.warn("found encrypted NewID, but no decryption credential was available");
384                     else {
385                         Locker credlocker(cr);
386                         auto_ptr<MetadataCredentialCriteria> mcc(
387                             policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
388                             );
389                         try {
390                             auto_ptr<XMLObject> decryptedID(
391                                 encnewid->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
392                                 );
393                             newid = dynamic_cast<NewID*>(decryptedID.get());
394                             if (newid) {
395                                 ownedNewID = true;
396                                 decryptedID.release();
397                             }
398                         }
399                         catch (exception& ex) {
400                             m_log.error(ex.what());
401                         }
402                     }
403                 }
404             }
405
406             if (!newid) {
407                 // No NewID, so must respond with an error.
408                 m_log.error("NewID not found in request");
409                 return sendResponse(
410                     mgmtRequest->getID(),
411                     StatusCode::REQUESTER, nullptr, "NewID not found in request.",
412                     relayState.c_str(),
413                     policy->getIssuerMetadata(),
414                     application,
415                     response,
416                     m_decoder->isUserAgentPresent()
417                     );
418             }
419         }
420
421         auto_ptr<NewID> newwrapper(ownedNewID ? newid : nullptr);
422
423         // TODO: maybe support in-place modification of sessions?
424         /*
425         vector<string> sessions;
426         try {
427             time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
428             cache->logout(entity, *nameid, &indexes, expires, application, sessions);
429
430             // Now we actually terminate everything except for the active session,
431             // if this is front-channel, for notification purposes.
432             for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
433                 if (session_id && strcmp(sit->c_str(), session_id))
434                     cache->remove(sit->c_str(), application);
435         }
436         catch (exception& ex) {
437             m_log.error("error while logging out matching sessions: %s", ex.what());
438             return sendResponse(
439                 logoutRequest->getID(),
440                 StatusCode::RESPONDER, nullptr, ex.what(),
441                 relayState.c_str(),
442                 policy.getIssuerMetadata(),
443                 application,
444                 response,
445                 m_decoder->isUserAgentPresent()
446                 );
447         }
448         */
449
450         // Do back-channel app notifications.
451         // Not supporting front-channel due to privacy fears.
452         bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
453
454         return sendResponse(
455             mgmtRequest->getID(),
456             worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
457             nullptr,
458             nullptr,
459             relayState.c_str(),
460             policy->getIssuerMetadata(),
461             application,
462             response,
463             m_decoder->isUserAgentPresent()
464             );
465     }
466
467     // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
468     /*
469     const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
470     if (mgmtResponse) {
471         if (!policy.isAuthenticated()) {
472             SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
473             if (policy.getIssuerMetadata())
474                 annotateException(&ex, policy.getIssuerMetadata()); // throws it
475             ex.raise();
476         }
477         checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
478
479         // Return template for completion.
480         return sendLogoutPage(application, response, false, "Global logout completed.");
481     }
482     */
483
484     FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
485     if (policy->getIssuerMetadata())
486         annotateException(&ex, policy->getIssuerMetadata()); // throws it
487     ex.raise();
488     return make_pair(false,0L);  // never happen, satisfies compiler
489 #else
490     throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
491 #endif
492 }
493
494 #ifndef SHIBSP_LITE
495
496 pair<bool,long> SAML2NameIDMgmt::sendResponse(
497     const XMLCh* requestID,
498     const XMLCh* code,
499     const XMLCh* subcode,
500     const char* msg,
501     const char* relayState,
502     const RoleDescriptor* role,
503     const Application& application,
504     HTTPResponse& httpResponse,
505     bool front
506     ) const
507 {
508     // Get endpoint and encoder to use.
509     const EndpointType* ep = nullptr;
510     const MessageEncoder* encoder = nullptr;
511     if (front) {
512         const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
513         for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
514             if (ep=EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(*b)) {
515                 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
516                 if (enc!=m_encoders.end())
517                     encoder = enc->second;
518                 break;
519             }
520         }
521         if (!ep || !encoder) {
522             auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
523             m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
524             MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
525             annotateException(&ex, role);   // throws it
526         }
527     }
528     else {
529         encoder = m_encoders.begin()->second;
530     }
531
532     // Prepare response.
533     auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
534     nim->setInResponseTo(requestID);
535     if (ep) {
536         const XMLCh* loc = ep->getResponseLocation();
537         if (!loc || !*loc)
538             loc = ep->getLocation();
539         nim->setDestination(loc);
540     }
541     Issuer* issuer = IssuerBuilder::buildIssuer();
542     nim->setIssuer(issuer);
543     issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
544     fillStatus(*nim.get(), code, subcode, msg);
545
546     auto_ptr_char dest(nim->getDestination());
547
548     long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
549     nim.release();  // freed by encoder
550     return make_pair(true,ret);
551 }
552
553 #include "util/SPConstants.h"
554 #include <xmltooling/impl/AnyElement.h>
555 #include <xmltooling/soap/SOAP.h>
556 #include <xmltooling/soap/SOAPClient.h>
557 #include <xmltooling/soap/HTTPSOAPTransport.h>
558 using namespace soap11;
559 namespace {
560     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);
561
562     class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
563     {
564     public:
565         SOAPNotifier() {}
566         virtual ~SOAPNotifier() {}
567     private:
568         void prepareTransport(SOAPTransport& transport) {
569             transport.setVerifyHost(false);
570             HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
571             if (http) {
572                 http->useChunkedEncoding(false);
573                 http->setRequestHeader("User-Agent", PACKAGE_NAME);
574                 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
575             }
576         }
577     };
578 };
579
580 bool SAML2NameIDMgmt::notifyBackChannel(
581     const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
582     ) const
583 {
584     unsigned int index = 0;
585     string endpoint = application.getNotificationURL(requestURL, false, index++);
586     if (endpoint.empty())
587         return true;
588
589     auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
590     Body* body = BodyBuilder::buildBody();
591     env->setBody(body);
592     ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
593     body->getUnknownXMLObjects().push_back(msg);
594     msg->getUnknownXMLObjects().push_back(nameid.clone());
595     if (newid)
596         msg->getUnknownXMLObjects().push_back(newid->clone());
597     else
598         msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
599
600     bool result = true;
601     SOAPNotifier soaper;
602     while (!endpoint.empty()) {
603         try {
604             soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
605             delete soaper.receive();
606         }
607         catch (exception& ex) {
608             m_log.error("error notifying application of logout event: %s", ex.what());
609             result = false;
610         }
611         soaper.reset();
612         endpoint = application.getNotificationURL(requestURL, false, index++);
613     }
614     return result;
615 }
616
617 #endif