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