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