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