Merge branch 'master' of ssh://moonshot.suchdamage.org:822/srv/git/moonshot
[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 /*
34  * SAML attribute provider implementation.
35  */
36
37 #include "gssapiP_eap.h"
38
39 #include <sstream>
40
41 #include <xercesc/util/XMLUniDefs.hpp>
42 #include <xmltooling/unicode.h>
43 #include <xmltooling/XMLToolingConfig.h>
44 #include <xmltooling/util/XMLHelper.h>
45 #include <xmltooling/util/ParserPool.h>
46 #include <xmltooling/util/DateTime.h>
47
48 #include <saml/saml1/core/Assertions.h>
49 #include <saml/saml2/core/Assertions.h>
50 #include <saml/saml2/metadata/Metadata.h>
51
52 using namespace xmltooling;
53 using namespace opensaml::saml2md;
54 using namespace opensaml;
55 using namespace xercesc;
56 using namespace std;
57
58 /*
59  * gss_eap_saml_assertion_provider is for retrieving the underlying
60  * assertion.
61  */
62 gss_eap_saml_assertion_provider::gss_eap_saml_assertion_provider(void)
63 {
64     m_assertion = NULL;
65     m_authenticated = false;
66 }
67
68 gss_eap_saml_assertion_provider::~gss_eap_saml_assertion_provider(void)
69 {
70     delete m_assertion;
71 }
72
73 bool
74 gss_eap_saml_assertion_provider::initFromExistingContext(const gss_eap_attr_ctx *manager,
75                                                          const gss_eap_attr_provider *ctx)
76 {
77     /* Then we may be creating from an existing attribute context */
78     const gss_eap_saml_assertion_provider *saml;
79
80     assert(m_assertion == NULL);
81
82     if (!gss_eap_attr_provider::initFromExistingContext(manager, ctx))
83         return false;
84
85     saml = static_cast<const gss_eap_saml_assertion_provider *>(ctx);
86     setAssertion(saml->getAssertion(), saml->authenticated());
87
88     return true;
89 }
90
91 bool
92 gss_eap_saml_assertion_provider::initFromGssContext(const gss_eap_attr_ctx *manager,
93                                                     const gss_cred_id_t gssCred,
94                                                     const gss_ctx_id_t gssCtx)
95 {
96     const gss_eap_radius_attr_provider *radius;
97     gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
98     int authenticated, complete;
99     OM_uint32 minor;
100
101     assert(m_assertion == NULL);
102
103     if (!gss_eap_attr_provider::initFromGssContext(manager, gssCred, gssCtx))
104         return false;
105
106     /*
107      * XXX TODO we need to support draft-howlett-radius-saml-attr-00
108      */
109     radius = static_cast<const gss_eap_radius_attr_provider *>
110         (m_manager->getProvider(ATTR_TYPE_RADIUS));
111     if (radius != NULL &&
112         radius->getFragmentedAttribute(PW_SAML_AAA_ASSERTION,
113                                        VENDORPEC_UKERNA,
114                                        &authenticated, &complete, &value)) {
115         setAssertion(&value, authenticated);
116         gss_release_buffer(&minor, &value);
117     } else {
118         m_assertion = NULL;
119     }
120
121     return true;
122 }
123
124 void
125 gss_eap_saml_assertion_provider::setAssertion(const saml2::Assertion *assertion,
126                                               bool authenticated)
127 {
128
129     delete m_assertion;
130
131     if (assertion != NULL) {
132 #ifdef __APPLE__
133         m_assertion = (saml2::Assertion *)((void *)assertion->clone());
134 #else
135         m_assertion = dynamic_cast<saml2::Assertion *>(assertion->clone());
136 #endif
137         m_authenticated = authenticated;
138     } else {
139         m_assertion = NULL;
140         m_authenticated = false;
141     }
142 }
143
144 void
145 gss_eap_saml_assertion_provider::setAssertion(const gss_buffer_t buffer,
146                                               bool authenticated)
147 {
148     delete m_assertion;
149
150     m_assertion = parseAssertion(buffer);
151     m_authenticated = (m_assertion != NULL && authenticated);
152 }
153
154 saml2::Assertion *
155 gss_eap_saml_assertion_provider::parseAssertion(const gss_buffer_t buffer)
156 {
157     string str((char *)buffer->value, buffer->length);
158     istringstream istream(str);
159     DOMDocument *doc;
160     const XMLObjectBuilder *b;
161
162     doc = XMLToolingConfig::getConfig().getParser().parse(istream);
163     if (doc == NULL)
164         return NULL;
165
166     b = XMLObjectBuilder::getBuilder(doc->getDocumentElement());
167
168 #ifdef __APPLE__
169     return (saml2::Assertion *)((void *)b->buildFromDocument(doc));
170 #else
171     return dynamic_cast<saml2::Assertion *>(b->buildFromDocument(doc));
172 #endif
173 }
174
175 bool
176 gss_eap_saml_assertion_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
177                                                    void *data) const
178 {
179     bool ret;
180
181     /* just add the prefix */
182     if (m_assertion != NULL)
183         ret = addAttribute(this, GSS_C_NO_BUFFER, data);
184     else
185         ret = true;
186
187     return ret;
188 }
189
190 bool
191 gss_eap_saml_assertion_provider::setAttribute(int complete,
192                                               const gss_buffer_t attr,
193                                               const gss_buffer_t value)
194 {
195     if (attr == GSS_C_NO_BUFFER || attr->length == 0) {
196         setAssertion(value);
197         return true;
198     }
199
200     return false;
201 }
202
203 bool
204 gss_eap_saml_assertion_provider::deleteAttribute(const gss_buffer_t value)
205 {
206     delete m_assertion;
207     m_assertion = NULL;
208     m_authenticated = false;
209
210     return true;
211 }
212
213 time_t
214 gss_eap_saml_assertion_provider::getExpiryTime(void) const
215 {
216     saml2::Conditions *conditions;
217     time_t expiryTime = 0;
218
219     if (m_assertion == NULL)
220         return 0;
221
222     conditions = m_assertion->getConditions();
223
224     if (conditions != NULL && conditions->getNotOnOrAfter() != NULL)
225         expiryTime = conditions->getNotOnOrAfter()->getEpoch();
226
227     return expiryTime;
228 }
229
230 bool
231 gss_eap_saml_assertion_provider::getAttribute(const gss_buffer_t attr,
232                                               int *authenticated,
233                                               int *complete,
234                                               gss_buffer_t value,
235                                               gss_buffer_t display_value,
236                                               int *more) const
237 {
238     string str;
239
240     if (attr != GSS_C_NO_BUFFER && attr->length != 0)
241         return false;
242
243     if (m_assertion == NULL)
244         return false;
245
246     if (*more != -1)
247         return false;
248
249     if (authenticated != NULL)
250         *authenticated = m_authenticated;
251     if (complete != NULL)
252         *complete = true;
253
254     XMLHelper::serialize(m_assertion->marshall((DOMDocument *)NULL), str);
255
256     duplicateBuffer(str, value);
257     *more = 0;
258
259     return true;
260 }
261
262 gss_any_t
263 gss_eap_saml_assertion_provider::mapToAny(int authenticated,
264                                           gss_buffer_t type_id) const
265 {
266     if (authenticated && !m_authenticated)
267         return (gss_any_t)NULL;
268
269     return (gss_any_t)m_assertion;
270 }
271
272 void
273 gss_eap_saml_assertion_provider::releaseAnyNameMapping(gss_buffer_t type_id,
274                                                        gss_any_t input) const
275 {
276     delete ((saml2::Assertion *)input);
277 }
278
279 void
280 gss_eap_saml_assertion_provider::exportToBuffer(gss_buffer_t buffer) const
281 {
282     ostringstream sink;
283     string str;
284
285     buffer->length = 0;
286     buffer->value = NULL;
287
288     if (m_assertion == NULL)
289         return;
290
291     sink << *m_assertion;
292     str = sink.str();
293
294     duplicateBuffer(str, buffer);
295 }
296
297 bool
298 gss_eap_saml_assertion_provider::initFromBuffer(const gss_eap_attr_ctx *ctx,
299                                                 const gss_buffer_t buffer)
300 {
301     if (!gss_eap_attr_provider::initFromBuffer(ctx, buffer))
302         return false;
303
304     if (buffer->length == 0)
305         return true;
306
307     assert(m_assertion == NULL);
308
309     setAssertion(buffer);
310     /* TODO XXX how to propagate authenticated flag? */
311
312     return true;
313 }
314
315 bool
316 gss_eap_saml_assertion_provider::init(void)
317 {
318     gss_eap_attr_ctx::registerProvider(ATTR_TYPE_SAML_ASSERTION,
319                                        "urn:ietf:params:gss-eap:saml-aaa-assertion",
320                                        gss_eap_saml_assertion_provider::createAttrContext);
321     return true;
322 }
323
324 void
325 gss_eap_saml_assertion_provider::finalize(void)
326 {
327     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_SAML_ASSERTION);
328 }
329
330 gss_eap_attr_provider *
331 gss_eap_saml_assertion_provider::createAttrContext(void)
332 {
333     return new gss_eap_saml_assertion_provider;
334 }
335
336 saml2::Assertion *
337 gss_eap_saml_assertion_provider::initAssertion(void)
338 {
339     delete m_assertion;
340     m_assertion = saml2::AssertionBuilder::buildAssertion();
341     m_authenticated = false;
342
343     return m_assertion;
344 }
345
346 /*
347  * gss_eap_saml_attr_provider is for retrieving the underlying attributes.
348  */
349 bool
350 gss_eap_saml_attr_provider::getAssertion(int *authenticated,
351                                          saml2::Assertion **pAssertion,
352                                          bool createIfAbsent) const
353 {
354     gss_eap_saml_assertion_provider *saml;
355
356     if (authenticated != NULL)
357         *authenticated = false;
358     if (pAssertion != NULL)
359         *pAssertion = NULL;
360
361     saml = static_cast<const gss_eap_saml_assertion_provider *>
362         (m_manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
363     if (saml == NULL)
364         return false;
365
366     if (authenticated != NULL)
367         *authenticated = saml->authenticated();
368     if (pAssertion != NULL)
369         *pAssertion = saml->getAssertion();
370
371     if (saml->getAssertion() == NULL) {
372         if (createIfAbsent) {
373             if (authenticated != NULL)
374                 *authenticated = false;
375             if (pAssertion != NULL)
376                 *pAssertion = saml->initAssertion();
377         } else
378             return false;
379     }
380
381     return true;
382 }
383
384 bool
385 gss_eap_saml_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
386                                               void *data) const
387 {
388     saml2::Assertion *assertion;
389     int authenticated;
390
391     if (!getAssertion(&authenticated, &assertion))
392         return true;
393
394     /*
395      * Note: the first prefix is added by the attribute provider manager
396      *
397      * From draft-hartman-gss-eap-naming-00:
398      *
399      *   Each attribute carried in the assertion SHOULD also be a GSS name
400      *   attribute.  The name of this attribute has three parts, all separated
401      *   by an ASCII space character.  The first part is
402      *   urn:ietf:params:gss-eap:saml-attr.  The second part is the URI for
403      *   the SAML attribute name format.  The final part is the name of the
404      *   SAML attribute.  If the mechanism performs an additional attribute
405      *   query, the retrieved attributes SHOULD be GSS-API name attributes
406      *   using the same name syntax.
407      */
408     /* For each attribute statement, look for an attribute match */
409     const vector <saml2::AttributeStatement *> &statements =
410         const_cast<const saml2::Assertion *>(assertion)->getAttributeStatements();
411
412     for (vector<saml2::AttributeStatement *>::const_iterator s = statements.begin();
413         s != statements.end();
414         ++s) {
415         const vector<saml2::Attribute*> &attrs =
416             const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
417
418         for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a != attrs.end(); ++a) {
419             const XMLCh *attributeName = (*a)->getName();
420             const XMLCh *attributeNameFormat = (*a)->getNameFormat();
421             XMLCh *qualifiedName;
422             XMLCh space[2] = { ' ', 0 };
423             gss_buffer_desc utf8;
424             bool ret;
425
426             qualifiedName = new XMLCh[XMLString::stringLen(attributeNameFormat) + 1 +
427                                       XMLString::stringLen(attributeName) + 1];
428             XMLString::copyString(qualifiedName, attributeNameFormat);
429             XMLString::catString(qualifiedName, space);
430             XMLString::catString(qualifiedName, attributeName);
431
432             utf8.value = (void *)toUTF8(qualifiedName);
433             utf8.length = strlen((char *)utf8.value);
434
435             ret = addAttribute(this, &utf8, data);
436
437             delete qualifiedName;
438
439             if (!ret)
440                 return ret;
441         }
442     }
443
444     return true;
445 }
446
447 static BaseRefVectorOf<XMLCh> *
448 decomposeAttributeName(const gss_buffer_t attr)
449 {
450     XMLCh *qualifiedAttr = new XMLCh[attr->length + 1];
451     XMLString::transcode((const char *)attr->value, qualifiedAttr, attr->length);
452
453     BaseRefVectorOf<XMLCh> *components = XMLString::tokenizeString(qualifiedAttr);
454
455     delete qualifiedAttr;
456
457     if (components->size() != 2) {
458         delete components;
459         components = NULL;
460     }
461
462     return components;
463 }
464
465 bool
466 gss_eap_saml_attr_provider::setAttribute(int complete,
467                                          const gss_buffer_t attr,
468                                          const gss_buffer_t value)
469 {
470     saml2::Assertion *assertion;
471     saml2::Attribute *attribute;
472     saml2::AttributeValue *attributeValue;
473     saml2::AttributeStatement *attributeStatement;
474
475     if (!getAssertion(NULL, &assertion, true))
476         return false;
477
478     if (assertion->getAttributeStatements().size() != 0) {
479         attributeStatement = assertion->getAttributeStatements().front();
480     } else {
481         attributeStatement = saml2::AttributeStatementBuilder::buildAttributeStatement();
482         assertion->getAttributeStatements().push_back(attributeStatement);
483     }
484
485     /* Check the attribute name consists of name format | whsp | name */
486     BaseRefVectorOf<XMLCh> *components = decomposeAttributeName(attr);
487     if (components == NULL)
488         return false;
489
490     attribute = saml2::AttributeBuilder::buildAttribute();
491     attribute->setNameFormat(components->elementAt(0));
492     attribute->setName(components->elementAt(1));
493
494     XMLCh *xmlValue = new XMLCh[value->length + 1];
495     XMLString::transcode((const char *)value->value, xmlValue, attr->length);
496
497     attributeValue = saml2::AttributeValueBuilder::buildAttributeValue();
498     attributeValue->setTextContent(xmlValue);
499
500     attribute->getAttributeValues().push_back(attributeValue);
501
502     assert(attributeStatement != NULL);
503     attributeStatement->getAttributes().push_back(attribute);
504
505     delete components;
506     delete xmlValue;
507
508     return true;
509 }
510
511 bool
512 gss_eap_saml_attr_provider::deleteAttribute(const gss_buffer_t attr)
513 {
514     saml2::Assertion *assertion;
515     bool ret = false;
516
517     if (!getAssertion(NULL, &assertion) ||
518         assertion->getAttributeStatements().size() == 0)
519         return false;
520
521     /* Check the attribute name consists of name format | whsp | name */
522     BaseRefVectorOf<XMLCh> *components = decomposeAttributeName(attr);
523     if (components == NULL)
524         return false;
525
526     /* For each attribute statement, look for an attribute match */
527     const vector<saml2::AttributeStatement *> &statements =
528         const_cast<const saml2::Assertion *>(assertion)->getAttributeStatements();
529
530     for (vector<saml2::AttributeStatement *>::const_iterator s = statements.begin();
531         s != statements.end();
532         ++s) {
533         const vector<saml2::Attribute *> &attrs =
534             const_cast<const saml2::AttributeStatement *>(*s)->getAttributes();
535         ssize_t index = -1, i = 0;
536
537         /* There's got to be an easier way to do this */
538         for (vector<saml2::Attribute *>::const_iterator a = attrs.begin();
539              a != attrs.end();
540              ++a) {
541             if (XMLString::equals((*a)->getNameFormat(), components->elementAt(0)) &&
542                 XMLString::equals((*a)->getName(), components->elementAt(1))) {
543                 index = i;
544                 break;
545             }
546             ++i;
547         }
548         if (index != -1) {
549             (*s)->getAttributes().erase((*s)->getAttributes().begin() + index);
550             ret = true;
551         }
552     }
553
554     delete components;
555
556     return ret;
557 }
558
559 bool
560 gss_eap_saml_attr_provider::getAttribute(const gss_buffer_t attr,
561                                          int *authenticated,
562                                          int *complete,
563                                          const saml2::Attribute **pAttribute) const
564 {
565     saml2::Assertion *assertion;
566
567     if (authenticated != NULL)
568         *authenticated = false;
569     if (complete != NULL)
570         *complete = true;
571     *pAttribute = NULL;
572
573     if (!getAssertion(authenticated, &assertion) ||
574         assertion->getAttributeStatements().size() == 0)
575         return false;
576
577     /* Check the attribute name consists of name format | whsp | name */
578     BaseRefVectorOf<XMLCh> *components = decomposeAttributeName(attr);
579     if (components == NULL)
580         return false;
581
582     /* For each attribute statement, look for an attribute match */
583     const vector <saml2::AttributeStatement *> &statements =
584         const_cast<const saml2::Assertion *>(assertion)->getAttributeStatements();
585     const saml2::Attribute *ret = NULL;
586
587     for (vector<saml2::AttributeStatement *>::const_iterator s = statements.begin();
588         s != statements.end();
589         ++s) {
590         const vector<saml2::Attribute *> &attrs =
591             const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
592
593         for (vector<saml2::Attribute *>::const_iterator a = attrs.begin(); a != attrs.end(); ++a) {
594             if (XMLString::equals((*a)->getNameFormat(), components->elementAt(0)) &&
595                 XMLString::equals((*a)->getName(), components->elementAt(1))) {
596                 ret = *a;
597                 break;
598             }
599         }
600
601         if (ret != NULL)
602             break;
603     }
604
605     delete components;
606
607     *pAttribute = ret;
608
609     return (ret != NULL);
610 }
611
612 bool
613 gss_eap_saml_attr_provider::getAttribute(const gss_buffer_t attr,
614                                          int *authenticated,
615                                          int *complete,
616                                          gss_buffer_t value,
617                                          gss_buffer_t display_value,
618                                          int *more) const
619 {
620     const saml2::Attribute *a;
621     const saml2::AttributeValue *av;
622     int nvalues, i = *more;
623
624     *more = 0;
625
626     if (!getAttribute(attr, authenticated, complete, &a))
627         return false;
628
629     nvalues = a->getAttributeValues().size();
630
631     if (i == -1)
632         i = 0;
633     else if (i >= nvalues)
634         return false;
635 #ifdef __APPLE__
636     av = (const saml2::AttributeValue *)((void *)(a->getAttributeValues().at(i)));
637 #else
638     av = dynamic_cast<const saml2::AttributeValue *>(a->getAttributeValues().at(i));
639 #endif
640     if (av != NULL) {
641         if (value != NULL) {
642             value->value = toUTF8(av->getTextContent(), true);
643             value->length = strlen((char *)value->value);
644         }
645         if (display_value != NULL) {
646             display_value->value = toUTF8(av->getTextContent(), true);
647             display_value->length = strlen((char *)value->value);
648         }
649     }
650
651     if (nvalues > ++i)
652         *more = i;
653
654     return true;
655 }
656
657 gss_any_t
658 gss_eap_saml_attr_provider::mapToAny(int authenticated,
659                                      gss_buffer_t type_id) const
660 {
661     return (gss_any_t)NULL;
662 }
663
664 void
665 gss_eap_saml_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id,
666                                                   gss_any_t input) const
667 {
668 }
669
670 void
671 gss_eap_saml_attr_provider::exportToBuffer(gss_buffer_t buffer) const
672 {
673     buffer->length = 0;
674     buffer->value = NULL;
675 }
676
677 bool
678 gss_eap_saml_attr_provider::initFromBuffer(const gss_eap_attr_ctx *ctx,
679                                            const gss_buffer_t buffer)
680 {
681     return gss_eap_attr_provider::initFromBuffer(ctx, buffer);
682 }
683
684 bool
685 gss_eap_saml_attr_provider::init(void)
686 {
687     gss_eap_attr_ctx::registerProvider(ATTR_TYPE_SAML,
688                                        "urn:ietf:params:gss-eap:saml-attr",
689                                        gss_eap_saml_attr_provider::createAttrContext);
690     return true;
691 }
692
693 void
694 gss_eap_saml_attr_provider::finalize(void)
695 {
696     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_SAML);
697 }
698
699 gss_eap_attr_provider *
700 gss_eap_saml_attr_provider::createAttrContext(void)
701 {
702     return new gss_eap_saml_attr_provider;
703 }
704
705 OM_uint32
706 gssEapSamlAttrProvidersInit(OM_uint32 *minor)
707 {
708     if (!gss_eap_saml_assertion_provider::init() ||
709         !gss_eap_saml_attr_provider::init()) {
710         *minor = GSSEAP_SAML_INIT_FAILURE;
711         return GSS_S_FAILURE;
712     }
713
714     return GSS_S_COMPLETE;
715 }
716
717 OM_uint32
718 gssEapSamlAttrProvidersFinalize(OM_uint32 *minor)
719 {
720     gss_eap_saml_attr_provider::finalize();
721     gss_eap_saml_assertion_provider::finalize();
722     return GSS_S_COMPLETE;
723 }