Logging improvements, especially around trust operations.
[shibboleth/cpp-sp.git] / adfs / listener.cpp
1 /*
2  *  Copyright 2001-2005 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  * listener.cpp -- implementation of IListener functional methods that includes ADFS support
19  *
20  * Scott Cantor
21  * 10/10/05
22  *
23  */
24
25 #include "internal.h"
26
27 #include <xercesc/framework/MemBufInputSource.hpp>
28
29 using namespace std;
30 using namespace saml;
31 using namespace shibboleth;
32 using namespace shibtarget;
33 using namespace adfs;
34 using namespace adfs::logging;
35
36 namespace {
37     class ADFSListener : public virtual IListener
38     {
39     public:
40         ADFSListener(const DOMElement* e) : log(&Category::getInstance(ADFS_LOGCAT".Listener")) {}
41         ~ADFSListener() {}
42
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;}
48
49         void sessionNew(
50             const IApplication* application,
51             int supported_profiles,
52             const char* recipient,
53             const char* packet,
54             const char* ip,
55             std::string& target,
56             std::string& cookie,
57             std::string& provider_id
58             ) const;
59     
60         void sessionGet(
61             const IApplication* application,
62             const char* cookie,
63             const char* ip,
64             ISessionCacheEntry** pentry
65             ) const;
66     
67         void sessionEnd(
68             const IApplication* application,
69             const char* cookie
70         ) const;
71         
72         void ping(int& i) const;
73
74     private:
75         Category* log;
76     };
77 }
78
79 IPlugIn* ADFSListenerFactory(const DOMElement* e)
80 {
81     return new ADFSListener(e);
82 }
83
84 void ADFSListener::sessionNew(
85     const IApplication* app,
86     int supported_profiles,
87     const char* recipient,
88     const char* packet,
89     const char* ip,
90     string& target,
91     string& cookie,
92     string& provider_id
93     ) const
94 {
95 #ifdef _DEBUG
96     saml::NDC ndc("sessionNew");
97 #endif
98
99     log->debug("creating session for %s", ip);
100     log->debug("recipient: %s", recipient);
101     log->debug("application: %s", app->getId());
102
103     auto_ptr_XMLCh wrecipient(recipient);
104
105     // Access the application config. It's already locked behind us.
106     ShibTargetConfig& stc=ShibTargetConfig::getConfig();
107     IConfig* conf=stc.getINI();
108
109     bool checkIPAddress=true;
110     const IPropertySet* props=app->getPropertySet("Sessions");
111     if (props) {
112         pair<bool,bool> pcheck=props->getBool("checkAddress");
113         if (pcheck.first)
114             checkIPAddress = pcheck.second;
115     }
116
117     pair<bool,bool> checkReplay=pair<bool,bool>(false,false);
118     props=app->getPropertySet("Sessions");
119     if (props)
120         checkReplay=props->getBool("checkReplay");
121  
122     const IRoleDescriptor* role=NULL;
123     Metadata m(app->getMetadataProviders());
124
125     bool bADFS = false;
126     SAMLBrowserProfile::BrowserProfileResponse bpr;
127
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")) {
134             bADFS=true;
135             param=parser.get_value("wresult");
136             if (!param)
137                 throw FatalProfileException("ADFS profile required wresult parameter not found");
138             
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;
142             try {
143                 saml::XML::Parser p;
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);
147                 rdoc=p.parse(dsrc);
148         
149                 // Process the wrapper and extract the assertion.
150                 if (saml::XML::isElementNamed(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestSecurityTokenResponse))) {
151                     DOMElement* e=
152                         saml::XML::getFirstChildElement(rdoc->getDocumentElement(),adfs::XML::WSTRUST_NS,ADFS_L(RequestedSecurityToken));
153                     if (e) {
154                         e=saml::XML::getFirstChildElement(e,saml::XML::SAML_NS,L(Assertion));
155                         if (e) {
156
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.
160
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());
185                             rdoc=NULL;
186                             
187                             // Try and map to metadata.
188                             SAMLAssertion* assertion=response->getAssertions().next();
189                             const IEntityDescriptor* provider=m.lookup(assertion->getIssuer());
190                             if (provider)
191                                 role=provider->getIDPSSODescriptor(adfs::XML::WSFED_NS);
192                             if (!role) {
193                                 MetadataException ex("unable to locate role-specific metadata for identity provider.");
194                                 annotateException(&ex,provider); // throws it
195                             }
196                             
197                             try {
198                                 // Check over the assertion.
199                                 SAMLAuthenticationStatement* authnStatement=checkAssertionProfile(assertion);
200
201                                 if (!checkReplay.first || checkReplay.second) {
202                                     auto_ptr_char id(assertion->getId());
203                                     string key(id.get());
204                                     key="P_" + key;
205                                     if (!conf->getReplayCache()->check(key.c_str(),assertion->getNotOnOrAfter()->getEpoch()))
206                                         throw ReplayedAssertionException(string("Rejecting replayed assertion ID (") + id.get() + ")");
207                                 }
208                                 
209                                 // Check signature.
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");
215                                 }
216                                 log->info("verified digital signature over ADFS assertion");
217                                 
218                                 // Now dummy up the SAML profile response wrapper.
219                                 param=parser.get_value("wctx");
220                                 if (param)
221                                     bpr.TARGET=param;
222                                 bpr.profile=SAMLBrowserProfile::Post;   // not really, but...
223                                 bpr.response=response.release();
224                                 bpr.assertion=assertion;
225                                 bpr.authnStatement=authnStatement;
226                             }
227                             catch (SAMLException& ex) {
228                                 annotateException(&ex,role); // throws it
229                             }
230                         }
231                     }
232                 }
233                 if (rdoc) {
234                     rdoc->release();
235                     rdoc=NULL;
236                 }
237             }
238             catch(...) {
239                 if (rdoc) rdoc->release();
240                 throw;
241             }
242         }
243         if (bADFS && !bpr.response)
244             throw FatalProfileException("ADFS profile was indicated, but processing was unsuccesful");
245     }
246     
247     // If ADFS wasn't used, proceed to SAML processing up until we reach a common point.
248     int minorVersion = 1;
249     try {
250         if (!bADFS) {
251             int allowed = 0;
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;
257     
258             auto_ptr<SAMLBrowserProfile::ArtifactMapper> artifactMapper(app->getArtifactMapper());
259       
260             // Try and run the profile.
261             log->debug("executing browser profile...");
262             bpr=app->getBrowserProfile()->receive(
263                 packet,
264                 wrecipient.get(),
265                 allowed,
266                 (!checkReplay.first || checkReplay.second) ? conf->getReplayCache() : NULL,
267                 artifactMapper.get(),
268                 minorVersion
269                 );
270     
271             // Blow it away to clear any locks that might be held.
272             delete artifactMapper.release();
273     
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());
280             if (provider) {
281                 const IIDPSSODescriptor* IDP=provider->getIDPSSODescriptor(
282                     minorVersion==1 ? saml::XML::SAML11_PROTOCOL_ENUM : saml::XML::SAML10_PROTOCOL_ENUM
283                     );
284                 role=IDP;
285             }
286             
287             // This isn't likely, since the profile must have found a role.
288             if (!role) {
289                 MetadataException ex("Unable to locate role-specific metadata for identity provider.");
290                 annotateException(&ex,provider); // throws it
291             }
292         }
293         
294         // At this point, we link back up and do the same work for ADFS and SAML.
295         
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();
301             if (wip && *wip) {
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.",
310                         params(1,ip)
311                         );
312                     annotateException(&ex,role); // throws it
313                 }
314             }
315         }
316       
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);
323             if (!ac) {
324                 ostringstream os;
325                 os << *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
329             }
330             else if (!ac->eval(app->getAudiences())) {
331                 ostringstream os;
332                 os << *ac;
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
336             }
337         }
338     }
339     catch (SAMLException&) {
340         bpr.clear();
341         throw;
342     }
343     catch (...) {
344         log->error("caught unknown exception");
345         bpr.clear();
346 #ifdef _DEBUG
347         throw;
348 #else
349         SAMLException e("An unexpected error occurred while creating your session.");
350         annotateException(&e,role);
351 #endif
352     }
353
354     // It passes all our tests -- create a new session.
355
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;
364         }
365     }
366
367     auto_ptr_char oname(role->getEntityDescriptor()->getId());
368     auto_ptr_char hname(bpr.authnStatement->getSubject()->getNameIdentifier()->getName());
369
370     try {
371         // Create a new session key.
372         cookie = conf->getSessionCache()->generateKey();
373
374         // Insert into cache.
375         auto_ptr<SAMLAuthenticationStatement> as(static_cast<SAMLAuthenticationStatement*>(bpr.authnStatement->clone()));
376         conf->getSessionCache()->insert(
377             cookie.c_str(),
378             app,
379             ip,
380             (bADFS ? ADFS_SSO :
381                 ((bpr.profile==SAMLBrowserProfile::Post) ?
382                     (minorVersion==1 ? SAML11_POST : SAML10_POST) : (minorVersion==1 ? SAML11_ARTIFACT : SAML10_ARTIFACT))),
383             oname.get(),
384             as.get(),
385             (attributesPushed ? bpr.response : NULL),
386             role
387             );
388         as.release();   // owned by cache now
389     }
390     catch (SAMLException&) {
391         bpr.clear();
392         throw;
393     }
394     catch (...) {
395         log->error("caught unknown exception");
396         bpr.clear();
397 #ifdef _DEBUG
398         throw;
399 #else
400         SAMLException e("An unexpected error occurred while creating your session.");
401         annotateException(&e,role);
402 #endif
403     }
404
405     target = bpr.TARGET;
406     provider_id = oname.get();
407
408     // Maybe delete the response...
409     if (!attributesPushed)
410         bpr.clear();
411
412     log->debug("new session id: %s", cookie.c_str());
413   
414     // Transaction Logging
415     FixedContextCategory tranLog(SHIBTRAN_LOGCAT);
416     tranLog.infoStream() <<
417         "New session (ID: " <<
418             cookie <<
419         ") with (applicationId: " <<
420             app->getId() <<
421         ") for principal from (IdP: " <<
422             provider_id <<
423         ") at (ClientAddress: " <<
424             ip <<
425         ") with (NameIdentifier: " <<
426             hname.get() <<
427         ")";
428     //stc.releaseTransactionLog();
429 }
430
431 void ADFSListener::sessionGet(
432     const IApplication* app,
433     const char* cookie,
434     const char* ip,
435     ISessionCacheEntry** pentry
436     ) const
437 {
438     g_MemoryListener->sessionGet(app,cookie,ip,pentry);
439 }
440
441 void ADFSListener::sessionEnd(
442     const IApplication* application,
443     const char* cookie
444     ) const
445 {
446     g_MemoryListener->sessionEnd(application,cookie);
447 }
448
449 void ADFSListener::ping(int& i) const
450 {
451     g_MemoryListener->ping(i);
452 }