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