e7ba328a0a0bea5e54e61754bfd54cff857e3fb4
[shibboleth/sp.git] / shibsp / handler / impl / SAML2Consumer.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  * SAML2Consumer.cpp
19  * 
20  * SAML 2.0 assertion consumer service 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCache.h"
28 #include "attribute/resolver/ResolutionContext.h"
29 #include "handler/AssertionConsumerService.h"
30
31 #include <saml/saml2/core/Protocols.h>
32 #include <saml/saml2/profile/BrowserSSOProfileValidator.h>
33 #include <saml/saml2/metadata/Metadata.h>
34
35 using namespace shibsp;
36 using namespace opensaml::saml2;
37 using namespace opensaml::saml2p;
38 using namespace opensaml;
39 using namespace xmltooling;
40 using namespace log4cpp;
41 using namespace std;
42 using saml2md::EntityDescriptor;
43
44 namespace shibsp {
45
46 #if defined (_MSC_VER)
47     #pragma warning( push )
48     #pragma warning( disable : 4250 )
49 #endif
50     
51     class SHIBSP_DLLLOCAL SAML2Consumer : public AssertionConsumerService
52     {
53     public:
54         SAML2Consumer(const DOMElement* e, const char* appId)
55                 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SAML2")) {
56         }
57         virtual ~SAML2Consumer() {}
58         
59     private:
60         string implementProtocol(
61             const Application& application,
62             const HTTPRequest& httpRequest,
63             SecurityPolicy& policy,
64             const PropertySet* settings,
65             const XMLObject& xmlObject
66             ) const;
67     };
68
69 #if defined (_MSC_VER)
70     #pragma warning( pop )
71 #endif
72
73     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
74     {
75         return new SAML2Consumer(p.first, p.second);
76     }
77     
78 };
79
80 string SAML2Consumer::implementProtocol(
81     const Application& application,
82     const HTTPRequest& httpRequest,
83     SecurityPolicy& policy,
84     const PropertySet* settings,
85     const XMLObject& xmlObject
86     ) const
87 {
88     // Implementation of SAML 2.0 SSO profile(s).
89     m_log.debug("processing message against SAML 2.0 SSO profile");
90
91     // Remember whether we already established trust.
92     // None of the SAML 2 bindings require security at the protocol layer.
93     bool alreadySecured = policy.isSecure();
94
95     // Check for errors...this will throw if it's not a successful message.
96     checkError(&xmlObject);
97
98     const Response* response = dynamic_cast<const Response*>(&xmlObject);
99     if (!response)
100         throw FatalProfileException("Incoming message was not a samlp:Response.");
101
102     const vector<saml2::Assertion*>& assertions = response->getAssertions();
103     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
104     if (assertions.empty() && encassertions.empty())
105         throw FatalProfileException("Incoming message contained no SAML assertions.");
106
107     // Maintain list of "legit" tokens to feed to SP subsystems.
108     const Subject* ssoSubject=NULL;
109     const AuthnStatement* ssoStatement=NULL;
110     vector<const opensaml::Assertion*> tokens;
111
112     // Also track "bad" tokens that we'll cache but not use.
113     // This is necessary because there may be valid tokens not aimed at us.
114     vector<const opensaml::Assertion*> badtokens;
115
116     // And also track "owned" tokens that we decrypt here.
117     vector<saml2::Assertion*> ownedtokens;
118
119     // Profile validator.
120     time_t now = time(NULL);
121     string dest = httpRequest.getRequestURL();
122     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
123
124     // With this flag on, we ignore any unsigned assertions.
125     pair<bool,bool> flag = settings->getBool("signedAssertions");
126
127     // Saves off IP-mismatch error message because it's potentially helpful for users.
128     string addressMismatch;
129
130     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
131         // Skip unsigned assertion?
132         if (!(*a)->getSignature() && flag.first && flag.second) {
133             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
134             badtokens.push_back(*a);
135             continue;
136         }
137
138         try {
139             // We clear the security flag, so we can tell whether the token was secured on its own.
140             policy.setSecure(false);
141             
142             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
143             // and signature verification, assuming the relevant rules are configured.
144             policy.evaluate(*(*a));
145             
146             // If no security is in place now, we kick it.
147             if (!alreadySecured && !policy.isSecure()) {
148                 m_log.warn("unable to establish security of assertion");
149                 badtokens.push_back(*a);
150                 continue;
151             }
152
153             // Now do profile and core semantic validation to ensure we can use it for SSO.
154             ssoValidator.validateAssertion(*(*a));
155
156             // Address checking.
157             try {
158                 if (ssoValidator.getAddress())
159                     checkAddress(application, httpRequest, ssoValidator.getAddress());
160             }
161             catch (exception& ex) {
162                 // We save off the message if there's no SSO statement yet.
163                 if (!ssoStatement)
164                     addressMismatch = ex.what();
165                 throw;
166             }
167
168             // Track it as a valid token.
169             tokens.push_back(*a);
170
171             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
172             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
173             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
174                 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
175                     ssoStatement = *s;
176             }
177
178             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
179             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
180                 ssoSubject = (*a)->getSubject();
181         }
182         catch (exception& ex) {
183             m_log.warn("detected a problem with assertion: %s", ex.what());
184             badtokens.push_back(*a);
185         }
186     }
187 \r
188     CredentialResolver* cr=NULL;\r
189     const PropertySet* credUse = application.getCredentialUse(\r
190         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL\r
191         );\r
192     if (credUse)\r
193         cr = application.getServiceProvider().getCredentialResolver(credUse->getString("Encryption").second);
194     if (!cr && !encassertions.empty())
195         m_log.warn("found encrypted assertions, but no decryption credential was available");
196
197     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
198         // Attempt to decrypt it.
199         saml2::Assertion* decrypted=NULL;
200         try {
201             Locker credlocker(cr);
202             auto_ptr<XMLObject> wrapper((*ea)->decrypt(cr, application.getXMLString("providerId").second));
203             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
204             if (decrypted) {
205                 wrapper.release();
206                 ownedtokens.push_back(decrypted);
207             }
208         }
209         catch (exception& ex) {
210             m_log.error(ex.what());
211         }
212         if (!decrypted)
213             continue;
214
215         // Skip unsigned assertion?
216         if (!decrypted->getSignature() && flag.first && flag.second) {
217             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
218             badtokens.push_back(decrypted);
219             continue;
220         }
221
222         try {
223             // We clear the security flag, so we can tell whether the token was secured on its own.
224             policy.setSecure(false);
225             
226             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
227             // and signature verification, assuming the relevant rules are configured.
228             // We have to marshall the object first to ensure signatures can be checked.
229             decrypted->marshall();
230             policy.evaluate(*decrypted);
231             
232             // If no security is in place now, we kick it.
233             if (!alreadySecured && !policy.isSecure()) {
234                 m_log.warn("unable to establish security of assertion");
235                 badtokens.push_back(decrypted);
236                 continue;
237             }
238
239             // Now do profile and core semantic validation to ensure we can use it for SSO.
240             ssoValidator.validateAssertion(*decrypted);
241
242             // Address checking.
243             try {
244                 if (ssoValidator.getAddress())
245                     checkAddress(application, httpRequest, ssoValidator.getAddress());
246             }
247             catch (exception& ex) {
248                 // We save off the message if there's no SSO statement yet.
249                 if (!ssoStatement)
250                     addressMismatch = ex.what();
251                 throw;
252             }
253
254             // Track it as a valid token.
255             tokens.push_back(decrypted);
256
257             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
258             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
259             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
260                 if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
261                     ssoStatement = *s;
262             }
263
264             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
265             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
266                 ssoSubject = decrypted->getSubject();
267         }
268         catch (exception& ex) {
269             m_log.warn("detected a problem with assertion: %s", ex.what());
270             badtokens.push_back(decrypted);
271         }
272     }
273
274     if (!ssoStatement) {
275         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
276         if (addressMismatch.empty())
277             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
278         throw FatalProfileException(addressMismatch.c_str());
279     }
280
281     // May need to decrypt NameID.
282     bool ownedName = false;
283     NameID* ssoName = ssoSubject->getNameID();
284     if (!ssoName) {
285         EncryptedID* encname = ssoSubject->getEncryptedID();
286         if (encname) {
287             if (!cr)
288                 m_log.warn("found encrypted NameID, but no decryption credential was available");
289             else {
290                 Locker credlocker(cr);
291                 try {
292                     auto_ptr<XMLObject> decryptedID(encname->decrypt(cr,application.getXMLString("providerId").second));
293                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
294                     if (ssoName) {
295                         ownedName = true;
296                         decryptedID.release();
297                     }
298                 }
299                 catch (exception& ex) {
300                     m_log.error(ex.what());
301                 }
302             }
303         }
304     }
305
306     m_log.debug("SSO profile processing completed successfully");
307
308     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
309     // To complete processing, we need to resolve attributes and then create the session.
310
311     try {
312         const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
313         auto_ptr<ResolutionContext> ctx(
314             resolveAttributes(application, httpRequest, issuerMetadata, ssoName, &tokens)
315             );
316
317         // Copy over any new tokens, but leave them in the context for cleanup.
318         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
319
320         // Now merge in bad tokens for caching.
321         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
322
323         // Now we have to extract the authentication details for session setup.
324
325         // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
326         time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
327         const PropertySet* sessionProps = application.getPropertySet("Sessions");
328         pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
329         if (!lifetime.first)
330             lifetime.second = 28800;
331         if (lifetime.second != 0) {
332             if (sessionExp == 0)
333                 sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
334             else
335                 sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
336         }
337
338         // Other details...
339         const AuthnContext* authnContext = ssoStatement->getAuthnContext();
340         auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
341         auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
342         auto_ptr_char index(ssoStatement->getSessionIndex());
343         auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
344
345         vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
346         string key = application.getServiceProvider().getSessionCache()->insert(
347             sessionExp,
348             application,
349             httpRequest.getRemoteAddr().c_str(),
350             issuerMetadata,
351             ssoName,
352             authnInstant.get(),
353             index.get(),
354             authnClass.get(),
355             authnDecl.get(),
356             &tokens,
357             &attrs
358             );
359         attrs.clear();  // Attributes are owned by cache now.
360
361         if (ownedName)
362             delete ssoName;
363         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
364
365         return key;
366     }
367     catch (exception&) {
368         if (ownedName)
369             delete ssoName;
370         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
371         throw;
372     }
373 }