Improve property inheritance, first batch of SessionInitiators, rename providerId.
[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
188     // We look up decryption credentials based on the peer who did the encrypting.
189     CredentialCriteria cc;
190     if (policy.getIssuerMetadata()) {
191         auto_ptr_char assertingParty(dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent())->getEntityID());
192         cc.setPeerName(assertingParty.get());
193     }
194     CredentialResolver* cr=application.getCredentialResolver();
195
196     if (!cr && !encassertions.empty())
197         m_log.warn("found encrypted assertions, but no CredentialResolver was available");
198
199     for (vector<saml2::EncryptedAssertion*>::const_iterator ea = encassertions.begin(); cr && ea!=encassertions.end(); ++ea) {
200         // Attempt to decrypt it.
201         saml2::Assertion* decrypted=NULL;
202         try {
203             Locker credlocker(cr);
204             auto_ptr<XMLObject> wrapper((*ea)->decrypt(*cr, application.getXMLString("entityID").second, &cc));
205             decrypted = dynamic_cast<saml2::Assertion*>(wrapper.get());
206             if (decrypted) {
207                 wrapper.release();
208                 ownedtokens.push_back(decrypted);
209             }
210         }
211         catch (exception& ex) {
212             m_log.error(ex.what());
213         }
214         if (!decrypted)
215             continue;
216
217         // Skip unsigned assertion?
218         if (!decrypted->getSignature() && flag.first && flag.second) {
219             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
220             badtokens.push_back(decrypted);
221             continue;
222         }
223
224         try {
225             // We clear the security flag, so we can tell whether the token was secured on its own.
226             policy.setSecure(false);
227             
228             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
229             // and signature verification, assuming the relevant rules are configured.
230             // We have to marshall the object first to ensure signatures can be checked.
231             decrypted->marshall();
232             policy.evaluate(*decrypted);
233             
234             // If no security is in place now, we kick it.
235             if (!alreadySecured && !policy.isSecure()) {
236                 m_log.warn("unable to establish security of assertion");
237                 badtokens.push_back(decrypted);
238                 continue;
239             }
240
241             // Now do profile and core semantic validation to ensure we can use it for SSO.
242             ssoValidator.validateAssertion(*decrypted);
243
244             // Address checking.
245             try {
246                 if (ssoValidator.getAddress())
247                     checkAddress(application, httpRequest, ssoValidator.getAddress());
248             }
249             catch (exception& ex) {
250                 // We save off the message if there's no SSO statement yet.
251                 if (!ssoStatement)
252                     addressMismatch = ex.what();
253                 throw;
254             }
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 (!ssoStatement || (*s)->getSessionNotOnOrAfterEpoch() < ssoStatement->getSessionNotOnOrAfterEpoch())
263                     ssoStatement = *s;
264             }
265
266             // Save off the first valid Subject, but favor an unencrypted NameID over anything else.
267             if (!ssoSubject || (!ssoSubject->getNameID() && decrypted->getSubject()->getNameID()))
268                 ssoSubject = decrypted->getSubject();
269         }
270         catch (exception& ex) {
271             m_log.warn("detected a problem with assertion: %s", ex.what());
272             badtokens.push_back(decrypted);
273         }
274     }
275
276     if (!ssoStatement) {
277         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
278         if (addressMismatch.empty())
279             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
280         throw FatalProfileException(addressMismatch.c_str());
281     }
282
283     // May need to decrypt NameID.
284     bool ownedName = false;
285     NameID* ssoName = ssoSubject->getNameID();
286     if (!ssoName) {
287         EncryptedID* encname = ssoSubject->getEncryptedID();
288         if (encname) {
289             if (!cr)
290                 m_log.warn("found encrypted NameID, but no decryption credential was available");
291             else {
292                 Locker credlocker(cr);
293                 try {
294                     auto_ptr<XMLObject> decryptedID(encname->decrypt(*cr,application.getXMLString("entityID").second,&cc));
295                     ssoName = dynamic_cast<NameID*>(decryptedID.get());
296                     if (ssoName) {
297                         ownedName = true;
298                         decryptedID.release();
299                     }
300                 }
301                 catch (exception& ex) {
302                     m_log.error(ex.what());
303                 }
304             }
305         }
306     }
307
308     m_log.debug("SSO profile processing completed successfully");
309
310     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
311     // To complete processing, we need to resolve attributes and then create the session.
312
313     try {
314         const EntityDescriptor* issuerMetadata = dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent());
315         auto_ptr<ResolutionContext> ctx(
316             resolveAttributes(application, httpRequest, issuerMetadata, ssoName, &tokens)
317             );
318
319         // Copy over any new tokens, but leave them in the context for cleanup.
320         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
321
322         // Now merge in bad tokens for caching.
323         tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
324
325         // Now we have to extract the authentication details for session setup.
326
327         // Session expiration for SAML 2.0 is jointly IdP- and SP-driven.
328         time_t sessionExp = ssoStatement->getSessionNotOnOrAfter() ? ssoStatement->getSessionNotOnOrAfterEpoch() : 0;
329         const PropertySet* sessionProps = application.getPropertySet("Sessions");
330         pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : make_pair(true,28800);
331         if (!lifetime.first)
332             lifetime.second = 28800;
333         if (lifetime.second != 0) {
334             if (sessionExp == 0)
335                 sessionExp = now + lifetime.second;     // IdP says nothing, calulate based on SP.
336             else
337                 sessionExp = min(sessionExp, now + lifetime.second);    // Use the lowest.
338         }
339
340         // Other details...
341         const AuthnContext* authnContext = ssoStatement->getAuthnContext();
342         auto_ptr_char authnClass((authnContext && authnContext->getAuthnContextClassRef()) ? authnContext->getAuthnContextClassRef()->getReference() : NULL);
343         auto_ptr_char authnDecl((authnContext && authnContext->getAuthnContextDeclRef()) ? authnContext->getAuthnContextDeclRef()->getReference() : NULL);
344         auto_ptr_char index(ssoStatement->getSessionIndex());
345         auto_ptr_char authnInstant(ssoStatement->getAuthnInstant() ? ssoStatement->getAuthnInstant()->getRawData() : NULL);
346
347         vector<shibsp::Attribute*>& attrs = ctx->getResolvedAttributes();
348         string key = application.getServiceProvider().getSessionCache()->insert(
349             sessionExp,
350             application,
351             httpRequest.getRemoteAddr().c_str(),
352             issuerMetadata,
353             ssoName,
354             authnInstant.get(),
355             index.get(),
356             authnClass.get(),
357             authnDecl.get(),
358             &tokens,
359             &attrs
360             );
361         attrs.clear();  // Attributes are owned by cache now.
362
363         if (ownedName)
364             delete ssoName;
365         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
366
367         return key;
368     }
369     catch (exception&) {
370         if (ownedName)
371             delete ssoName;
372         for_each(ownedtokens.begin(), ownedtokens.end(), xmltooling::cleanup<saml2::Assertion>());
373         throw;
374     }
375 }