Move all attribute work into base class.
[shibboleth/cpp-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 #else
43 # include "lite/SAMLConstants.h"
44 #endif
45
46 using namespace shibsp;
47 using namespace xmltooling;
48 using namespace std;
49
50 namespace shibsp {
51
52 #if defined (_MSC_VER)
53     #pragma warning( push )
54     #pragma warning( disable : 4250 )
55 #endif
56     
57     class SHIBSP_DLLLOCAL SAML1Consumer : public AssertionConsumerService
58     {
59     public:
60         SAML1Consumer(const DOMElement* e, const char* appId)
61                 : AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".SSO.SAML1")) {
62 #ifndef SHIBSP_LITE
63             m_post = XMLString::equals(getString("Binding").second, samlconstants::SAML1_PROFILE_BROWSER_POST);
64 #endif
65         }
66         virtual ~SAML1Consumer() {}
67         
68     private:
69 #ifndef SHIBSP_LITE
70         string implementProtocol(
71             const Application& application,
72             const HTTPRequest& httpRequest,
73             SecurityPolicy& policy,
74             const PropertySet* settings,
75             const XMLObject& xmlObject
76             ) const;
77         bool m_post;
78 #endif
79     };
80
81 #if defined (_MSC_VER)
82     #pragma warning( pop )
83 #endif
84
85     Handler* SHIBSP_DLLLOCAL SAML1ConsumerFactory(const pair<const DOMElement*,const char*>& p)
86     {
87         return new SAML1Consumer(p.first, p.second);
88     }
89     
90 };
91
92 #ifndef SHIBSP_LITE
93
94 string SAML1Consumer::implementProtocol(
95     const Application& application,
96     const HTTPRequest& httpRequest,
97     SecurityPolicy& policy,
98     const PropertySet* settings,
99     const XMLObject& xmlObject
100     ) const
101 {
102     // Implementation of SAML 1.x SSO profile(s).
103     m_log.debug("processing message against SAML 1.x SSO profile");
104
105     // With the binding aspects now moved out to the MessageDecoder,
106     // the focus here is on the assertion content. For SAML 1.x POST,
107     // all the security comes from the protocol layer, and signing
108     // the assertion isn't sufficient. So we can check the policy
109     // object now and bail if it's not a secure message.
110     if (m_post && !policy.isSecure())
111         throw SecurityPolicyException("Security of SAML 1.x SSO POST response not established.");
112         
113     // Remember whether we already established trust.
114     bool alreadySecured = policy.isSecure();
115
116     // Check for errors...this will throw if it's not a successful message.
117     checkError(&xmlObject);
118
119     const Response* response = dynamic_cast<const Response*>(&xmlObject);
120     if (!response)
121         throw FatalProfileException("Incoming message was not a samlp:Response.");
122
123     const vector<saml1::Assertion*>& assertions = response->getAssertions();
124     if (assertions.empty())
125         throw FatalProfileException("Incoming message contained no SAML assertions.");
126
127     // Maintain list of "legit" tokens to feed to SP subsystems.
128     const AuthenticationStatement* ssoStatement=NULL;
129     vector<const opensaml::Assertion*> tokens;
130
131     // Also track "bad" tokens that we'll cache but not use.
132     // This is necessary because there may be valid tokens not aimed at us.
133     vector<const opensaml::Assertion*> badtokens;
134
135     // Profile validator.
136     time_t now = time(NULL);
137     BrowserSSOProfileValidator ssoValidator(application.getAudiences(), now);
138
139     // With this flag on, we ignore any unsigned assertions.
140     pair<bool,bool> flag = settings->getBool("signedAssertions");
141
142     for (vector<saml1::Assertion*>::const_iterator a = assertions.begin(); a!=assertions.end(); ++a) {
143         // Skip unsigned assertion?
144         if (!(*a)->getSignature() && flag.first && flag.second) {
145             m_log.warn("found unsigned assertion in SAML response, ignoring it per signedAssertions policy");
146             badtokens.push_back(*a);
147             continue;
148         }
149
150         try {
151             // We clear the security flag, so we can tell whether the token was secured on its own.
152             policy.setSecure(false);
153             
154             // Run the policy over the assertion. Handles issuer consistency, replay, freshness,
155             // and signature verification, assuming the relevant rules are configured.
156             policy.evaluate(*(*a));
157             
158             // If no security is in place now, we kick it.
159             if (!alreadySecured && !policy.isSecure()) {
160                 m_log.warn("unable to establish security of assertion");
161                 badtokens.push_back(*a);
162                 continue;
163             }
164
165             // Now do profile and core semantic validation to ensure we can use it for SSO.
166             ssoValidator.validateAssertion(*(*a));
167
168             // Track it as a valid token.
169             tokens.push_back(*a);
170
171             // Save off the first valid SSO statement.
172             if (!ssoStatement && !(*a)->getAuthenticationStatements().empty())
173                 ssoStatement = (*a)->getAuthenticationStatements().front();
174         }
175         catch (exception& ex) {
176             m_log.warn("detected a problem with assertion: %s", ex.what());
177             badtokens.push_back(*a);
178         }
179     }
180
181     if (!ssoStatement)
182         throw FatalProfileException("A valid authentication statement was not found in the incoming message.");
183
184     // Address checking.
185     SubjectLocality* locality = ssoStatement->getSubjectLocality();
186     if (locality && locality->getIPAddress()) {
187         auto_ptr_char ip(locality->getIPAddress());
188         checkAddress(application, httpRequest, ip.get());
189     }
190
191     m_log.debug("SSO profile processing completed successfully");
192
193     NameIdentifier* n = ssoStatement->getSubject()->getNameIdentifier();
194
195     // Now we have to extract the authentication details for attribute and session setup.
196
197     // Session expiration for SAML 1.x is purely SP-driven, and the method is mapped to a ctx class.
198     const PropertySet* sessionProps = application.getPropertySet("Sessions");
199     pair<bool,unsigned int> lifetime = sessionProps ? sessionProps->getUnsignedInt("lifetime") : pair<bool,unsigned int>(true,28800);
200     if (!lifetime.first || lifetime.second == 0)
201         lifetime.second = 28800;
202
203     // We've successfully "accepted" at least one SSO token, along with any additional valid tokens.
204     // To complete processing, we need to extract and resolve attributes and then create the session.
205
206     // Normalize the SAML 1.x NameIdentifier...
207     auto_ptr<NameID> nameid(n ? NameIDBuilder::buildNameID() : NULL);
208     if (n) {
209         nameid->setName(n->getName());
210         nameid->setFormat(n->getFormat());
211         nameid->setNameQualifier(n->getNameQualifier());
212     }
213
214     // The context will handle deleting attributes and new tokens.
215     auto_ptr<ResolutionContext> ctx(
216         resolveAttributes(
217             application,
218             policy.getIssuerMetadata(),
219             (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
220                 samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
221             n,
222             nameid.get(),
223             ssoStatement->getAuthenticationMethod(),
224             NULL,
225             &tokens
226             )
227         );
228
229     if (ctx.get()) {
230         // Copy over any new tokens, but leave them in the context for cleanup.
231         tokens.insert(tokens.end(), ctx->getResolvedAssertions().begin(), ctx->getResolvedAssertions().end());
232     }
233
234     // Now merge in bad tokens for caching.
235     tokens.insert(tokens.end(), badtokens.begin(), badtokens.end());
236
237     return application.getServiceProvider().getSessionCache()->insert(
238         now + lifetime.second,
239         application,
240         httpRequest.getRemoteAddr().c_str(),
241         policy.getIssuerMetadata() ? dynamic_cast<const EntityDescriptor*>(policy.getIssuerMetadata()->getParent()) : NULL,
242         (!response->getMinorVersion().first || response->getMinorVersion().second==1) ?
243             samlconstants::SAML11_PROTOCOL_ENUM : samlconstants::SAML10_PROTOCOL_ENUM,
244         nameid.get(),
245         ssoStatement->getAuthenticationInstant() ? ssoStatement->getAuthenticationInstant()->getRawData() : NULL,
246         NULL,
247         ssoStatement->getAuthenticationMethod(),
248         NULL,
249         &tokens,
250         ctx.get() ? &ctx->getResolvedAttributes() : NULL
251         );
252 }
253
254 #endif