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