7b624848b7afd7dfba157544b8986430034cfce6
[mech_eap.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 "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     gss_eap_attrid attrid(VENDORPEC_UKERNA, PW_SAML_AAA_ASSERTION);
167
168     radius = static_cast<const gss_eap_radius_attr_provider *>
169         (m_manager->getProvider(ATTR_TYPE_RADIUS));
170     if (radius != NULL &&
171         radius->getFragmentedAttribute(attrid, &authenticated, &complete, &value)) {
172         string str((char *)value.value, value.length);
173         istringstream istream(str);
174         DOMDocument *doc = XMLToolingConfig::getConfig().getParser().parse(istream);
175         const XMLObjectBuilder *b = XMLObjectBuilder::getBuilder(doc->getDocumentElement());
176         resolver->addToken(b->buildFromDocument(doc));
177         gss_release_buffer(&minor, &value);
178     }
179 #endif /* HAVE_OPENSAML */
180
181     try {
182         resolver->resolve();
183         m_attributes = resolver->getResolvedAttributes();
184         resolver->getResolvedAttributes().clear();
185     } catch (exception &e) {
186         return false;
187     }
188
189     m_authenticated = true;
190     m_initialized = true;
191
192     return true;
193 }
194
195 ssize_t
196 gss_eap_shib_attr_provider::getAttributeIndex(const gss_buffer_t attr) const
197 {
198     int i = 0;
199
200     GSSEAP_ASSERT(m_initialized);
201
202     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
203          a != m_attributes.end();
204          ++a)
205     {
206         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
207              s != (*a)->getAliases().end();
208              ++s) {
209             if (attr->length == (*s).length() &&
210                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
211                 return i;
212             }
213         }
214     }
215
216     return -1;
217 }
218
219 bool
220 gss_eap_shib_attr_provider::setAttribute(int complete GSSEAP_UNUSED,
221                                          const gss_buffer_t attr,
222                                          const gss_buffer_t value)
223 {
224     string attrStr((char *)attr->value, attr->length);
225     vector <string> ids(1, attrStr);
226     BinaryAttribute *a = new BinaryAttribute(ids);
227
228     GSSEAP_ASSERT(m_initialized);
229
230     if (value->length != 0) {
231         string valueStr((char *)value->value, value->length);
232
233         a->getValues().push_back(valueStr);
234     }
235
236     m_attributes.push_back(a);
237     m_authenticated = false;
238
239     return true;
240 }
241
242 bool
243 gss_eap_shib_attr_provider::deleteAttribute(const gss_buffer_t attr)
244 {
245     int i;
246
247     GSSEAP_ASSERT(m_initialized);
248
249     i = getAttributeIndex(attr);
250     if (i >= 0)
251         m_attributes.erase(m_attributes.begin() + i);
252
253     m_authenticated = false;
254
255     return true;
256 }
257
258 bool
259 gss_eap_shib_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
260                                               void *data) const
261 {
262     GSSEAP_ASSERT(m_initialized);
263
264     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
265         a != m_attributes.end();
266         ++a)
267     {
268         gss_buffer_desc attribute;
269
270         attribute.value = (void *)((*a)->getId());
271         attribute.length = strlen((char *)attribute.value);
272
273         if (!addAttribute(m_manager, this, &attribute, data))
274             return false;
275     }
276
277     return true;
278 }
279
280 const Attribute *
281 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr) const
282 {
283     const Attribute *ret = NULL;
284
285     GSSEAP_ASSERT(m_initialized);
286
287     for (vector<Attribute *>::const_iterator a = m_attributes.begin();
288          a != m_attributes.end();
289          ++a)
290     {
291         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
292              s != (*a)->getAliases().end();
293              ++s) {
294             if (attr->length == (*s).length() &&
295                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
296                 ret = *a;
297                 break;
298             }
299         }
300         if (ret != NULL)
301             break;
302     }
303
304     return ret;
305 }
306
307 bool
308 gss_eap_shib_attr_provider::getAttribute(const gss_buffer_t attr,
309                                          int *authenticated,
310                                          int *complete,
311                                          gss_buffer_t value,
312                                          gss_buffer_t display_value,
313                                          int *more) const
314 {
315     const Attribute *shibAttr = NULL;
316     const BinaryAttribute *binaryAttr;
317     gss_buffer_desc valueBuf = GSS_C_EMPTY_BUFFER;
318     gss_buffer_desc displayValueBuf = GSS_C_EMPTY_BUFFER;
319     int nvalues, i = *more;
320
321     GSSEAP_ASSERT(m_initialized);
322
323     *more = 0;
324
325     shibAttr = getAttribute(attr);
326     if (shibAttr == NULL)
327         return false;
328
329     nvalues = shibAttr->valueCount();
330
331     if (i == -1)
332         i = 0;
333     if (i >= nvalues)
334         return false;
335
336     binaryAttr = dynamic_cast<const BinaryAttribute *>(shibAttr);
337     if (binaryAttr != NULL) {
338         std::string str = binaryAttr->getValues()[*more];
339
340         valueBuf.value = (void *)str.data();
341         valueBuf.length = str.size();
342     } else {
343         std::string str = shibAttr->getSerializedValues()[*more];
344
345         valueBuf.value = (void *)str.c_str();
346         valueBuf.length = str.length();
347
348         const SimpleAttribute *simpleAttr =
349             dynamic_cast<const SimpleAttribute *>(shibAttr);
350         const ScopedAttribute *scopedAttr =
351             dynamic_cast<const ScopedAttribute *>(shibAttr);
352         if (simpleAttr != NULL || scopedAttr != NULL)
353             displayValueBuf = valueBuf;
354     }
355
356     if (authenticated != NULL)
357         *authenticated = m_authenticated;
358     if (complete != NULL)
359         *complete = true;
360     if (value != NULL)
361         duplicateBuffer(valueBuf, value);
362     if (display_value != NULL)
363         duplicateBuffer(displayValueBuf, display_value);
364     if (nvalues > ++i)
365         *more = i;
366
367     return true;
368 }
369
370 gss_any_t
371 gss_eap_shib_attr_provider::mapToAny(int authenticated,
372                                      gss_buffer_t type_id GSSEAP_UNUSED) const
373 {
374     gss_any_t output;
375
376     GSSEAP_ASSERT(m_initialized);
377
378     if (authenticated && !m_authenticated)
379         return (gss_any_t)NULL;
380
381     vector <Attribute *>v = duplicateAttributes(m_attributes);
382
383     output = (gss_any_t)new vector <Attribute *>(v);
384
385     return output;
386 }
387
388 void
389 gss_eap_shib_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id GSSEAP_UNUSED,
390                                                   gss_any_t input) const
391 {
392     GSSEAP_ASSERT(m_initialized);
393
394     vector <Attribute *> *v = ((vector <Attribute *> *)input);
395     delete v;
396 }
397
398 const char *
399 gss_eap_shib_attr_provider::prefix(void) const
400 {
401     return NULL;
402 }
403
404 const char *
405 gss_eap_shib_attr_provider::name(void) const
406 {
407     return "local";
408 }
409
410 JSONObject
411 gss_eap_shib_attr_provider::jsonRepresentation(void) const
412 {
413     JSONObject obj;
414
415     if (m_initialized == false)
416         return obj; /* don't export incomplete context */
417
418     JSONObject jattrs = JSONObject::array();
419
420     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
421          a != m_attributes.end(); ++a) {
422         DDF attr = (*a)->marshall();
423         JSONObject jattr = JSONObject::ddf(attr);
424         jattrs.append(jattr);
425     }
426
427     obj.set("attributes", jattrs);
428
429     obj.set("authenticated", m_authenticated);
430
431     return obj;
432 }
433
434 bool
435 gss_eap_shib_attr_provider::initWithJsonObject(const gss_eap_attr_ctx *ctx,
436                                                JSONObject &obj)
437 {
438     if (!gss_eap_attr_provider::initWithJsonObject(ctx, obj))
439         return false;
440
441     GSSEAP_ASSERT(m_authenticated == false);
442     GSSEAP_ASSERT(m_attributes.size() == 0);
443
444     JSONObject jattrs = obj["attributes"];
445     size_t nelems = jattrs.size();
446
447     for (size_t i = 0; i < nelems; i++) {
448         JSONObject jattr = jattrs.get(i);
449
450         DDF attr = jattr.ddf();
451         Attribute *attribute = Attribute::unmarshall(attr);
452         m_attributes.push_back(attribute);
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     bool ret = false;
465
466     try {
467         ret = ShibbolethResolver::init();
468     } catch (exception &e) {
469     }
470
471     if (ret)
472         gss_eap_attr_ctx::registerProvider(ATTR_TYPE_LOCAL, createAttrContext);
473
474     return ret;
475 }
476
477 void
478 gss_eap_shib_attr_provider::finalize(void)
479 {
480     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_LOCAL);
481     ShibbolethResolver::term();
482 }
483
484 OM_uint32
485 gss_eap_shib_attr_provider::mapException(OM_uint32 *minor,
486                                          std::exception &e) const
487 {
488     if (typeid(e) == typeid(AttributeException))
489         *minor = GSSEAP_SHIB_ATTR_FAILURE;
490     else if (typeid(e) == typeid(AttributeExtractionException))
491         *minor = GSSEAP_SHIB_ATTR_EXTRACT_FAILURE;
492     else if (typeid(e) == typeid(AttributeFilteringException))
493         *minor = GSSEAP_SHIB_ATTR_FILTER_FAILURE;
494     else if (typeid(e) == typeid(AttributeResolutionException))
495         *minor = GSSEAP_SHIB_ATTR_RESOLVE_FAILURE;
496     else if (typeid(e) == typeid(ConfigurationException))
497         *minor = GSSEAP_SHIB_CONFIG_FAILURE;
498     else if (typeid(e) == typeid(ListenerException))
499         *minor = GSSEAP_SHIB_LISTENER_FAILURE;
500     else
501         return GSS_S_CONTINUE_NEEDED;
502
503     gssEapSaveStatusInfo(*minor, "%s", e.what());
504
505     return GSS_S_FAILURE;
506 }
507
508 gss_eap_attr_provider *
509 gss_eap_shib_attr_provider::createAttrContext(void)
510 {
511     return new gss_eap_shib_attr_provider;
512 }
513
514 Attribute *
515 gss_eap_shib_attr_provider::duplicateAttribute(const Attribute *src)
516 {
517     DDF obj = src->marshall();
518     Attribute *attribute = Attribute::unmarshall(obj);
519     obj.destroy();
520
521     return attribute;
522 }
523
524 vector <Attribute *>
525 gss_eap_shib_attr_provider::duplicateAttributes(const vector <Attribute *>src)
526 {
527     vector <Attribute *> dst;
528
529     for (vector<Attribute *>::const_iterator a = src.begin();
530          a != src.end();
531          ++a)
532         dst.push_back(duplicateAttribute(*a));
533
534     return dst;
535 }
536
537 OM_uint32
538 gssEapLocalAttrProviderInit(OM_uint32 *minor)
539 {
540     if (!gss_eap_shib_attr_provider::init()) {
541         *minor = GSSEAP_SHIB_INIT_FAILURE;
542         return GSS_S_FAILURE;
543     }
544     return GSS_S_COMPLETE;
545 }
546
547 OM_uint32
548 gssEapLocalAttrProviderFinalize(OM_uint32 *minor)
549 {
550     gss_eap_shib_attr_provider::finalize();
551
552     *minor = 0;
553     return GSS_S_COMPLETE;
554 }