Extend attribute resolution to include authn statement.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAML1Consumer.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * SAML1Consumer.cpp
23  *
24  * SAML 1.x assertion consumer service.
25  */
26
27 #include "internal.h"
28 #include "handler/AssertionConsumerService.h"
29
30 #ifndef SHIBSP_LITE
31 # include "Application.h"
32 # include "ServiceProvider.h"
33 # include "SessionCache.h"
34 # include "attribute/resolver/ResolutionContext.h"
35 # include <saml/exceptions.h>
36 # include <saml/SAMLConfig.h>
37 # include <saml/binding/SecurityPolicy.h>
38 # include <saml/binding/SecurityPolicyRule.h>
39 # include <saml/saml1/core/Assertions.h>
40 # include <saml/saml1/core/Protocols.h>
41 # include <saml/saml2/metadata/Metadata.h>
42 # include <xmltooling/XMLToolingConfig.h>
43 # include <xmltooling/io/HTTPRequest.h>
44 # include <xmltooling/util/DateTime.h>
45 using namespace opensaml::saml1;
46 using namespace opensaml::saml1p;
47 using namespace opensaml;
48 using saml2::NameID;
49 using saml2::NameIDBuilder;
50 using saml2md::EntityDescriptor;
51 using saml2md::SPSSODescriptor;
52 using saml2md::MetadataException;
53 #else
54 # include "lite/SAMLConstants.h"
55 #endif
56
57 using namespace shibsp;
58 using namespace xmltooling;
59 using namespace std;
60
61 namespace shibsp {
62
63 #if defined (_MSC_VER)
64     #pragma warning( push )
65     #pragma warning( disable : 4250 )
66 #endif
67
68     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
69     {
70     public:
71         SAML1Consumer(const DOMElement* e, const char* appId)
72             : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
73 #ifndef SHIBSP_LITE
74             m_ssoRule = nullptr;
75             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
76             if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
77                 m_ssoRule = SAMLConfig::getConfig().SecurityPolicyRuleManager.newPlugin(SAML1BROWSERSSO_POLICY_RULE, e);
78 #endif
79         }
80         virtual ~SAML1Consumer() {
81 #ifndef SHIBSP_LITE
82             delete m_ssoRule;
83 #endif
84         }
85
86 #ifndef SHIBSP_LITE
87         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
88             AssertionConsumerService::generateMetadata(role, handlerURL);
89             role.addSupport(samlconstants::SAML11_PROTOCOL_ENUM);
90             role.addSupport(samlconstants::SAML10_PROTOCOL_ENUM);
91         }
92
93     private:
94         void implementProtocol(
95             const Application& application,
96             const HTTPRequest& httpRequest,
97             HTTPResponse& httpResponse,
98             SecurityPolicy& policy,
99             const PropertySet*,
100             const XMLObject& xmlObject
101             ) const;
102
103         bool m_post;
104         SecurityPolicyRule* m_ssoRule;
105 #else
106         const XMLCh* getProtocolFamily() const {
107             return samlconstants::SAML11_PROTOCOL_ENUM;
108         }
109 #endif
110     };
111
112 #if defined (_MSC_VER)
113     #pragma warning( pop )
114 #endif
115
116     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
117     {
118         return new SAML1Consumer(p.first, p.second);
119     }
120
121 #ifndef SHIBSP_LITE
122     class SHIBSP_DLLLOCAL _rulenamed : std::unary_function<const SecurityPolicyRule*,bool>
123     {
124     public:
125         _rulenamed(const char* name) : m_name(name) {}
126         bool operator()(const SecurityPolicyRule* rule) const {
127             return rule ? !strcmp(m_name, rule->getType()) : false;
128         }
129     private:
130         const char* m_name;
131     };
132 #endif
133 };
134
135 #ifndef SHIBSP_LITE
136
137 void SAML1Consumer::implementProtocol(
138     const Application& application,
139     const HTTPRequest& httpRequest,
140     HTTPResponse& httpResponse,
141     SecurityPolicy& policy,
142     const PropertySet*,
143     const XMLObject& xmlObject
144     ) const
145 {
146     // Implementation of SAML 1.x SSO profile(s).
147     m_log.debug("processing message against SAML 1.x SSO profile");
148
149     // Check for errors...this will throw if it's not a successful message.
150     checkError(&xmlObject);
151
152     // With the binding aspects now moved out to the MessageDecoder,
153     // the focus here is on the assertion content. For SAML 1.x POST,
154     // all the security comes from the protocol layer, and signing
155     // the assertion isn't sufficient. So we can check the policy
156     // object now and bail if it's not a secured message.
157     if (m_post && !policy.isAuthenticated()) {
158         if (policy.getIssuer() && !policy.getIssuerMetadata())
159             throw MetadataException("Security of SAML 1.x SSO POST response not established.");
160         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
161     }
162
163     // Remember whether we already established trust.
164     bool alreadySecured = policy.isAuthenticated();
165
166     const Response* response = dynamic_cast<const Response*>(&xmlObject);
167     if (!response)
168         throw FatalProfileException("Incoming message was not a samlp:Response.");
169
170     const vector<saml1::Assertion*>& assertions = response->getAssertions();
171     if (assertions.empty())
172         throw FatalProfileException("Incoming message contained no SAML assertions.");
173
174     pair<bool,int> minor = response->getMinorVersion();
175
176     // Maintain list of "legit" tokens to feed to SP subsystems.
177     const AuthenticationStatement* ssoStatement=nullptr;
178     vector<const opensaml::Assertion*> tokens;
179
180     // Also track "bad" tokens that we'll cache but not use.
181     // This is necessary because there may be valid tokens not aimed at us.
182     vector<const opensaml::Assertion*> badtokens;
183
184     // With this flag on, we ignore any unsigned assertions.
185     const EntityDescriptor* entity = policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : nullptr;
186     pair<bool,bool> flag = application.getRelyingParty(entity)->getBool("requireSignedAssertions");
187
188     // authnskew allows rejection of SSO if AuthnInstant is too old.
189     const PropertySet* sessionProps = application.getPropertySet("Sessions");
190     pair<bool,unsigned int> authnskew = sessionProps ? sessionProps->getUnsignedInt("maxTimeSinceAuthn") : pair<bool,unsigned int>(false,0);
191
192     // Saves off error messages potentially helpful for users.
193     string contextualError;
194
195     // Ensure the BrowserSSO rule is in the policy set.
196     if (find_if(policy.getRules(), _rulenamed(SAML1BROWSERSSO_POLICY_RULE)) == nullptr)
197         policy.getRules().push_back(m_ssoRule);
198
199     // Populate recipient as audience.
200     policy.getAudiences().push_back(application.getRelyingParty(entity)->getXMLString("entityID").second);
201
202     time_t now = time(nullptr);
203     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
204         try {
205             // Skip unsigned assertion?
206             if (!(*a)->getSignature() && flag.first && flag.second)
207                 throw SecurityPolicyException("The incoming assertion was unsigned, violating local security policy.");
208
209             // We clear the security flag, so we can tell whether the token was secured on its own.
210             policy.setAuthenticated(false);
211             policy.reset(true);
212
213             // Extract message bits and re-verify Issuer information.
214             extractMessageDetails(
215                 *(*a),
216                 (minor.first && minor.second==0) ? samlconstants::SAML10_PROTOCOL_ENUM : samlconstants::SAML11_PROTOCOL_ENUM, policy
217                 );
218
219             // Run the policy over the assertion. Handles replay, freshness, and
220             // signature verification, assuming the relevant rules are configured,
221             // along with condition and profile enforcement.
222             policy.evaluate(*(*a), &httpRequest);
223
224             // If no security is in place now, we kick it.
225             if (!alreadySecured && !policy.isAuthenticated())
226                 throw SecurityPolicyException("Unable to establish security of incoming assertion.");
227
228             // Track it as a valid token.
229             tokens.push_back(*a);
230
231             // Save off the first valid SSO statement.
232             const vector<AuthenticationStatement*>& statements =
233                     const_cast<const saml1::Assertion*>(*a)->getAuthenticationStatements();
234             for (vector<AuthenticationStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
235                 if ((*s)->getAuthenticationInstant() &&
236                         (*s)->getAuthenticationInstantEpoch() - XMLToolingConfig::getConfig().clock_skew_secs > now) {
237                     contextualError = "The login time at your identity provider was future-dated.";
238                 }
239                 else if (authnskew.first && authnskew.second && (*s)->getAuthenticationInstant() &&
240                         (*s)->getAuthenticationInstantEpoch() <= now && (now - (*s)->getAuthenticationInstantEpoch() > authnskew.second)) {
241                     contextualError = "The gap between now and the time you logged into your identity provider exceeds the allowed limit.";
242                 }
243                 else if (authnskew.first && authnskew.second && (*s)->getAuthenticationInstant() == nullptr) {
244                     contextualError = "Your identity provider did not supply a time of login, violating local policy.";
245                 }
246                 else if (!ssoStatement) {
247                     ssoStatement = *s;
248                     break;
249                 }
250             }
251         }
252         catch (exception& ex) {
253             m_log.warn("detected a problem with assertion: %s", ex.what());
254             if (!ssoStatement)
255                 contextualError = ex.what();
256             badtokens.push_back(*a);
257         }
258     }
259
260     if (!ssoStatement) {
261         if (contextualError.empty())
262             throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
263         throw FatalProfileException(contextualError.c_str());
264     }
265
266     // Address checking.
267     SubjectLocality* locality = ssoStatement->getSubjectLocality();
268     if (locality && locality->getIPAddress()) {
269         auto_ptr_char ip(locality->getIPAddress());
270         checkAddress(application, httpRequest, ip.get());
271     }
272
273     m_log.debug("SSO profile processing completed successfully");
274
275     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
276
277     // Now we have to extract the authentication details for attribute and session setup.
278
279     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
280     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
281     if (!lifetime.first || lifetime.second == 0)
282         lifetime.second = 28800;
283
284     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
285     // To complete processing, we need to extract and resolve attributes and then create the session.
286
287     // Normalize the SAML 1.x NameIdentifier...
288     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : nullptr);
289     if (n) {
290         nameid->setName(n->getName());
291         nameid->setFormat(n->getFormat());
292         nameid->setNameQualifier(n->getNameQualifier());
293     }
294
295     // The context will handle deleting attributes and new tokens.
296     auto_ptr<ResolutionContext> ctx(
297         resolveAttributes(
298             application,
299             policy.getIssuerMetadata(),
300             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
301                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
302             n,
303             ssoStatement,
304             nameid.get(),
305             nullptr,
306             ssoStatement->getAuthenticationMethod(),
307             nullptr,
308             &tokens
309             )
310         );
311
312     if (ctx.get()) {
313         // Copy over any new tokens, but leave them in the context for cleanup.
314         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
315     }
316
317     // Now merge in bad tokens for caching.
318     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
319
320     application.getServiceProvider().getSessionCache()->insert(
321         application,
322         httpRequest,
323         httpResponse,
324         now + lifetime.second,
325         entity,
326         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
327             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
328         nameid.get(),
329         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : nullptr,
330         nullptr,
331         ssoStatement->getAuthenticationMethod(),
332         nullptr,
333         &tokens,
334         ctx.get() ? &ctx->getResolvedAttributes() : nullptr
335         );
336 }
337
338 #endif