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