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