Fix for empty decoder result, take out old logout handler.
[shibboleth/cpp-sp.git] / shibsp / attribute / resolver / impl / XMLAttributeExtractor.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  * XMLAttributeExtractor.cpp
19  * 
20  * AttributeExtractor based on an XML mapping file.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "ServiceProvider.h"
26 #include "attribute/AttributeDecoder.h"
27 #include "attribute/resolver/AttributeExtractor.h"
28 #include "util/SPConstants.h"
29
30 #include <saml/saml1/core/Assertions.h>
31 #include <saml/saml2/core/Assertions.h>
32 #include <saml/saml2/metadata/MetadataCredentialCriteria.h>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/ReloadableXMLFile.h>
35 #include <xmltooling/util/XMLHelper.h>
36 #include <xercesc/util/XMLUniDefs.hpp>
37
38 using namespace shibsp;
39 using namespace opensaml::saml2md;
40 using namespace opensaml;
41 using namespace xmltooling;
42 using namespace log4cpp;
43 using namespace std;
44 using saml1::NameIdentifier;
45 using saml2::NameID;
46 using saml2::EncryptedAttribute;
47
48 namespace shibsp {
49
50 #if defined (_MSC_VER)
51     #pragma warning( push )
52     #pragma warning( disable : 4250 )
53 #endif
54
55     class XMLExtractorImpl
56     {
57     public:
58         XMLExtractorImpl(const DOMElement* e, Category& log);
59         ~XMLExtractorImpl() {
60             for (attrmap_t::iterator i = m_attrMap.begin(); i!=m_attrMap.end(); ++i)
61                 delete i->second.first;
62             if (m_document)
63                 m_document->release();
64         }
65
66         void setDocument(DOMDocument* doc) {
67             m_document = doc;
68         }
69
70         void extractAttributes(
71             const Application& application, const char* assertingParty, const NameIdentifier& nameid, multimap<string,Attribute*>& attributes
72             ) const;
73         void extractAttributes(
74             const Application& application, const char* assertingParty, const NameID& nameid, multimap<string,Attribute*>& attributes
75             ) const;
76         void extractAttributes(
77             const Application& application, const char* assertingParty, const saml1::Attribute& attr, multimap<string,Attribute*>& attributes
78             ) const;
79         void extractAttributes(
80             const Application& application, const char* assertingParty, const saml2::Attribute& attr, multimap<string,Attribute*>& attributes
81             ) const;
82
83         void getAttributeIds(vector<string>& attributes) const {
84             attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
85         }
86
87     private:
88         Category& m_log;
89         DOMDocument* m_document;
90 #ifdef HAVE_GOOD_STL
91         typedef map< pair<xstring,xstring>,pair<AttributeDecoder*,string> > attrmap_t;
92 #else
93         typedef map< pair<string,string>,pair<AttributeDecoder*,string> > attrmap_t;
94 #endif
95         attrmap_t m_attrMap;
96         vector<string> m_attributeIds;
97     };
98     
99     class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
100     {
101     public:
102         XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor")), m_impl(NULL) {
103             load();
104         }
105         ~XMLExtractor() {
106             delete m_impl;
107         }
108         
109         void extractAttributes(
110             const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, multimap<string,Attribute*>& attributes
111             ) const;
112
113         void getAttributeIds(std::vector<std::string>& attributes) const {
114             if (m_impl)
115                 m_impl->getAttributeIds(attributes);
116         }
117
118     protected:
119         pair<bool,DOMElement*> load();
120
121     private:
122         XMLExtractorImpl* m_impl;
123     };
124
125 #if defined (_MSC_VER)
126     #pragma warning( pop )
127 #endif
128
129     AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
130     {
131         return new XMLExtractor(e);
132     }
133     
134     static const XMLCh _AttributeDecoder[] =    UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
135     static const XMLCh Attributes[] =           UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
136     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
137     static const XMLCh _name[] =                UNICODE_LITERAL_4(n,a,m,e);
138     static const XMLCh nameFormat[] =           UNICODE_LITERAL_10(n,a,m,e,F,o,r,m,a,t);
139 };
140
141 void SHIBSP_API shibsp::registerAttributeExtractors()
142 {
143     SPConfig::getConfig().AttributeExtractorManager.registerFactory(XML_ATTRIBUTE_EXTRACTOR, XMLAttributeExtractorFactory);
144 }
145
146 XMLExtractorImpl::XMLExtractorImpl(const DOMElement* e, Category& log) : m_log(log), m_document(NULL)
147 {
148 #ifdef _DEBUG
149     xmltooling::NDC ndc("XMLExtractorImpl");
150 #endif
151     
152     if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
153         throw ConfigurationException("XML AttributeExtractor requires am:Attributes at root of configuration.");
154
155     DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
156     while (child) {
157         // Check for missing name or id.
158         const XMLCh* name = child->getAttributeNS(NULL, _name);
159         if (!name || !*name) {
160             m_log.warn("skipping Attribute with no name");
161             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
162             continue;
163         }
164
165         auto_ptr_char id(child->getAttributeNS(NULL, _id));
166         if (!id.get() || !*id.get()) {
167             m_log.warn("skipping Attribute with no id");
168             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
169             continue;
170         }
171         else if (!strcmp(id.get(), "REMOTE_USER")) {
172             m_log.warn("skipping Attribute, id of REMOTE_USER is a reserved name");
173             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
174             continue;
175         }
176
177         AttributeDecoder* decoder=NULL;
178         try {
179             DOMElement* dchild = XMLHelper::getFirstChildElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, _AttributeDecoder);
180             if (dchild) {
181                 auto_ptr<QName> q(XMLHelper::getXSIType(dchild));
182                 if (q.get())
183                     decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(*q.get(), dchild);
184             }
185             if (!decoder)
186                 decoder = SPConfig::getConfig().AttributeDecoderManager.newPlugin(StringAttributeDecoderType, NULL);
187         }
188         catch (exception& ex) {
189             m_log.error("skipping Attribute (%s), error building AttributeDecoder: %s", id.get(), ex.what());
190         }
191
192         if (!decoder) {
193             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
194             continue;
195         }
196
197         // Empty NameFormat implies the usual Shib URI naming defaults.
198         const XMLCh* format = child->getAttributeNS(NULL, nameFormat);
199         if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI) ||
200                 XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
201             format = &chNull;  // ignore default Format/Namespace values
202
203         // Fetch/create the map entry and see if it's a duplicate rule.
204 #ifdef HAVE_GOOD_STL
205         pair<AttributeDecoder*,string>& decl = m_attrMap[make_pair(name,format)];
206 #else
207         auto_ptr_char n(name);
208         auto_ptr_char f(format);
209         pair<AttributeDecoder*,string>& decl = m_attrMap[make_pair(n.get(),f.get())];
210 #endif
211         if (decl.first) {
212             m_log.warn("skipping duplicate Attribute mapping (same name and nameFormat)");
213             delete decoder;
214             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
215             continue;
216         }
217
218         if (m_log.isInfoEnabled()) {
219 #ifdef HAVE_GOOD_STL
220             auto_ptr_char n(name);
221             auto_ptr_char f(format);
222 #endif
223             m_log.info("creating mapping for Attribute %s%s%s", n.get(), *f.get() ? ", Format/Namespace:" : "", f.get());
224         }
225         
226         decl.first = decoder;
227         decl.second = id.get();
228         m_attributeIds.push_back(id.get());
229         
230         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
231     }
232 }
233
234 void XMLExtractorImpl::extractAttributes(
235     const Application& application, const char* assertingParty, const NameIdentifier& nameid, multimap<string,Attribute*>& attributes
236     ) const
237 {
238 #ifdef HAVE_GOOD_STL
239     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
240 #else
241     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
242 #endif
243
244     const XMLCh* format = nameid.getFormat();
245     if (!format || !*format)
246         format = NameIdentifier::UNSPECIFIED;
247 #ifdef HAVE_GOOD_STL
248     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
249 #else
250     auto_ptr_char temp(format);
251     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
252 #endif
253         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &nameid, assertingParty, application.getString("entityID").second);
254         if (a)
255             attributes.insert(make_pair(rule->second.second, a));
256     }
257 }
258
259 void XMLExtractorImpl::extractAttributes(
260     const Application& application, const char* assertingParty, const NameID& nameid, multimap<string,Attribute*>& attributes
261     ) const
262 {
263 #ifdef HAVE_GOOD_STL
264     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
265 #else
266     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
267 #endif
268
269     const XMLCh* format = nameid.getFormat();
270     if (!format || !*format)
271         format = NameID::UNSPECIFIED;
272 #ifdef HAVE_GOOD_STL
273     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
274 #else
275     auto_ptr_char temp(format);
276     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
277 #endif
278         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &nameid, assertingParty, application.getString("entityID").second);
279         if (a)
280             attributes.insert(make_pair(rule->second.second, a));
281     }
282 }
283
284 void XMLExtractorImpl::extractAttributes(
285     const Application& application, const char* assertingParty, const saml1::Attribute& attr, multimap<string,Attribute*>& attributes
286     ) const
287 {
288 #ifdef HAVE_GOOD_STL
289     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
290 #else
291     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
292 #endif
293
294     const XMLCh* name = attr.getAttributeName();
295     const XMLCh* format = attr.getAttributeNamespace();
296     if (!name || !*name)
297         return;
298     if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
299         format = &chNull;
300 #ifdef HAVE_GOOD_STL
301     if ((rule=m_attrMap.find(make_pair(name,format))) != m_attrMap.end()) {
302 #else
303     auto_ptr_char temp1(name);
304     auto_ptr_char temp2(format);
305     if ((rule=m_attrMap.find(make_pair(temp1.get(),temp2.get()))) != m_attrMap.end()) {
306 #endif
307         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &attr, assertingParty, application.getString("entityID").second);
308         if (a)
309             attributes.insert(make_pair(rule->second.second, a));
310     }
311 }
312
313 void XMLExtractorImpl::extractAttributes(
314     const Application& application, const char* assertingParty, const saml2::Attribute& attr, multimap<string,Attribute*>& attributes
315     ) const
316 {
317 #ifdef HAVE_GOOD_STL
318     map< pair<xstring,xstring>,pair<AttributeDecoder*,string> >::const_iterator rule;
319 #else
320     map< pair<string,string>,pair<AttributeDecoder*,string> >::const_iterator rule;
321 #endif
322
323     const XMLCh* name = attr.getName();
324     const XMLCh* format = attr.getNameFormat();
325     if (!name || !*name)
326         return;
327     if (!format || !*format)
328         format = saml2::Attribute::UNSPECIFIED;
329     else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
330         format = &chNull;
331 #ifdef HAVE_GOOD_STL
332     if ((rule=m_attrMap.find(make_pair(name,format))) != m_attrMap.end()) {
333 #else
334     auto_ptr_char temp1(name);
335     auto_ptr_char temp2(format);
336     if ((rule=m_attrMap.find(make_pair(temp1.get(),temp2.get()))) != m_attrMap.end()) {
337 #endif
338         Attribute* a = rule->second.first->decode(rule->second.second.c_str(), &attr, assertingParty, application.getString("entityID").second);
339         if (a)
340             attributes.insert(make_pair(rule->second.second, a));
341     }
342 }
343
344 void XMLExtractor::extractAttributes(
345     const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, multimap<string,Attribute*>& attributes
346     ) const
347 {
348     if (!m_impl)
349         return;
350
351     // Check for assertions.
352     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
353         const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
354         if (token2) {
355             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
356             const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
357             for (vector<saml2::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
358                 const vector<saml2::Attribute*>& attrs = const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
359                 for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
360                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
361
362                 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement*>(*s)->getEncryptedAttributes();
363                 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
364                     extractAttributes(application, issuer, *(*ea), attributes);
365             }
366             return;
367         }
368
369         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
370         if (token1) {
371             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
372             const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
373             for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
374                 const vector<saml1::Attribute*>& attrs = const_cast<const saml1::AttributeStatement*>(*s)->getAttributes();
375                 for (vector<saml1::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
376                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
377             }
378             return;
379         }
380
381         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
382     }
383
384     // Check for attributes.
385     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
386         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
387
388         const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
389         if (attr2)
390             return m_impl->extractAttributes(application, assertingParty.get(), *attr2, attributes);
391
392         const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
393         if (attr1)
394             return m_impl->extractAttributes(application, assertingParty.get(), *attr1, attributes);
395
396         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
397     }
398
399     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
400         const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
401         if (encattr) {
402             const XMLCh* recipient = application.getXMLString("entityID").second;
403             CredentialResolver* cr = application.getCredentialResolver();
404             if (!cr) {
405                 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
406                 return;
407             }
408
409             try {
410                 Locker credlocker(cr);
411                 if (issuer) {
412                     MetadataCredentialCriteria mcc(*issuer);
413                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
414                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
415                 }
416                 else {
417                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
418                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
419                 }
420             }
421             catch (exception& ex) {
422                 m_log.error("caught exception decrypting Attribute: %s", ex.what());
423                 return;
424             }
425         }
426     }
427
428     // Check for NameIDs.
429     const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
430     if (name2) {
431         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
432         return m_impl->extractAttributes(application, assertingParty.get(), *name2, attributes);
433     }
434
435     const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
436     if (name1) {
437         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
438         return m_impl->extractAttributes(application, assertingParty.get(), *name1, attributes);
439     }
440
441     throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
442 }
443
444 pair<bool,DOMElement*> XMLExtractor::load()
445 {
446     // Load from source using base class.
447     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
448     
449     // If we own it, wrap it.
450     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
451
452     XMLExtractorImpl* impl = new XMLExtractorImpl(raw.second, m_log);
453     
454     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
455     impl->setDocument(docjanitor.release());
456
457     delete m_impl;
458     m_impl = impl;
459
460     return make_pair(false,(DOMElement*)NULL);
461 }