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;
161 // No override, so we'll install a default binding precedence.
162 dupBindings = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
163 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
166 split(m_bindings, dupBindings, is_space(), algorithm::token_compress_on);
167 for (vector<string>::const_iterator b = m_bindings.begin(); b != m_bindings.end(); ++b) {
169 boost::shared_ptr<MessageEncoder> encoder(
170 conf.MessageEncoderManager.newPlugin(*b, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
172 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
173 m_encoders[*b] = encoder;
174 m_log.debug("supporting outgoing binding (%s)", b->c_str());
177 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b->c_str());
180 catch (std::exception& ex) {
181 m_log.error("error building MessageEncoder: %s", ex.what());
186 pair<bool,const char*> b = getString("Binding");
187 boost::shared_ptr<MessageEncoder> encoder(
188 conf.MessageEncoderManager.newPlugin(b.second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS))
190 m_encoders[b.second] = encoder;
195 string address(appId);
196 address += getString("Location").second;
197 setAddress(address.c_str());
200 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
202 SPConfig& conf = SPConfig::getConfig();
203 if (conf.isEnabled(SPConfig::OutOfProcess)) {
204 // When out of process, we run natively and directly process the message.
205 return doRequest(request.getApplication(), request, request);
208 // When not out of process, we remote all the message processing.
209 vector<string> headers(1,"Cookie");
210 headers.push_back("User-Agent");
211 DDF out,in = wrap(request, &headers, true);
212 DDFJanitor jin(in), jout(out);
213 out=request.getServiceProvider().getListenerService()->send(in);
214 return unwrap(request, out);
218 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
221 const char* aid = in["application_id"].string();
222 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
224 // Something's horribly wrong.
225 m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
226 throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
229 // Unpack the request.
230 scoped_ptr<HTTPRequest> req(getRequest(in));
232 // Wrap a response shim.
234 DDFJanitor jout(ret);
235 scoped_ptr<HTTPResponse> resp(getResponse(ret));
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, *req, *resp);
244 pair<bool,long> SAML2NameIDMgmt::doRequest(const Application& application, const HTTPRequest& request, HTTPResponse& response) const
247 SessionCache* cache = application.getServiceProvider().getSessionCache();
249 // Locate policy key.
250 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // may be namespace-qualified inside handler element
252 policyId = getString("policyId"); // try unqualified
254 policyId = application.getString("policyId"); // unqualified in Application(s) element
256 // Lock metadata for use by policy.
257 Locker metadataLocker(application.getMetadataProvider());
259 // Create the policy.
260 scoped_ptr<SecurityPolicy> policy(
261 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &IDPSSODescriptor::ELEMENT_QNAME, policyId.second)
264 // Decode the message.
266 scoped_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy));
267 const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
269 if (!policy->isAuthenticated())
270 throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
272 // Message from IdP to change or terminate a NameID.
274 // If this is front-channel, we have to have a session_id to use already.
275 string session_id = cache->active(application, request);
276 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
277 m_log.error("no active session");
279 mgmtRequest->getID(),
280 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
282 policy->getIssuerMetadata(),
289 EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
291 scoped_ptr<XMLObject> decryptedID;
292 NameID* nameid = mgmtRequest->getNameID();
294 // Check for EncryptedID.
295 EncryptedID* encname = mgmtRequest->getEncryptedID();
297 CredentialResolver* cr=application.getCredentialResolver();
299 m_log.warn("found encrypted NameID, but no decryption credential was available");
301 Locker credlocker(cr);
302 scoped_ptr<MetadataCredentialCriteria> mcc(
303 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
306 decryptedID.reset(encname->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
307 nameid = dynamic_cast<NameID*>(decryptedID.get());
309 catch (std::exception& ex) {
310 m_log.error(ex.what());
316 // No NameID, so must respond with an error.
317 m_log.error("NameID not found in request");
319 mgmtRequest->getID(),
320 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
322 policy->getIssuerMetadata(),
325 m_decoder->isUserAgentPresent()
329 // For a front-channel request, we have to match the information in the request
330 // against the current session.
331 if (!session_id.empty()) {
332 if (!cache->matches(application, request, entity, *nameid, nullptr)) {
334 mgmtRequest->getID(),
335 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
337 policy->getIssuerMetadata(),
346 // Determine what's happening...
347 scoped_ptr<XMLObject> newDecryptedID;
348 NewID* newid = nullptr;
349 if (!mgmtRequest->getTerminate()) {
350 // Better be a NewID in there.
351 newid = mgmtRequest->getNewID();
353 // Check for NewEncryptedID.
354 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
356 CredentialResolver* cr=application.getCredentialResolver();
358 m_log.warn("found encrypted NewID, but no decryption credential was available");
360 Locker credlocker(cr);
361 scoped_ptr<MetadataCredentialCriteria> mcc(
362 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
365 newDecryptedID.reset(encnewid->decrypt(*cr, application.getRelyingParty(entity)->getXMLString("entityID").second, mcc.get()));
366 newid = dynamic_cast<NewID*>(newDecryptedID.get());
368 catch (std::exception& ex) {
369 m_log.error(ex.what());
376 // No NewID, so must respond with an error.
377 m_log.error("NewID not found in request");
379 mgmtRequest->getID(),
380 StatusCode::REQUESTER, nullptr, "NewID not found in request.",
382 policy->getIssuerMetadata(),
385 m_decoder->isUserAgentPresent()
390 // TODO: maybe support in-place modification of sessions?
392 vector<string> sessions;
394 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
395 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
397 // Now we actually terminate everything except for the active session,
398 // if this is front-channel, for notification purposes.
399 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
400 if (session_id && strcmp(sit->c_str(), session_id))
401 cache->remove(sit->c_str(), application);
403 catch (exception& ex) {
404 m_log.error("error while logging out matching sessions: %s", ex.what());
406 logoutRequest->getID(),
407 StatusCode::RESPONDER, nullptr, ex.what(),
409 policy.getIssuerMetadata(),
412 m_decoder->isUserAgentPresent()
417 // Do back-channel app notifications.
418 // Not supporting front-channel due to privacy concerns.
419 bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
422 mgmtRequest->getID(),
423 worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
427 policy->getIssuerMetadata(),
430 m_decoder->isUserAgentPresent()
434 // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
436 const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
438 if (!policy.isAuthenticated()) {
439 SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
440 if (policy.getIssuerMetadata())
441 annotateException(&ex, policy.getIssuerMetadata()); // throws it
444 checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
446 // Return template for completion.
447 return sendLogoutPage(application, response, false, "Global logout completed.");
451 FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
452 annotateException(&ex, policy->getIssuerMetadata()); // throws it
453 return make_pair(false, 0L); // never happen, satisfies compiler
455 throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
461 pair<bool,long> SAML2NameIDMgmt::sendResponse(
462 const XMLCh* requestID,
464 const XMLCh* subcode,
466 const char* relayState,
467 const RoleDescriptor* role,
468 const Application& application,
469 HTTPResponse& httpResponse,
473 // Get endpoint and encoder to use.
474 const EndpointType* ep = nullptr;
475 const MessageEncoder* encoder = nullptr;
477 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
478 for (vector<string>::const_iterator b = m_bindings.begin(); idp && b != m_bindings.end(); ++b) {
479 auto_ptr_XMLCh wideb(b->c_str());
480 if ((ep = EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(wideb.get()))) {
481 map< string,boost::shared_ptr<MessageEncoder> >::const_iterator enc = m_encoders.find(*b);
482 if (enc != m_encoders.end())
483 encoder = enc->second.get();
487 if (!ep || !encoder) {
488 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
489 m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
490 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
491 annotateException(&ex, role); // throws it
495 encoder = m_encoders.begin()->second.get();
499 auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
500 nim->setInResponseTo(requestID);
502 const XMLCh* loc = ep->getResponseLocation();
504 loc = ep->getLocation();
505 nim->setDestination(loc);
507 Issuer* issuer = IssuerBuilder::buildIssuer();
508 nim->setIssuer(issuer);
509 issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
510 fillStatus(*nim, code, subcode, msg);
512 auto_ptr_char dest(nim->getDestination());
514 long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
515 nim.release(); // freed by encoder
516 return make_pair(true, ret);
519 #include "util/SPConstants.h"
520 #include <xmltooling/impl/AnyElement.h>
521 #include <xmltooling/soap/SOAP.h>
522 #include <xmltooling/soap/SOAPClient.h>
523 #include <xmltooling/soap/HTTPSOAPTransport.h>
524 using namespace soap11;
526 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);
528 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
532 virtual ~SOAPNotifier() {}
534 void prepareTransport(SOAPTransport& transport) {
535 transport.setVerifyHost(false);
536 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
538 http->useChunkedEncoding(false);
539 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
545 bool SAML2NameIDMgmt::notifyBackChannel(
546 const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
549 unsigned int index = 0;
550 string endpoint = application.getNotificationURL(requestURL, false, index++);
551 if (endpoint.empty())
554 scoped_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
555 Body* body = BodyBuilder::buildBody();
557 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
558 body->getUnknownXMLObjects().push_back(msg);
559 msg->getUnknownXMLObjects().push_back(nameid.clone());
561 msg->getUnknownXMLObjects().push_back(newid->clone());
563 msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
567 while (!endpoint.empty()) {
569 soaper.send(*env, SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
570 delete soaper.receive();
572 catch (std::exception& ex) {
573 m_log.error("error notifying application of logout event: %s", ex.what());
577 endpoint = application.getNotificationURL(requestURL, false, index++);