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