434d1f01cdfe8d232fd3a5b31d825922084c5cba
[shibboleth/sp.git] / shibsp / handler / impl / AssertionConsumerService.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /**
18  * AssertionConsumerService.cpp
19  * 
20  * Base class for handlers that create sessions by consuming SSO protocol responses. 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "handler/AssertionConsumerService.h"
28 #include "util/SPConstants.h"
29
30 # include <ctime>
31 #ifndef SHIBSP_LITE
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;
39 #else
40 # include "lite/CommonDomainCookie.h"
41 #endif
42
43 using namespace shibspconstants;
44 using namespace shibsp;
45 using namespace opensaml;
46 using namespace xmltooling;
47 using namespace log4cpp;
48 using namespace std;
49
50 AssertionConsumerService::AssertionConsumerService(const DOMElement* e, const char* appId, Category& log)
51     : AbstractHandler(e, log)
52 #ifndef SHIBSP_LITE
53         ,m_decoder(NULL), m_role(samlconstants::SAML20MD_NS, opensaml::saml2md::IDPSSODescriptor::LOCAL_NAME)
54 #endif
55 {
56     string address(appId);
57     address += getString("Location").second;
58     setAddress(address.c_str());
59 #ifndef SHIBSP_LITE
60     if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
61         m_decoder = SAMLConfig::getConfig().MessageDecoderManager.newPlugin(getString("Binding").second,e);
62         m_decoder->setArtifactResolver(SPConfig::getConfig().getArtifactResolver());
63     }
64 #endif
65 }
66
67 AssertionConsumerService::~AssertionConsumerService()
68 {
69 #ifndef SHIBSP_LITE
70     delete m_decoder;
71 #endif
72 }
73
74 pair<bool,long> AssertionConsumerService::run(SPRequest& request, bool isHandler) const
75 {
76     string relayState;
77     SPConfig& conf = SPConfig::getConfig();
78     
79     try {
80         if (conf.isEnabled(SPConfig::OutOfProcess)) {
81             // When out of process, we run natively and directly process the message.
82             // RelayState will be fully handled during message processing.
83             string entityID;
84             string key = processMessage(request.getApplication(), request, entityID, relayState);
85             return sendRedirect(request, key.c_str(), entityID.c_str(), relayState.c_str());
86         }
87         else {
88             // When not out of process, we remote all the message processing.
89             DDF out,in = wrap(request);
90             DDFJanitor jin(in), jout(out);
91             
92             try {
93                 out=request.getServiceProvider().getListenerService()->send(in);
94             }
95             catch (XMLToolingException& ex) {
96                 // Try for RelayState recovery.
97                 if (ex.getProperty("RelayState"))
98                     relayState = ex.getProperty("RelayState");
99                 try {
100                     recoverRelayState(request.getApplication(), request, relayState);
101                 }
102                 catch (exception& ex2) {
103                     m_log.error("trapped an error during RelayState recovery while handling an error: %s", ex2.what());
104                 }
105                 throw;
106             }
107                 
108             // We invoke RelayState recovery one last time on this side of the boundary.
109             if (out["RelayState"].isstring())
110                 relayState = out["RelayState"].string(); 
111             recoverRelayState(request.getApplication(), request, relayState);
112     
113             // If it worked, we have a session key.
114             if (!out["key"].isstring())
115                 throw FatalProfileException("Remote processing of SSO profile did not return a usable session key.");
116             
117             // Take care of cookie business and wrap it up.
118             return sendRedirect(request, out["key"].string(), out["entity_id"].string(), relayState.c_str());
119         }
120     }
121     catch (XMLToolingException& ex) {
122         // Try and preserve RelayState.
123         if (!relayState.empty())
124             ex.addProperty("RelayState", relayState.c_str());
125         throw;
126     }
127 }
128
129 void AssertionConsumerService::receive(DDF& in, ostream& out)
130 {
131     // Find application.
132     const char* aid=in["application_id"].string();
133     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
134     if (!app) {
135         // Something's horribly wrong.
136         m_log.error("couldn't find application (%s) for new session", aid ? aid : "(missing)");
137         throw ConfigurationException("Unable to locate application for new session, deleted?");
138     }
139     
140     // Unpack the request.
141     auto_ptr<HTTPRequest> http(getRequest(in));
142     
143     // Do the work.
144     string relayState, entityID;
145     try {
146         string key = processMessage(*app, *http.get(), entityID, relayState);
147
148         // Repack for return to caller.
149         DDF ret=DDF(NULL).structure();
150         DDFJanitor jret(ret);
151         ret.addmember("key").string(key.c_str());
152         if (!entityID.empty())
153             ret.addmember("entity_id").string(entityID.c_str());
154         if (!relayState.empty())
155             ret.addmember("RelayState").string(relayState.c_str());
156         out << ret;
157     }
158     catch (XMLToolingException& ex) {
159         // Try and preserve RelayState if we can.
160         if (!relayState.empty())
161             ex.addProperty("RelayState", relayState.c_str());
162         throw;
163     }
164 }
165
166 string AssertionConsumerService::processMessage(
167     const Application& application, HTTPRequest& httpRequest, string& entityID, string& relayState
168     ) const
169 {
170 #ifndef SHIBSP_LITE
171     // Locate policy key.
172     pair<bool,const char*> policyId = getString("policyId", m_configNS.get());  // namespace-qualified if inside handler element
173     if (!policyId.first)
174         policyId = application.getString("policyId");   // unqualified in Application(s) element
175         
176     // Access policy properties.
177     const PropertySet* settings = application.getServiceProvider().getPolicySettings(policyId.second);
178     pair<bool,bool> validate = settings->getBool("validate");
179
180     // Lock metadata for use by policy.
181     Locker metadataLocker(application.getMetadataProvider());
182
183     // Create the policy.
184     shibsp::SecurityPolicy policy(application, &m_role, validate.first && validate.second);
185     
186     // Decode the message and process it in a protocol-specific way.
187     auto_ptr<XMLObject> msg(m_decoder->decode(relayState, httpRequest, policy));
188     if (!msg.get())
189         throw BindingException("Failed to decode an SSO protocol response.");
190     recoverRelayState(application, httpRequest, relayState);
191     string key = implementProtocol(application, httpRequest, policy, settings, *msg.get());
192
193     auto_ptr_char issuer(policy.getIssuer() ? policy.getIssuer()->getName() : NULL);
194     if (issuer.get())
195         entityID = issuer.get();
196     
197     return key;
198 #else
199     throw ConfigurationException("Cannot process message using lite version of shibsp library.");
200 #endif
201 }
202
203 pair<bool,long> AssertionConsumerService::sendRedirect(
204     SPRequest& request, const char* key, const char* entityID, const char* relayState
205     ) const
206 {
207     // We've got a good session, so set the session cookie.
208     pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibsession_");
209     string k(key);
210     k += shib_cookie.second;
211     request.setCookie(shib_cookie.first.c_str(), k.c_str());
212
213     // History cookie.
214     maintainHistory(request, entityID, shib_cookie.second);
215
216     // Now redirect to the state value. By now, it should be set to *something* usable.
217     return make_pair(true, request.sendRedirect(relayState));
218 }
219
220 void AssertionConsumerService::checkAddress(
221     const Application& application, const HTTPRequest& httpRequest, const char* issuedTo
222     ) const
223 {
224     const PropertySet* props=application.getPropertySet("Sessions");
225     pair<bool,bool> checkAddress = props ? props->getBool("checkAddress") : make_pair(false,true);
226     if (!checkAddress.first)
227         checkAddress.second=true;
228
229     if (checkAddress.second) {
230         m_log.debug("checking client address");
231         if (httpRequest.getRemoteAddr() != issuedTo) {
232             throw FatalProfileException(
233                "Your client's current address ($client_addr) differs from the one used when you authenticated "
234                 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
235                 "Please contact your local support staff or help desk for assistance.",
236                 namedparams(1,"client_addr",httpRequest.getRemoteAddr().c_str())
237                 );
238         }
239     }
240 }
241
242 #ifndef SHIBSP_LITE
243 ResolutionContext* AssertionConsumerService::resolveAttributes(
244     const Application& application,
245     const saml2md::EntityDescriptor* issuer,
246     const saml2::NameID* nameid,
247     const char* authncontext_class,
248     const char* authncontext_decl,
249     const vector<const Assertion*>* tokens,
250     const multimap<string,Attribute*>* attributes
251     ) const
252 {
253     try {
254         AttributeResolver* resolver = application.getAttributeResolver();
255         if (!resolver) {
256             m_log.info("no AttributeResolver available, skipping resolution");
257             return NULL;
258         }
259         
260         m_log.debug("resolving attributes...");
261
262         Locker locker(resolver);
263         auto_ptr<ResolutionContext> ctx(
264             resolver->createResolutionContext(application, issuer, nameid, authncontext_class, authncontext_decl, tokens, attributes)
265             );
266         resolver->resolveAttributes(*ctx.get());
267         return ctx.release();
268     }
269     catch (exception& ex) {
270         m_log.error("attribute resolution failed: %s", ex.what());
271     }
272     
273     return NULL;
274 }
275 #endif
276
277 void AssertionConsumerService::maintainHistory(SPRequest& request, const char* entityID, const char* cookieProps) const
278 {
279     if (!entityID)
280         return;
281         
282     const PropertySet* sessionProps=request.getApplication().getPropertySet("Sessions");
283     pair<bool,bool> idpHistory=sessionProps->getBool("idpHistory");
284     if (!idpHistory.first || idpHistory.second) {
285         // Set an IdP history cookie locally (essentially just a CDC).
286         CommonDomainCookie cdc(request.getCookie(CommonDomainCookie::CDCName));
287
288         // Either leave in memory or set an expiration.
289         pair<bool,unsigned int> days=sessionProps->getUnsignedInt("idpHistoryDays");
290         if (!days.first || days.second==0) {
291             string c = string(cdc.set(entityID)) + cookieProps;
292             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
293         }
294         else {
295             time_t now=time(NULL) + (days.second * 24 * 60 * 60);
296 #ifdef HAVE_GMTIME_R
297             struct tm res;
298             struct tm* ptime=gmtime_r(&now,&res);
299 #else
300             struct tm* ptime=gmtime(&now);
301 #endif
302             char timebuf[64];
303             strftime(timebuf,64,"%a, %d %b %Y %H:%M:%S GMT",ptime);
304             string c = string(cdc.set(entityID)) + cookieProps + "; expires=" + timebuf;
305             request.setCookie(CommonDomainCookie::CDCName, c.c_str());
306         }
307     }
308 }