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