Add regex support to acl plugin.
[shibboleth/cpp-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 #ifndef SHIBSP_LITE
65         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
66             AssertionConsumerService::generateMetadata(role, handlerURL);
67             role.addSupport(samlconstants::SAML20P_NS);
68         }
69
70     private:
71         void implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             HTTPResponse& httpResponse,
75             SecurityPolicy& policy,
76             const PropertySet* settings,
77             const XMLObject& xmlObject
78             ) const;
79 #endif
80     };
81
82 #if defined (_MSC_VER)
83     #pragma warning( pop )
84 #endif
85
86     Handler* SHIBSP_DLLLOCAL SAML2ConsumerFactory(const pair<const DOMElement*,const char*>& p)
87     {
88         return new SAML2Consumer(p.first, p.second);
89     }
90     
91 };
92
93 #ifndef SHIBSP_LITE
94
95 void SAML2Consumer::implementProtocol(
96     const Application& application,
97     const HTTPRequest& httpRequest,
98     HTTPResponse& httpResponse,
99     SecurityPolicy& policy,
100     const PropertySet* settings,
101     const XMLObject& xmlObject
102     ) const
103 {
104     // Implementation of SAML 2.0 SSO profile(s).
105     m_log.debug("processing message against SAML 2.0 SSO profile");
106
107     // Remember whether we already established trust.
108     // None of the SAML 2 bindings require security at the protocol layer.
109     bool alreadySecured = policy.isAuthenticated();
110
111     // Check for errors...this will throw if it's not a successful message.
112     checkError(&xmlObject);
113
114     const Response* response = dynamic_cast<const Response*>(&xmlObject);
115     if (!response)
116         throw FatalProfileException("Incoming message was not a samlp:Response.");
117
118     const vector<saml2::Assertion*>& assertions = response->getAssertions();
119     const vector<saml2::EncryptedAssertion*>& encassertions = response->getEncryptedAssertions();
120     if (assertions.empty() && encassertions.empty())
121         throw FatalProfileException("Incoming message contained no SAML assertions.");
122
123     // Maintain list of "legit" tokens to feed to SP subsystems.
124     const Subject* ssoSubject=NULL;
125     const AuthnStatement* ssoStatement=NULL;
126     vector<const opensaml::Assertion*> tokens;
127
128     // Also track "bad" tokens that we'll cache but not use.
129     // This is necessary because there may be valid tokens not aimed at us.
130     vector<const opensaml::Assertion*> badtokens;
131
132     // And also track "owned" tokens that we decrypt here.
133     vector<saml2::Assertion*> ownedtokens;
134
135     // Profile validator.
136     time_t now = time(NULL);
137     string dest = httpRequest.getRequestURL();
138     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now, dest.substr(0,dest.find('?')).c_str());
139
140     // With this flag on, we ignore any unsigned assertions.
141     pair<bool,bool> flag = settings->getBool("signedAssertions");
142
143     // authnskew allows rejection of SSO if AuthnInstant is too old.
144     const PropertySet* sessionProps = application.getPropertySet("Sessions");
145     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("authnskew") : pair<bool,unsigned int>(false,0);
146
147     // Saves off error messages potentially helpful for users.
148     string contextualError;
149
150     for (vector<saml2::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
151         try {
152             // Skip unsigned assertion?
153             if (!(*a)->getSignature() && flag.first && flag.second)
154                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
155
156             // We clear the security flag, so we can tell whether the token was secured on its own.
157             policy.setAuthenticated(false);
158             policy.reset(true);
159
160             // Extract message bits and re-verify Issuer information.
161             extractMessageDetails(*(*a), samlconstants::SAML20P_NS, policy);
162
163             // Run the policy over the assertion. Handles replay, freshness, and
164             // signature verification, assuming the relevant rules are configured.
165             policy.evaluate(*(*a));
166             
167             // If no security is in place now, we kick it.
168             if (!alreadySecured && !policy.isAuthenticated())
169                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
170
171             // Now do profile and core semantic validation to ensure we can use it for SSO.
172             ssoValidator.validateAssertion(*(*a));
173
174             // Address checking.
175             checkAddress(application, httpRequest, ssoValidator.getAddress());
176
177             // Track it as a valid token.
178             tokens.push_back(*a);
179
180             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
181             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(*a)->getAuthnStatements();
182             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
183                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
184                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
185                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
186                     ssoStatement = *s;
187             }
188
189             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
190             if (!ssoSubject || (!ssoSubject->getNameID() && (*a)->getSubject()->getNameID()))
191                 ssoSubject = (*a)->getSubject();
192         }
193         catch (exception& ex) {
194             m_log.warn("detected a problem with assertion: %s", ex.what());
195             if (!ssoStatement)
196                 contextualError = 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         try {
228             // Skip unsigned assertion?
229             if (!decrypted->getSignature() && flag.first && flag.second)
230                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
231
232             // We clear the security flag, so we can tell whether the token was secured on its own.
233             policy.setAuthenticated(false);
234             policy.reset(true);
235
236             // Extract message bits and re-verify Issuer information.
237             extractMessageDetails(*decrypted, samlconstants::SAML20P_NS, policy);
238
239             // Run the policy over the assertion. Handles replay, freshness, and
240             // signature verification, assuming the relevant rules are configured.
241             // We have to marshall the object first to ensure signatures can be checked.
242             if (!decrypted->getDOM())
243                 decrypted->marshall();
244             policy.evaluate(*decrypted);
245             
246             // If no security is in place now, we kick it.
247             if (!alreadySecured && !policy.isAuthenticated())
248                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
249
250             // Now do profile and core semantic validation to ensure we can use it for SSO.
251             ssoValidator.validateAssertion(*decrypted);
252
253             // Address checking.
254             checkAddress(application, httpRequest, ssoValidator.getAddress());
255
256             // Track it as a valid token.
257             tokens.push_back(decrypted);
258
259             // Save off the first valid SSO statement, but favor the "soonest" session expiration.
260             const vector<AuthnStatement*>& statements = const_cast<const saml2::Assertion*>(decrypted)->getAuthnStatements();
261             for (vector<AuthnStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
262                 if (authnskew.first && authnskew.second && (*s)->getAuthnInstant() && (now - (*s)->getAuthnInstantEpoch() > authnskew.second))
263                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the limit.";
264                 else if (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
265                     ssoStatement = *s;
266             }
267
268             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
269             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
270                 ssoSubject = decrypted->getSubject();
271         }
272         catch (exception& ex) {
273             m_log.warn("detected a problem with assertion: %s", ex.what());
274             if (!ssoStatement)
275                 contextualError = ex.what();
276             badtokens.push_back(decrypted);
277         }
278     }
279
280     if (!ssoStatement) {
281         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
282         if (contextualError.empty())
283             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
284         throw FatalProfileException(contextualError.c_str());
285     }
286
287     // May need to decrypt NameID.
288     bool ownedName = false;
289     NameID* ssoName = ssoSubject->getNameID();
290     if (!ssoName) {
291         EncryptedID* encname = ssoSubject->getEncryptedID();
292         if (encname) {
293             if (!cr)
294                 m_log.warn("found encrypted NameID, but no decryption credential was available");
295             else {
296                 Locker credlocker(cr);
297                 auto_ptr<MetadataCredentialCriteria> mcc(
298                     policy.getIssuerMetadata() ? new MetadataCredentialCriteria(*policy.getIssuerMetadata()) : NULL
299                     );
300                 try {
301                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,mcc.get()));
302                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
303                     if (ssoName) {
304                         ownedName = true;
305                         decryptedID.release();
306                     }
307                 }
308                 catch (exception& ex) {
309                     m_log.error(ex.what());
310                 }
311             }
312         }
313     }
314
315     m_log.debug("SSO profile processing completed successfully");
316
317     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
318     // To complete processing, we need to extract and resolve attributes and then create the session.
319
320     // Now we have to extract the authentication details for session setup.
321
322     // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
323     time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
324     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
325     if (!lifetime.first || lifetime.second == 0)
326         lifetime.second = 28800;
327     if (sessionExp == 0)
328         sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
329     else
330         sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
331
332     const AuthnContext* authnContext = ssoStatement->getAuthnContext();
333
334     try {
335         // The context will handle deleting attributes and new tokens.
336         auto_ptr<ResolutionContext> ctx(
337             resolveAttributes(
338                 application,
339                 policy.getIssuerMetadata(),
340                 samlconstants::SAML20P_NS,
341                 NULL,
342                 ssoName,
343                 (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
344                 (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
345                 &tokens
346                 )
347             );
348
349         if (ctx.get()) {
350             // Copy over any new tokens, but leave them in the context for cleanup.
351             tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
352         }
353
354         // Now merge in bad tokens for caching.
355         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
356
357         application.getServiceProvider().getSessionCache()->insert(
358             application,
359             httpRequest,
360             httpResponse,
361             sessionExp,
362             policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
363             samlconstants::SAML20P_NS,
364             ssoName,
365             ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL,
366             ssoStatement->getSessionIndex(),
367             (authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL,
368             (authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL,
369             &tokens,
370             ctx.get() ? &ctx->getResolvedAttributes() : NULL
371             );
372
373         if (ownedName)
374             delete ssoName;
375         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
376     }
377     catch (exception&) {
378         if (ownedName)
379             delete ssoName;
380         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
381         throw;
382     }
383 }
384
385 #endif