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