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