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