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