Refactor assertion extraction into handlers.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML1Consumer.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  * SAML1Consumer.cpp
19  * 
20  * SAML 1.x 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/saml1/core/Assertions.h>
33 # include <saml/saml1/core/Protocols.h>
34 # include <saml/saml1/profile/BrowserSSOProfileValidator.h>
35 # include <saml/saml2/metadata/Metadata.h>
36 using namespace opensaml::saml1;
37 using namespace opensaml::saml1p;
38 using namespace opensaml;
39 using saml2::NameID;
40 using saml2::NameIDBuilder;
41 using saml2md::EntityDescriptor;
42 using saml2md::MetadataException;
43 #else
44 # include "lite/SAMLConstants.h"
45 #endif
46
47 using namespace shibsp;
48 using namespace xmltooling;
49 using namespace std;
50
51 namespace shibsp {
52
53 #if defined (_MSC_VER)
54     #pragma warning( push )
55     #pragma warning( disable : 4250 )
56 #endif
57     
58     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
59     {
60     public:
61         SAML1Consumer(const DOMElement* e, const char* appId)
62                 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
63 #ifndef SHIBSP_LITE
64             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
65 #endif
66         }
67         virtual ~SAML1Consumer() {}
68         
69     private:
70 #ifndef SHIBSP_LITE
71         string implementProtocol(
72             const Application& application,
73             const HTTPRequest& httpRequest,
74             SecurityPolicy& policy,
75             const PropertySet* settings,
76             const XMLObject& xmlObject
77             ) const;
78         bool m_post;
79 #endif
80     };
81
82 #if defined (_MSC_VER)
83     #pragma warning( pop )
84 #endif
85
86     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
87     {
88         return new SAML1Consumer(p.first, p.second);
89     }
90     
91 };
92
93 #ifndef SHIBSP_LITE
94
95 string SAML1Consumer::implementProtocol(
96     const Application& application,
97     const HTTPRequest& httpRequest,
98     SecurityPolicy& policy,
99     const PropertySet* settings,
100     const XMLObject& xmlObject
101     ) const
102 {
103     // Implementation of SAML 1.x SSO profile(s).
104     m_log.debug("processing message against SAML 1.x SSO profile");
105
106     // Check for errors...this will throw if it's not a successful message.
107     checkError(&xmlObject);
108
109     // With the binding aspects now moved out to the MessageDecoder,
110     // the focus here is on the assertion content. For SAML 1.x POST,
111     // all the security comes from the protocol layer, and signing
112     // the assertion isn't sufficient. So we can check the policy
113     // object now and bail if it's not a secured message.
114     if (m_post && !policy.isAuthenticated()) {
115         if (policy.getIssuer() && !policy.getIssuerMetadata())
116             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
117         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
118     }
119         
120     // Remember whether we already established trust.
121     bool alreadySecured = policy.isAuthenticated();
122
123     const Response* response = dynamic_cast<const Response*>(&xmlObject);
124     if (!response)
125         throw FatalProfileException("Incoming message was not a samlp:Response.");
126
127     const vector<saml1::Assertion*>& assertions = response->getAssertions();
128     if (assertions.empty())
129         throw FatalProfileException("Incoming message contained no SAML assertions.");
130
131     pair<bool,int> minor = response->getMinorVersion();
132
133     // Maintain list of "legit" tokens to feed to SP subsystems.
134     const AuthenticationStatement* ssoStatement=NULL;
135     vector<const opensaml::Assertion*> tokens;
136
137     // Also track "bad" tokens that we'll cache but not use.
138     // This is necessary because there may be valid tokens not aimed at us.
139     vector<const opensaml::Assertion*> badtokens;
140
141     // Profile validator.
142     time_t now = time(NULL);
143     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
144
145     // With this flag on, we ignore any unsigned assertions.
146     pair<bool,bool> flag = settings->getBool("signedAssertions");
147
148     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
149         // Skip unsigned assertion?
150         if (!(*a)->getSignature() && flag.first && flag.second) {
151             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
152             badtokens.push_back(*a);
153             continue;
154         }
155
156         try {
157             // We clear the security flag, so we can tell whether the token was secured on its own.
158             policy.setAuthenticated(false);
159             policy.reset(true);
160
161             // Extract message bits and re-verify Issuer information.
162             extractMessageDetails(
163                 *(*a), (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
164                 );
165
166             // Run the policy over the assertion. Handles replay, freshness, and
167             // signature verification, assuming the relevant rules are configured.
168             policy.evaluate(*(*a));
169             
170             // If no security is in place now, we kick it.
171             if (!alreadySecured && !policy.isAuthenticated()) {
172                 m_log.warn("unable to establish security of assertion");
173                 badtokens.push_back(*a);
174                 continue;
175             }
176
177             // Now do profile and core semantic validation to ensure we can use it for SSO.
178             ssoValidator.validateAssertion(*(*a));
179
180             // Track it as a valid token.
181             tokens.push_back(*a);
182
183             // Save off the first valid SSO statement.
184             if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
185                 ssoStatement = (*a)->getAuthenticationStatements().front();
186         }
187         catch (exception& ex) {
188             m_log.warn("detected a problem with assertion: %s", ex.what());
189             badtokens.push_back(*a);
190         }
191     }
192
193     if (!ssoStatement)
194         throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
195
196     // Address checking.
197     SubjectLocality* locality = ssoStatement->getSubjectLocality();
198     if (locality && locality->getIPAddress()) {
199         auto_ptr_char ip(locality->getIPAddress());
200         checkAddress(application, httpRequest, ip.get());
201     }
202
203     m_log.debug("SSO profile processing completed successfully");
204
205     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
206
207     // Now we have to extract the authentication details for attribute and session setup.
208
209     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
210     const PropertySet* sessionProps = application.getPropertySet("Sessions");
211     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
212     if (!lifetime.first || lifetime.second == 0)
213         lifetime.second = 28800;
214
215     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
216     // To complete processing, we need to extract and resolve attributes and then create the session.
217
218     // Normalize the SAML 1.x NameIdentifier...
219     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
220     if (n) {
221         nameid->setName(n->getName());
222         nameid->setFormat(n->getFormat());
223         nameid->setNameQualifier(n->getNameQualifier());
224     }
225
226     // The context will handle deleting attributes and new tokens.
227     auto_ptr<ResolutionContext> ctx(
228         resolveAttributes(
229             application,
230             policy.getIssuerMetadata(),
231             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
232                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
233             n,
234             nameid.get(),
235             ssoStatement->getAuthenticationMethod(),
236             NULL,
237             &tokens
238             )
239         );
240
241     if (ctx.get()) {
242         // Copy over any new tokens, but leave them in the context for cleanup.
243         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
244     }
245
246     // Now merge in bad tokens for caching.
247     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
248
249     return application.getServiceProvider().getSessionCache()->insert(
250         now + lifetime.second,
251         application,
252         httpRequest.getRemoteAddr().c_str(),
253         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
254         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
255             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
256         nameid.get(),
257         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
258         NULL,
259         ssoStatement->getAuthenticationMethod(),
260         NULL,
261         &tokens,
262         ctx.get() ? &ctx->getResolvedAttributes() : NULL
263         );
264 }
265
266 #endif