2 * Copyright 2001-2009 Internet2
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * listener.cpp -- implementation of IListener functional methods that includes ADFS support
27 #include <xercesc/framework/MemBufInputSource.hpp>
31 using namespace shibboleth;
32 using namespace shibtarget;
34 using namespace adfs::logging;
37 class ADFSListener : public virtual IListener
40 ADFSListener(const DOMElement* e) : log(&Category::getInstance(ADFS_LOGCAT".Listener")) {}
43 bool create(ShibSocket& s) const {return true;}
44 bool bind(ShibSocket& s, bool force=false) const {return true;}
45 bool connect(ShibSocket& s) const {return true;}
46 bool close(ShibSocket& s) const {return true;}
47 bool accept(ShibSocket& listener, ShibSocket& s) const {return true;}
50 const IApplication* application,
51 int supported_profiles,
52 const char* recipient,
57 std::string& provider_id
61 const IApplication* application,
64 ISessionCacheEntry** pentry
68 const IApplication* application,
72 void ping(int& i) const;
79 IPlugIn* ADFSListenerFactory(const DOMElement* e)
81 return new ADFSListener(e);
84 void ADFSListener::sessionNew(
85 const IApplication* app,
86 int supported_profiles,
87 const char* recipient,
96 saml::NDC ndc("sessionNew");
99 log->debug("creating session for %s", ip);
100 log->debug("recipient: %s", recipient);
101 log->debug("application: %s", app->getId());
103 auto_ptr_XMLCh wrecipient(recipient);
105 // Access the application config. It's already locked behind us.
106 ShibTargetConfig& stc=ShibTargetConfig::getConfig();
107 IConfig* conf=stc.getINI();
109 bool checkIPAddress=true;
110 const IPropertySet* props=app->getPropertySet("Sessions");
112 pair<bool,bool> pcheck=props->getBool("checkAddress");
114 checkIPAddress = pcheck.second;
117 pair<bool,bool> checkReplay=pair<bool,bool>(false,false);
118 props=app->getPropertySet("Sessions");
120 checkReplay=props->getBool("checkReplay");
122 const IRoleDescriptor* role=NULL;
123 Metadata m(app->getMetadataProviders());
126 SAMLBrowserProfile::BrowserProfileResponse bpr;
128 // For now, just branch off to handle ADFS inline, I'll wrap all this up later.
129 if (supported_profiles & ADFS_SSO) {
130 log->debug("executing ADFS profile...");
131 CgiParse parser(packet,strlen(packet));
132 const char* param=parser.get_value("wa");
133 if (param && !strcmp(param,"wsignin1.0")) {
135 param=parser.get_value("wresult");
137 throw FatalProfileException("ADFS profile required wresult parameter not found");
139 log->debug("decoded ADFS Token response:\n%s",param);
140 // wresult should carry an wst:RequestSecurityTokenResponse message so we parse it manually
141 DOMDocument* rdoc=NULL;
144 static const XMLCh systemId[]={chLatin_W, chLatin_S, chDash, chLatin_T, chLatin_r, chLatin_u, chLatin_s, chLatin_t, chNull};
145 MemBufInputSource membufsrc(reinterpret_cast<const XMLByte*>(param),strlen(param),systemId,false);
146 Wrapper4InputSource dsrc(&membufsrc,false);
149 // Process the wrapper and extract the assertion.
150 if (saml::XML::isElementNamed(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestSecurityTokenResponse))) {
152 saml::XML::getFirstChildElement(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestedSecurityToken));
154 e=saml::XML::getFirstChildElement(e,saml::XML::SAML_NS,L(Assertion));
157 // Wrap the assertion DOM in a dummy samlp:Response for subsequent processing.
158 // We have to manually create the Response DOM first in order to avoid
159 // corrupting the namespace declarations in the Assertion.
161 static const XMLCh One[]={chDigit_1, chNull};
162 static const XMLCh dummyID[] = {chLatin_A, chLatin_D, chLatin_F, chLatin_S, chNull};
163 static const XMLCh samlp_Success[]=
164 { chLatin_s, chLatin_a, chLatin_m, chLatin_l, chLatin_p, chColon,
165 chLatin_S, chLatin_u, chLatin_c, chLatin_c, chLatin_e, chLatin_s, chLatin_s, chNull };
166 DOMElement* rdom=rdoc->createElementNS(saml::XML::SAMLP_NS,L(Response));
167 rdom->setAttributeNS(saml::XML::XMLNS_NS,L_QNAME(xmlns,samlp),saml::XML::SAMLP_NS);
168 rdom->setAttributeNS(saml::XML::XMLNS_NS,L(xmlns),saml::XML::SAMLP_NS);
169 rdom->setAttributeNS(NULL,L(MajorVersion),One);
170 rdom->setAttributeNS(NULL,L(MinorVersion),One);
171 rdom->setAttributeNS(NULL,L(ResponseID),dummyID);
172 SAMLDateTime issued(time(NULL));
173 issued.parseDateTime();
174 rdom->setAttributeNS(NULL,L(IssueInstant),issued.getRawData());
175 DOMElement* status=rdoc->createElementNS(saml::XML::SAMLP_NS,L(Status));
176 rdom->appendChild(status);
177 DOMElement* code=rdoc->createElementNS(saml::XML::SAMLP_NS,L(StatusCode));
178 code->setAttributeNS(NULL,L(Value),samlp_Success);
179 status->appendChild(code);
180 rdom->appendChild(e); // append the assertion
181 auto_ptr<SAMLResponse> response(new SAMLResponse(rdom));
182 response->setDocument(rdoc); // give the Document to the response object
183 // root the response in the document so the signature will verify
184 rdoc->replaceChild(response->toDOM(rdoc,false),rdoc->getDocumentElement());
187 // Try and map to metadata.
188 SAMLAssertion* assertion=response->getAssertions().next();
189 const IEntityDescriptor* provider=m.lookup(assertion->getIssuer());
191 role=provider->getIDPSSODescriptor(adfs::XML::WSFED_NS);
193 MetadataException ex("unable to locate role-specific metadata for identity provider.");
194 annotateException(&ex,provider); // throws it
198 // Check over the assertion.
199 SAMLAuthenticationStatement* authnStatement=checkAssertionProfile(assertion);
201 if (!checkReplay.first || checkReplay.second) {
202 auto_ptr_char id(assertion->getId());
203 string key(id.get());
205 if (!conf->getReplayCache()->check(key.c_str(),assertion->getNotOnOrAfter()->getEpoch()))
206 throw ReplayedAssertionException(string("Rejecting replayed assertion ID (") + id.get() + ")");
210 log->debug("passing signed ADFS assertion to trust layer");
211 Trust t(app->getTrustProviders());
212 if (!t.validate(*assertion,role)) {
213 log->error("unable to verify signed ADFS assertion");
214 throw TrustException("unable to verify signed authentication assertion");
216 log->info("verified digital signature over ADFS assertion");
218 // Now dummy up the SAML profile response wrapper.
219 param=parser.get_value("wctx");
222 bpr.profile=SAMLBrowserProfile::Post; // not really, but...
223 bpr.response=response.release();
224 bpr.assertion=assertion;
225 bpr.authnStatement=authnStatement;
227 catch (SAMLException& ex) {
228 annotateException(&ex,role); // throws it
239 if (rdoc) rdoc->release();
243 if (bADFS && !bpr.response)
244 throw FatalProfileException("ADFS profile was indicated, but processing was unsuccesful");
247 // If ADFS wasn't used, proceed to SAML processing up until we reach a common point.
248 int minorVersion = 1;
252 if (supported_profiles & SAML11_POST || supported_profiles & SAML10_POST)
253 allowed |= SAMLBrowserProfile::Post;
254 if (supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML10_ARTIFACT)
255 allowed |= SAMLBrowserProfile::Artifact;
256 minorVersion=(supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML11_POST) ? 1 : 0;
258 auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
260 // Try and run the profile.
261 log->debug("executing browser profile...");
262 bpr=app->getBrowserProfile()->receive(
266 (!checkReplay.first || checkReplay.second) ? conf->getReplayCache() : NULL,
267 artifactMapper.get(),
271 // Blow it away to clear any locks that might be held.
272 delete artifactMapper.release();
274 // Try and map to metadata (again).
275 // Once the metadata layer is in the SAML core, the repetition should be fixed.
276 const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
277 if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
278 bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
279 provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
281 const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
282 minorVersion==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
287 // This isn't likely, since the profile must have found a role.
289 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
290 annotateException(&ex,provider); // throws it
294 // At this point, we link back up and do the same work for ADFS and SAML.
296 // Maybe verify the origin address....
297 if (checkIPAddress) {
298 log->debug("verifying client address");
299 // Verify the client address exists
300 const XMLCh* wip = bpr.authnStatement->getSubjectIP();
302 // Verify the client address matches authentication
303 auto_ptr_char this_ip(wip);
304 if (strcmp(ip, this_ip.get())) {
305 FatalProfileException ex(
306 SESSION_E_ADDRESSMISMATCH,
307 "Your client's current address ($1) differs from the one used when you authenticated "
308 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
309 "Please contact your local support staff or help desk for assistance.",
312 annotateException(&ex,role); // throws it
317 // Verify condition(s) on authentication assertion.
318 // Attribute assertions get filtered later by the AAP.
319 Iterator<SAMLCondition*> conditions=bpr.assertion->getConditions();
320 while (conditions.hasNext()) {
321 SAMLCondition* cond=conditions.next();
322 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
326 log->error("Unrecognized Condition in authentication assertion (%s), tossing it.",os.str().c_str());
327 FatalProfileException ex("unable to create session due to unrecognized condition in authentication assertion.");
328 annotateException(&ex,role); // throws it
330 else if (!ac->eval(app->getAudiences())) {
333 log->error("Unacceptable AudienceRestrictionCondition in authentication assertion (%s), tossing it.",os.str().c_str());
334 FatalProfileException ex("unable to create session due to unacceptable AudienceRestrictionCondition in authentication assertion.");
335 annotateException(&ex,role); // throws it
339 catch (SAMLException&) {
344 log->error("caught unknown exception");
349 SAMLException e("An unexpected error occurred while creating your session.");
350 annotateException(&e,role);
354 // It passes all our tests -- create a new session.
356 // Are attributes present?
357 bool attributesPushed=false;
358 Iterator<SAMLAssertion*> assertions=bpr.response->getAssertions();
359 while (!attributesPushed && assertions.hasNext()) {
360 Iterator<SAMLStatement*> statements=assertions.next()->getStatements();
361 while (!attributesPushed && statements.hasNext()) {
362 if (dynamic_cast<SAMLAttributeStatement*>(statements.next()))
363 attributesPushed=true;
367 auto_ptr_char oname(role->getEntityDescriptor()->getId());
369 bpr.authnStatement->getSubject()->getNameIdentifier() ?
370 bpr.authnStatement->getSubject()->getNameIdentifier()->getName() :
375 // Create a new session key.
376 cookie = conf->getSessionCache()->generateKey();
378 // Insert into cache.
379 auto_ptr<SAMLAuthenticationStatement> as(static_cast<SAMLAuthenticationStatement*>(bpr.authnStatement->clone()));
380 conf->getSessionCache()->insert(
385 ((bpr.profile==SAMLBrowserProfile::Post) ?
386 (minorVersion==1 ? SAML11_POST : SAML10_POST) : (minorVersion==1 ? SAML11_ARTIFACT : SAML10_ARTIFACT))),
389 (attributesPushed ? bpr.response : NULL),
392 as.release(); // owned by cache now
394 catch (SAMLException&) {
399 log->error("caught unknown exception");
404 SAMLException e("An unexpected error occurred while creating your session.");
405 annotateException(&e,role);
410 provider_id = oname.get();
412 // Maybe delete the response...
413 if (!attributesPushed)
416 log->debug("new session id: %s", cookie.c_str());
418 // Transaction Logging
419 FixedContextCategory tranLog(SHIBTRAN_LOGCAT);
420 tranLog.infoStream() <<
421 "New session (ID: " <<
423 ") with (applicationId: " <<
425 ") for principal from (IdP: " <<
427 ") at (ClientAddress: " <<
429 ") with (NameIdentifier: " <<
430 (hname.get() ? hname.get() : "none") <<
432 //stc.releaseTransactionLog();
435 void ADFSListener::sessionGet(
436 const IApplication* app,
439 ISessionCacheEntry** pentry
442 g_MemoryListener->sessionGet(app,cookie,ip,pentry);
445 void ADFSListener::sessionEnd(
446 const IApplication* application,
450 g_MemoryListener->sessionEnd(application,cookie);
453 void ADFSListener::ping(int& i) const
455 g_MemoryListener->ping(i);