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"
40 # include "util/TemplateParameters.h"
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;
54 # include "lite/SAMLConstants.h"
57 using namespace shibsp;
58 using namespace xmltooling;
63 #if defined (_MSC_VER)
64 #pragma warning( push )
65 #pragma warning( disable : 4250 )
68 class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
71 SAML2NameIDMgmt(const DOMElement* e, const char* appId);
72 virtual ~SAML2NameIDMgmt() {
74 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
76 XMLString::release(&m_outgoing);
77 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
82 void receive(DDF& in, ostream& out);
83 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
86 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
87 const char* loc = getString("Location").second;
88 string hurl(handlerURL);
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);
100 const char* getType() const {
101 return "ManageNameIDService";
104 const XMLCh* getProtocolFamily() const {
105 return samlconstants::SAML20P_NS;
109 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
112 bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
114 pair<bool,long> sendResponse(
115 const XMLCh* requestID,
117 const XMLCh* subcode,
119 const char* relayState,
120 const RoleDescriptor* role,
121 const Application& application,
122 HTTPResponse& httpResponse,
126 xmltooling::QName m_role;
127 MessageDecoder* m_decoder;
129 vector<const XMLCh*> m_bindings;
130 map<const XMLCh*,MessageEncoder*> m_encoders;
134 #if defined (_MSC_VER)
135 #pragma warning( pop )
138 Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
140 return new SAML2NameIDMgmt(p.first, p.second);
144 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
145 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
147 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(nullptr), m_outgoing(nullptr)
151 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
152 SAMLConfig& conf = SAMLConfig::getConfig();
154 // Handle incoming binding.
155 m_decoder = conf.MessageDecoderManager.newPlugin(
156 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
158 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
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);
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());
175 XMLCh* start = m_outgoing;
176 while (start && *start) {
177 pos = XMLString::indexOf(start,chSpace);
179 *(start + pos)=chNull;
180 m_bindings.push_back(start);
182 auto_ptr_char b(start);
183 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
184 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
186 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
187 m_encoders[start] = encoder;
188 m_log.debug("supporting outgoing binding (%s)", b.get());
192 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b.get());
195 catch (exception& ex) {
196 m_log.error("error building MessageEncoder: %s", ex.what());
199 start = start + pos + 1;
205 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
206 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
208 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(nullptr, encoder));
213 string address(appId);
214 address += getString("Location").second;
215 setAddress(address.c_str());
218 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
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);
226 // When not out of process, we remote all the message processing.
227 vector<string> headers(1,"Cookie");
228 headers.push_back("User-Agent");
229 DDF out,in = wrap(request, &headers, true);
230 DDFJanitor jin(in), jout(out);
231 out=request.getServiceProvider().getListenerService()->send(in);
232 return unwrap(request, out);
236 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
239 const char* aid=in["application_id"].string();
240 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
242 // Something's horribly wrong.
243 m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
244 throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
247 // Unpack the request.
248 auto_ptr<HTTPRequest> req(getRequest(in));
250 // Wrap a response shim.
252 DDFJanitor jout(ret);
253 auto_ptr<HTTPResponse> resp(getResponse(ret));
255 // Since we're remoted, the result should either be a throw, which we pass on,
256 // a false/0 return, which we just return as an empty structure, or a response/redirect,
257 // which we capture in the facade and send back.
258 doRequest(*app, *req.get(), *resp.get());
262 pair<bool,long> SAML2NameIDMgmt::doRequest(
263 const Application& application, const HTTPRequest& request, HTTPResponse& response
267 SessionCache* cache = application.getServiceProvider().getSessionCache();
269 // Locate policy key.
270 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
272 policyId = application.getString("policyId"); // unqualified in Application(s) element
274 // Lock metadata for use by policy.
275 Locker metadataLocker(application.getMetadataProvider());
277 // Create the policy.
278 auto_ptr<SecurityPolicy> policy(
279 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
282 // Decode the message.
284 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy.get()));
285 const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
287 if (!policy->isAuthenticated())
288 throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
290 // Message from IdP to change or terminate a NameID.
292 // If this is front-channel, we have to have a session_id to use already.
293 string session_id = cache->active(application, request);
294 if (m_decoder->isUserAgentPresent() && session_id.empty()) {
295 m_log.error("no active session");
297 mgmtRequest->getID(),
298 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
300 policy->getIssuerMetadata(),
307 EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
309 bool ownedName = false;
310 NameID* nameid = mgmtRequest->getNameID();
312 // Check for EncryptedID.
313 EncryptedID* encname = mgmtRequest->getEncryptedID();
315 CredentialResolver* cr=application.getCredentialResolver();
317 m_log.warn("found encrypted NameID, but no decryption credential was available");
319 Locker credlocker(cr);
320 auto_ptr<MetadataCredentialCriteria> mcc(
321 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
324 auto_ptr<XMLObject> decryptedID(
325 encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
327 nameid = dynamic_cast<NameID*>(decryptedID.get());
330 decryptedID.release();
333 catch (exception& ex) {
334 m_log.error(ex.what());
340 // No NameID, so must respond with an error.
341 m_log.error("NameID not found in request");
343 mgmtRequest->getID(),
344 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
346 policy->getIssuerMetadata(),
349 m_decoder->isUserAgentPresent()
353 auto_ptr<NameID> namewrapper(ownedName ? nameid : nullptr);
355 // For a front-channel request, we have to match the information in the request
356 // against the current session.
357 if (!session_id.empty()) {
358 if (!cache->matches(application, request, entity, *nameid, nullptr)) {
360 mgmtRequest->getID(),
361 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
363 policy->getIssuerMetadata(),
372 // Determine what's happening...
373 bool ownedNewID = false;
374 NewID* newid = nullptr;
375 if (!mgmtRequest->getTerminate()) {
376 // Better be a NewID in there.
377 newid = mgmtRequest->getNewID();
379 // Check for NewEncryptedID.
380 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
382 CredentialResolver* cr=application.getCredentialResolver();
384 m_log.warn("found encrypted NewID, but no decryption credential was available");
386 Locker credlocker(cr);
387 auto_ptr<MetadataCredentialCriteria> mcc(
388 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
391 auto_ptr<XMLObject> decryptedID(
392 encnewid->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
394 newid = dynamic_cast<NewID*>(decryptedID.get());
397 decryptedID.release();
400 catch (exception& ex) {
401 m_log.error(ex.what());
408 // No NewID, so must respond with an error.
409 m_log.error("NewID not found in request");
411 mgmtRequest->getID(),
412 StatusCode::REQUESTER, nullptr, "NewID not found in request.",
414 policy->getIssuerMetadata(),
417 m_decoder->isUserAgentPresent()
422 auto_ptr<NewID> newwrapper(ownedNewID ? newid : nullptr);
424 // TODO: maybe support in-place modification of sessions?
426 vector<string> sessions;
428 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
429 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
431 // Now we actually terminate everything except for the active session,
432 // if this is front-channel, for notification purposes.
433 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
434 if (session_id && strcmp(sit->c_str(), session_id))
435 cache->remove(sit->c_str(), application);
437 catch (exception& ex) {
438 m_log.error("error while logging out matching sessions: %s", ex.what());
440 logoutRequest->getID(),
441 StatusCode::RESPONDER, nullptr, ex.what(),
443 policy.getIssuerMetadata(),
446 m_decoder->isUserAgentPresent()
451 // Do back-channel app notifications.
452 // Not supporting front-channel due to privacy fears.
453 bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
456 mgmtRequest->getID(),
457 worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
461 policy->getIssuerMetadata(),
464 m_decoder->isUserAgentPresent()
468 // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
470 const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
472 if (!policy.isAuthenticated()) {
473 SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
474 if (policy.getIssuerMetadata())
475 annotateException(&ex, policy.getIssuerMetadata()); // throws it
478 checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
480 // Return template for completion.
481 return sendLogoutPage(application, response, false, "Global logout completed.");
485 FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
486 if (policy->getIssuerMetadata())
487 annotateException(&ex, policy->getIssuerMetadata()); // throws it
489 return make_pair(false,0L); // never happen, satisfies compiler
491 throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
497 pair<bool,long> SAML2NameIDMgmt::sendResponse(
498 const XMLCh* requestID,
500 const XMLCh* subcode,
502 const char* relayState,
503 const RoleDescriptor* role,
504 const Application& application,
505 HTTPResponse& httpResponse,
509 // Get endpoint and encoder to use.
510 const EndpointType* ep = nullptr;
511 const MessageEncoder* encoder = nullptr;
513 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
514 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
515 if (ep=EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(*b)) {
516 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
517 if (enc!=m_encoders.end())
518 encoder = enc->second;
522 if (!ep || !encoder) {
523 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
524 m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
525 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
526 annotateException(&ex, role); // throws it
530 encoder = m_encoders.begin()->second;
534 auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
535 nim->setInResponseTo(requestID);
537 const XMLCh* loc = ep->getResponseLocation();
539 loc = ep->getLocation();
540 nim->setDestination(loc);
542 Issuer* issuer = IssuerBuilder::buildIssuer();
543 nim->setIssuer(issuer);
544 issuer->setName(application.getRelyingParty(dynamic_cast<EntityDescriptor*>(role->getParent()))->getXMLString("entityID").second);
545 fillStatus(*nim.get(), code, subcode, msg);
547 auto_ptr_char dest(nim->getDestination());
549 long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
550 nim.release(); // freed by encoder
551 return make_pair(true,ret);
554 #include "util/SPConstants.h"
555 #include <xmltooling/impl/AnyElement.h>
556 #include <xmltooling/soap/SOAP.h>
557 #include <xmltooling/soap/SOAPClient.h>
558 #include <xmltooling/soap/HTTPSOAPTransport.h>
559 using namespace soap11;
561 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);
563 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
567 virtual ~SOAPNotifier() {}
569 void prepareTransport(SOAPTransport& transport) {
570 transport.setVerifyHost(false);
571 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
573 http->useChunkedEncoding(false);
574 http->setRequestHeader("User-Agent", PACKAGE_NAME);
575 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
581 bool SAML2NameIDMgmt::notifyBackChannel(
582 const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
585 unsigned int index = 0;
586 string endpoint = application.getNotificationURL(requestURL, false, index++);
587 if (endpoint.empty())
590 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
591 Body* body = BodyBuilder::buildBody();
593 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
594 body->getUnknownXMLObjects().push_back(msg);
595 msg->getUnknownXMLObjects().push_back(nameid.clone());
597 msg->getUnknownXMLObjects().push_back(newid->clone());
599 msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
603 while (!endpoint.empty()) {
605 soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
606 delete soaper.receive();
608 catch (exception& ex) {
609 m_log.error("error notifying application of logout event: %s", ex.what());
613 endpoint = application.getNotificationURL(requestURL, false, index++);