Add back alias support for attributes.
[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 std;
43 using saml1::NameIdentifier;
44 using saml2::NameID;
45 using saml2::EncryptedAttribute;
46
47 namespace shibsp {
48
49 #if defined (_MSC_VER)
50     #pragma warning( push )
51     #pragma warning( disable : 4250 )
52 #endif
53
54     class XMLExtractorImpl
55     {
56     public:
57         XMLExtractorImpl(const DOMElement* e, Category& log);
58         ~XMLExtractorImpl() {
59             for (attrmap_t::iterator i = m_attrMap.begin(); i!=m_attrMap.end(); ++i)
60                 delete i->second.first;
61             if (m_document)
62                 m_document->release();
63         }
64
65         void setDocument(DOMDocument* doc) {
66             m_document = doc;
67         }
68
69         void extractAttributes(
70             const Application& application, const char* assertingParty, const NameIdentifier& nameid, vector<Attribute*>& attributes
71             ) const;
72         void extractAttributes(
73             const Application& application, const char* assertingParty, const NameID& nameid, vector<Attribute*>& attributes
74             ) const;
75         void extractAttributes(
76             const Application& application, const char* assertingParty, const saml1::Attribute& attr, vector<Attribute*>& attributes
77             ) const;
78         void extractAttributes(
79             const Application& application, const char* assertingParty, const saml2::Attribute& attr, vector<Attribute*>& attributes
80             ) const;
81
82         void getAttributeIds(vector<string>& attributes) const {
83             attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
84         }
85
86     private:
87         Category& m_log;
88         DOMDocument* m_document;
89 #ifdef HAVE_GOOD_STL
90         typedef map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
91 #else
92         typedef map< pair<string,string>,pair< AttributeDecoder*,vector<string> > > attrmap_t;
93 #endif
94         attrmap_t m_attrMap;
95         vector<string> m_attributeIds;
96     };
97     
98     class XMLExtractor : public AttributeExtractor, public ReloadableXMLFile
99     {
100     public:
101         XMLExtractor(const DOMElement* e) : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor")), m_impl(NULL) {
102             load();
103         }
104         ~XMLExtractor() {
105             delete m_impl;
106         }
107         
108         void extractAttributes(
109             const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
110             ) const;
111
112         void getAttributeIds(std::vector<std::string>& attributes) const {
113             if (m_impl)
114                 m_impl->getAttributeIds(attributes);
115         }
116
117     protected:
118         pair<bool,DOMElement*> load();
119
120     private:
121         XMLExtractorImpl* m_impl;
122     };
123
124 #if defined (_MSC_VER)
125     #pragma warning( pop )
126 #endif
127
128     AttributeExtractor* SHIBSP_DLLLOCAL XMLAttributeExtractorFactory(const DOMElement* const & e)
129     {
130         return new XMLExtractor(e);
131     }
132     
133     static const XMLCh _AttributeDecoder[] =    UNICODE_LITERAL_16(A,t,t,r,i,b,u,t,e,D,e,c,o,d,e,r);
134     static const XMLCh Attributes[] =           UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
135     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
136     static const XMLCh _aliases[] =             UNICODE_LITERAL_7(a,l,i,a,s,e,s);
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*,vector<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*,vector<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.push_back(id.get());
228         m_attributeIds.push_back(id.get());
229
230         name = child->getAttributeNS(NULL, _aliases);
231         if (name && *name) {
232             auto_ptr_char aliases(name);
233             char* pos;
234             char* start = const_cast<char*>(aliases.get());
235             while (start && *start) {
236                 while (*start && isspace(*start))
237                     start++;
238                 if (!*start)
239                     break;
240                 pos = strchr(start,' ');
241                 if (pos)
242                     *pos=0;
243                 if (strcmp(start, "REMOTE_USER")) {
244                     decl.second.push_back(start);
245                     m_attributeIds.push_back(start);
246                 }
247                 else {
248                     m_log.warn("skipping alias, REMOTE_USER is a reserved name");
249                 }
250                 start = pos ? pos+1 : NULL;
251             }
252         }
253         
254         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, saml1::Attribute::LOCAL_NAME);
255     }
256 }
257
258 void XMLExtractorImpl::extractAttributes(
259     const Application& application, const char* assertingParty, const NameIdentifier& nameid, vector<Attribute*>& attributes
260     ) const
261 {
262 #ifdef HAVE_GOOD_STL
263     map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
264 #else
265     map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
266 #endif
267
268     const XMLCh* format = nameid.getFormat();
269     if (!format || !*format)
270         format = NameIdentifier::UNSPECIFIED;
271 #ifdef HAVE_GOOD_STL
272     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
273 #else
274     auto_ptr_char temp(format);
275     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
276 #endif
277         Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, application.getString("entityID").second);
278         if (a)
279             attributes.push_back(a);
280     }
281 }
282
283 void XMLExtractorImpl::extractAttributes(
284     const Application& application, const char* assertingParty, const NameID& nameid, vector<Attribute*>& attributes
285     ) const
286 {
287 #ifdef HAVE_GOOD_STL
288     map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
289 #else
290     map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
291 #endif
292
293     const XMLCh* format = nameid.getFormat();
294     if (!format || !*format)
295         format = NameID::UNSPECIFIED;
296 #ifdef HAVE_GOOD_STL
297     if ((rule=m_attrMap.find(make_pair(format,xstring()))) != m_attrMap.end()) {
298 #else
299     auto_ptr_char temp(format);
300     if ((rule=m_attrMap.find(make_pair(temp.get(),string()))) != m_attrMap.end()) {
301 #endif
302         Attribute* a = rule->second.first->decode(rule->second.second, &nameid, assertingParty, application.getString("entityID").second);
303         if (a)
304             attributes.push_back(a);
305     }
306 }
307
308 void XMLExtractorImpl::extractAttributes(
309     const Application& application, const char* assertingParty, const saml1::Attribute& attr, vector<Attribute*>& attributes
310     ) const
311 {
312 #ifdef HAVE_GOOD_STL
313     map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
314 #else
315     map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
316 #endif
317
318     const XMLCh* name = attr.getAttributeName();
319     const XMLCh* format = attr.getAttributeNamespace();
320     if (!name || !*name)
321         return;
322     if (!format || XMLString::equals(format, shibspconstants::SHIB1_ATTRIBUTE_NAMESPACE_URI))
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         Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, application.getString("entityID").second);
332         if (a)
333             attributes.push_back(a);
334     }
335 }
336
337 void XMLExtractorImpl::extractAttributes(
338     const Application& application, const char* assertingParty, const saml2::Attribute& attr, vector<Attribute*>& attributes
339     ) const
340 {
341 #ifdef HAVE_GOOD_STL
342     map< pair<xstring,xstring>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
343 #else
344     map< pair<string,string>,pair< AttributeDecoder*,vector<string> > >::const_iterator rule;
345 #endif
346
347     const XMLCh* name = attr.getName();
348     const XMLCh* format = attr.getNameFormat();
349     if (!name || !*name)
350         return;
351     if (!format || !*format)
352         format = saml2::Attribute::UNSPECIFIED;
353     else if (XMLString::equals(format, saml2::Attribute::URI_REFERENCE))
354         format = &chNull;
355 #ifdef HAVE_GOOD_STL
356     if ((rule=m_attrMap.find(make_pair(name,format))) != m_attrMap.end()) {
357 #else
358     auto_ptr_char temp1(name);
359     auto_ptr_char temp2(format);
360     if ((rule=m_attrMap.find(make_pair(temp1.get(),temp2.get()))) != m_attrMap.end()) {
361 #endif
362         Attribute* a = rule->second.first->decode(rule->second.second, &attr, assertingParty, application.getString("entityID").second);
363         if (a)
364             attributes.push_back(a);
365     }
366 }
367
368 void XMLExtractor::extractAttributes(
369     const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
370     ) const
371 {
372     if (!m_impl)
373         return;
374
375     // Check for assertions.
376     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Assertion::LOCAL_NAME)) {
377         const saml2::Assertion* token2 = dynamic_cast<const saml2::Assertion*>(&xmlObject);
378         if (token2) {
379             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
380             const vector<saml2::AttributeStatement*>& statements = token2->getAttributeStatements();
381             for (vector<saml2::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
382                 const vector<saml2::Attribute*>& attrs = const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
383                 for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
384                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
385
386                 const vector<saml2::EncryptedAttribute*>& encattrs = const_cast<const saml2::AttributeStatement*>(*s)->getEncryptedAttributes();
387                 for (vector<saml2::EncryptedAttribute*>::const_iterator ea = encattrs.begin(); ea!=encattrs.end(); ++ea)
388                     extractAttributes(application, issuer, *(*ea), attributes);
389             }
390             return;
391         }
392
393         const saml1::Assertion* token1 = dynamic_cast<const saml1::Assertion*>(&xmlObject);
394         if (token1) {
395             auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
396             const vector<saml1::AttributeStatement*>& statements = token1->getAttributeStatements();
397             for (vector<saml1::AttributeStatement*>::const_iterator s = statements.begin(); s!=statements.end(); ++s) {
398                 const vector<saml1::Attribute*>& attrs = const_cast<const saml1::AttributeStatement*>(*s)->getAttributes();
399                 for (vector<saml1::Attribute*>::const_iterator a = attrs.begin(); a!=attrs.end(); ++a)
400                     m_impl->extractAttributes(application, assertingParty.get(), *(*a), attributes);
401             }
402             return;
403         }
404
405         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
406     }
407
408     // Check for attributes.
409     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), saml1::Attribute::LOCAL_NAME)) {
410         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
411
412         const saml2::Attribute* attr2 = dynamic_cast<const saml2::Attribute*>(&xmlObject);
413         if (attr2)
414             return m_impl->extractAttributes(application, assertingParty.get(), *attr2, attributes);
415
416         const saml1::Attribute* attr1 = dynamic_cast<const saml1::Attribute*>(&xmlObject);
417         if (attr1)
418             return m_impl->extractAttributes(application, assertingParty.get(), *attr1, attributes);
419
420         throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
421     }
422
423     if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), EncryptedAttribute::LOCAL_NAME)) {
424         const EncryptedAttribute* encattr = dynamic_cast<const EncryptedAttribute*>(&xmlObject);
425         if (encattr) {
426             const XMLCh* recipient = application.getXMLString("entityID").second;
427             CredentialResolver* cr = application.getCredentialResolver();
428             if (!cr) {
429                 m_log.warn("found encrypted attribute, but no CredentialResolver was available");
430                 return;
431             }
432
433             try {
434                 Locker credlocker(cr);
435                 if (issuer) {
436                     MetadataCredentialCriteria mcc(*issuer);
437                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient, &mcc));
438                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
439                 }
440                 else {
441                     auto_ptr<XMLObject> decrypted(encattr->decrypt(*cr, recipient));
442                     return extractAttributes(application, issuer, *(decrypted.get()), attributes);
443                 }
444             }
445             catch (exception& ex) {
446                 m_log.error("caught exception decrypting Attribute: %s", ex.what());
447                 return;
448             }
449         }
450     }
451
452     // Check for NameIDs.
453     const NameID* name2 = dynamic_cast<const NameID*>(&xmlObject);
454     if (name2) {
455         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
456         return m_impl->extractAttributes(application, assertingParty.get(), *name2, attributes);
457     }
458
459     const NameIdentifier* name1 = dynamic_cast<const NameIdentifier*>(&xmlObject);
460     if (name1) {
461         auto_ptr_char assertingParty(issuer ? dynamic_cast<const EntityDescriptor*>(issuer->getParent())->getEntityID() : NULL);
462         return m_impl->extractAttributes(application, assertingParty.get(), *name1, attributes);
463     }
464
465     throw AttributeExtractionException("Unable to extract attributes, unknown object type.");
466 }
467
468 pair<bool,DOMElement*> XMLExtractor::load()
469 {
470     // Load from source using base class.
471     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
472     
473     // If we own it, wrap it.
474     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : NULL);
475
476     XMLExtractorImpl* impl = new XMLExtractorImpl(raw.second, m_log);
477     
478     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
479     impl->setDocument(docjanitor.release());
480
481     delete m_impl;
482     m_impl = impl;
483
484     return make_pair(false,(DOMElement*)NULL);
485 }