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 "attribute/resolver/AttributeResolver.h"
28 #include "attribute/resolver/ResolutionContext.h"
29 #include "handler/AssertionConsumerService.h"
30 #include "security/SecurityPolicy.h"
31 #include "util/SPConstants.h"
33 #include <saml/SAMLConfig.h>
34 #include <saml/saml1/core/Assertions.h>
35 #include <saml/util/CommonDomainCookie.h>
37 using namespace shibspconstants;
38 using namespace samlconstants;
39 using namespace shibsp;
40 using namespace opensaml;
41 using namespace xmltooling;
42 using namespace log4cpp;
45 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
46 : AbstractHandler(e, log), m_decoder(NULL), m_configNS(SHIB2SPCONFIG_NS),
47 m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
49 string address(appId);
50 address += getString("Location").second;
51 address += "::run::ACS";
52 setAddress(address.c_str());
53 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
54 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
55 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
59 AssertionConsumerService::~AssertionConsumerService()
64 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
67 SPConfig& conf = SPConfig::getConfig();
70 if (conf.isEnabled(SPConfig::OutOfProcess)) {
71 // When out of process, we run natively and directly process the message.
72 // RelayState will be fully handled during message processing.
74 string key = processMessage(request.getApplication(), request, entityID, relayState);
75 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
78 // When not out of process, we remote all the message processing.
79 DDF out,in = wrap(request);
80 DDFJanitor jin(in), jout(out);
82 in.addmember("application_id").string(request.getApplication().getId());
84 out=request.getServiceProvider().getListenerService()->send(in);
86 catch (XMLToolingException& ex) {
87 // Try for RelayState recovery.
88 if (ex.getProperty("RelayState"))
89 relayState = ex.getProperty("RelayState");
91 recoverRelayState(request.getApplication(), request, relayState);
93 catch (exception& ex2) {
94 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
99 // We invoke RelayState recovery one last time on this side of the boundary.
100 if (out["RelayState"].isstring())
101 relayState = out["RelayState"].string();
102 recoverRelayState(request.getApplication(), request, relayState);
104 // If it worked, we have a session key.
105 if (!out["key"].isstring())
106 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
108 // Take care of cookie business and wrap it up.
109 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
112 catch (XMLToolingException& ex) {
113 // Try and preserve RelayState.
114 if (!relayState.empty())
115 ex.addProperty("RelayState", relayState.c_str());
120 void AssertionConsumerService::receive(DDF& in, ostream& out)
123 const char* aid=in["application_id"].string();
124 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
126 // Something's horribly wrong.
127 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
128 throw ConfigurationException("Unable to locate application for new session, deleted?");
131 // Unpack the request.
132 auto_ptr<HTTPRequest> http(getRequest(in));
135 string relayState, entityID;
137 string key = processMessage(*app, *http.get(), entityID, relayState);
139 // Repack for return to caller.
140 DDF ret=DDF(NULL).structure();
141 DDFJanitor jret(ret);
142 ret.addmember("key").string(key.c_str());
143 if (!entityID.empty())
144 ret.addmember("entity_id").string(entityID.c_str());
145 if (!relayState.empty())
146 ret.addmember("RelayState").string(relayState.c_str());
149 catch (XMLToolingException& ex) {
150 // Try and preserve RelayState if we can.
151 if (!relayState.empty())
152 ex.addProperty("RelayState", relayState.c_str());
157 string AssertionConsumerService::processMessage(
158 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
161 // Locate policy key.
162 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
164 policyId = application.getString("policyId"); // unqualified in Application(s) element
166 // Access policy properties.
167 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
168 pair<bool,bool> validate = settings->getBool("validate");
170 // Lock metadata for use by policy.
171 Locker metadataLocker(application.getMetadataProvider());
173 // Create the policy.
174 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
176 // Decode the message and process it in a protocol-specific way.
177 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
179 throw BindingException("Failed to decode an SSO protocol response.");
180 recoverRelayState(application, httpRequest, relayState);
181 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
183 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
185 entityID = issuer.get();
190 pair<bool,long> AssertionConsumerService::sendRedirect(
191 SPRequest& request, const char* key, const char* entityID, const char* relayState
194 // We've got a good session, so set the session cookie.
195 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
197 k += shib_cookie.second;
198 request.setCookie(shib_cookie.first.c_str(), k.c_str());
201 maintainHistory(request, entityID, shib_cookie.second);
203 // Now redirect to the state value. By now, it should be set to *something* usable.
204 return make_pair(true, request.sendRedirect(relayState));
207 void AssertionConsumerService::checkAddress(
208 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
211 const PropertySet* props=application.getPropertySet("Sessions");
212 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
213 if (!checkAddress.first)
214 checkAddress.second=true;
216 if (checkAddress.second) {
217 m_log.debug("checking client address");
218 if (httpRequest.getRemoteAddr() != issuedTo) {
219 throw FatalProfileException(
220 "Your client's current address ($client_addr) differs from the one used when you authenticated "
221 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
222 "Please contact your local support staff or help desk for assistance.",
223 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
229 ResolutionContext* AssertionConsumerService::resolveAttributes(
230 const Application& application,
231 const saml2md::EntityDescriptor* issuer,
232 const saml2::NameID* nameid,
233 const char* authncontext_class,
234 const char* authncontext_decl,
235 const vector<const Assertion*>* tokens,
236 const multimap<string,Attribute*>* attributes
240 AttributeResolver* resolver = application.getAttributeResolver();
242 m_log.info("no AttributeResolver available, skipping resolution");
246 m_log.debug("resolving attributes...");
248 Locker locker(resolver);
249 auto_ptr<ResolutionContext> ctx(
250 resolver->createResolutionContext(application, issuer, nameid, authncontext_class, authncontext_decl, tokens, attributes)
252 resolver->resolveAttributes(*ctx.get());
253 return ctx.release();
255 catch (exception& ex) {
256 m_log.error("attribute resolution failed: %s", ex.what());
262 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
267 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
268 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
269 if (!idpHistory.first || idpHistory.second) {
270 // Set an IdP history cookie locally (essentially just a CDC).
271 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
273 // Either leave in memory or set an expiration.
274 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
275 if (!days.first || days.second==0) {
276 string c = string(cdc.set(entityID)) + cookieProps;
277 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
280 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
283 struct tm* ptime=gmtime_r(&now,&res);
285 struct tm* ptime=gmtime(&now);
288 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
289 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
290 request.setCookie(CommonDomainCookie::CDCName, c.c_str());