Boost changes to rest of project
[shibboleth/cpp-sp.git] / plugins / GSSAPIAttributeExtractor.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * GSSAPIAttributeExtractor.cpp
23  *
24  * AttributeExtractor for a base64-encoded GSS-API context or name.
25  */
26
27 #include "internal.h"
28
29 #ifdef HAVE_GSSAPI_NAMINGEXTS
30
31 #include <shibsp/exceptions.h>
32 #include <shibsp/Application.h>
33 #include <shibsp/SPConfig.h>
34 #include <shibsp/attribute/BinaryAttribute.h>
35 #include <shibsp/attribute/ScopedAttribute.h>
36 #include <shibsp/attribute/SimpleAttribute.h>
37 #include <shibsp/attribute/resolver/AttributeExtractor.h>
38 #include <shibsp/remoting/ddf.h>
39 #include <shibsp/util/SPConstants.h>
40 #include <saml/saml1/core/Assertions.h>
41 #include <saml/saml2/metadata/Metadata.h>
42 #include <xmltooling/unicode.h>
43 #include <xmltooling/XMLToolingConfig.h>
44 #include <xmltooling/util/NDC.h>
45 #include <xmltooling/util/ReloadableXMLFile.h>
46 #include <xmltooling/util/Threads.h>
47 #include <xmltooling/util/XMLHelper.h>
48 #include <xercesc/util/Base64.hpp>
49 #include <xercesc/util/XMLUniDefs.hpp>
50 #include <boost/scoped_ptr.hpp>
51 #include <boost/algorithm/string.hpp>
52
53 #ifdef SHIBSP_HAVE_GSSGNU
54 # include <gss.h>
55 #elif defined SHIBSP_HAVE_GSSMIT
56 # include <gssapi/gssapi_ext.h>
57 #else
58 # include <gssapi.h>
59 #endif
60
61
62 using namespace shibsp;
63 using namespace opensaml::saml2md;
64 using namespace opensaml;
65 using namespace xmltooling;
66 using namespace xercesc;
67 using namespace boost;
68 using namespace std;
69
70 namespace shibsp {
71
72 #if defined (_MSC_VER)
73     #pragma warning( push )
74     #pragma warning( disable : 4250 )
75 #endif
76
77     class GSSAPIExtractorImpl
78     {
79     public:
80         GSSAPIExtractorImpl(const DOMElement* e, Category& log);
81         ~GSSAPIExtractorImpl() {
82             if (m_document)
83                 m_document->release();
84         }
85
86         void setDocument(DOMDocument* doc) {
87             m_document = doc;
88         }
89
90         void extractAttributes(gss_name_t initiatorName, vector<Attribute*>& attributes) const;
91         void extractAttributes(gss_name_t initiatorName, gss_buffer_t namingAttribute, vector<Attribute*>& attributes) const;
92
93         void getAttributeIds(vector<string>& attributes) const {
94             attributes.insert(attributes.end(), m_attributeIds.begin(), m_attributeIds.end());
95         }
96
97     private:
98         struct Rule {
99             Rule() : authenticated(true), binary(false), scopeDelimiter(0) {}
100             vector<string> ids;
101             bool authenticated,binary;
102             char scopeDelimiter;
103         };
104
105         Category& m_log;
106         DOMDocument* m_document;
107         map<string,Rule> m_attrMap;
108         vector<string> m_attributeIds;
109     };
110
111     class GSSAPIExtractor : public AttributeExtractor, public ReloadableXMLFile
112     {
113     public:
114         GSSAPIExtractor(const DOMElement* e)
115                 : ReloadableXMLFile(e, Category::getInstance(SHIBSP_LOGCAT".AttributeExtractor.GSSAPI")) {
116             background_load();
117         }
118         ~GSSAPIExtractor() {
119             shutdown();
120             delete m_impl;
121         }
122
123         void extractAttributes(
124             const Application& application,
125             const RoleDescriptor* issuer,
126             const XMLObject& xmlObject,
127             vector<Attribute*>& attributes
128             ) const;
129
130         void getAttributeIds(std::vector<std::string>& attributes) const {
131             if (m_impl)
132                 m_impl->getAttributeIds(attributes);
133         }
134
135     protected:
136         pair<bool,DOMElement*> background_load();
137
138     private:
139         scoped_ptr<GSSAPIExtractorImpl> m_impl;
140     };
141
142 #if defined (_MSC_VER)
143     #pragma warning( pop )
144 #endif
145
146     AttributeExtractor* GSSAPIExtractorFactory(const DOMElement* const & e)
147     {
148         return new GSSAPIExtractor(e);
149     }
150
151     static const XMLCh _aliases[] =             UNICODE_LITERAL_7(a,l,i,a,s,e,s);
152     static const XMLCh Attributes[] =           UNICODE_LITERAL_10(A,t,t,r,i,b,u,t,e,s);
153     static const XMLCh _authenticated[] =       UNICODE_LITERAL_13(a,u,t,h,e,n,t,i,c,a,t,e,d);
154     static const XMLCh _binary[] =              UNICODE_LITERAL_6(b,i,n,a,r,y);
155     static const XMLCh GSSAPIAttribute[] =      UNICODE_LITERAL_15(G,S,S,A,P,I,A,t,t,r,i,b,u,t,e);
156     static const XMLCh _id[] =                  UNICODE_LITERAL_2(i,d);
157     static const XMLCh _name[] =                UNICODE_LITERAL_4(n,a,m,e);
158     static const XMLCh _scopeDelimiter[] =      UNICODE_LITERAL_14(s,c,o,p,e,D,e,l,i,m,i,t,e,r);
159 };
160
161 GSSAPIExtractorImpl::GSSAPIExtractorImpl(const DOMElement* e, Category& log)
162     : m_log(log), m_document(nullptr)
163 {
164 #ifdef _DEBUG
165     xmltooling::NDC ndc("GSSAPIExtractorImpl");
166 #endif
167
168     if (!XMLHelper::isNodeNamed(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, Attributes))
169         throw ConfigurationException("GSSAPI AttributeExtractor requires am:Attributes at root of configuration.");
170
171     DOMElement* child = XMLHelper::getFirstChildElement(e, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
172     while (child) {
173         // Check for missing name or id.
174         const XMLCh* name = child->getAttributeNS(nullptr, _name);
175         if (!name || !*name) {
176             m_log.warn("skipping GSSAPIAttribute with no name");
177             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
178             continue;
179         }
180
181         auto_ptr_char id(child->getAttributeNS(nullptr, _id));
182         if (!id.get() || !*id.get()) {
183             m_log.warn("skipping GSSAPIAttribute with no id");
184             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
185             continue;
186         }
187         else if (!strcmp(id.get(), "REMOTE_USER")) {
188             m_log.warn("skipping GSSAPIAttribute, id of REMOTE_USER is a reserved name");
189             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
190             continue;
191         }
192
193         // Fetch/create the map entry and see if it's a duplicate rule.
194         auto_ptr_char attrname(name);
195         Rule& decl = m_attrMap[attrname.get()];
196         if (!decl.ids.empty()) {
197             m_log.warn("skipping duplicate GSS-API Attribute mapping (same name)");
198             child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
199             continue;
200         }
201
202         m_log.info("creating mapping for GSS-API Attribute %s", attrname.get());
203
204         decl.ids.push_back(id.get());
205         m_attributeIds.push_back(id.get());
206
207         name = child->getAttributeNS(nullptr, _aliases);
208         if (name && *name) {
209             auto_ptr_char aliases(name);
210             string dup(aliases.get());
211             set<string> new_aliases;
212             split(new_aliases, dup, is_space(), algorithm::token_compress_on);
213             set<string>::iterator ru = new_aliases.find("REMOTE_USER");
214             if (ru != new_aliases.end()) {
215                 m_log.warn("skipping alias, REMOTE_USER is a reserved name");
216                 new_aliases.erase(ru);
217             }
218             m_attributeIds.insert(m_attributeIds.end(), new_aliases.begin(), new_aliases.end());
219         }
220
221         decl.authenticated = XMLHelper::getAttrBool(child, true, _authenticated);
222         decl.binary = XMLHelper::getAttrBool(child, false, _binary);
223         string delim = XMLHelper::getAttrString(child, "", _scopeDelimiter);
224         if (!delim.empty())
225             decl.scopeDelimiter = delim[0];
226
227         child = XMLHelper::getNextSiblingElement(child, shibspconstants::SHIB2ATTRIBUTEMAP_NS, GSSAPIAttribute);
228     }
229 }
230
231 void GSSAPIExtractorImpl::extractAttributes(gss_name_t initiatorName, vector<Attribute*>& attributes) const
232 {
233     OM_uint32 minor;
234     gss_buffer_set_t attrnames = GSS_C_NO_BUFFER_SET;
235     OM_uint32 major = gss_inquire_name(&minor, initiatorName, nullptr, nullptr, &attrnames);
236     if (major == GSS_S_COMPLETE) {
237         for (size_t i = 0; i < attrnames->count; ++i) {
238             extractAttributes(initiatorName, &attrnames->elements[i], attributes);
239         }
240         gss_release_buffer_set(&minor, &attrnames);
241     }
242     else {
243         m_log.warn("unable to extract attributes, GSS name attribute inquiry failed (%u:%u)", major, minor);
244     }
245 }
246
247 void GSSAPIExtractorImpl::extractAttributes(
248     gss_name_t initiatorName, gss_buffer_t namingAttribute, vector<Attribute*>& attributes
249     ) const
250 {
251     // First we have to determine if this GSS attribute is something we recognize.
252     string attrname(reinterpret_cast<char*>(namingAttribute->value), namingAttribute->length);
253     map<string,Rule>::const_iterator rule = m_attrMap.find(attrname);
254     if (rule == m_attrMap.end()) {
255         m_log.info("skipping unmapped GSS-API attribute: %s", attrname.c_str());
256         return;
257     }
258
259     vector<string> values;
260
261     OM_uint32 major,minor;
262     int authenticated=-1,more=-1;
263     do {
264         gss_buffer_desc buf = GSS_C_EMPTY_BUFFER;
265         major = gss_get_name_attribute(
266             &minor, initiatorName, namingAttribute, &authenticated, nullptr, &buf, nullptr, &more
267             );
268         if (major == GSS_S_COMPLETE) {
269             if (rule->second.authenticated && !authenticated) {
270                 m_log.warn("skipping unauthenticated GSS-API attribute: %s", attrname.c_str());
271                 gss_release_buffer(&minor, &buf);
272                 return;
273             }
274             if (buf.length) {
275                 values.push_back(string(reinterpret_cast<char*>(buf.value), buf.length));
276             }
277             gss_release_buffer(&minor, &buf);
278         }
279         else {
280             m_log.warn("error obtaining values for GSS-API attribute (%s): %u:%u", attrname.c_str(), major, minor);
281         }
282     } while (major == GSS_S_COMPLETE && more);
283
284     if (values.empty())
285         return;
286
287     if (rule->second.scopeDelimiter && !rule->second.binary) {
288         auto_ptr<ScopedAttribute> scoped(new ScopedAttribute(rule->second.ids, rule->second.scopeDelimiter));
289         vector< pair<string,string> >& dest = scoped->getValues();
290         for (vector<string>::const_iterator v = values.begin(); v != values.end(); ++v) {
291             const char* value = v->c_str();
292             const char* scope = strchr(value, rule->second.scopeDelimiter);
293             if (scope) {
294                 if (*(scope+1))
295                     dest.push_back(pair<string,string>(v->substr(0, scope-value), scope + 1));
296                 else
297                     m_log.warn("ignoring unscoped value");
298             }
299             else {
300                 m_log.warn("ignoring unscoped value");
301             }
302         }
303         if (!scoped->getValues().empty()) {
304             attributes.push_back(scoped.get());
305             scoped.release();
306         }
307     }
308     else if (rule->second.binary) {
309         auto_ptr<BinaryAttribute> binary(new BinaryAttribute(rule->second.ids));
310         binary->getValues() = values;
311         attributes.push_back(binary.get());
312         binary.release();
313     }
314     else {
315         auto_ptr<SimpleAttribute> simple(new SimpleAttribute(rule->second.ids));
316         simple->getValues() = values;
317         attributes.push_back(simple.get());
318         simple.release();
319     }
320 }
321
322 void GSSAPIExtractor::extractAttributes(
323     const Application& application, const RoleDescriptor* issuer, const XMLObject& xmlObject, vector<Attribute*>& attributes
324     ) const
325 {
326     if (!m_impl)
327         return;
328
329     static const XMLCh _GSSAPIContext[] = UNICODE_LITERAL_13(G,S,S,A,P,I,C,o,n,t,e,x,t);
330     static const XMLCh _GSSAPIName[] = UNICODE_LITERAL_10(G,S,S,A,P,I,N,a,m,e);
331
332     if (!XMLString::equals(xmlObject.getElementQName().getLocalPart(), _GSSAPIContext)
333            && !XMLString::equals(xmlObject.getElementQName().getLocalPart(), _GSSAPIName)
334         ) {
335         m_log.debug("unable to extract attributes, unknown XML object type: %s", xmlObject.getElementQName().toString().c_str());
336         return;
337     }
338
339     const XMLCh* encodedWide = xmlObject.getTextContent();
340     if (!encodedWide || !*encodedWide) {
341         m_log.warn("unable to extract attributes, GSSAPI element had no text content");
342         return;
343     }
344
345     xsecsize_t x;
346     OM_uint32 major,minor;
347     auto_ptr_char encoded(encodedWide);
348
349     gss_name_t srcname;
350     gss_ctx_id_t gss = GSS_C_NO_CONTEXT;
351
352     XMLByte* decoded=Base64::decode(reinterpret_cast<const XMLByte*>(encoded.get()), &x);
353     if (decoded) {
354         gss_buffer_desc importbuf;
355         importbuf.length = x;
356         importbuf.value = decoded;
357         if (XMLString::equals(xmlObject.getElementQName().getLocalPart(), _GSSAPIName)) {
358 #ifdef HAVE_GSSAPI_COMPOSITE_NAME
359             major = gss_import_name(&minor, &importbuf, GSS_C_NT_EXPORT_NAME_COMPOSITE, &srcname);
360 #else
361             major = gss_import_name(&minor, &importbuf, GSS_C_NT_EXPORT_NAME, &srcname);
362 #endif
363             if (major == GSS_S_COMPLETE) {
364                 m_impl->extractAttributes(srcname, attributes);
365                 gss_release_name(&minor, &srcname);
366             }
367             else {
368                 m_log.warn("unable to extract attributes, GSS name import failed (%u:%u)", major, minor);
369             }
370             // We fall through here down to the GSS context check, which will exit us.
371         }
372         else {
373             major = gss_import_sec_context(&minor, &importbuf, &gss);
374             if (major != GSS_S_COMPLETE) {
375                 m_log.warn("unable to extract attributes, GSS context import failed (%u:%u)", major, minor);
376                 gss = GSS_C_NO_CONTEXT;
377             }
378         }
379 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
380         XMLString::release(&decoded);
381 #else
382         XMLString::release((char**)&decoded);
383 #endif
384     }
385     else {
386         m_log.warn("unable to extract attributes, base64 decode of GSSAPI context or name failed");
387     }
388
389     if (gss == GSS_C_NO_CONTEXT) {
390         return;
391     }
392
393     // Extract the initiator name from the context.
394     major = gss_inquire_context(&minor, gss, &srcname, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
395     if (major == GSS_S_COMPLETE) {
396         m_impl->extractAttributes(srcname, attributes);
397         gss_release_name(&minor, &srcname);
398     }
399     else {
400         m_log.warn("unable to extract attributes, GSS initiator name extraction failed (%u:%u)", major, minor);
401     }
402
403     gss_delete_sec_context(&minor, &gss, GSS_C_NO_BUFFER);
404 }
405
406 pair<bool,DOMElement*> GSSAPIExtractor::background_load()
407 {
408     // Load from source using base class.
409     pair<bool,DOMElement*> raw = ReloadableXMLFile::load();
410
411     // If we own it, wrap it.
412     XercesJanitor<DOMDocument> docjanitor(raw.first ? raw.second->getOwnerDocument() : nullptr);
413
414     scoped_ptr<GSSAPIExtractorImpl> impl(new GSSAPIExtractorImpl(raw.second, m_log));
415
416     // If we held the document, transfer it to the impl. If we didn't, it's a no-op.
417     impl->setDocument(docjanitor.release());
418
419     // Perform the swap inside a lock.
420     if (m_lock)
421         m_lock->wrlock();
422     SharedLock locker(m_lock, false);
423     m_impl.swap(impl);
424
425     return make_pair(false,(DOMElement*)nullptr);
426 }
427
428 #endif