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