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