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