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