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