more work on SAML ification
[mech_eap.orig] / 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     bool 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 bool
190 eap_gss_saml_attr_ctx::parseAssertion(const gss_buffer_t buffer)
191 {
192     DOMDocument *doc;
193     const XMLObjectBuilder *b;
194     DOMElement *elem;
195     XMLObject *xobj;
196     string str((char *)buffer->value, buffer->length);
197     istringstream istream(str);
198
199     doc = XMLToolingConfig::getConfig().getParser().parse(istream);
200     b = XMLObjectBuilder::getDefaultBuilder();
201     elem = doc->getDocumentElement();
202     xobj = b->buildOneFromElement(elem, true);
203
204     m_assertion = dynamic_cast<saml2::Assertion *>(xobj);
205
206     return (m_assertion != NULL);
207 }
208
209 static inline bool
210 duplicateBuffer(string &str, gss_buffer_t buffer)
211 {
212     gss_buffer_desc tmp;
213     OM_uint32 minor;
214
215     tmp.length = str.length();
216     tmp.value = (char *)str.c_str();
217
218     if (GSS_ERROR(duplicateBuffer(&minor, &tmp, buffer)))
219         return false;
220
221     return true;
222 }
223
224 DDF
225 eap_gss_saml_attr_ctx::marshall() const
226 {
227     DDF obj;
228     DDF attrs;
229     DDF assertion;
230
231     obj.addmember("version").integer(1);
232
233     attrs = obj.addmember("attributes").list();
234     for (vector<Attribute*>::const_iterator a = m_attributes.begin();
235          a != m_attributes.end(); ++a) {
236         DDF attr = (*a)->marshall();
237         attrs.add(attr);
238     }
239
240     ostringstream sink;
241     sink << *m_assertion;
242     assertion = obj.addmember("assertion").string(sink.str().c_str());
243
244     return obj;
245 }
246
247 eap_gss_saml_attr_ctx *
248 eap_gss_saml_attr_ctx::unmarshall(DDF &obj)
249 {
250     eap_gss_saml_attr_ctx *ctx = new eap_gss_saml_attr_ctx();
251
252     DDF version = obj["version"];
253     if (version.integer() != 1)
254         return NULL;
255
256     DDF assertion = obj["assertion"];
257     gss_buffer_desc buffer;
258
259     if (!assertion.isnull()) {
260         buffer.length = assertion.strlen();
261         buffer.value = (void *)assertion.string();
262     } else {
263         buffer.length = 0;
264     }
265
266     if (buffer.length != 0)
267         ctx->parseAssertion(&buffer);
268
269     DDF attrs = obj["attributes"];
270     DDF attr = attrs.first();
271     while (!attr.isnull()) {
272         Attribute *attribute = Attribute::unmarshall(attr);
273         ctx->addAttribute(attribute, false);
274         attr = attrs.next();
275     }
276
277     return ctx;
278 }
279
280 bool
281 eap_gss_saml_attr_ctx::marshall(gss_buffer_t buffer)
282 {
283     DDF obj;
284     ostringstream sink;
285     string str;
286
287     obj = marshall();
288     sink << obj;
289     str = sink.str();
290
291     return duplicateBuffer(str, buffer);
292 }
293
294 eap_gss_saml_attr_ctx *
295 eap_gss_saml_attr_ctx::unmarshall(const gss_buffer_t buffer)
296 {
297     DDF obj;
298     string str((const char *)buffer->value, buffer->length);
299     istringstream source(str);
300     source >> obj;
301
302     return unmarshall(obj);
303 }
304
305 bool
306 eap_gss_saml_attr_ctx::getAssertion(gss_buffer_t buffer)
307 {
308     string str;
309
310     buffer->value = NULL;
311     buffer->length = 0;
312
313     XMLHelper::serialize(m_assertion->marshall((DOMDocument *)NULL), str);
314
315     return duplicateBuffer(str, buffer);
316 }
317
318 void
319 eap_gss_saml_attr_ctx::addAttribute(Attribute *attribute, bool copy)
320 {
321     Attribute *a;
322     if (copy) {
323         DDF obj = attribute->marshall();
324         a = Attribute::unmarshall(obj);
325     } else {
326         a = attribute;
327     }
328     m_attributes.push_back(a);
329 }
330
331 void
332 eap_gss_saml_attr_ctx::setAttributes(const vector<Attribute*> attributes)
333 {
334     for (vector<Attribute *>::const_iterator a = attributes.begin();
335          a != attributes.end();
336          ++a)
337         addAttribute(*a);
338 }
339
340 int
341 eap_gss_saml_attr_ctx::getAttributeIndex(const gss_buffer_t attr) const
342 {
343     int i = 0;
344
345     for (vector<Attribute *>::const_iterator a = getAttributes().begin();
346          a != getAttributes().end();
347          ++a)
348     {
349         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
350              s != (*a)->getAliases().end();
351              ++s) {
352             if (attr->length == (*s).length() &&
353                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
354                 return i;
355             }
356         }
357     }
358
359     return -1;
360 }
361
362 const Attribute *
363 eap_gss_saml_attr_ctx::getAttribute(const gss_buffer_t attr) const
364 {
365     const Attribute *ret = NULL;
366
367     for (vector<Attribute *>::const_iterator a = getAttributes().begin();
368          a != getAttributes().end();
369          ++a)
370     {
371         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
372              s != (*a)->getAliases().end();
373              ++s) {
374             if (attr->length == (*s).length() &&
375                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
376                 ret = *a;
377                 break;
378             }
379         }
380         if (ret != NULL)
381             break;
382     }
383
384     return ret;
385 }
386
387 bool
388 eap_gss_saml_attr_ctx::getAttribute(const gss_buffer_t attr,
389                                     int *authenticated,
390                                     int *complete,
391                                     gss_buffer_t value,
392                                     gss_buffer_t display_value,
393                                     int *more)
394 {
395     OM_uint32 major, minor;
396     const Attribute *shibAttr = NULL;
397     gss_buffer_desc buf;
398
399     shibAttr = getAttribute(attr);
400     if (shibAttr == NULL)
401         return false;
402
403     if (*more == -1) {
404         *more = 0;
405     } else if (*more >= (int)shibAttr->valueCount()) {
406         *more = 0;
407         return true;
408     }
409
410     buf.value = (void *)shibAttr->getString(*more);
411     buf.length = strlen((char *)buf.value);
412
413     major = duplicateBuffer(&minor, &buf, value);
414     if (GSS_ERROR(major))
415         return false;
416  
417     *authenticated = TRUE;
418     *complete = FALSE;
419
420     return true;
421 }
422
423 void
424 eap_gss_saml_attr_ctx::setAttribute(int complete,
425                                     const gss_buffer_t attr,
426                                     const gss_buffer_t value)
427 {
428     string attrStr((char *)attr->value, attr->length);
429     vector <string> ids(1);
430     SimpleAttribute *a;
431
432     ids.push_back(attrStr);
433
434     a = new SimpleAttribute(ids);
435
436     if (value->length != 0) {
437         string valStr((char *)value->value, value->length);
438
439         a->getValues().push_back(valStr);        
440     }
441
442     m_attributes.push_back(a);
443 }
444
445 void
446 eap_gss_saml_attr_ctx::deleteAttribute(const gss_buffer_t attr)
447 {
448     int i;
449
450     i = getAttributeIndex(attr);
451     if (i >= 0)
452         m_attributes.erase(m_attributes.begin() + i);
453 }
454
455 OM_uint32
456 samlReleaseAttrContext(OM_uint32 *minor,
457                        struct eap_gss_saml_attr_ctx **pCtx)
458 {
459     eap_gss_saml_attr_ctx *ctx = *pCtx;
460
461     if (ctx != NULL) {
462         delete ctx;
463         *pCtx = NULL;
464     }
465
466     *minor = 0;
467     return GSS_S_COMPLETE;
468 }
469
470 OM_uint32
471 samlCreateAttrContext(OM_uint32 *minor,
472                       gss_buffer_t buffer,
473                       gss_name_t acceptorName,
474                       struct eap_gss_saml_attr_ctx **pCtx)
475 {
476     OM_uint32 major, tmpMinor;
477     eap_gss_saml_attr_ctx *ctx = NULL;
478     SPConfig &conf = SPConfig::getConfig();
479     ServiceProvider *sp;
480     const Application *app;
481     MetadataProvider *m;
482     gss_buffer_desc nameBuf;
483     const XMLCh *issuer = NULL;
484     saml2::NameID *subjectName = NULL;
485     saml2::Assertion *assertion;
486     ResolutionContext *resolverContext;
487
488     nameBuf.length = 0;
489     nameBuf.value = NULL;
490
491     conf.setFeatures(SPConfig::Metadata             |
492                      SPConfig::Trust                |
493                      SPConfig::AttributeResolution  |
494                      SPConfig::Credentials          |
495                      SPConfig::OutOfProcess);
496     if (!conf.init())
497         return GSS_S_FAILURE;
498     if (!conf.instantiate())
499         return GSS_S_FAILURE;
500
501     sp = conf.getServiceProvider();
502     sp->lock();
503
504     major = gss_display_name(minor, acceptorName, &nameBuf, NULL);
505     if (GSS_ERROR(major))
506         goto cleanup;
507
508     app = sp->getApplication((const char *)nameBuf.value);
509     if (app == NULL) {
510         major = GSS_S_FAILURE;
511         goto cleanup;
512     }
513
514     try {
515         ctx = new eap_gss_saml_attr_ctx(buffer);
516
517         if (assertion->getIssuer() != NULL)
518             issuer = assertion->getIssuer()->getName();
519         if (assertion->getSubject() != NULL)
520             subjectName = assertion->getSubject()->getNameID();
521
522         m = app->getMetadataProvider();
523         xmltooling::Locker mlocker(m);
524         MetadataProviderCriteria mc(*app, issuer,
525                                     &IDPSSODescriptor::ELEMENT_QNAME,
526                                     samlconstants::SAML20P_NS);
527         pair<const EntityDescriptor *, const RoleDescriptor *> site =
528             m->getEntityDescriptor(mc);
529         if (!site.first) {
530             auto_ptr_char temp(issuer);
531             throw MetadataException("Unable to locate metadata for IdP ($1).",
532                                     params(1,temp.get()));
533         }
534         vector<const Assertion*> tokens(1, assertion);
535         GSSEAPResolver gssResolver(NULL, (const char *)nameBuf.value);
536         resolverContext = gssResolver.resolveAttributes(*app, site.second,
537                                                         samlconstants::SAML20P_NS,
538                                                         NULL, subjectName, NULL,
539                                                         NULL, &tokens);
540         ctx->setAttributes(resolverContext->getResolvedAttributes());
541     } catch (exception &ex) {
542         major = GSS_S_BAD_NAME;
543         goto cleanup;
544     }
545
546     major = GSS_S_COMPLETE;
547     *pCtx = ctx;
548
549 cleanup:
550     sp->unlock();
551     conf.term();
552
553     if (GSS_ERROR(major))
554         delete ctx;
555     gss_release_buffer(&tmpMinor, &nameBuf);
556
557     return major;
558 }
559
560 OM_uint32
561 samlGetAttributeTypes(OM_uint32 *minor,
562                       const struct eap_gss_saml_attr_ctx *ctx,
563                       void *data,
564                       OM_uint32 (*addAttribute)(OM_uint32 *, void *, gss_buffer_t))
565 {
566     OM_uint32 major = GSS_S_COMPLETE;
567
568     if (ctx == NULL)
569         return GSS_S_COMPLETE;
570
571     for (vector<Attribute*>::const_iterator a = ctx->getAttributes().begin();
572         a != ctx->getAttributes().end();
573         ++a)
574     {
575         gss_buffer_desc attribute;
576
577         attribute.value = (void *)((*a)->getId());
578         attribute.length = strlen((char *)attribute.value);
579
580         major = addAttribute(minor, data, &attribute);
581         if (GSS_ERROR(major))
582             break;
583     }
584
585     return major;
586 }
587
588 /*
589  * SAML implementation of gss_get_name_attribute
590  */
591 OM_uint32
592 samlGetAttribute(OM_uint32 *minor,
593                  struct eap_gss_saml_attr_ctx *ctx,
594                  gss_buffer_t attr,
595                  int *authenticated,
596                  int *complete,
597                  gss_buffer_t value,
598                  gss_buffer_t display_value,
599                  int *more)
600 {
601     if (ctx == NULL)
602         return GSS_S_UNAVAILABLE;
603
604     if (!ctx->getAttribute(attr, authenticated, complete,
605                            value, display_value, more))
606         return GSS_S_UNAVAILABLE;
607
608     return GSS_S_COMPLETE;
609 }
610
611 OM_uint32
612 samlSetAttribute(OM_uint32 *minor,
613                  struct eap_gss_saml_attr_ctx *ctx,
614                  int complete,
615                  gss_buffer_t attr,
616                  gss_buffer_t value)
617 {
618     try {
619         ctx->setAttribute(complete, attr, value);
620     } catch (exception &e) {
621         return GSS_S_FAILURE;
622     }
623
624     return GSS_S_COMPLETE;
625 }
626
627 OM_uint32
628 samlDeleteAttribute(OM_uint32 *minor,
629                     struct eap_gss_saml_attr_ctx *ctx,
630                     gss_buffer_t attr)
631 {
632     try {
633         ctx->deleteAttribute(attr);
634     } catch (exception &e) {
635         return GSS_S_FAILURE;
636     }
637
638     return GSS_S_COMPLETE;
639 }
640
641 /*
642  * In order to implement gss_export_name and gss_export_sec_context,
643  * we need to serialise a resolved attribute context to a buffer.
644  */
645 OM_uint32
646 samlExportAttrContext(OM_uint32 *minor,
647                       struct eap_gss_saml_attr_ctx *ctx,
648                       gss_buffer_t buffer)
649 {
650     try {
651         if (!ctx->marshall(buffer))
652             return GSS_S_FAILURE;
653     } catch (exception &e) {
654         return GSS_S_FAILURE;
655     }        
656
657     return GSS_S_COMPLETE;
658 }
659
660 /*
661  * In order to implement gss_import_name and gss_import_sec_context,
662  * we need to deserialise a resolved attribute context from a buffer.
663  */
664 OM_uint32
665 samlImportAttrContext(OM_uint32 *minor,
666                       gss_buffer_t buffer,
667                       struct eap_gss_saml_attr_ctx **pCtx)
668 {
669     try {
670         *pCtx = eap_gss_saml_attr_ctx::unmarshall(buffer);
671     } catch (exception &e) {
672         return GSS_S_FAILURE;
673     }
674
675     return GSS_S_COMPLETE;
676 }
677
678 OM_uint32
679 samlGetAssertion(OM_uint32 *minor,
680                  struct eap_gss_saml_attr_ctx *ctx,
681                  gss_buffer_t assertion)
682 {
683     try {
684         ctx->getAssertion(assertion);
685     } catch (exception &e) {
686         return GSS_S_FAILURE;
687     }
688
689     return GSS_S_COMPLETE;
690 }
691
692 OM_uint32
693 samlDuplicateAttrContext(OM_uint32 *minor,
694                          const struct eap_gss_saml_attr_ctx *in,
695                          struct eap_gss_saml_attr_ctx **out)
696 {
697     try {
698         *out = new eap_gss_saml_attr_ctx(*in);
699     } catch (exception &e) {
700         return GSS_S_FAILURE;
701     }
702
703     return GSS_S_COMPLETE;
704 }