SAML cleanups
[mech_eap.git] / util_saml.cpp
1 /*
2  * Copyright (c) 2010, 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 #include <gssapi/gssapi.h>
49 #include <gssapi/gssapi_ext.h>
50 #include "util.h"
51
52 #include <shibsp/Application.h>
53 #include <shibsp/exceptions.h>
54 #include <shibsp/SPConfig.h>
55 #include <shibsp/ServiceProvider.h>
56 #include <shibsp/attribute/Attribute.h>
57 #include <shibsp/attribute/SimpleAttribute.h>
58 #include <shibsp/attribute/resolver/ResolutionContext.h>
59 #include <shibsp/handler/AssertionConsumerService.h>
60 #include <shibsp/metadata/MetadataProviderCriteria.h>
61 #include <shibsp/util/SPConstants.h>
62
63 #include <saml/saml1/core/Assertions.h>
64 #include <saml/saml2/core/Assertions.h>
65 #include <saml/saml2/metadata/Metadata.h>
66 #include <xercesc/util/XMLUniDefs.hpp>
67 #include <xmltooling/XMLToolingConfig.h>
68 #include <xmltooling/util/XMLHelper.h>
69
70 using namespace shibsp;
71 using namespace opensaml::saml2md;
72 using namespace opensaml;
73 using namespace xmltooling::logging;
74 using namespace xmltooling;
75 using namespace xercesc;
76 using namespace std;
77
78 class GSSEAPResolver : public shibsp::AssertionConsumerService
79 {
80 public:
81     GSSEAPResolver(const DOMElement *e, const char *appId)
82         : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".GSSEAPResolver")) {
83     }
84     virtual ~GSSEAPResolver() {}
85
86     ResolutionContext* resolveAttributes (
87         const Application& application,
88         const RoleDescriptor* issuer,
89         const XMLCh* protocol,
90         const saml1::NameIdentifier* v1nameid,
91         const saml2::NameID* nameid,
92         const XMLCh* authncontext_class,
93         const XMLCh* authncontext_decl,
94         const vector<const Assertion*>* tokens
95         ) const {
96             return shibsp::AssertionConsumerService::resolveAttributes(
97                     application, issuer, protocol, v1nameid,
98                     nameid, authncontext_class, authncontext_decl, tokens
99             );
100     }
101
102 private:
103     void implementProtocol(
104         const Application& application,
105         const HTTPRequest& httpRequest,
106         HTTPResponse& httpResponse,
107         SecurityPolicy& policy,
108         const PropertySet* settings,
109         const XMLObject& xmlObject
110         ) const {
111             throw FatalProfileException("Should never be called.");
112     }
113 };
114
115 struct eap_gss_saml_attr_ctx {
116 public:
117     eap_gss_saml_attr_ctx();
118     eap_gss_saml_attr_ctx(const gss_buffer_t buffer);
119     eap_gss_saml_attr_ctx(const Assertion *assertion);
120
121     eap_gss_saml_attr_ctx(const vector<Attribute*>& attributes,
122                           const Assertion *assertion);
123
124     eap_gss_saml_attr_ctx(const eap_gss_saml_attr_ctx &ctx) {
125         eap_gss_saml_attr_ctx(ctx.m_attributes, ctx.m_assertion);
126     }
127
128     ~eap_gss_saml_attr_ctx();
129
130     const vector <Attribute *> getAttributes(void) const {
131         return m_attributes;
132     }
133
134     void addAttribute(Attribute *attr, bool copy = true);
135     void setAttributes(const vector<Attribute*> attributes);
136
137     void setAttribute(int complete,
138                       const gss_buffer_t attr,
139                       const gss_buffer_t value);
140     void deleteAttribute(const gss_buffer_t attr);
141
142     int getAttributeIndex(const gss_buffer_t attr) const;
143     const Attribute *getAttribute(const gss_buffer_t attr) const;
144
145     bool getAttribute(const gss_buffer_t attr,
146                       int *authenticated,
147                       int *complete,
148                       gss_buffer_t value,
149                       gss_buffer_t display_value,
150                       int *more);
151
152     const Assertion *getAssertion(void) const {
153         return m_assertion;
154     }
155
156     bool getAssertion(gss_buffer_t buffer);
157
158     DDF marshall() const;
159     static eap_gss_saml_attr_ctx *unmarshall(DDF &in);
160
161     void marshall(gss_buffer_t buffer);
162     static eap_gss_saml_attr_ctx *unmarshall(const gss_buffer_t buffer);
163
164 private:
165     mutable vector<Attribute*> m_attributes;
166     mutable Assertion *m_assertion;
167
168     bool parseAssertion(const gss_buffer_t buffer);
169 };
170
171 eap_gss_saml_attr_ctx::eap_gss_saml_attr_ctx(const vector<Attribute*>& attributes,
172                                              const Assertion *assertion)
173 {
174     m_assertion = dynamic_cast<saml2::Assertion *>(assertion->clone());
175     setAttributes(attributes);
176 }
177
178 eap_gss_saml_attr_ctx::~eap_gss_saml_attr_ctx()
179 {
180     for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
181     delete m_assertion;
182 }
183
184 eap_gss_saml_attr_ctx::eap_gss_saml_attr_ctx(const gss_buffer_t buffer)
185 {
186     parseAssertion(buffer);
187 }
188
189 static OM_uint32
190 mapException(OM_uint32 *minor, exception &e)
191 {
192     return GSS_S_FAILURE;
193 }
194
195 bool
196 eap_gss_saml_attr_ctx::parseAssertion(const gss_buffer_t buffer)
197 {
198     DOMDocument *doc;
199     const XMLObjectBuilder *b;
200     DOMElement *elem;
201     XMLObject *xobj;
202     string str((char *)buffer->value, buffer->length);
203     istringstream istream(str);
204
205     doc = XMLToolingConfig::getConfig().getParser().parse(istream);
206     b = XMLObjectBuilder::getDefaultBuilder();
207     elem = doc->getDocumentElement();
208     xobj = b->buildOneFromElement(elem, true);
209
210     m_assertion = dynamic_cast<saml2::Assertion *>(xobj);
211
212     return (m_assertion != NULL);
213 }
214
215 static inline void
216 duplicateBuffer(gss_buffer_desc &src, gss_buffer_t dst)
217 {
218     OM_uint32 minor;
219
220     if (GSS_ERROR(duplicateBuffer(&minor, &src, dst)))
221         throw new bad_alloc();
222 }
223
224 static inline void
225 duplicateBuffer(string &str, gss_buffer_t buffer)
226 {
227     gss_buffer_desc tmp;
228
229     tmp.length = str.length();
230     tmp.value = (char *)str.c_str();
231
232     duplicateBuffer(tmp, buffer);
233 }
234
235 DDF
236 eap_gss_saml_attr_ctx::marshall() const
237 {
238     DDF obj;
239     DDF attrs;
240     DDF assertion;
241
242     obj.addmember("version").integer(1);
243
244     attrs = obj.addmember("attributes").list();
245     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
246          a != m_attributes.end(); ++a) {
247         DDF attr = (*a)->marshall();
248         attrs.add(attr);
249     }
250
251     ostringstream sink;
252     sink << *m_assertion;
253     assertion = obj.addmember("assertion").string(sink.str().c_str());
254
255     return obj;
256 }
257
258 eap_gss_saml_attr_ctx *
259 eap_gss_saml_attr_ctx::unmarshall(DDF &obj)
260 {
261     eap_gss_saml_attr_ctx *ctx = new eap_gss_saml_attr_ctx();
262
263     DDF version = obj["version"];
264     if (version.integer() != 1)
265         return NULL;
266
267     DDF assertion = obj["assertion"];
268     gss_buffer_desc buffer;
269
270     if (!assertion.isnull()) {
271         buffer.length = assertion.strlen();
272         buffer.value = (void *)assertion.string();
273     } else {
274         buffer.length = 0;
275     }
276
277     if (buffer.length != 0)
278         ctx->parseAssertion(&buffer);
279
280     DDF attrs = obj["attributes"];
281     DDF attr = attrs.first();
282     while (!attr.isnull()) {
283         Attribute *attribute = Attribute::unmarshall(attr);
284         ctx->addAttribute(attribute, false);
285         attr = attrs.next();
286     }
287
288     return ctx;
289 }
290
291 void
292 eap_gss_saml_attr_ctx::marshall(gss_buffer_t buffer)
293 {
294     DDF obj;
295     ostringstream sink;
296     string str;
297
298     obj = marshall();
299     sink << obj;
300     str = sink.str();
301
302     duplicateBuffer(str, buffer);
303 }
304
305 eap_gss_saml_attr_ctx *
306 eap_gss_saml_attr_ctx::unmarshall(const gss_buffer_t buffer)
307 {
308     DDF obj;
309     string str((const char *)buffer->value, buffer->length);
310     istringstream source(str);
311     source >> obj;
312
313     return unmarshall(obj);
314 }
315
316 bool
317 eap_gss_saml_attr_ctx::getAssertion(gss_buffer_t buffer)
318 {
319     string str;
320
321     if (m_assertion == NULL)
322         return false;
323
324     buffer->value = NULL;
325     buffer->length = 0;
326
327     XMLHelper::serialize(m_assertion->marshall((DOMDocument *)NULL), str);
328
329     duplicateBuffer(str, buffer);
330
331     return true;
332 }
333
334 void
335 eap_gss_saml_attr_ctx::addAttribute(Attribute *attribute, bool copy)
336 {
337     Attribute *a;
338
339     if (copy) {
340         DDF obj = attribute->marshall();
341         a = Attribute::unmarshall(obj);
342     } else {
343         a = attribute;
344     }
345
346     m_attributes.push_back(a);
347 }
348
349 void
350 eap_gss_saml_attr_ctx::setAttributes(const vector<Attribute*> attributes)
351 {
352     for (vector<Attribute *>::const_iterator a = attributes.begin();
353          a != attributes.end();
354          ++a)
355         addAttribute(*a);
356 }
357
358 int
359 eap_gss_saml_attr_ctx::getAttributeIndex(const gss_buffer_t attr) const
360 {
361     int i = 0;
362
363     for (vector<Attribute *>::const_iterator a = getAttributes().begin();
364          a != getAttributes().end();
365          ++a)
366     {
367         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
368              s != (*a)->getAliases().end();
369              ++s) {
370             if (attr->length == (*s).length() &&
371                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
372                 return i;
373             }
374         }
375     }
376
377     return -1;
378 }
379
380 const Attribute *
381 eap_gss_saml_attr_ctx::getAttribute(const gss_buffer_t attr) const
382 {
383     const Attribute *ret = NULL;
384
385     for (vector<Attribute *>::const_iterator a = getAttributes().begin();
386          a != getAttributes().end();
387          ++a)
388     {
389         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
390              s != (*a)->getAliases().end();
391              ++s) {
392             if (attr->length == (*s).length() &&
393                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
394                 ret = *a;
395                 break;
396             }
397         }
398         if (ret != NULL)
399             break;
400     }
401
402     return ret;
403 }
404
405 bool
406 eap_gss_saml_attr_ctx::getAttribute(const gss_buffer_t attr,
407                                     int *authenticated,
408                                     int *complete,
409                                     gss_buffer_t value,
410                                     gss_buffer_t display_value,
411                                     int *more)
412 {
413     const Attribute *shibAttr = NULL;
414     gss_buffer_desc buf;
415
416     shibAttr = getAttribute(attr);
417     if (shibAttr == NULL)
418         return false;
419
420     if (*more == -1) {
421         *more = 0;
422     } else if (*more >= (int)shibAttr->valueCount()) {
423         *more = 0;
424         return true;
425     }
426
427     buf.value = (void *)shibAttr->getString(*more);
428     buf.length = strlen((char *)buf.value);
429
430     duplicateBuffer(buf, value);
431  
432     *authenticated = TRUE;
433     *complete = FALSE;
434
435     return true;
436 }
437
438 void
439 eap_gss_saml_attr_ctx::setAttribute(int complete,
440                                     const gss_buffer_t attr,
441                                     const gss_buffer_t value)
442 {
443     string attrStr((char *)attr->value, attr->length);
444     vector <string> ids(1);
445     SimpleAttribute *a;
446
447     ids.push_back(attrStr);
448
449     a = new SimpleAttribute(ids);
450
451     if (value->length != 0) {
452         string valStr((char *)value->value, value->length);
453
454         a->getValues().push_back(valStr);        
455     }
456
457     m_attributes.push_back(a);
458 }
459
460 void
461 eap_gss_saml_attr_ctx::deleteAttribute(const gss_buffer_t attr)
462 {
463     int i;
464
465     i = getAttributeIndex(attr);
466     if (i >= 0)
467         m_attributes.erase(m_attributes.begin() + i);
468 }
469
470 OM_uint32
471 samlReleaseAttrContext(OM_uint32 *minor,
472                        struct eap_gss_saml_attr_ctx **pCtx)
473 {
474     eap_gss_saml_attr_ctx *ctx = *pCtx;
475
476     if (ctx != NULL) {
477         delete ctx;
478         *pCtx = NULL;
479     }
480
481     *minor = 0;
482     return GSS_S_COMPLETE;
483 }
484
485 OM_uint32
486 samlCreateAttrContext(OM_uint32 *minor,
487                       gss_buffer_t buffer,
488                       gss_name_t acceptorName,
489                       struct eap_gss_saml_attr_ctx **pCtx)
490 {
491     OM_uint32 major, tmpMinor;
492     eap_gss_saml_attr_ctx *ctx = NULL;
493     SPConfig &conf = SPConfig::getConfig();
494     ServiceProvider *sp;
495     const Application *app;
496     MetadataProvider *m;
497     gss_buffer_desc nameBuf;
498     const XMLCh *issuer = NULL;
499     saml2::NameID *subjectName = NULL;
500     saml2::Assertion *assertion;
501     ResolutionContext *resolverContext;
502
503     nameBuf.length = 0;
504     nameBuf.value = NULL;
505
506     conf.setFeatures(SPConfig::Metadata             |
507                      SPConfig::Trust                |
508                      SPConfig::AttributeResolution  |
509                      SPConfig::Credentials          |
510                      SPConfig::OutOfProcess);
511     if (!conf.init())
512         return GSS_S_FAILURE;
513     if (!conf.instantiate())
514         return GSS_S_FAILURE;
515
516     sp = conf.getServiceProvider();
517     sp->lock();
518
519     major = gss_display_name(minor, acceptorName, &nameBuf, NULL);
520     if (GSS_ERROR(major))
521         goto cleanup;
522
523     app = sp->getApplication((const char *)nameBuf.value);
524     if (app == NULL) {
525         major = GSS_S_FAILURE;
526         goto cleanup;
527     }
528
529     try {
530         ctx = new eap_gss_saml_attr_ctx(buffer);
531
532         if (assertion->getIssuer() != NULL)
533             issuer = assertion->getIssuer()->getName();
534         if (assertion->getSubject() != NULL)
535             subjectName = assertion->getSubject()->getNameID();
536
537         m = app->getMetadataProvider();
538         xmltooling::Locker mlocker(m);
539         MetadataProviderCriteria mc(*app, issuer,
540                                     &IDPSSODescriptor::ELEMENT_QNAME,
541                                     samlconstants::SAML20P_NS);
542         pair<const EntityDescriptor *, const RoleDescriptor *> site =
543             m->getEntityDescriptor(mc);
544         if (!site.first) {
545             auto_ptr_char temp(issuer);
546             throw MetadataException("Unable to locate metadata for IdP ($1).",
547                                     params(1,temp.get()));
548         }
549         vector<const Assertion*> tokens(1, assertion);
550         GSSEAPResolver gssResolver(NULL, (const char *)nameBuf.value);
551         resolverContext = gssResolver.resolveAttributes(*app, site.second,
552                                                         samlconstants::SAML20P_NS,
553                                                         NULL, subjectName, NULL,
554                                                         NULL, &tokens);
555         ctx->setAttributes(resolverContext->getResolvedAttributes());
556     } catch (exception &ex) {
557         major = mapException(minor, ex);
558         goto cleanup;
559     }
560
561     major = GSS_S_COMPLETE;
562     *pCtx = ctx;
563
564 cleanup:
565     sp->unlock();
566     conf.term();
567
568     if (GSS_ERROR(major))
569         delete ctx;
570     gss_release_buffer(&tmpMinor, &nameBuf);
571
572     return major;
573 }
574
575 OM_uint32
576 samlGetAttributeTypes(OM_uint32 *minor,
577                       const struct eap_gss_saml_attr_ctx *ctx,
578                       void *data,
579                       OM_uint32 (*addAttribute)(OM_uint32 *, void *, gss_buffer_t))
580 {
581     OM_uint32 major = GSS_S_COMPLETE;
582
583     if (ctx == NULL)
584         return GSS_S_COMPLETE;
585
586     for (vector<Attribute*>::const_iterator a = ctx->getAttributes().begin();
587         a != ctx->getAttributes().end();
588         ++a)
589     {
590         gss_buffer_desc attribute;
591
592         attribute.value = (void *)((*a)->getId());
593         attribute.length = strlen((char *)attribute.value);
594
595         major = addAttribute(minor, data, &attribute);
596         if (GSS_ERROR(major))
597             break;
598     }
599
600     return major;
601 }
602
603 /*
604  * SAML implementation of gss_get_name_attribute
605  */
606 OM_uint32
607 samlGetAttribute(OM_uint32 *minor,
608                  struct eap_gss_saml_attr_ctx *ctx,
609                  gss_buffer_t attr,
610                  int *authenticated,
611                  int *complete,
612                  gss_buffer_t value,
613                  gss_buffer_t display_value,
614                  int *more)
615 {
616     if (ctx == NULL)
617         return GSS_S_UNAVAILABLE;
618
619     if (!ctx->getAttribute(attr, authenticated, complete,
620                            value, display_value, more))
621         return GSS_S_UNAVAILABLE;
622
623     return GSS_S_COMPLETE;
624 }
625
626 OM_uint32
627 samlSetAttribute(OM_uint32 *minor,
628                  struct eap_gss_saml_attr_ctx *ctx,
629                  int complete,
630                  gss_buffer_t attr,
631                  gss_buffer_t value)
632 {
633     try {
634         ctx->setAttribute(complete, attr, value);
635     } catch (exception &e) {
636         return mapException(minor, e);
637     }
638
639     return GSS_S_COMPLETE;
640 }
641
642 OM_uint32
643 samlDeleteAttribute(OM_uint32 *minor,
644                     struct eap_gss_saml_attr_ctx *ctx,
645                     gss_buffer_t attr)
646 {
647     try {
648         ctx->deleteAttribute(attr);
649     } catch (exception &e) {
650         return mapException(minor, e);
651     }
652
653     return GSS_S_COMPLETE;
654 }
655
656 /*
657  * In order to implement gss_export_name and gss_export_sec_context,
658  * we need to serialise a resolved attribute context to a buffer.
659  */
660 OM_uint32
661 samlExportAttrContext(OM_uint32 *minor,
662                       struct eap_gss_saml_attr_ctx *ctx,
663                       gss_buffer_t buffer)
664 {
665     try {
666         ctx->marshall(buffer);
667     } catch (exception &e) {
668         return mapException(minor, e);
669     }        
670
671     return GSS_S_COMPLETE;
672 }
673
674 /*
675  * In order to implement gss_import_name and gss_import_sec_context,
676  * we need to deserialise a resolved attribute context from a buffer.
677  */
678 OM_uint32
679 samlImportAttrContext(OM_uint32 *minor,
680                       gss_buffer_t buffer,
681                       struct eap_gss_saml_attr_ctx **pCtx)
682 {
683     try {
684         *pCtx = eap_gss_saml_attr_ctx::unmarshall(buffer);
685     } catch (exception &e) {
686         return mapException(minor, e);
687     }
688
689     return GSS_S_COMPLETE;
690 }
691
692 OM_uint32
693 samlGetAssertion(OM_uint32 *minor,
694                  struct eap_gss_saml_attr_ctx *ctx,
695                  gss_buffer_t assertion)
696 {
697     try {
698         ctx->getAssertion(assertion);
699     } catch (exception &e) {
700         return mapException(minor, e);
701     }
702
703     return GSS_S_COMPLETE;
704 }
705
706 OM_uint32
707 samlDuplicateAttrContext(OM_uint32 *minor,
708                          const struct eap_gss_saml_attr_ctx *in,
709                          struct eap_gss_saml_attr_ctx **out)
710 {
711     try {
712         *out = new eap_gss_saml_attr_ctx(*in);
713     } catch (exception &e) {
714         return mapException(minor, e);
715     }
716
717     return GSS_S_COMPLETE;
718 }