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