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