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