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 <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;
53 # include "lite/SAMLConstants.h"
56 using namespace shibsp;
57 using namespace xmltooling;
62 #if defined (_MSC_VER)
63 #pragma warning( push )
64 #pragma warning( disable : 4250 )
67 class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
70 SAML2NameIDMgmt(const DOMElement* e, const char* appId);
71 virtual ~SAML2NameIDMgmt() {
73 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
75 XMLString::release(&m_outgoing);
76 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
81 void receive(DDF& in, ostream& out);
82 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
85 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
86 const char* loc = getString("Location").second;
87 string hurl(handlerURL);
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);
99 const char* getType() const {
100 return "ManageNameIDService";
103 const XMLCh* getProtocolFamily() const {
104 return samlconstants::SAML20P_NS;
108 pair<bool,long> doRequest(const Application& application, const HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
111 bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
113 pair<bool,long> sendResponse(
114 const XMLCh* requestID,
116 const XMLCh* subcode,
118 const char* relayState,
119 const RoleDescriptor* role,
120 const Application& application,
121 HTTPResponse& httpResponse,
125 xmltooling::QName m_role;
126 MessageDecoder* m_decoder;
128 vector<const XMLCh*> m_bindings;
129 map<const XMLCh*,MessageEncoder*> m_encoders;
133 #if defined (_MSC_VER)
134 #pragma warning( pop )
137 Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
139 return new SAML2NameIDMgmt(p.first, p.second);
143 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
144 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
146 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(nullptr), m_outgoing(nullptr)
150 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
151 SAMLConfig& conf = SAMLConfig::getConfig();
153 // Handle incoming binding.
154 m_decoder = conf.MessageDecoderManager.newPlugin(
155 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
157 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
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);
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());
174 XMLCh* start = m_outgoing;
175 while (start && *start) {
176 pos = XMLString::indexOf(start,chSpace);
178 *(start + pos)=chNull;
179 m_bindings.push_back(start);
181 auto_ptr_char b(start);
182 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
183 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
185 if (encoder->isUserAgentPresent() && XMLString::equals(getProtocolFamily(), encoder->getProtocolFamily())) {
186 m_encoders[start] = encoder;
187 m_log.debug("supporting outgoing binding (%s)", b.get());
191 m_log.warn("skipping outgoing binding (%s), not a SAML 2.0 front-channel mechanism", b.get());
194 catch (exception& ex) {
195 m_log.error("error building MessageEncoder: %s", ex.what());
198 start = start + pos + 1;
204 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
205 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
207 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(nullptr, encoder));
212 string address(appId);
213 address += getString("Location").second;
214 setAddress(address.c_str());
217 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
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);
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);
235 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
238 const char* aid=in["application_id"].string();
239 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
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?");
246 // Unpack the request.
247 auto_ptr<HTTPRequest> req(getRequest(in));
249 // Wrap a response shim.
251 DDFJanitor jout(ret);
252 auto_ptr<HTTPResponse> resp(getResponse(ret));
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());
261 pair<bool,long> SAML2NameIDMgmt::doRequest(
262 const Application& application, const HTTPRequest& request, HTTPResponse& response
266 SessionCache* cache = application.getServiceProvider().getSessionCache();
268 // Locate policy key.
269 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
271 policyId = application.getString("policyId"); // unqualified in Application(s) element
273 // Lock metadata for use by policy.
274 Locker metadataLocker(application.getMetadataProvider());
276 // Create the policy.
277 auto_ptr<SecurityPolicy> policy(
278 application.getServiceProvider().getSecurityPolicyProvider()->createSecurityPolicy(application, &m_role, policyId.second)
281 // Decode the message.
283 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, *policy.get()));
284 const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
286 if (!policy->isAuthenticated())
287 throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
289 // Message from IdP to change or terminate a NameID.
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");
296 mgmtRequest->getID(),
297 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
299 policy->getIssuerMetadata(),
306 EntityDescriptor* entity = policy->getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy->getIssuerMetadata()->getParent()) : nullptr;
308 bool ownedName = false;
309 NameID* nameid = mgmtRequest->getNameID();
311 // Check for EncryptedID.
312 EncryptedID* encname = mgmtRequest->getEncryptedID();
314 CredentialResolver* cr=application.getCredentialResolver();
316 m_log.warn("found encrypted NameID, but no decryption credential was available");
318 Locker credlocker(cr);
319 auto_ptr<MetadataCredentialCriteria> mcc(
320 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
323 auto_ptr<XMLObject> decryptedID(
324 encname->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
326 nameid = dynamic_cast<NameID*>(decryptedID.get());
329 decryptedID.release();
332 catch (exception& ex) {
333 m_log.error(ex.what());
339 // No NameID, so must respond with an error.
340 m_log.error("NameID not found in request");
342 mgmtRequest->getID(),
343 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
345 policy->getIssuerMetadata(),
348 m_decoder->isUserAgentPresent()
352 auto_ptr<NameID> namewrapper(ownedName ? nameid : nullptr);
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)) {
359 mgmtRequest->getID(),
360 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
362 policy->getIssuerMetadata(),
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();
378 // Check for NewEncryptedID.
379 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
381 CredentialResolver* cr=application.getCredentialResolver();
383 m_log.warn("found encrypted NewID, but no decryption credential was available");
385 Locker credlocker(cr);
386 auto_ptr<MetadataCredentialCriteria> mcc(
387 policy->getIssuerMetadata() ? new MetadataCredentialCriteria(*policy->getIssuerMetadata()) : nullptr
390 auto_ptr<XMLObject> decryptedID(
391 encnewid->decrypt(*cr,application.getRelyingParty(entity)->getXMLString("entityID").second,mcc.get())
393 newid = dynamic_cast<NewID*>(decryptedID.get());
396 decryptedID.release();
399 catch (exception& ex) {
400 m_log.error(ex.what());
407 // No NewID, so must respond with an error.
408 m_log.error("NewID not found in request");
410 mgmtRequest->getID(),
411 StatusCode::REQUESTER, nullptr, "NewID not found in request.",
413 policy->getIssuerMetadata(),
416 m_decoder->isUserAgentPresent()
421 auto_ptr<NewID> newwrapper(ownedNewID ? newid : nullptr);
423 // TODO: maybe support in-place modification of sessions?
425 vector<string> sessions;
427 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
428 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
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);
436 catch (exception& ex) {
437 m_log.error("error while logging out matching sessions: %s", ex.what());
439 logoutRequest->getID(),
440 StatusCode::RESPONDER, nullptr, ex.what(),
442 policy.getIssuerMetadata(),
445 m_decoder->isUserAgentPresent()
450 // Do back-channel app notifications.
451 // Not supporting front-channel due to privacy fears.
452 bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
455 mgmtRequest->getID(),
456 worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
460 policy->getIssuerMetadata(),
463 m_decoder->isUserAgentPresent()
467 // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
469 const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
471 if (!policy.isAuthenticated()) {
472 SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
473 if (policy.getIssuerMetadata())
474 annotateException(&ex, policy.getIssuerMetadata()); // throws it
477 checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
479 // Return template for completion.
480 return sendLogoutPage(application, response, false, "Global logout completed.");
484 FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
485 if (policy->getIssuerMetadata())
486 annotateException(&ex, policy->getIssuerMetadata()); // throws it
488 return make_pair(false,0L); // never happen, satisfies compiler
490 throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
496 pair<bool,long> SAML2NameIDMgmt::sendResponse(
497 const XMLCh* requestID,
499 const XMLCh* subcode,
501 const char* relayState,
502 const RoleDescriptor* role,
503 const Application& application,
504 HTTPResponse& httpResponse,
508 // Get endpoint and encoder to use.
509 const EndpointType* ep = nullptr;
510 const MessageEncoder* encoder = nullptr;
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;
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
529 encoder = m_encoders.begin()->second;
533 auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
534 nim->setInResponseTo(requestID);
536 const XMLCh* loc = ep->getResponseLocation();
538 loc = ep->getLocation();
539 nim->setDestination(loc);
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);
546 auto_ptr_char dest(nim->getDestination());
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);
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;
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);
562 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
566 virtual ~SOAPNotifier() {}
568 void prepareTransport(SOAPTransport& transport) {
569 transport.setVerifyHost(false);
570 HTTPSOAPTransport* http = dynamic_cast<HTTPSOAPTransport*>(&transport);
572 http->useChunkedEncoding(false);
573 http->setRequestHeader("User-Agent", PACKAGE_NAME);
574 http->setRequestHeader(PACKAGE_NAME, PACKAGE_VERSION);
580 bool SAML2NameIDMgmt::notifyBackChannel(
581 const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
584 unsigned int index = 0;
585 string endpoint = application.getNotificationURL(requestURL, false, index++);
586 if (endpoint.empty())
589 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
590 Body* body = BodyBuilder::buildBody();
592 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
593 body->getUnknownXMLObjects().push_back(msg);
594 msg->getUnknownXMLObjects().push_back(nameid.clone());
596 msg->getUnknownXMLObjects().push_back(newid->clone());
598 msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
602 while (!endpoint.empty()) {
604 soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
605 delete soaper.receive();
607 catch (exception& ex) {
608 m_log.error("error notifying application of logout event: %s", ex.what());
612 endpoint = application.getNotificationURL(requestURL, false, index++);