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