Fixes for Heimdal (macOS) builds from Stefan.
[mech_eap.git] / mech_eap / util_shib.cpp
1 /*
2  * Copyright (c) 2011, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 /*
33  * Copyright 2001-2009 Internet2
34  *
35  * Licensed under the Apache License, Version 2.0 (the "License");
36  * you may not use this file except in compliance with the License.
37  * You may obtain a copy of the License at
38  *
39  *     http://www.apache.org/licenses/LICENSE-2.0
40  *
41  * Unless required by applicable law or agreed to in writing, software
42  * distributed under the License is distributed on an "AS IS" BASIS,
43  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
44  * See the License for the specific language governing permissions and
45  * limitations under the License.
46  */
47
48 /*
49  * Local attribute provider implementation.
50  */
51
52 #include "gssapiP_eap.h"
53
54 #include <xmltooling/XMLObject.h>
55 #ifndef HAVE_OPENSAML
56 #include <xmltooling/XMLToolingConfig.h>
57 #include <xmltooling/util/ParserPool.h>
58 #endif
59
60 #include <saml/saml2/core/Assertions.h>
61
62 #include <shibsp/exceptions.h>
63 #include <shibsp/attribute/SimpleAttribute.h>
64 #include <shibsp/attribute/BinaryAttribute.h>
65 #include <shibsp/attribute/ScopedAttribute.h>
66 #include <shibresolver/resolver.h>
67
68 #include <sstream>
69
70 using namespace shibsp;
71 using namespace shibresolver;
72 using namespace xmltooling;
73 using namespace std;
74 #ifdef HAVE_OPENSAML
75 using namespace opensaml::saml2md;
76 using namespace opensaml;
77 #else
78 using namespace xercesc;
79 #endif
80
81
82 namespace {
83
84
85     class ShibFinalizer {
86     public:
87
88         static bool isShibInitialized() {return shibInitialized;}
89         static void createSingleton();
90
91     private:
92         ShibFinalizer(): is_extra(false) {
93             if (shibInitialized) {
94                 // This should never, ever happen. Initialization is (supposed to be)
95                 // funneled through a single thread, so there should be no race
96                 // conditions here. And only this class sets this flag, and there's
97                 // only a single instance of this class.
98                 wpa_printf(MSG_ERROR, "### ShibFinalizer::ShibFinalizer(): Attempt to construct an extraneous instance!");
99                 is_extra = true;
100             }
101             else {
102                 wpa_printf(MSG_INFO, "### ShibFinalizer::ShibFinalizer(): Constructing");
103                 shibInitialized = true;
104             }
105         }
106
107         ~ShibFinalizer() {
108             if (!is_extra) {
109                 wpa_printf(MSG_INFO, "### ShibFinalizer::~ShibFinalizer(): Destructing");
110                 gss_eap_shib_attr_provider::finalize();
111                 shibInitialized = false;
112             }
113             else {
114                 wpa_printf(MSG_INFO, "### ShibFinalizer::~ShibFinalizer(): This was an extraneous instance; not destructing anything.");
115             }
116         }
117
118         bool is_extra;
119         static bool shibInitialized;
120     };
121 }
122
123
124 bool ShibFinalizer::shibInitialized = false;
125
126 void ShibFinalizer::createSingleton() {
127     // This object's constructor is invoked on the first call to this method.
128     // At exit, its destructor will terminate Shibboleth.
129     static ShibFinalizer finalizer;
130 }
131
132
133 gss_eap_shib_attr_provider::gss_eap_shib_attr_provider(void)
134 {
135     m_initialized = false;
136     m_authenticated = false;
137 }
138
139 gss_eap_shib_attr_provider::~gss_eap_shib_attr_provider(void)
140 {
141     for_each(m_attributes.begin(),
142              m_attributes.end(),
143              xmltooling::cleanup<Attribute>())
144         ;
145 }
146
147 bool
148 gss_eap_shib_attr_provider::initWithExistingContext(const gss_eap_attr_ctx *manager,
149                                                     const gss_eap_attr_provider *ctx)
150 {
151     const gss_eap_shib_attr_provider *shib;
152
153     if (!gss_eap_attr_provider::initWithExistingContext(manager, ctx)) {
154         return false;
155     }
156
157     m_authenticated = false;
158
159     shib = static_cast<const gss_eap_shib_attr_provider *>(ctx);
160     if (shib != NULL) {
161         m_attributes = duplicateAttributes(shib->getAttributes());
162         m_authenticated = shib->authenticated();
163     }
164
165     m_initialized = true;
166
167     return true;
168 }
169
170 bool
171 gss_eap_shib_attr_provider::initWithGssContext(const gss_eap_attr_ctx *manager,
172                                                const gss_cred_id_t gssCred,
173                                                const gss_ctx_id_t gssCtx)
174 {
175     if (!gss_eap_attr_provider::initWithGssContext(manager, gssCred, gssCtx))
176         return false;
177
178     auto_ptr<ShibbolethResolver> resolver(ShibbolethResolver::create());
179
180     /*
181      * For now, leave ApplicationID defaulted.
182      * Later on, we could allow this via config option to the mechanism
183      * or rely on an SPRequest interface to pass in a URI identifying the
184      * acceptor.
185      */
186 #if 0
187     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
188     if (gssCred != GSS_C_NO_CREDENTIAL &&
189         gssEapDisplayName(&minor, gssCred->name, &nameBuf, NULL) == GSS_S_COMPLETE) {
190         resolver->setApplicationID((const char *)nameBuf.value);
191         gss_release_buffer(&minor, &nameBuf);
192     }
193 #endif
194
195     gss_buffer_desc mechName = GSS_C_EMPTY_BUFFER;
196     OM_uint32 major, minor;
197
198     major = gssEapExportNameInternal(&minor, gssCtx->initiatorName, &mechName,
199                                      EXPORT_NAME_FLAG_OID |
200                                      EXPORT_NAME_FLAG_COMPOSITE);
201     if (major == GSS_S_COMPLETE) {
202         resolver->addToken(&mechName);
203         gss_release_buffer(&minor, &mechName);
204     }
205
206 #ifdef HAVE_OPENSAML
207     const gss_eap_saml_assertion_provider *saml;
208     saml = static_cast<const gss_eap_saml_assertion_provider *>
209         (m_manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
210     if (saml != NULL && saml->getAssertion() != NULL) {
211         resolver->addToken(saml->getAssertion());
212     }
213 #else
214     /* If no OpenSAML, parse the XML assertion explicitly */
215     const gss_eap_radius_attr_provider *radius;
216     int authenticated, complete;
217     gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
218     gss_eap_attrid attrid(VENDORPEC_UKERNA, PW_SAML_AAA_ASSERTION);
219
220     radius = static_cast<const gss_eap_radius_attr_provider *>
221         (m_manager->getProvider(ATTR_TYPE_RADIUS));
222     if (radius != NULL &&
223         radius->getFragmentedAttribute(attrid, &authenticated, &complete, &value)) {
224         string str((char *)value.value, value.length);
225         istringstream istream(str);
226         DOMDocument *doc = XMLToolingConfig::getConfig().getParser().parse(istream);
227         const XMLObjectBuilder *b = XMLObjectBuilder::getBuilder(doc->getDocumentElement());
228         resolver->addToken(b->buildFromDocument(doc));
229         gss_release_buffer(&minor, &value);
230     }
231 #endif /* HAVE_OPENSAML */
232
233     try {
234         resolver->resolve();
235         m_attributes = resolver->getResolvedAttributes();
236         resolver->getResolvedAttributes().clear();
237     } catch (exception &e) {
238         return false;
239     }
240
241     m_authenticated = true;
242     m_initialized = true;
243
244     return true;
245 }
246
247 ssize_t
248 gss_eap_shib_attr_provider::getAttributeIndex(const gss_buffer_t attr) const
249 {
250     int i = 0;
251
252     GSSEAP_ASSERT(m_initialized);
253
254     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
255          a != m_attributes.end();
256          ++a)
257     {
258         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
259              s != (*a)->getAliases().end();
260              ++s) {
261             if (attr->length == (*s).length() &&
262                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
263                 return i;
264             }
265         }
266     }
267
268     return -1;
269 }
270
271 bool
272 gss_eap_shib_attr_provider::setAttribute(int complete GSSEAP_UNUSED,
273                                          const gss_buffer_t attr,
274                                          const gss_buffer_t value)
275 {
276     string attrStr((char *)attr->value, attr->length);
277     vector <string> ids(1, attrStr);
278     BinaryAttribute *a = new BinaryAttribute(ids);
279
280     GSSEAP_ASSERT(m_initialized);
281
282     if (value->length != 0) {
283         string valueStr((char *)value->value, value->length);
284
285         a->getValues().push_back(valueStr);
286     }
287
288     m_attributes.push_back(a);
289     m_authenticated = false;
290
291     return true;
292 }
293
294 bool
295 gss_eap_shib_attr_provider::deleteAttribute(const gss_buffer_t attr)
296 {
297     int i;
298
299     GSSEAP_ASSERT(m_initialized);
300
301     i = getAttributeIndex(attr);
302     if (i >= 0)
303         m_attributes.erase(m_attributes.begin() + i);
304
305     m_authenticated = false;
306
307     return true;
308 }
309
310 bool
311 gss_eap_shib_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
312                                               void *data) const
313 {
314     GSSEAP_ASSERT(m_initialized);
315
316     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
317         a != m_attributes.end();
318         ++a)
319     {
320         gss_buffer_desc attribute;
321
322         attribute.value = (void *)((*a)->getId());
323         attribute.length = strlen((char *)attribute.value);
324
325         if (!addAttribute(m_manager, this, &attribute, data))
326             return false;
327     }
328
329     return true;
330 }
331
332 const Attribute *
333 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr) const
334 {
335     const Attribute *ret = NULL;
336
337     GSSEAP_ASSERT(m_initialized);
338
339     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
340          a != m_attributes.end();
341          ++a)
342     {
343         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
344              s != (*a)->getAliases().end();
345              ++s) {
346             if (attr->length == (*s).length() &&
347                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
348                 ret = *a;
349                 break;
350             }
351         }
352         if (ret != NULL)
353             break;
354     }
355
356     return ret;
357 }
358
359 bool
360 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr,
361                                          int *authenticated,
362                                          int *complete,
363                                          gss_buffer_t value,
364                                          gss_buffer_t display_value,
365                                          int *more) const
366 {
367     const Attribute *shibAttr = NULL;
368     const BinaryAttribute *binaryAttr;
369     gss_buffer_desc valueBuf = GSS_C_EMPTY_BUFFER;
370     gss_buffer_desc displayValueBuf = GSS_C_EMPTY_BUFFER;
371     int nvalues, i = *more;
372
373     GSSEAP_ASSERT(m_initialized);
374
375     *more = 0;
376
377     shibAttr = getAttribute(attr);
378     if (shibAttr == NULL)
379         return false;
380
381     nvalues = shibAttr->valueCount();
382
383     if (i == -1)
384         i = 0;
385     if (i >= nvalues)
386         return false;
387
388     binaryAttr = dynamic_cast<const BinaryAttribute *>(shibAttr);
389     if (binaryAttr != NULL) {
390         std::string str = binaryAttr->getValues()[*more];
391
392         valueBuf.value = (void *)str.data();
393         valueBuf.length = str.size();
394     } else {
395         std::string str = shibAttr->getSerializedValues()[*more];
396
397         valueBuf.value = (void *)str.c_str();
398         valueBuf.length = str.length();
399
400         const SimpleAttribute *simpleAttr =
401             dynamic_cast<const SimpleAttribute *>(shibAttr);
402         const ScopedAttribute *scopedAttr =
403             dynamic_cast<const ScopedAttribute *>(shibAttr);
404         if (simpleAttr != NULL || scopedAttr != NULL)
405             displayValueBuf = valueBuf;
406     }
407
408     if (authenticated != NULL)
409         *authenticated = m_authenticated;
410     if (complete != NULL)
411         *complete = true;
412     if (value != NULL)
413         duplicateBuffer(valueBuf, value);
414     if (display_value != NULL)
415         duplicateBuffer(displayValueBuf, display_value);
416     if (nvalues > ++i)
417         *more = i;
418
419     return true;
420 }
421
422 gss_any_t
423 gss_eap_shib_attr_provider::mapToAny(int authenticated,
424                                      gss_buffer_t type_id GSSEAP_UNUSED) const
425 {
426     gss_any_t output;
427
428     GSSEAP_ASSERT(m_initialized);
429
430     if (authenticated && !m_authenticated)
431         return (gss_any_t)NULL;
432
433     vector <Attribute *>v = duplicateAttributes(m_attributes);
434
435     output = (gss_any_t)new vector <Attribute *>(v);
436
437     return output;
438 }
439
440 void
441 gss_eap_shib_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id GSSEAP_UNUSED,
442                                                   gss_any_t input) const
443 {
444     GSSEAP_ASSERT(m_initialized);
445
446     vector <Attribute *> *v = ((vector <Attribute *> *)input);
447     delete v;
448 }
449
450 const char *
451 gss_eap_shib_attr_provider::prefix(void) const
452 {
453     return NULL;
454 }
455
456 const char *
457 gss_eap_shib_attr_provider::name(void) const
458 {
459     return "local";
460 }
461
462 JSONObject
463 gss_eap_shib_attr_provider::jsonRepresentation(void) const
464 {
465     JSONObject obj;
466
467     if (m_initialized == false)
468         return obj; /* don't export incomplete context */
469
470     JSONObject jattrs = JSONObject::array();
471
472     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
473          a != m_attributes.end(); ++a) {
474         DDF attr = (*a)->marshall();
475         JSONObject jattr = JSONObject::ddf(attr);
476         jattrs.append(jattr);
477     }
478
479     obj.set("attributes", jattrs);
480
481     obj.set("authenticated", m_authenticated);
482
483     return obj;
484 }
485
486 bool
487 gss_eap_shib_attr_provider::initWithJsonObject(const gss_eap_attr_ctx *ctx,
488                                                JSONObject &obj)
489 {
490     if (!gss_eap_attr_provider::initWithJsonObject(ctx, obj))
491         return false;
492
493     GSSEAP_ASSERT(m_authenticated == false);
494     GSSEAP_ASSERT(m_attributes.size() == 0);
495
496     JSONObject jattrs = obj["attributes"];
497     size_t nelems = jattrs.size();
498
499     for (size_t i = 0; i < nelems; i++) {
500         JSONObject jattr = jattrs.get(i);
501
502         DDF attr = jattr.ddf();
503         Attribute *attribute = Attribute::unmarshall(attr);
504         m_attributes.push_back(attribute);
505     }
506
507     m_authenticated = obj["authenticated"].integer();
508     m_initialized = true;
509
510     return true;
511 }
512
513 bool
514 gss_eap_shib_attr_provider::init(void)
515 {
516     bool ret = false;
517
518     if (ShibFinalizer::isShibInitialized()) {
519         wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::init(): ShibResolver library is already initialized; ignoring.");
520         return true;
521     }
522
523     wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::init(): Initializing ShibResolver library");
524
525     try {
526         ret = ShibbolethResolver::init();
527     } catch (exception &e) {
528     }
529
530     if (ret) {
531         ShibFinalizer::createSingleton();
532         gss_eap_attr_ctx::registerProvider(ATTR_TYPE_LOCAL, createAttrContext);
533     }
534
535     return ret;
536 }
537
538 void
539 gss_eap_shib_attr_provider::finalize(void)
540 {
541     wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::finalize(): calling ShibbolethResolver::term()");
542     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_LOCAL);
543     ShibbolethResolver::term();
544 }
545
546 OM_uint32
547 gss_eap_shib_attr_provider::mapException(OM_uint32 *minor,
548                                          std::exception &e) const
549 {
550     if (typeid(e) == typeid(AttributeException))
551         *minor = GSSEAP_SHIB_ATTR_FAILURE;
552     else if (typeid(e) == typeid(AttributeExtractionException))
553         *minor = GSSEAP_SHIB_ATTR_EXTRACT_FAILURE;
554     else if (typeid(e) == typeid(AttributeFilteringException))
555         *minor = GSSEAP_SHIB_ATTR_FILTER_FAILURE;
556     else if (typeid(e) == typeid(AttributeResolutionException))
557         *minor = GSSEAP_SHIB_ATTR_RESOLVE_FAILURE;
558     else if (typeid(e) == typeid(ConfigurationException))
559         *minor = GSSEAP_SHIB_CONFIG_FAILURE;
560     else if (typeid(e) == typeid(ListenerException))
561         *minor = GSSEAP_SHIB_LISTENER_FAILURE;
562     else
563         return GSS_S_CONTINUE_NEEDED;
564
565     gssEapSaveStatusInfo(*minor, "%s", e.what());
566
567     return GSS_S_FAILURE;
568 }
569
570 gss_eap_attr_provider *
571 gss_eap_shib_attr_provider::createAttrContext(void)
572 {
573     return new gss_eap_shib_attr_provider;
574 }
575
576 Attribute *
577 gss_eap_shib_attr_provider::duplicateAttribute(const Attribute *src)
578 {
579     DDF obj = src->marshall();
580     Attribute *attribute = Attribute::unmarshall(obj);
581     obj.destroy();
582
583     return attribute;
584 }
585
586 vector <Attribute *>
587 gss_eap_shib_attr_provider::duplicateAttributes(const vector <Attribute *>src)
588 {
589     vector <Attribute *> dst;
590
591     for (vector<Attribute *>::const_iterator a = src.begin();
592          a != src.end();
593          ++a)
594         dst.push_back(duplicateAttribute(*a));
595
596     return dst;
597 }
598
599
600 OM_uint32
601 gssEapLocalAttrProviderInit(OM_uint32 *minor)
602 {
603     if (!gss_eap_shib_attr_provider::init()) {
604         *minor = GSSEAP_SHIB_INIT_FAILURE;
605         return GSS_S_FAILURE;
606     }
607
608     return GSS_S_COMPLETE;
609 }