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