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