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.
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
24 * Handles SAML 2.0 NameID management protocol messages.
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"
37 # include "SessionCache.h"
38 # include "security/SecurityPolicy.h"
39 # include "security/SecurityPolicyProvider.h"
41 # include <boost/algorithm/string.hpp>
42 # include <boost/iterator/indirect_iterator.hpp>
43 # include <saml/exceptions.h>
44 # include <saml/SAMLConfig.h>
45 # include <saml/saml2/core/Protocols.h>
46 # include <saml/saml2/metadata/EndpointManager.h>
47 # include <saml/saml2/metadata/Metadata.h>
48 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
49 # include <xmltooling/util/URLEncoder.h>
50 using namespace opensaml::saml2;
51 using namespace opensaml::saml2p;
52 using namespace opensaml::saml2md;
53 using namespace opensaml;
55 # include "lite/SAMLConstants.h"
58 #include <boost/scoped_ptr.hpp>
60 using namespace shibsp;
61 using namespace xmltooling;
62 using namespace boost;
67 #if defined (_MSC_VER)
68 #pragma warning( push )
69 #pragma warning( disable : 4250 )
72 class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
75 SAML2NameIDMgmt(const DOMElement* e, const char* appId);
76 virtual ~SAML2NameIDMgmt() {}
78 void receive(DDF& in, ostream& out);
79 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
82 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
83 const char* loc = getString("Location").second;
84 string hurl(handlerURL);
88 auto_ptr_XMLCh widen(hurl.c_str());
89 ManageNameIDService* ep = ManageNameIDServiceBuilder::buildManageNameIDService();
90 ep->setLocation(widen.get());
91 ep->setBinding(getXMLString("Binding").second);
92 role.getManageNameIDServices().push_back(ep);
93 role.addSupport(samlconstants::SAML20P_NS);
96 const char* getType() const {
97 return "ManageNameIDService";
100 const XMLCh* getProtocolFamily() const {
101 return samlconstants::SAML20P_NS;
105 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
108 bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
110 pair<bool,long> sendResponse(
111 const XMLCh* requestID,
113 const XMLCh* subcode,
115 const char* relayState,
116 const RoleDescriptor* role,
117 const Application& application,
118 HTTPResponse& httpResponse,
122 scoped_ptr<MessageDecoder> m_decoder;
123 vector<string> m_bindings;
124 map< string,boost::shared_ptr<MessageEncoder> > m_encoders;
128 #if defined (_MSC_VER)
129 #pragma warning( pop )
132 Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
134 return new SAML2NameIDMgmt(p.first, p.second);
138 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
139 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
142 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
143 SAMLConfig& conf = SAMLConfig::getConfig();
145 // Handle incoming binding.
147 conf.MessageDecoderManager.newPlugin(
148 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
151 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
153 if (m_decoder->isUserAgentPresent()) {
154 // Handle front-channel binding setup.
156 pair<bool,const char*> outgoing = getString("outgoingBindings", m_configNS.get());
157 if (outgoing.first) {
158 dupBindings = outgoing.second;
162 // No override, so we'll install a default binding precedence.
163 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
164 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
167 split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
168 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
170 boost::shared_ptr<MessageEncoder> encoder(
171 conf.MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
173 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
174 m_encoders[*b] = encoder;
175 m_log.debug("supporting outgoing binding (%s)", b->c_str());
178 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
181 catch (std::exception& ex) {
182 m_log.error("error building MessageEncoder: %s", ex.what());
187 pair<bool,const char*> b = getString("Binding");
188 boost::shared_ptr<MessageEncoder> encoder(
189 conf.MessageEncoderManager.newPlugin(b.second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
191 m_encoders[b.second] = encoder;
196 string address(appId);
197 address += getString("Location").second;
198 setAddress(address.c_str());
201 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
203 SPConfig& conf = SPConfig::getConfig();
204 if (conf.isEnabled(SPConfig::OutOfProcess)) {
205 // When out of process, we run natively and directly process the message.
206 return doRequest(request.getApplication(), request, request);
209 // When not out of process, we remote all the message processing.
210 vector<string> headers(1,"Cookie");
211 headers.push_back("User-Agent");
212 DDF out,in = wrap(request, &headers, true);
213 DDFJanitor jin(in), jout(out);
214 out=request.getServiceProvider().getListenerService()->send(in);
215 return unwrap(request, out);
219 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
222 const char* aid = in["application_id"].string();
223 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
225 // Something's horribly wrong.
226 m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
227 throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
230 // Unpack the request.
231 scoped_ptr<HTTPRequest> req(getRequest(in));
233 // Wrap a response shim.
235 DDFJanitor jout(ret);
236 scoped_ptr<HTTPResponse> resp(getResponse(ret));
238 // Since we're remoted, the result should either be a throw, which we pass on,
239 // a false/0 return, which we just return as an empty structure, or a response/redirect,
240 // which we capture in the facade and send back.
241 doRequest(*app, *req, *resp);
245 pair<bool,long> SAML2NameIDMgmt::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
248 SessionCache* cache = application.getServiceProvider().getSessionCache();
250 // Locate policy key.
251 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // may be namespace-qualified inside handler element
253 policyId = getString("policyId"); // try unqualified
255 policyId = application.getString("policyId"); // unqualified in Application(s) element
257 // Lock metadata for use by policy.
258 Locker metadataLocker(application.getMetadataProvider());
260 // Create the policy.
261 scoped_ptr<SecurityPolicy> policy(
262 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &IDPSSODescriptor::ELEMENT_QNAME, policyId.second)
265 // Decode the message.
267 scoped_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy));
268 const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
270 if (!policy->isAuthenticated())
271 throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
273 // Message from IdP to change or terminate a NameID.
275 // If this is front-channel, we have to have a session_id to use already.
276 string session_id = cache->active(application, request);
277 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
278 m_log.error("no active session");
280 mgmtRequest->getID(),
281 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
283 policy->getIssuerMetadata(),
290 EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
292 scoped_ptr<XMLObject> decryptedID;
293 NameID* nameid = mgmtRequest->getNameID();
295 // Check for EncryptedID.
296 EncryptedID* encname = mgmtRequest->getEncryptedID();
298 CredentialResolver* cr=application.getCredentialResolver();
300 m_log.warn("found encrypted NameID, but no decryption credential was available");
302 Locker credlocker(cr);
303 scoped_ptr<MetadataCredentialCriteria> mcc(
304 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
307 decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
308 nameid = dynamic_cast<NameID*>(decryptedID.get());
310 catch (std::exception& ex) {
311 m_log.error(ex.what());
317 // No NameID, so must respond with an error.
318 m_log.error("NameID not found in request");
320 mgmtRequest->getID(),
321 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
323 policy->getIssuerMetadata(),
326 m_decoder->isUserAgentPresent()
330 // For a front-channel request, we have to match the information in the request
331 // against the current session.
332 if (!session_id.empty()) {
333 if (!cache->matches(application, request, entity, *nameid, nullptr)) {
335 mgmtRequest->getID(),
336 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
338 policy->getIssuerMetadata(),
347 // Determine what's happening...
348 scoped_ptr<XMLObject> newDecryptedID;
349 NewID* newid = nullptr;
350 if (!mgmtRequest->getTerminate()) {
351 // Better be a NewID in there.
352 newid = mgmtRequest->getNewID();
354 // Check for NewEncryptedID.
355 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
357 CredentialResolver* cr=application.getCredentialResolver();
359 m_log.warn("found encrypted NewID, but no decryption credential was available");
361 Locker credlocker(cr);
362 scoped_ptr<MetadataCredentialCriteria> mcc(
363 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
366 newDecryptedID.reset(encnewid->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
367 newid = dynamic_cast<NewID*>(newDecryptedID.get());
369 catch (std::exception& ex) {
370 m_log.error(ex.what());
377 // No NewID, so must respond with an error.
378 m_log.error("NewID not found in request");
380 mgmtRequest->getID(),
381 StatusCode::REQUESTER, nullptr, "NewID not found in request.",
383 policy->getIssuerMetadata(),
386 m_decoder->isUserAgentPresent()
391 // TODO: maybe support in-place modification of sessions?
393 vector<string> sessions;
395 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
396 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
398 // Now we actually terminate everything except for the active session,
399 // if this is front-channel, for notification purposes.
400 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
401 if (session_id && strcmp(sit->c_str(), session_id))
402 cache->remove(sit->c_str(), application);
404 catch (exception& ex) {
405 m_log.error("error while logging out matching sessions: %s", ex.what());
407 logoutRequest->getID(),
408 StatusCode::RESPONDER, nullptr, ex.what(),
410 policy.getIssuerMetadata(),
413 m_decoder->isUserAgentPresent()
418 // Do back-channel app notifications.
419 // Not supporting front-channel due to privacy concerns.
420 bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
423 mgmtRequest->getID(),
424 worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
428 policy->getIssuerMetadata(),
431 m_decoder->isUserAgentPresent()
435 // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
437 const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
439 if (!policy.isAuthenticated()) {
440 SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
441 if (policy.getIssuerMetadata())
442 annotateException(&ex, policy.getIssuerMetadata()); // throws it
445 checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
447 // Return template for completion.
448 return sendLogoutPage(application, response, false, "Global logout completed.");
452 FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
453 annotateException(&ex, policy->getIssuerMetadata()); // throws it
454 return make_pair(false, 0L); // never happen, satisfies compiler
456 throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
462 pair<bool,long> SAML2NameIDMgmt::sendResponse(
463 const XMLCh* requestID,
465 const XMLCh* subcode,
467 const char* relayState,
468 const RoleDescriptor* role,
469 const Application& application,
470 HTTPResponse& httpResponse,
474 // Get endpoint and encoder to use.
475 const EndpointType* ep = nullptr;
476 const MessageEncoder* encoder = nullptr;
478 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
479 for (vector<string>::const_iterator b = m_bindings.begin(); idp && b != m_bindings.end(); ++b) {
480 auto_ptr_XMLCh wideb(b->c_str());
481 if ((ep = EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(wideb.get()))) {
482 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
483 if (enc != m_encoders.end())
484 encoder = enc->second.get();
488 if (!ep || !encoder) {
489 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
490 m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
491 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
492 annotateException(&ex, role); // throws it
496 encoder = m_encoders.begin()->second.get();
500 auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
501 nim->setInResponseTo(requestID);
503 const XMLCh* loc = ep->getResponseLocation();
505 loc = ep->getLocation();
506 nim->setDestination(loc);
508 Issuer* issuer = IssuerBuilder::buildIssuer();
509 nim->setIssuer(issuer);
510 issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
511 fillStatus(*nim, code, subcode, msg);
513 auto_ptr_char dest(nim->getDestination());
515 long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
516 nim.release(); // freed by encoder
517 return make_pair(true, ret);
520 #include "util/SPConstants.h"
521 #include <xmltooling/impl/AnyElement.h>
522 #include <xmltooling/soap/SOAP.h>
523 #include <xmltooling/soap/SOAPClient.h>
524 #include <xmltooling/soap/HTTPSOAPTransport.h>
525 using namespace soap11;
527 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);
529 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
533 virtual ~SOAPNotifier() {}
535 void prepareTransport(SOAPTransport& transport) {
536 transport.setVerifyHost(false);
537 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
539 http->useChunkedEncoding(false);
540 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
546 bool SAML2NameIDMgmt::notifyBackChannel(
547 const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
550 unsigned int index = 0;
551 string endpoint = application.getNotificationURL(requestURL, false, index++);
552 if (endpoint.empty())
555 scoped_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
556 Body* body = BodyBuilder::buildBody();
558 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
559 body->getUnknownXMLObjects().push_back(msg);
560 msg->getUnknownXMLObjects().push_back(nameid.clone());
562 msg->getUnknownXMLObjects().push_back(newid->clone());
564 msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
568 while (!endpoint.empty()) {
570 soaper.send(*env, SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
571 delete soaper.receive();
573 catch (std::exception& ex) {
574 m_log.error("error notifying application of logout event: %s", ex.what());
578 endpoint = application.getNotificationURL(requestURL, false, index++);