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