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