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