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