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/resolver/AttributeResolver.h"
33 # include "attribute/resolver/ResolutionContext.h"
34 # include "security/SecurityPolicy.h"
35 # include <saml/SAMLConfig.h>
36 # include <saml/saml1/core/Assertions.h>
37 # include <saml/util/CommonDomainCookie.h>
38 using namespace samlconstants;
40 # include "lite/CommonDomainCookie.h"
43 using namespace shibspconstants;
44 using namespace shibsp;
45 using namespace opensaml;
46 using namespace xmltooling;
49 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
50 : AbstractHandler(e, log)
52 ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
55 string address(appId);
56 address += getString("Location").second;
57 setAddress(address.c_str());
59 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
60 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(
61 getString("Binding").second,make_pair(e,shibspconstants::SHIB2SPCONFIG_NS)
63 m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
68 AssertionConsumerService::~AssertionConsumerService()
75 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
78 SPConfig& conf = SPConfig::getConfig();
81 if (conf.isEnabled(SPConfig::OutOfProcess)) {
82 // When out of process, we run natively and directly process the message.
83 // RelayState will be fully handled during message processing.
85 string key = processMessage(request.getApplication(), request, entityID, relayState);
86 return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
89 // When not out of process, we remote all the message processing.
90 DDF out,in = wrap(request);
91 DDFJanitor jin(in), jout(out);
94 out=request.getServiceProvider().getListenerService()->send(in);
96 catch (XMLToolingException& ex) {
97 // Try for RelayState recovery.
98 if (ex.getProperty("RelayState"))
99 relayState = ex.getProperty("RelayState");
101 recoverRelayState(request.getApplication(), request, relayState);
103 catch (exception& ex2) {
104 m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
109 // We invoke RelayState recovery one last time on this side of the boundary.
110 if (out["RelayState"].isstring())
111 relayState = out["RelayState"].string();
112 recoverRelayState(request.getApplication(), request, relayState);
114 // If it worked, we have a session key.
115 if (!out["key"].isstring())
116 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
118 // Take care of cookie business and wrap it up.
119 return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
122 catch (XMLToolingException& ex) {
123 // Try and preserve RelayState.
124 if (!relayState.empty())
125 ex.addProperty("RelayState", relayState.c_str());
130 void AssertionConsumerService::receive(DDF& in, ostream& out)
133 const char* aid=in["application_id"].string();
134 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
136 // Something's horribly wrong.
137 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
138 throw ConfigurationException("Unable to locate application for new session, deleted?");
141 // Unpack the request.
142 auto_ptr<HTTPRequest> http(getRequest(in));
145 string relayState, entityID;
147 string key = processMessage(*app, *http.get(), entityID, relayState);
149 // Repack for return to caller.
150 DDF ret=DDF(NULL).structure();
151 DDFJanitor jret(ret);
152 ret.addmember("key").string(key.c_str());
153 if (!entityID.empty())
154 ret.addmember("entity_id").string(entityID.c_str());
155 if (!relayState.empty())
156 ret.addmember("RelayState").string(relayState.c_str());
159 catch (XMLToolingException& ex) {
160 // Try and preserve RelayState if we can.
161 if (!relayState.empty())
162 ex.addProperty("RelayState", relayState.c_str());
167 string AssertionConsumerService::processMessage(
168 const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
172 // Locate policy key.
173 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
175 policyId = application.getString("policyId"); // unqualified in Application(s) element
177 // Access policy properties.
178 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
179 pair<bool,bool> validate = settings->getBool("validate");
181 // Lock metadata for use by policy.
182 Locker metadataLocker(application.getMetadataProvider());
184 // Create the policy.
185 shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
187 // Decode the message and process it in a protocol-specific way.
188 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
190 throw BindingException("Failed to decode an SSO protocol response.");
191 recoverRelayState(application, httpRequest, relayState);
192 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
194 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
196 entityID = issuer.get();
200 throw ConfigurationException("Cannot process message using lite version of shibsp library.");
204 pair<bool,long> AssertionConsumerService::sendRedirect(
205 SPRequest& request, const char* key, const char* entityID, const char* relayState
208 // We've got a good session, so set the session cookie.
209 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
211 k += shib_cookie.second;
212 request.setCookie(shib_cookie.first.c_str(), k.c_str());
215 maintainHistory(request, entityID, shib_cookie.second);
217 // Now redirect to the state value. By now, it should be set to *something* usable.
218 return make_pair(true, request.sendRedirect(relayState));
221 void AssertionConsumerService::checkAddress(
222 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
225 const PropertySet* props=application.getPropertySet("Sessions");
226 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
227 if (!checkAddress.first)
228 checkAddress.second=true;
230 if (checkAddress.second) {
231 m_log.debug("checking client address");
232 if (httpRequest.getRemoteAddr() != issuedTo) {
233 throw FatalProfileException(
234 "Your client's current address ($client_addr) differs from the one used when you authenticated "
235 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
236 "Please contact your local support staff or help desk for assistance.",
237 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
244 ResolutionContext* AssertionConsumerService::resolveAttributes(
245 const Application& application,
246 const saml2md::EntityDescriptor* issuer,
247 const XMLCh* protocol,
248 const saml2::NameID* nameid,
249 const XMLCh* authncontext_class,
250 const XMLCh* authncontext_decl,
251 const vector<const Assertion*>* tokens,
252 const multimap<string,Attribute*>* attributes
256 AttributeResolver* resolver = application.getAttributeResolver();
258 m_log.info("no AttributeResolver available, skipping resolution");
262 m_log.debug("resolving attributes...");
264 Locker locker(resolver);
265 auto_ptr<ResolutionContext> ctx(
266 resolver->createResolutionContext(application, issuer, protocol, nameid, authncontext_class, authncontext_decl, tokens, attributes)
268 resolver->resolveAttributes(*ctx.get());
269 return ctx.release();
271 catch (exception& ex) {
272 m_log.error("attribute resolution failed: %s", ex.what());
279 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
284 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
285 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
286 if (!idpHistory.first || idpHistory.second) {
287 // Set an IdP history cookie locally (essentially just a CDC).
288 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
290 // Either leave in memory or set an expiration.
291 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
292 if (!days.first || days.second==0) {
293 string c = string(cdc.set(entityID)) + cookieProps;
294 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
297 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
300 struct tm* ptime=gmtime_r(&now,&res);
302 struct tm* ptime=gmtime(&now);
305 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
306 string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
307 request.setCookie(CommonDomainCookie::CDCName, c.c_str());