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