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 "util/SPConstants.h"
32 #include <saml/SAMLConfig.h>
33 #include <saml/saml1/core/Assertions.h>
34 #include <saml/util/CommonDomainCookie.h>
36 using namespace shibspconstants;
37 using namespace samlconstants;
38 using namespace shibsp;
39 using namespace opensaml;
40 using namespace xmltooling;
41 using namespace log4cpp;
44 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, Category& log)
45 : AbstractHandler(e, log), m_configNS(SHIB2SPCONFIG_NS),
46 m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
48 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
49 m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
52 AssertionConsumerService::~AssertionConsumerService()
57 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
59 SPConfig& conf = SPConfig::getConfig();
60 if (conf.isEnabled(SPConfig::OutOfProcess)) {
61 // When out of process, we run natively and directly process the message.
62 // RelayState will be fully handled during message processing.
63 string relayState, providerId;
64 string key = processMessage(request.getApplication(), request, providerId, relayState);
65 return sendRedirect(request, key.c_str(), providerId.c_str(), relayState.c_str());
68 // When not out of process, we remote all the message processing.
69 DDF in = wrap(request);
71 in.addmember("application_id").string(request.getApplication().getId());
72 DDF out=request.getServiceProvider().getListenerService()->send(in);
75 // If it worked, we have a session key.
76 if (!out["key"].isstring())
77 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
79 // We invoke the RelayState method one last time on this side of the process boundary.
81 if (out["RelayState"].isstring())
82 relayState = out["RelayState"].string();
83 recoverRelayState(request, relayState);
84 return sendRedirect(request, out["key"].string(), out["provider_id"].string(), relayState.c_str());
88 void AssertionConsumerService::receive(DDF& in, ostream& out)
91 const char* aid=in["application_id"].string();
92 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
94 // Something's horribly wrong.
95 m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
96 throw ConfigurationException("Unable to locate application for new session, deleted?");
99 // Unpack the request.
100 auto_ptr<HTTPRequest> http(getRequest(in));
103 string relayState, providerId;
104 string key = processMessage(*app, *http.get(), providerId, relayState);
106 // Repack for return to caller.
107 DDF ret=DDF(NULL).structure();
108 DDFJanitor jret(ret);
109 ret.addmember("key").string(key.c_str());
110 if (!providerId.empty())
111 ret.addmember("provider_id").string(providerId.c_str());
112 if (!relayState.empty())
113 ret.addmember("RelayState").string(relayState.c_str());
117 string AssertionConsumerService::processMessage(
118 const Application& application, HTTPRequest& httpRequest, string& providerId, string& relayState
121 // Locate policy key.
122 pair<bool,const char*> policyId = getString("policyId", m_configNS.get()); // namespace-qualified if inside handler element
124 policyId = application.getString("policyId"); // unqualified in Application(s) element
126 // Access policy properties.
127 const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
128 pair<bool,bool> validate = settings->getBool("validate");
130 // Lock metadata for use by policy.
131 Locker metadataLocker(application.getMetadataProvider());
133 // Create the policy.
134 SecurityPolicy policy(
135 application.getServiceProvider().getPolicyRules(policyId.second),
136 application.getMetadataProvider(),
138 application.getTrustEngine(),
139 validate.first && validate.second
142 // Decode the message and process it in a protocol-specific way.
143 auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
144 recoverRelayState(httpRequest, relayState);
145 string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
147 auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
149 providerId = issuer.get();
154 pair<bool,long> AssertionConsumerService::sendRedirect(
155 SPRequest& request, const char* key, const char* providerId, const char* relayState
158 // We've got a good session, so set the session cookie.
159 pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
161 k += shib_cookie.second;
162 request.setCookie(shib_cookie.first.c_str(), k.c_str());
165 maintainHistory(request, providerId, shib_cookie.second);
167 // Now redirect to the state value. By now, it should be set to *something* usable.
168 return make_pair(true, request.sendRedirect(relayState));
171 void AssertionConsumerService::checkAddress(
172 const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
175 const PropertySet* props=application.getPropertySet("Sessions");
176 pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
177 if (!checkAddress.first)
178 checkAddress.second=true;
180 if (checkAddress.second) {
181 m_log.debug("checking client address");
182 if (httpRequest.getRemoteAddr() != issuedTo) {
183 throw FatalProfileException(
184 "Your client's current address ($client_addr) differs from the one used when you authenticated "
185 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
186 "Please contact your local support staff or help desk for assistance.",
187 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
193 ResolutionContext* AssertionConsumerService::resolveAttributes(
194 const Application& application,
195 const HTTPRequest& httpRequest,
196 const saml2md::EntityDescriptor* issuer,
197 const saml2::NameID& nameid,
198 const vector<const Assertion*>* tokens
201 AttributeResolver* resolver = application.getAttributeResolver();
203 m_log.info("no AttributeResolver available, skipping resolution");
208 m_log.debug("resolving attributes...");
209 auto_ptr<ResolutionContext> ctx(
210 resolver->createResolutionContext(application, httpRequest.getRemoteAddr().c_str(), issuer, nameid, tokens)
212 resolver->resolveAttributes(*ctx.get());
213 return ctx.release();
215 catch (exception& ex) {
216 m_log.error("attribute resolution failed: %s", ex.what());
222 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* providerId, const char* cookieProps) const
227 const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
228 pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
229 if (!idpHistory.first || idpHistory.second) {
230 // Set an IdP history cookie locally (essentially just a CDC).
231 CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
233 // Either leave in memory or set an expiration.
234 pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
235 if (!days.first || days.second==0) {
236 string c = string(cdc.set(providerId)) + cookieProps;
237 request.setCookie(CommonDomainCookie::CDCName, c.c_str());
240 time_t now=time(NULL) + (days.second * 24 * 60 * 60);
243 struct tm* ptime=gmtime_r(&now,&res);
245 struct tm* ptime=gmtime(&now);
248 strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
249 string c = string(cdc.set(providerId)) + cookieProps + "; expires=" + timebuf;
250 request.setCookie(CommonDomainCookie::CDCName, c.c_str());