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.
18 * AssertionConsumerService.cpp
20 * Base class for handlers that create sessions by consuming SSO protocol responses.
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
32 # include "attribute/Attribute.h"
33 # include "attribute/filtering/AttributeFilter.h"
34 # include "attribute/filtering/BasicFilteringContext.h"
35 # include "attribute/resolver/AttributeExtractor.h"
36 # include "attribute/resolver/AttributeResolver.h"
37 # include "attribute/resolver/ResolutionContext.h"
38 # include "security/SecurityPolicy.h"
39 # include <saml/SAMLConfig.h>
40 # include <saml/saml1/core/Assertions.h>
41 # include <saml/util/CommonDomainCookie.h>
42 using namespace samlconstants;
43 using opensaml::saml2md::EntityDescriptor;
44 using opensaml::saml2md::IDPSSODescriptor;
46 # include "lite/CommonDomainCookie.h"
49 using namespace shibspconstants;
50 using namespace shibsp;
51 using namespace opensaml;
52 using namespace xmltooling;
55 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
56 : AbstractHandler(e, log)
58 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
63 string address(appId);
64 address += getString("Location").second;
65 setAddress(address.c_str());
67 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
68 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
69 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
71 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
76 AssertionConsumerService::~AssertionConsumerService()
83 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
86 SPConfig& conf = SPConfig::getConfig();
89 if (conf.isEnabled(SPConfig::OutOfProcess)) {
90 // When out of process, we run natively and directly process the message.
91 // RelayState will be fully handled during message processing.
93 string key = processMessage(request.getApplication(), request, entityID, relayState);
94 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
97 // When not out of process, we remote all the message processing.
98 DDF out,in = wrap(request);
99 DDFJanitor jin(in), jout(out);
102 out=request.getServiceProvider().getListenerService()->send(in);
104 catch (XMLToolingException& ex) {
105 // Try for RelayState recovery.
106 if (ex.getProperty("RelayState"))
107 relayState = ex.getProperty("RelayState");
109 recoverRelayState(request.getApplication(), request, relayState);
111 catch (exception& ex2) {
112 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
117 // We invoke RelayState recovery one last time on this side of the boundary.
118 if (out["RelayState"].isstring())
119 relayState = out["RelayState"].string();
120 recoverRelayState(request.getApplication(), request, relayState);
122 // If it worked, we have a session key.
123 if (!out["key"].isstring())
124 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
126 // Take care of cookie business and wrap it up.
127 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
130 catch (XMLToolingException& ex) {
131 // Try and preserve RelayState.
132 if (!relayState.empty())
133 ex.addProperty("RelayState", relayState.c_str());
138 void AssertionConsumerService::receive(DDF& in, ostream& out)
141 const char* aid=in["application_id"].string();
142 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
144 // Something's horribly wrong.
145 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
146 throw ConfigurationException("Unable to locate application for new session, deleted?");
149 // Unpack the request.
150 auto_ptr<HTTPRequest> http(getRequest(in));
153 string relayState, entityID;
155 string key = processMessage(*app, *http.get(), entityID, relayState);
157 // Repack for return to caller.
158 DDF ret=DDF(NULL).structure();
159 DDFJanitor jret(ret);
160 ret.addmember("key").string(key.c_str());
161 if (!entityID.empty())
162 ret.addmember("entity_id").string(entityID.c_str());
163 if (!relayState.empty())
164 ret.addmember("RelayState").string(relayState.c_str());
167 catch (XMLToolingException& ex) {
168 // Try and preserve RelayState if we can.
169 if (!relayState.empty())
170 ex.addProperty("RelayState", relayState.c_str());
175 string AssertionConsumerService::processMessage(
176 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
180 // Locate policy key.
181 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
183 policyId = application.getString("policyId"); // unqualified in Application(s) element
185 // Access policy properties.
186 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
187 pair<bool,bool> validate = settings->getBool("validate");
189 // Lock metadata for use by policy.
190 Locker metadataLocker(application.getMetadataProvider());
192 // Create the policy.
193 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
195 // Decode the message and process it in a protocol-specific way.
196 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
198 throw BindingException("Failed to decode an SSO protocol response.");
199 recoverRelayState(application, httpRequest, relayState);
200 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
202 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
204 entityID = issuer.get();
208 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
212 pair<bool,long> AssertionConsumerService::sendRedirect(
213 SPRequest& request, const char* key, const char* entityID, const char* relayState
216 // We've got a good session, so set the session cookie.
217 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
219 k += shib_cookie.second;
220 request.setCookie(shib_cookie.first.c_str(), k.c_str());
223 maintainHistory(request, entityID, shib_cookie.second);
225 // Now redirect to the state value. By now, it should be set to *something* usable.
226 return make_pair(true, request.sendRedirect(relayState));
229 void AssertionConsumerService::checkAddress(
230 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
233 const PropertySet* props=application.getPropertySet("Sessions");
234 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
235 if (!checkAddress.first)
236 checkAddress.second=true;
238 if (checkAddress.second) {
239 m_log.debug("checking client address");
240 if (httpRequest.getRemoteAddr() != issuedTo) {
241 throw FatalProfileException(
242 "Your client's current address ($client_addr) differs from the one used when you authenticated "
243 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
244 "Please contact your local support staff or help desk for assistance.",
245 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
253 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
256 DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
259 virtual ~DummyContext() {
260 for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
263 vector<Attribute*>& getResolvedAttributes() {
266 vector<Assertion*>& getResolvedAssertions() {
271 vector<Attribute*> m_attributes;
272 static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
275 vector<Assertion*> DummyContext::m_tokens;
277 ResolutionContext* AssertionConsumerService::resolveAttributes(
278 const Application& application,
279 const saml2md::RoleDescriptor* issuer,
280 const XMLCh* protocol,
281 const saml1::NameIdentifier* v1nameid,
282 const saml2::NameID* nameid,
283 const XMLCh* authncontext_class,
284 const XMLCh* authncontext_decl,
285 const vector<const Assertion*>* tokens
288 const saml2md::EntityDescriptor* entity = issuer ? dynamic_cast<const saml2md::EntityDescriptor*>(issuer->getParent()) : NULL;
290 // First we do the extraction of any pushed information, including from metadata.
291 vector<Attribute*> resolvedAttributes;
292 AttributeExtractor* extractor = application.getAttributeExtractor();
294 Locker extlocker(extractor);
296 pair<bool,const char*> prefix = application.getString("metadataAttributePrefix");
298 m_log.debug("extracting metadata-derived attributes...");
300 extractor->extractAttributes(application, issuer, *entity, resolvedAttributes);
301 for (vector<Attribute*>::iterator a = resolvedAttributes.begin(); a != resolvedAttributes.end(); ++a) {
302 vector<string>& ids = (*a)->getAliases();
303 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
304 *id = prefix.second + *id;
307 catch (exception& ex) {
308 m_log.error("caught exception extracting attributes: %s", ex.what());
312 m_log.debug("extracting pushed attributes...");
315 extractor->extractAttributes(application, issuer, *v1nameid, resolvedAttributes);
317 catch (exception& ex) {
318 m_log.error("caught exception extracting attributes: %s", ex.what());
323 extractor->extractAttributes(application, issuer, *nameid, resolvedAttributes);
325 catch (exception& ex) {
326 m_log.error("caught exception extracting attributes: %s", ex.what());
330 for (vector<const Assertion*>::const_iterator t = tokens->begin(); t!=tokens->end(); ++t) {
332 extractor->extractAttributes(application, issuer, *(*t), resolvedAttributes);
334 catch (exception& ex) {
335 m_log.error("caught exception extracting attributes: %s", ex.what());
340 AttributeFilter* filter = application.getAttributeFilter();
341 if (filter && !resolvedAttributes.empty()) {
342 BasicFilteringContext fc(application, resolvedAttributes, issuer, authncontext_class);
343 Locker filtlocker(filter);
345 filter->filterAttributes(fc, resolvedAttributes);
347 catch (exception& ex) {
348 m_log.error("caught exception filtering attributes: %s", ex.what());
349 m_log.error("dumping extracted attributes due to filtering exception");
350 for_each(resolvedAttributes.begin(), resolvedAttributes.end(), xmltooling::cleanup<shibsp::Attribute>());
351 resolvedAttributes.clear();
357 AttributeResolver* resolver = application.getAttributeResolver();
359 m_log.debug("resolving attributes...");
361 Locker locker(resolver);
362 auto_ptr<ResolutionContext> ctx(
363 resolver->createResolutionContext(
374 resolver->resolveAttributes(*ctx.get());
375 // Copy over any pushed attributes.
376 if (!resolvedAttributes.empty())
377 ctx->getResolvedAttributes().insert(ctx->getResolvedAttributes().end(), resolvedAttributes.begin(), resolvedAttributes.end());
378 return ctx.release();
381 catch (exception& ex) {
382 m_log.error("attribute resolution failed: %s", ex.what());
385 if (!resolvedAttributes.empty())
386 return new DummyContext(resolvedAttributes);
390 void AssertionConsumerService::extractMessageDetails(const Assertion& assertion, const XMLCh* protocol, opensaml::SecurityPolicy& policy) const
392 policy.setMessageID(assertion.getID());
393 policy.setIssueInstant(assertion.getIssueInstantEpoch());
395 if (XMLString::equals(assertion.getElementQName().getNamespaceURI(), samlconstants::SAML20P_NS)) {
396 const saml2::Assertion* a2 = dynamic_cast<const saml2::Assertion*>(&assertion);
398 m_log.debug("extracting issuer from SAML 2.0 assertion");
399 policy.setIssuer(a2->getIssuer());
403 const saml1::Assertion* a1 = dynamic_cast<const saml1::Assertion*>(&assertion);
405 m_log.debug("extracting issuer from SAML 1.x assertion");
406 policy.setIssuer(a1->getIssuer());
410 if (policy.getIssuer() && !policy.getIssuerMetadata() && policy.getMetadataProvider()) {
411 m_log.debug("searching metadata for assertion issuer...");
412 const EntityDescriptor* entity = policy.getMetadataProvider()->getEntityDescriptor(policy.getIssuer()->getName());
\r
414 m_log.debug("matched assertion issuer against metadata, searching for applicable role...");
\r
415 const IDPSSODescriptor* idp=entity->getIDPSSODescriptor(protocol);
\r
417 policy.setIssuerMetadata(idp);
\r
418 else if (m_log.isWarnEnabled())
\r
419 m_log.warn("unable to find compatible IdP role in metadata");
\r
421 else if (m_log.isWarnEnabled()) {
\r
422 auto_ptr_char iname(policy.getIssuer()->getName());
\r
423 m_log.warn("no metadata found, can't establish identity of issuer (%s)", iname.get());
\r
430 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
435 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
436 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
437 if (!idpHistory.first || idpHistory.second) {
438 // Set an IdP history cookie locally (essentially just a CDC).
439 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
441 // Either leave in memory or set an expiration.
442 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
443 if (!days.first || days.second==0) {
444 string c = string(cdc.set(entityID)) + cookieProps;
445 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
448 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
451 struct tm* ptime=gmtime_r(&now,&res);
453 struct tm* ptime=gmtime(&now);
456 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
457 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
458 request.setCookie(CommonDomainCookie::CDCName, c.c_str());