Fix some warnings.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML2NameIDMgmt.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML2NameIDMgmt.cpp
23  *
24  * Handles SAML 2.0 NameID management protocol messages.
25  */
26
27 #include "internal.h"
28 #include "exceptions.h"
29 #include "Application.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "util/SPConstants.h"
35
36 #ifndef SHIBSP_LITE
37 # include "SessionCache.h"
38 # include "security/SecurityPolicy.h"
39 # include "security/SecurityPolicyProvider.h"
40 # include <fstream>
41 # include <saml/exceptions.h>
42 # include <saml/SAMLConfig.h>
43 # include <saml/saml2/core/Protocols.h>
44 # include <saml/saml2/metadata/EndpointManager.h>
45 # include <saml/saml2/metadata/Metadata.h>
46 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
47 # include <xmltooling/util/URLEncoder.h>
48 using namespace opensaml::saml2;
49 using namespace opensaml::saml2p;
50 using namespace opensaml::saml2md;
51 using namespace opensaml;
52 #else
53 # include "lite/SAMLConstants.h"
54 #endif
55
56 using namespace shibsp;
57 using namespace xmltooling;
58 using namespace std;
59
60 namespace shibsp {
61
62 #if defined (_MSC_VER)
63     #pragma warning( push )
64     #pragma warning( disable : 4250 )
65 #endif
66
67     class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
68     {
69     public:
70         SAML2NameIDMgmt(const DOMElement* e, const char* appId);
71         virtual ~SAML2NameIDMgmt() {
72 #ifndef SHIBSP_LITE
73             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
74                 delete m_decoder;
75                 XMLString::release(&m_outgoing);
76                 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
77             }
78 #endif
79         }
80
81         void receive(DDF& in, ostream& out);
82         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
83
84 #ifndef SHIBSP_LITE
85         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
86             const char* loc = getString("Location").second;
87             string hurl(handlerURL);
88             if (*loc != '/')
89                 hurl += '/';
90             hurl += loc;
91             auto_ptr_XMLCh widen(hurl.c_str());
92             ManageNameIDService* ep = ManageNameIDServiceBuilder::buildManageNameIDService();
93             ep->setLocation(widen.get());
94             ep->setBinding(getXMLString("Binding").second);
95             role.getManageNameIDServices().push_back(ep);
96             role.addSupport(samlconstants::SAML20P_NS);
97         }
98
99         const char* getType() const {
100             return "ManageNameIDService";
101         }
102 #endif
103         const XMLCh* getProtocolFamily() const {
104             return samlconstants::SAML20P_NS;
105         }
106
107     private:
108         pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
109
110 #ifndef SHIBSP_LITE
111         bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
112
113         pair<bool,long> sendResponse(
114             const XMLCh* requestID,
115             const XMLCh* code,
116             const XMLCh* subcode,
117             const char* msg,
118             const char* relayState,
119             const RoleDescriptor* role,
120             const Application& application,
121             HTTPResponse& httpResponse,
122             bool front
123             ) const;
124
125         xmltooling::QName m_role;
126         MessageDecoder* m_decoder;
127         XMLCh* m_outgoing;
128         vector<const XMLCh*> m_bindings;
129         map<const XMLCh*,MessageEncoder*> m_encoders;
130 #endif
131     };
132
133 #if defined (_MSC_VER)
134     #pragma warning( pop )
135 #endif
136
137     Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
138     {
139         return new SAML2NameIDMgmt(p.first, p.second);
140     }
141 };
142
143 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
144     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
145 #ifndef SHIBSP_LITE
146         ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(nullptr), m_outgoing(nullptr)
147 #endif
148 {
149 #ifndef SHIBSP_LITE
150     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
151         SAMLConfig& conf = SAMLConfig::getConfig();
152
153         // Handle incoming binding.
154         m_decoder = conf.MessageDecoderManager.newPlugin(
155             getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
156             );
157         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
158
159         if (m_decoder->isUserAgentPresent()) {
160             // Handle front-channel binding setup.
161             pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
162             if (outgoing.first) {
163                 m_outgoing = XMLString::replicate(outgoing.second);
164                 XMLString::trim(m_outgoing);
165             }
166             else {
167                 // No override, so we'll install a default binding precedence.
168                 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
169                     samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
170                 m_outgoing = XMLString::transcode(prec.c_str());
171             }
172
173             int pos;
174             XMLCh* start = m_outgoing;
175             while (start && *start) {
176                 pos = XMLString::indexOf(start,chSpace);
177                 if (pos != -1)
178                     *(start + pos)=chNull;
179                 m_bindings.push_back(start);
180                 try {
181                     auto_ptr_char b(start);
182                     MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
183                         b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
184                         );
185                     if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
186                         m_encoders[start] = encoder;
187                         m_log.debug("supporting outgoing binding (%s)", b.get());
188                     }
189                     else {
190                         delete encoder;
191                         m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b.get());
192                     }
193                 }
194                 catch (exception& ex) {
195                     m_log.error("error building MessageEncoder: %s", ex.what());
196                 }
197                 if (pos != -1)
198                     start = start + pos + 1;
199                 else
200                     break;
201             }
202         }
203         else {
204             MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
205                 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
206                 );
207             m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(nullptr, encoder));
208         }
209     }
210 #endif
211
212     string address(appId);
213     address += getString("Location").second;
214     setAddress(address.c_str());
215 }
216
217 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
218 {
219     SPConfig& conf = SPConfig::getConfig();
220     if (conf.isEnabled(SPConfig::OutOfProcess)) {
221         // When out of process, we run natively and directly process the message.
222         return doRequest(request.getApplication(), request, request);
223     }
224     else {
225         // When not out of process, we remote all the message processing.
226         vector<string> headers(1,"Cookie");
227         headers.push_back("User-Agent");
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