2 * Copyright 2001-2007 Internet2
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * Handles SAML 2.0 NameID management protocol messages.
24 #include "exceptions.h"
25 #include "Application.h"
26 #include "ServiceProvider.h"
27 #include "handler/AbstractHandler.h"
28 #include "handler/RemotedHandler.h"
29 #include "util/SPConstants.h"
32 # include "SessionCache.h"
33 # include "security/SecurityPolicy.h"
34 # include "util/TemplateParameters.h"
36 # include <saml/SAMLConfig.h>
37 # include <saml/saml2/core/Protocols.h>
38 # include <saml/saml2/metadata/EndpointManager.h>
39 # include <saml/saml2/metadata/MetadataCredentialCriteria.h>
40 # include <xmltooling/util/URLEncoder.h>
41 using namespace opensaml::saml2;
42 using namespace opensaml::saml2p;
43 using namespace opensaml::saml2md;
44 using namespace opensaml;
47 using namespace shibsp;
48 using namespace xmltooling;
53 #if defined (_MSC_VER)
54 #pragma warning( push )
55 #pragma warning( disable : 4250 )
58 class SHIBSP_DLLLOCAL SAML2NameIDMgmt : public AbstractHandler, public RemotedHandler
61 SAML2NameIDMgmt(const DOMElement* e, const char* appId);
62 virtual ~SAML2NameIDMgmt() {
64 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
66 XMLString::release(&m_outgoing);
67 for_each(m_encoders.begin(), m_encoders.end(), cleanup_pair<const XMLCh*,MessageEncoder>());
72 void receive(DDF& in, ostream& out);
73 pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
76 void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
77 const char* loc = getString("Location").second;
78 string hurl(handlerURL);
82 auto_ptr_XMLCh widen(hurl.c_str());
83 ManageNameIDService* ep = ManageNameIDServiceBuilder::buildManageNameIDService();
84 ep->setLocation(widen.get());
85 ep->setBinding(getXMLString("Binding").second);
86 role.getManageNameIDServices().push_back(ep);
87 role.addSupport(samlconstants::SAML20P_NS);
90 const char* getType() const {
91 return "ManageNameIDService";
96 pair<bool,long> doRequest(
97 const Application& application, const char* session_id, const HTTPRequest& httpRequest, HTTPResponse& httpResponse
101 bool stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const;
102 bool notifyBackChannel(const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid) const;
104 pair<bool,long> sendResponse(
105 const XMLCh* requestID,
107 const XMLCh* subcode,
109 const char* relayState,
110 const RoleDescriptor* role,
111 const Application& application,
112 HTTPResponse& httpResponse,
117 MessageDecoder* m_decoder;
119 vector<const XMLCh*> m_bindings;
120 map<const XMLCh*,MessageEncoder*> m_encoders;
124 #if defined (_MSC_VER)
125 #pragma warning( pop )
128 Handler* SHIBSP_DLLLOCAL SAML2NameIDMgmtFactory(const pair<const DOMElement*,const char*>& p)
130 return new SAML2NameIDMgmt(p.first, p.second);
134 SAML2NameIDMgmt::SAML2NameIDMgmt(const DOMElement* e, const char* appId)
135 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".NameIDMgmt.SAML2"))
137 ,m_role(samlconstants::SAML20MD_NS, IDPSSODescriptor::LOCAL_NAME), m_decoder(NULL), m_outgoing(NULL)
141 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
142 SAMLConfig& conf = SAMLConfig::getConfig();
144 // Handle incoming binding.
145 m_decoder = conf.MessageDecoderManager.newPlugin(
146 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
148 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
150 if (m_decoder->isUserAgentPresent()) {
151 // Handle front-channel binding setup.
152 pair<bool,const XMLCh*> outgoing = getXMLString("outgoingBindings", m_configNS.get());
153 if (outgoing.first) {
154 m_outgoing = XMLString::replicate(outgoing.second);
155 XMLString::trim(m_outgoing);
158 // No override, so we'll install a default binding precedence.
159 string prec = string(samlconstants::SAML20_BINDING_HTTP_REDIRECT) + ' ' + samlconstants::SAML20_BINDING_HTTP_POST + ' ' +
160 samlconstants::SAML20_BINDING_HTTP_POST_SIMPLESIGN + ' ' + samlconstants::SAML20_BINDING_HTTP_ARTIFACT;
161 m_outgoing = XMLString::transcode(prec.c_str());
165 XMLCh* start = m_outgoing;
166 while (start && *start) {
167 pos = XMLString::indexOf(start,chSpace);
169 *(start + pos)=chNull;
170 m_bindings.push_back(start);
172 auto_ptr_char b(start);
173 MessageEncoder * encoder = conf.MessageEncoderManager.newPlugin(
174 b.get(), pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
176 m_encoders[start] = encoder;
177 m_log.debug("supporting outgoing front-channel binding (%s)", b.get());
179 catch (exception& ex) {
180 m_log.error("error building MessageEncoder: %s", ex.what());
183 start = start + pos + 1;
189 MessageEncoder* encoder = conf.MessageEncoderManager.newPlugin(
190 getString("Binding").second, pair<const DOMElement*,const XMLCh*>(e,shibspconstants::SHIB2SPCONFIG_NS)
192 m_encoders.insert(pair<const XMLCh*,MessageEncoder*>(NULL, encoder));
197 string address(appId);
198 address += getString("Location").second;
199 setAddress(address.c_str());
202 pair<bool,long> SAML2NameIDMgmt::run(SPRequest& request, bool isHandler) const
204 // Get the session_id in case this is a front-channel request.
205 pair<string,const char*> shib_cookie = request.getApplication().getCookieNameProps("_shibsession_");
206 const char* session_id = request.getCookie(shib_cookie.first.c_str());
208 SPConfig& conf = SPConfig::getConfig();
209 if (conf.isEnabled(SPConfig::OutOfProcess)) {
210 // When out of process, we run natively and directly process the message.
211 return doRequest(request.getApplication(), session_id, request, request);
214 // When not out of process, we remote all the message processing.
215 DDF out,in = wrap(request, NULL, true);
216 DDFJanitor jin(in), jout(out);
218 in.addmember("session_id").string(session_id);
219 out=request.getServiceProvider().getListenerService()->send(in);
220 return unwrap(request, out);
224 void SAML2NameIDMgmt::receive(DDF& in, ostream& out)
227 const char* aid=in["application_id"].string();
228 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
230 // Something's horribly wrong.
231 m_log.error("couldn't find application (%s) for NameID mgmt", aid ? aid : "(missing)");
232 throw ConfigurationException("Unable to locate application for NameID mgmt, deleted?");
235 // Unpack the request.
237 DDFJanitor jout(ret);
238 auto_ptr<HTTPRequest> req(getRequest(in));
239 auto_ptr<HTTPResponse> resp(getResponse(ret));
241 // Since we're remoted, the result should either be a throw, which we pass on,
242 // a false/0 return, which we just return as an empty structure, or a response/redirect,
243 // which we capture in the facade and send back.
244 doRequest(*app, in["session_id"].string(), *req.get(), *resp.get());
248 pair<bool,long> SAML2NameIDMgmt::doRequest(
249 const Application& application, const char* session_id, const HTTPRequest& request, HTTPResponse& response
253 SessionCache* cache = application.getServiceProvider().getSessionCache();
255 // Locate policy key.
256 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
258 policyId = application.getString("policyId"); // unqualified in Application(s) element
260 // Access policy properties.
261 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
262 pair<bool,bool> validate = settings->getBool("validate");
264 // Lock metadata for use by policy.
265 Locker metadataLocker(application.getMetadataProvider());
267 // Create the policy.
268 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
270 // Decode the message.
272 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, request, policy));
273 const ManageNameIDRequest* mgmtRequest = dynamic_cast<ManageNameIDRequest*>(msg.get());
275 if (!policy.isAuthenticated())
276 throw SecurityPolicyException("Security of ManageNameIDRequest not established.");
278 // Message from IdP to change or terminate a NameID.
280 // If this is front-channel, we have to have a session_id to use already.
281 if (m_decoder->isUserAgentPresent() && !session_id) {
282 m_log.error("no active session");
284 mgmtRequest->getID(),
285 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "No active session found in request.",
287 policy.getIssuerMetadata(),
294 bool ownedName = false;
295 NameID* nameid = mgmtRequest->getNameID();
297 // Check for EncryptedID.
298 EncryptedID* encname = mgmtRequest->getEncryptedID();
300 CredentialResolver* cr=application.getCredentialResolver();
302 m_log.warn("found encrypted NameID, but no decryption credential was available");
304 Locker credlocker(cr);
305 auto_ptr<MetadataCredentialCriteria> mcc(
306 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
309 auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
310 nameid = dynamic_cast<NameID*>(decryptedID.get());
313 decryptedID.release();
316 catch (exception& ex) {
317 m_log.error(ex.what());
323 // No NameID, so must respond with an error.
324 m_log.error("NameID not found in request");
326 mgmtRequest->getID(),
327 StatusCode::REQUESTER, StatusCode::UNKNOWN_PRINCIPAL, "NameID not found in request.",
329 policy.getIssuerMetadata(),
332 m_decoder->isUserAgentPresent()
336 auto_ptr<NameID> namewrapper(ownedName ? nameid : NULL);
338 // For a front-channel request, we have to match the information in the request
339 // against the current session.
340 EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL;
342 if (!cache->matches(session_id, entity, *nameid, NULL, application)) {
344 mgmtRequest->getID(),
345 StatusCode::REQUESTER, StatusCode::REQUEST_DENIED, "Active session did not match NameID mgmt request.",
347 policy.getIssuerMetadata(),
356 // Determine what's happening...
357 bool ownedNewID = false;
359 if (!mgmtRequest->getTerminate()) {
360 // Better be a NewID in there.
361 newid = mgmtRequest->getNewID();
363 // Check for NewEncryptedID.
364 NewEncryptedID* encnewid = mgmtRequest->getNewEncryptedID();
366 CredentialResolver* cr=application.getCredentialResolver();
368 m_log.warn("found encrypted NewID, but no decryption credential was available");
370 Locker credlocker(cr);
371 auto_ptr<MetadataCredentialCriteria> mcc(
372 policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
375 auto_ptr<XMLObject> decryptedID(encnewid->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
376 newid = dynamic_cast<NewID*>(decryptedID.get());
379 decryptedID.release();
382 catch (exception& ex) {
383 m_log.error(ex.what());
390 // No NewID, so must respond with an error.
391 m_log.error("NewID not found in request");
393 mgmtRequest->getID(),
394 StatusCode::REQUESTER, NULL, "NewID not found in request.",
396 policy.getIssuerMetadata(),
399 m_decoder->isUserAgentPresent()
404 auto_ptr<NewID> newwrapper(ownedNewID ? newid : NULL);
406 // TODO: maybe support in-place modification of sessions?
408 vector<string> sessions;
410 time_t expires = logoutRequest->getNotOnOrAfter() ? logoutRequest->getNotOnOrAfterEpoch() : 0;
411 cache->logout(entity, *nameid, &indexes, expires, application, sessions);
413 // Now we actually terminate everything except for the active session,
414 // if this is front-channel, for notification purposes.
415 for (vector<string>::const_iterator sit = sessions.begin(); sit != sessions.end(); ++sit)
416 if (session_id && strcmp(sit->c_str(), session_id))
417 cache->remove(sit->c_str(), application);
419 catch (exception& ex) {
420 m_log.error("error while logging out matching sessions: %s", ex.what());
422 logoutRequest->getID(),
423 StatusCode::RESPONDER, NULL, ex.what(),
425 policy.getIssuerMetadata(),
428 m_decoder->isUserAgentPresent()
433 // Do back-channel app notifications.
434 // Not supporting front-channel due to privacy fears.
435 bool worked = notifyBackChannel(application, request.getRequestURL(), *nameid, newid);
438 mgmtRequest->getID(),
439 worked ? StatusCode::SUCCESS : StatusCode::RESPONDER,
443 policy.getIssuerMetadata(),
446 m_decoder->isUserAgentPresent()
450 // A ManageNameIDResponse completes an SP-initiated sequence, currently not supported.
452 const ManageNameIDResponse* mgmtResponse = dynamic_cast<ManageNameIDResponse*>(msg.get());
454 if (!policy.isAuthenticated()) {
455 SecurityPolicyException ex("Security of ManageNameIDResponse not established.");
456 if (policy.getIssuerMetadata())
457 annotateException(&ex, policy.getIssuerMetadata()); // throws it
460 checkError(mgmtResponse, policy.getIssuerMetadata()); // throws if Status doesn't look good...
462 // Return template for completion.
463 return sendLogoutPage(application, response, false, "Global logout completed.");
467 FatalProfileException ex("Incoming message was not a samlp:ManageNameIDRequest.");
468 if (policy.getIssuerMetadata())
469 annotateException(&ex, policy.getIssuerMetadata()); // throws it
471 return make_pair(false,0L); // never happen, satisfies compiler
473 throw ConfigurationException("Cannot process NameID mgmt message using lite version of shibsp library.");
479 bool SAML2NameIDMgmt::stronglyMatches(const XMLCh* idp, const XMLCh* sp, const saml2::NameID& n1, const saml2::NameID& n2) const
481 if (!XMLString::equals(n1.getName(), n2.getName()))
484 const XMLCh* s1 = n1.getFormat();
485 const XMLCh* s2 = n2.getFormat();
487 s1 = saml2::NameID::UNSPECIFIED;
489 s2 = saml2::NameID::UNSPECIFIED;
490 if (!XMLString::equals(s1,s2))
493 s1 = n1.getNameQualifier();
494 s2 = n2.getNameQualifier();
499 if (!XMLString::equals(s1,s2))
502 s1 = n1.getSPNameQualifier();
503 s2 = n2.getSPNameQualifier();
508 if (!XMLString::equals(s1,s2))
514 pair<bool,long> SAML2NameIDMgmt::sendResponse(
515 const XMLCh* requestID,
517 const XMLCh* subcode,
519 const char* relayState,
520 const RoleDescriptor* role,
521 const Application& application,
522 HTTPResponse& httpResponse,
526 // Get endpoint and encoder to use.
527 const EndpointType* ep = NULL;
528 const MessageEncoder* encoder = NULL;
530 const IDPSSODescriptor* idp = dynamic_cast<const IDPSSODescriptor*>(role);
531 for (vector<const XMLCh*>::const_iterator b = m_bindings.begin(); idp && b!=m_bindings.end(); ++b) {
532 if (ep=EndpointManager<ManageNameIDService>(idp->getManageNameIDServices()).getByBinding(*b)) {
533 map<const XMLCh*,MessageEncoder*>::const_iterator enc = m_encoders.find(*b);
534 if (enc!=m_encoders.end())
535 encoder = enc->second;
539 if (!ep || !encoder) {
540 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
541 m_log.error("unable to locate compatible NIM service for provider (%s)", id.get());
542 MetadataException ex("Unable to locate endpoint at IdP ($entityID) to send ManageNameIDResponse.");
543 annotateException(&ex, role); // throws it
547 encoder = m_encoders.begin()->second;
551 auto_ptr<ManageNameIDResponse> nim(ManageNameIDResponseBuilder::buildManageNameIDResponse());
552 nim->setInResponseTo(requestID);
554 const XMLCh* loc = ep->getResponseLocation();
556 loc = ep->getLocation();
557 nim->setDestination(loc);
559 Issuer* issuer = IssuerBuilder::buildIssuer();
560 nim->setIssuer(issuer);
561 issuer->setName(application.getXMLString("entityID").second);
562 fillStatus(*nim.get(), code, subcode, msg);
564 auto_ptr_char dest(nim->getDestination());
566 long ret = sendMessage(*encoder, nim.get(), relayState, dest.get(), role, application, httpResponse);
567 nim.release(); // freed by encoder
568 return make_pair(true,ret);
571 #include "util/SPConstants.h"
572 #include <xmltooling/impl/AnyElement.h>
573 #include <xmltooling/soap/SOAP.h>
574 #include <xmltooling/soap/SOAPClient.h>
575 using namespace soap11;
577 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);
579 class SHIBSP_DLLLOCAL SOAPNotifier : public soap11::SOAPClient
583 virtual ~SOAPNotifier() {}
585 void prepareTransport(SOAPTransport& transport) {
586 transport.setVerifyHost(false);
591 bool SAML2NameIDMgmt::notifyBackChannel(
592 const Application& application, const char* requestURL, const NameID& nameid, const NewID* newid
595 unsigned int index = 0;
596 string endpoint = application.getNotificationURL(requestURL, false, index++);
597 if (endpoint.empty())
600 auto_ptr<Envelope> env(EnvelopeBuilder::buildEnvelope());
601 Body* body = BodyBuilder::buildBody();
603 ElementProxy* msg = new AnyElementImpl(shibspconstants::SHIB2SPNOTIFY_NS, NameIDNotification);
604 body->getUnknownXMLObjects().push_back(msg);
605 msg->getUnknownXMLObjects().push_back(nameid.clone());
607 msg->getUnknownXMLObjects().push_back(newid->clone());
609 msg->getUnknownXMLObjects().push_back(TerminateBuilder::buildTerminate());
613 while (!endpoint.empty()) {
615 soaper.send(*env.get(), SOAPTransport::Address(application.getId(), application.getId(), endpoint.c_str()));
616 delete soaper.receive();
618 catch (exception& ex) {
619 m_log.error("error notifying application of logout event: %s", ex.what());
623 endpoint = application.getNotificationURL(requestURL, false, index++);