Merge branch 'master' into debian
[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 #include <memory>
70
71 using namespace shibsp;
72 using namespace shibresolver;
73 using namespace xmltooling;
74 using namespace std;
75 #ifdef HAVE_OPENSAML
76 using namespace opensaml::saml2md;
77 using namespace opensaml;
78 #else
79 using namespace xercesc;
80 #endif
81
82 // Use unique_ptr where available; auto_ptr otherwise.
83 #if __cplusplus > 199711L
84 #define UNIQUE_OR_AUTO_PTR unique_ptr
85 #else
86 #define UNIQUE_OR_AUTO_PTR auto_ptr
87 #endif
88
89
90
91 namespace {
92
93
94     class ShibFinalizer {
95     public:
96
97         static bool isShibInitialized() {return shibInitialized;}
98         static void createSingleton();
99
100     private:
101         ShibFinalizer(): is_extra(false) {
102             if (shibInitialized) {
103                 // This should never, ever happen. Initialization is (supposed to be)
104                 // funneled through a single thread, so there should be no race
105                 // conditions here. And only this class sets this flag, and there's
106                 // only a single instance of this class.
107                 wpa_printf(MSG_ERROR, "### ShibFinalizer::ShibFinalizer(): Attempt to construct an extraneous instance!");
108                 is_extra = true;
109             }
110             else {
111                 wpa_printf(MSG_INFO, "### ShibFinalizer::ShibFinalizer(): Constructing");
112                 shibInitialized = true;
113             }
114         }
115
116         ~ShibFinalizer() {
117             if (!is_extra) {
118                 wpa_printf(MSG_INFO, "### ShibFinalizer::~ShibFinalizer(): Destructing");
119                 gss_eap_shib_attr_provider::finalize();
120                 shibInitialized = false;
121             }
122             else {
123                 wpa_printf(MSG_INFO, "### ShibFinalizer::~ShibFinalizer(): This was an extraneous instance; not destructing anything.");
124             }
125         }
126
127         bool is_extra;
128         static bool shibInitialized;
129     };
130 }
131
132
133 bool ShibFinalizer::shibInitialized = false;
134
135 void ShibFinalizer::createSingleton() {
136     // This object's constructor is invoked on the first call to this method.
137     // At exit, its destructor will terminate Shibboleth.
138     static ShibFinalizer finalizer;
139 }
140
141
142 gss_eap_shib_attr_provider::gss_eap_shib_attr_provider(void)
143 {
144     m_initialized = false;
145     m_authenticated = false;
146 }
147
148 gss_eap_shib_attr_provider::~gss_eap_shib_attr_provider(void)
149 {
150     for_each(m_attributes.begin(),
151              m_attributes.end(),
152              xmltooling::cleanup<Attribute>())
153         ;
154 }
155
156 bool
157 gss_eap_shib_attr_provider::initWithExistingContext(const gss_eap_attr_ctx *manager,
158                                                     const gss_eap_attr_provider *ctx)
159 {
160     const gss_eap_shib_attr_provider *shib;
161
162     if (!gss_eap_attr_provider::initWithExistingContext(manager, ctx)) {
163         return false;
164     }
165
166     m_authenticated = false;
167
168     shib = static_cast<const gss_eap_shib_attr_provider *>(ctx);
169     if (shib != NULL) {
170         m_attributes = duplicateAttributes(shib->getAttributes());
171         m_authenticated = shib->authenticated();
172     }
173
174     m_initialized = true;
175
176     return true;
177 }
178
179 bool
180 gss_eap_shib_attr_provider::initWithGssContext(const gss_eap_attr_ctx *manager,
181                                                const gss_cred_id_t gssCred,
182                                                const gss_ctx_id_t gssCtx)
183 {
184     if (!gss_eap_attr_provider::initWithGssContext(manager, gssCred, gssCtx))
185         return false;
186
187     UNIQUE_OR_AUTO_PTR<ShibbolethResolver> resolver(ShibbolethResolver::create());
188
189     /*
190      * For now, leave ApplicationID defaulted.
191      * Later on, we could allow this via config option to the mechanism
192      * or rely on an SPRequest interface to pass in a URI identifying the
193      * acceptor.
194      */
195 #if 0
196     gss_buffer_desc nameBuf = GSS_C_EMPTY_BUFFER;
197     if (gssCred != GSS_C_NO_CREDENTIAL &&
198         gssEapDisplayName(&minor, gssCred->name, &nameBuf, NULL) == GSS_S_COMPLETE) {
199         resolver->setApplicationID((const char *)nameBuf.value);
200         gss_release_buffer(&minor, &nameBuf);
201     }
202 #endif
203
204     gss_buffer_desc mechName = GSS_C_EMPTY_BUFFER;
205     OM_uint32 major, minor;
206
207     major = gssEapExportNameInternal(&minor, gssCtx->initiatorName, &mechName,
208                                      EXPORT_NAME_FLAG_OID |
209                                      EXPORT_NAME_FLAG_COMPOSITE);
210     if (major == GSS_S_COMPLETE) {
211         resolver->addToken(&mechName);
212         gss_release_buffer(&minor, &mechName);
213     }
214
215 #ifdef HAVE_OPENSAML
216     const gss_eap_saml_assertion_provider *saml;
217     saml = static_cast<const gss_eap_saml_assertion_provider *>
218         (m_manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
219     if (saml != NULL && saml->getAssertion() != NULL) {
220         resolver->addToken(saml->getAssertion());
221     }
222 #else
223     /* If no OpenSAML, parse the XML assertion explicitly */
224     const gss_eap_radius_attr_provider *radius;
225     int authenticated, complete;
226     gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
227     gss_eap_attrid attrid(VENDORPEC_UKERNA, PW_SAML_AAA_ASSERTION);
228
229     radius = static_cast<const gss_eap_radius_attr_provider *>
230         (m_manager->getProvider(ATTR_TYPE_RADIUS));
231     if (radius != NULL &&
232         radius->getFragmentedAttribute(attrid, &authenticated, &complete, &value)) {
233         string str((char *)value.value, value.length);
234         istringstream istream(str);
235         DOMDocument *doc = XMLToolingConfig::getConfig().getParser().parse(istream);
236         const XMLObjectBuilder *b = XMLObjectBuilder::getBuilder(doc->getDocumentElement());
237         resolver->addToken(b->buildFromDocument(doc));
238         gss_release_buffer(&minor, &value);
239     }
240 #endif /* HAVE_OPENSAML */
241
242     try {
243         resolver->resolve();
244         m_attributes = resolver->getResolvedAttributes();
245         resolver->getResolvedAttributes().clear();
246     } catch (exception &e) {
247         return false;
248     }
249
250     m_authenticated = true;
251     m_initialized = true;
252
253     return true;
254 }
255
256 ssize_t
257 gss_eap_shib_attr_provider::getAttributeIndex(const gss_buffer_t attr) const
258 {
259     int i = 0;
260
261     GSSEAP_ASSERT(m_initialized);
262
263     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
264          a != m_attributes.end();
265          ++a)
266     {
267         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
268              s != (*a)->getAliases().end();
269              ++s) {
270             if (attr->length == (*s).length() &&
271                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
272                 return i;
273             }
274         }
275     }
276
277     return -1;
278 }
279
280 bool
281 gss_eap_shib_attr_provider::setAttribute(int complete GSSEAP_UNUSED,
282                                          const gss_buffer_t attr,
283                                          const gss_buffer_t value)
284 {
285     string attrStr((char *)attr->value, attr->length);
286     vector <string> ids(1, attrStr);
287     BinaryAttribute *a = new BinaryAttribute(ids);
288
289     GSSEAP_ASSERT(m_initialized);
290
291     if (value->length != 0) {
292         string valueStr((char *)value->value, value->length);
293
294         a->getValues().push_back(valueStr);
295     }
296
297     m_attributes.push_back(a);
298     m_authenticated = false;
299
300     return true;
301 }
302
303 bool
304 gss_eap_shib_attr_provider::deleteAttribute(const gss_buffer_t attr)
305 {
306     int i;
307
308     GSSEAP_ASSERT(m_initialized);
309
310     i = getAttributeIndex(attr);
311     if (i >= 0)
312         m_attributes.erase(m_attributes.begin() + i);
313
314     m_authenticated = false;
315
316     return true;
317 }
318
319 bool
320 gss_eap_shib_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
321                                               void *data) const
322 {
323     GSSEAP_ASSERT(m_initialized);
324
325     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
326         a != m_attributes.end();
327         ++a)
328     {
329         gss_buffer_desc attribute;
330
331         attribute.value = (void *)((*a)->getId());
332         attribute.length = strlen((char *)attribute.value);
333
334         if (!addAttribute(m_manager, this, &attribute, data))
335             return false;
336     }
337
338     return true;
339 }
340
341 const Attribute *
342 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr) const
343 {
344     const Attribute *ret = NULL;
345
346     GSSEAP_ASSERT(m_initialized);
347
348     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
349          a != m_attributes.end();
350          ++a)
351     {
352         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
353              s != (*a)->getAliases().end();
354              ++s) {
355             if (attr->length == (*s).length() &&
356                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
357                 ret = *a;
358                 break;
359             }
360         }
361         if (ret != NULL)
362             break;
363     }
364
365     return ret;
366 }
367
368 bool
369 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr,
370                                          int *authenticated,
371                                          int *complete,
372                                          gss_buffer_t value,
373                                          gss_buffer_t display_value,
374                                          int *more) const
375 {
376     const Attribute *shibAttr = NULL;
377     const BinaryAttribute *binaryAttr;
378     gss_buffer_desc valueBuf = GSS_C_EMPTY_BUFFER;
379     gss_buffer_desc displayValueBuf = GSS_C_EMPTY_BUFFER;
380     int nvalues, i = *more;
381
382     GSSEAP_ASSERT(m_initialized);
383
384     *more = 0;
385
386     shibAttr = getAttribute(attr);
387     if (shibAttr == NULL)
388         return false;
389
390     nvalues = shibAttr->valueCount();
391
392     if (i == -1)
393         i = 0;
394     if (i >= nvalues)
395         return false;
396
397     binaryAttr = dynamic_cast<const BinaryAttribute *>(shibAttr);
398     if (binaryAttr != NULL) {
399         std::string str = binaryAttr->getValues()[*more];
400
401         valueBuf.value = (void *)str.data();
402         valueBuf.length = str.size();
403     } else {
404         std::string str = shibAttr->getSerializedValues()[*more];
405
406         valueBuf.value = (void *)str.c_str();
407         valueBuf.length = str.length();
408
409         const SimpleAttribute *simpleAttr =
410             dynamic_cast<const SimpleAttribute *>(shibAttr);
411         const ScopedAttribute *scopedAttr =
412             dynamic_cast<const ScopedAttribute *>(shibAttr);
413         if (simpleAttr != NULL || scopedAttr != NULL)
414             displayValueBuf = valueBuf;
415     }
416
417     if (authenticated != NULL)
418         *authenticated = m_authenticated;
419     if (complete != NULL)
420         *complete = true;
421     if (value != NULL)
422         duplicateBuffer(valueBuf, value);
423     if (display_value != NULL)
424         duplicateBuffer(displayValueBuf, display_value);
425     if (nvalues > ++i)
426         *more = i;
427
428     return true;
429 }
430
431 gss_any_t
432 gss_eap_shib_attr_provider::mapToAny(int authenticated,
433                                      gss_buffer_t type_id GSSEAP_UNUSED) const
434 {
435     gss_any_t output;
436
437     GSSEAP_ASSERT(m_initialized);
438
439     if (authenticated && !m_authenticated)
440         return (gss_any_t)NULL;
441
442     vector <Attribute *>v = duplicateAttributes(m_attributes);
443
444     output = (gss_any_t)new vector <Attribute *>(v);
445
446     return output;
447 }
448
449 void
450 gss_eap_shib_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id GSSEAP_UNUSED,
451                                                   gss_any_t input) const
452 {
453     GSSEAP_ASSERT(m_initialized);
454
455     vector <Attribute *> *v = ((vector <Attribute *> *)input);
456     delete v;
457 }
458
459 const char *
460 gss_eap_shib_attr_provider::prefix(void) const
461 {
462     return NULL;
463 }
464
465 const char *
466 gss_eap_shib_attr_provider::name(void) const
467 {
468     return "local";
469 }
470
471 JSONObject
472 gss_eap_shib_attr_provider::jsonRepresentation(void) const
473 {
474     JSONObject obj;
475
476     if (m_initialized == false)
477         return obj; /* don't export incomplete context */
478
479     JSONObject jattrs = JSONObject::array();
480
481     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
482          a != m_attributes.end(); ++a) {
483         DDF attr = (*a)->marshall();
484         JSONObject jattr = JSONObject::ddf(attr);
485         jattrs.append(jattr);
486     }
487
488     obj.set("attributes", jattrs);
489
490     obj.set("authenticated", m_authenticated);
491
492     return obj;
493 }
494
495 bool
496 gss_eap_shib_attr_provider::initWithJsonObject(const gss_eap_attr_ctx *ctx,
497                                                JSONObject &obj)
498 {
499     if (!gss_eap_attr_provider::initWithJsonObject(ctx, obj))
500         return false;
501
502     GSSEAP_ASSERT(m_authenticated == false);
503     GSSEAP_ASSERT(m_attributes.size() == 0);
504
505     JSONObject jattrs = obj["attributes"];
506     size_t nelems = jattrs.size();
507
508     for (size_t i = 0; i < nelems; i++) {
509         JSONObject jattr = jattrs.get(i);
510
511         DDF attr = jattr.ddf();
512         Attribute *attribute = Attribute::unmarshall(attr);
513         m_attributes.push_back(attribute);
514     }
515
516     m_authenticated = obj["authenticated"].integer();
517     m_initialized = true;
518
519     return true;
520 }
521
522 bool
523 gss_eap_shib_attr_provider::init(void)
524 {
525     bool ret = false;
526
527     if (ShibFinalizer::isShibInitialized()) {
528         wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::init(): ShibResolver library is already initialized; ignoring.");
529         return true;
530     }
531
532     wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::init(): Initializing ShibResolver library");
533
534     try {
535         ret = ShibbolethResolver::init();
536     } catch (exception &e) {
537     }
538
539     if (ret) {
540         ShibFinalizer::createSingleton();
541         gss_eap_attr_ctx::registerProvider(ATTR_TYPE_LOCAL, createAttrContext);
542     }
543
544     return ret;
545 }
546
547 void
548 gss_eap_shib_attr_provider::finalize(void)
549 {
550     wpa_printf(MSG_INFO, "### gss_eap_shib_attr_provider::finalize(): calling ShibbolethResolver::term()");
551     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_LOCAL);
552     ShibbolethResolver::term();
553 }
554
555 OM_uint32
556 gss_eap_shib_attr_provider::mapException(OM_uint32 *minor,
557                                          std::exception &e) const
558 {
559     if (typeid(e) == typeid(AttributeException))
560         *minor = GSSEAP_SHIB_ATTR_FAILURE;
561     else if (typeid(e) == typeid(AttributeExtractionException))
562         *minor = GSSEAP_SHIB_ATTR_EXTRACT_FAILURE;
563     else if (typeid(e) == typeid(AttributeFilteringException))
564         *minor = GSSEAP_SHIB_ATTR_FILTER_FAILURE;
565     else if (typeid(e) == typeid(AttributeResolutionException))
566         *minor = GSSEAP_SHIB_ATTR_RESOLVE_FAILURE;
567     else if (typeid(e) == typeid(ConfigurationException))
568         *minor = GSSEAP_SHIB_CONFIG_FAILURE;
569     else if (typeid(e) == typeid(ListenerException))
570         *minor = GSSEAP_SHIB_LISTENER_FAILURE;
571     else
572         return GSS_S_CONTINUE_NEEDED;
573
574     gssEapSaveStatusInfo(*minor, "%s", e.what());
575
576     return GSS_S_FAILURE;
577 }
578
579 gss_eap_attr_provider *
580 gss_eap_shib_attr_provider::createAttrContext(void)
581 {
582     return new gss_eap_shib_attr_provider;
583 }
584
585 Attribute *
586 gss_eap_shib_attr_provider::duplicateAttribute(const Attribute *src)
587 {
588     DDF obj = src->marshall();
589     Attribute *attribute = Attribute::unmarshall(obj);
590     obj.destroy();
591
592     return attribute;
593 }
594
595 vector <Attribute *>
596 gss_eap_shib_attr_provider::duplicateAttributes(const vector <Attribute *>src)
597 {
598     vector <Attribute *> dst;
599
600     for (vector<Attribute *>::const_iterator a = src.begin();
601          a != src.end();
602          ++a)
603         dst.push_back(duplicateAttribute(*a));
604
605     return dst;
606 }
607
608
609 OM_uint32
610 gssEapLocalAttrProviderInit(OM_uint32 *minor)
611 {
612     if (!gss_eap_shib_attr_provider::init()) {
613         *minor = GSSEAP_SHIB_INIT_FAILURE;
614         return GSS_S_FAILURE;
615     }
616
617     return GSS_S_COMPLETE;
618 }