2 * Copyright 2001-2005 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>
30 using namespace log4cpp;
32 using namespace shibboleth;
33 using namespace shibtarget;
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 authentication assertion");
214 throw TrustException("unable to verify signed authentication assertion");
217 // Now dummy up the SAML profile response wrapper.
218 param=parser.get_value("wctx");
221 bpr.profile=SAMLBrowserProfile::Post; // not really, but...
222 bpr.response=response.release();
223 bpr.assertion=assertion;
224 bpr.authnStatement=authnStatement;
226 catch (SAMLException& ex) {
227 annotateException(&ex,role); // throws it
238 if (rdoc) rdoc->release();
242 if (bADFS && !bpr.response)
243 throw FatalProfileException("ADFS profile was indicated, but processing was unsuccesful");
246 // If ADFS wasn't used, proceed to SAML processing up until we reach a common point.
247 int minorVersion = 1;
251 if (supported_profiles & SAML11_POST || supported_profiles & SAML10_POST)
252 allowed |= SAMLBrowserProfile::Post;
253 if (supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML10_ARTIFACT)
254 allowed |= SAMLBrowserProfile::Artifact;
255 minorVersion=(supported_profiles & SAML11_ARTIFACT || supported_profiles & SAML11_POST) ? 1 : 0;
257 auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
259 // Try and run the profile.
260 log->debug("executing browser profile...");
261 bpr=app->getBrowserProfile()->receive(
265 (!checkReplay.first || checkReplay.second) ? conf->getReplayCache() : NULL,
266 artifactMapper.get(),
270 // Blow it away to clear any locks that might be held.
271 delete artifactMapper.release();
273 // Try and map to metadata (again).
274 // Once the metadata layer is in the SAML core, the repetition should be fixed.
275 const IEntityDescriptor* provider=m.lookup(bpr.assertion->getIssuer());
276 if (!provider && bpr.authnStatement->getSubject()->getNameIdentifier() &&
277 bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier())
278 provider=m.lookup(bpr.authnStatement->getSubject()->getNameIdentifier()->getNameQualifier());
280 const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
281 minorVersion==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
286 // This isn't likely, since the profile must have found a role.
288 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
289 annotateException(&ex,provider); // throws it
293 // At this point, we link back up and do the same work for ADFS and SAML.
295 // Maybe verify the origin address....
296 if (checkIPAddress) {
297 log->debug("verifying client address");
298 // Verify the client address exists
299 const XMLCh* wip = bpr.authnStatement->getSubjectIP();
301 // Verify the client address matches authentication
302 auto_ptr_char this_ip(ip);
303 if (strcmp(ip, this_ip.get())) {
304 FatalProfileException ex(
305 SESSION_E_ADDRESSMISMATCH,
306 "Your client's current address ($1) differs from the one used when you authenticated "
307 "to your identity provider. To correct this problem, you may need to bypass a proxy server. "
308 "Please contact your local support staff or help desk for assistance.",
311 annotateException(&ex,role); // throws it
316 // Verify condition(s) on authentication assertion.
317 // Attribute assertions get filtered later by the AAP.
318 Iterator<SAMLCondition*> conditions=bpr.assertion->getConditions();
319 while (conditions.hasNext()) {
320 SAMLCondition* cond=conditions.next();
321 const SAMLAudienceRestrictionCondition* ac=dynamic_cast<const SAMLAudienceRestrictionCondition*>(cond);
325 log->error("Unrecognized Condition in authentication assertion (%s), tossing it.",os.str().c_str());
326 FatalProfileException ex("unable to create session due to unrecognized condition in authentication assertion.");
327 annotateException(&ex,role); // throws it
329 else if (!ac->eval(app->getAudiences())) {
332 log->error("Unacceptable AudienceRestrictionCondition in authentication assertion (%s), tossing it.",os.str().c_str());
333 FatalProfileException ex("unable to create session due to unacceptable AudienceRestrictionCondition in authentication assertion.");
334 annotateException(&ex,role); // throws it
338 catch (SAMLException&) {
343 log->error("caught unknown exception");
348 SAMLException e("An unexpected error occurred while creating your session.");
349 annotateException(&e,role);
353 // It passes all our tests -- create a new session.
354 log->info("creating 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());
368 auto_ptr_char hname(bpr.authnStatement->getSubject()->getNameIdentifier()->getName());
371 // Create a new session key.
372 cookie = conf->getSessionCache()->generateKey();
374 // Insert into cache.
375 auto_ptr<SAMLAuthenticationStatement> as(static_cast<SAMLAuthenticationStatement*>(bpr.authnStatement->clone()));
376 conf->getSessionCache()->insert(
381 ((bpr.profile==SAMLBrowserProfile::Post) ?
382 (minorVersion==1 ? SAML11_POST : SAML10_POST) : (minorVersion==1 ? SAML11_ARTIFACT : SAML10_ARTIFACT))),
385 (attributesPushed ? bpr.response : NULL),
388 as.release(); // owned by cache now
390 catch (SAMLException&) {
395 log->error("caught unknown exception");
400 SAMLException e("An unexpected error occurred while creating your session.");
401 annotateException(&e,role);
406 provider_id = oname.get();
408 // Maybe delete the response...
409 if (!attributesPushed)
412 log->debug("new session id: %s", cookie.c_str());
414 // Transaction Logging
415 Category::getInstance(SHIBTRAN_LOGCAT).infoStream() <<
416 "New session (ID: " <<
418 ") with (applicationId: " <<
420 ") for principal from (IdP: " <<
422 ") at (ClientAddress: " <<
424 ") with (NameIdentifier: " <<
427 //stc.releaseTransactionLog();
430 void ADFSListener::sessionGet(
431 const IApplication* app,
434 ISessionCacheEntry** pentry
437 g_MemoryListener->sessionGet(app,cookie,ip,pentry);
440 void ADFSListener::sessionEnd(
441 const IApplication* application,
445 g_MemoryListener->sessionEnd(application,cookie);
448 void ADFSListener::ping(int& i) const
450 g_MemoryListener->ping(i);