cleanup and plugin attr context creation
[cyrus-sasl.git] / mech_eap / 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 #include "gssapiP_eap.h"
34
35 #include <sstream>
36
37 #include <xercesc/util/XMLUniDefs.hpp>
38 #include <xmltooling/XMLToolingConfig.h>
39 #include <xmltooling/util/XMLHelper.h>
40
41 #include <saml/saml1/core/Assertions.h>
42 #include <saml/saml2/core/Assertions.h>
43 #include <saml/saml2/metadata/Metadata.h>
44
45 using namespace xmltooling;
46 using namespace opensaml::saml2md;
47 using namespace opensaml;
48 using namespace xercesc;
49 using namespace std;
50
51 /*
52  * gss_eap_saml_assertion_provider is for retrieving the underlying
53  * assertion.
54  */
55 gss_eap_saml_assertion_provider::gss_eap_saml_assertion_provider(void)
56 {
57     m_assertion = NULL;
58     m_authenticated = false;
59 }
60
61 gss_eap_saml_assertion_provider::~gss_eap_saml_assertion_provider(void)
62 {
63     delete m_assertion;
64 }
65
66 bool
67 gss_eap_saml_assertion_provider::initFromExistingContext(const gss_eap_attr_ctx *manager,
68                                                          const gss_eap_attr_provider *ctx)
69 {
70     /* Then we may be creating from an existing attribute context */
71     const gss_eap_saml_assertion_provider *saml;
72
73     assert(m_assertion == NULL);
74
75     if (!gss_eap_attr_provider::initFromExistingContext(manager, ctx))
76         return false;
77
78     saml = static_cast<const gss_eap_saml_assertion_provider *>(ctx);
79     setAssertion(saml->getAssertion(), saml->authenticated());
80
81     return true;
82 }
83
84 bool
85 gss_eap_saml_assertion_provider::initFromGssContext(const gss_eap_attr_ctx *manager,
86                                                     const gss_cred_id_t gssCred,
87                                                     const gss_ctx_id_t gssCtx)
88 {
89     const gss_eap_radius_attr_provider *radius;
90     gss_buffer_desc value = GSS_C_EMPTY_BUFFER;
91     int authenticated, complete, more = -1;
92     OM_uint32 minor;
93
94     assert(m_assertion == NULL);
95
96     if (!gss_eap_attr_provider::initFromGssContext(manager, gssCred, gssCtx))
97         return false;
98
99     radius = static_cast<const gss_eap_radius_attr_provider *>
100         (m_manager->getProvider(ATTR_TYPE_RADIUS));
101     if (radius != NULL &&
102         radius->getAttribute(PW_SAML_ASSERTION, &authenticated, &complete,
103                              &value, NULL, &more)) {
104         setAssertion(&value, authenticated);
105         gss_release_buffer(&minor, &value);
106     } else {
107         m_assertion = NULL;
108     }
109
110     return true;
111 }
112
113 void
114 gss_eap_saml_assertion_provider::setAssertion(const saml2::Assertion *assertion,
115                                               bool authenticated)
116 {
117
118     delete m_assertion;
119
120     if (assertion != NULL) {
121         m_assertion = dynamic_cast<saml2::Assertion *>(assertion->clone());
122         m_authenticated = authenticated;
123     } else {
124         m_assertion = NULL;
125         m_authenticated = false;
126     }
127 }
128
129 void
130 gss_eap_saml_assertion_provider::setAssertion(const gss_buffer_t buffer,
131                                               bool authenticated)
132 {
133     delete m_assertion;
134
135     m_assertion = parseAssertion(buffer);
136     m_authenticated = (m_assertion != NULL && authenticated);
137 }
138
139 saml2::Assertion *
140 gss_eap_saml_assertion_provider::parseAssertion(const gss_buffer_t buffer)
141 {
142     string str((char *)buffer->value, buffer->length);
143     istringstream istream(str);
144     DOMDocument *doc;
145     const XMLObjectBuilder *b;
146
147     doc = XMLToolingConfig::getConfig().getParser().parse(istream);
148     b = XMLObjectBuilder::getBuilder(doc->getDocumentElement());
149
150     return dynamic_cast<saml2::Assertion *>(b->buildFromDocument(doc));
151 }
152
153 bool
154 gss_eap_saml_assertion_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
155                                                    void *data) const
156 {
157     /* just add the prefix */
158     return addAttribute(this, GSS_C_NO_BUFFER, data);
159 }
160
161 void
162 gss_eap_saml_assertion_provider::setAttribute(int complete,
163                                               const gss_buffer_t attr,
164                                               const gss_buffer_t value)
165 {
166     if (attr == GSS_C_NO_BUFFER || attr->length == 0) {
167         setAssertion(value);
168     }
169 }
170
171 void
172 gss_eap_saml_assertion_provider::deleteAttribute(const gss_buffer_t value)
173 {
174     delete m_assertion;
175     m_assertion = NULL;
176     m_authenticated = false;
177 }
178
179 time_t
180 gss_eap_saml_assertion_provider::getExpiryTime(void) const
181 {
182     saml2::Conditions *conditions;
183     time_t expiryTime = 0;
184
185     if (m_assertion == NULL)
186         return 0;
187
188     conditions = m_assertion->getConditions();
189
190     if (conditions != NULL && conditions->getNotOnOrAfter() != NULL)
191         expiryTime = conditions->getNotOnOrAfter()->getEpoch();
192
193     return expiryTime;
194 }
195
196 bool
197 gss_eap_saml_assertion_provider::getAttribute(const gss_buffer_t attr,
198                                               int *authenticated,
199                                               int *complete,
200                                               gss_buffer_t value,
201                                               gss_buffer_t display_value,
202                                               int *more) const
203 {
204     string str;
205
206     if (attr != GSS_C_NO_BUFFER || attr->length != 0)
207         return false;
208
209     if (m_assertion == NULL)
210         return false;
211
212     if (*more != -1)
213         return false;
214
215     if (authenticated != NULL)
216         *authenticated = m_authenticated;
217     if (complete != NULL)
218         *complete = true;
219
220     XMLHelper::serialize(m_assertion->marshall((DOMDocument *)NULL), str);
221
222     duplicateBuffer(str, value);
223     *more = 0;
224
225     return true;
226 }
227
228 gss_any_t
229 gss_eap_saml_assertion_provider::mapToAny(int authenticated,
230                                           gss_buffer_t type_id) const
231 {
232     return (gss_any_t)m_assertion;
233 }
234
235 void
236 gss_eap_saml_assertion_provider::releaseAnyNameMapping(gss_buffer_t type_id,
237                                                        gss_any_t input) const
238 {
239     delete ((saml2::Assertion *)input);
240 }
241
242 void
243 gss_eap_saml_assertion_provider::exportToBuffer(gss_buffer_t buffer) const
244 {
245     ostringstream sink;
246     string str;
247
248     buffer->length = 0;
249     buffer->value = NULL;
250
251     if (m_assertion == NULL)
252         return;
253
254     sink << *m_assertion;
255     str = sink.str();
256
257     duplicateBuffer(str, buffer);
258 }
259
260 bool
261 gss_eap_saml_assertion_provider::initFromBuffer(const gss_eap_attr_ctx *ctx,
262                                                 const gss_buffer_t buffer)
263 {
264     if (!gss_eap_attr_provider::initFromBuffer(ctx, buffer))
265         return false;
266
267     if (buffer->length == 0)
268         return true;
269
270     assert(m_assertion == NULL);
271
272     setAssertion(buffer);
273     /* TODO XXX how to propagate authenticated flag? */
274
275     return true;
276 }
277
278 bool
279 gss_eap_saml_assertion_provider::init(void)
280 {
281     gss_eap_attr_ctx::registerProvider(ATTR_TYPE_SAML_ASSERTION,
282                                        "urn:ietf:params:gss-eap:saml-aaa-assertion",
283                                        gss_eap_saml_assertion_provider::createAttrContext);
284     return true;
285 }
286
287 void
288 gss_eap_saml_assertion_provider::finalize(void)
289 {
290     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_SAML_ASSERTION);
291 }
292
293 gss_eap_attr_provider *
294 gss_eap_saml_assertion_provider::createAttrContext(void)
295 {
296     return new gss_eap_saml_assertion_provider;
297 }
298
299 /*
300  * gss_eap_saml_attr_provider is for retrieving the underlying attributes.
301  */
302 bool
303 gss_eap_saml_attr_provider::getAssertion(int *authenticated,
304                                          const saml2::Assertion **pAssertion) const
305 {
306     const gss_eap_saml_assertion_provider *saml;
307
308     if (authenticated != NULL)
309         *authenticated = false;
310     if (pAssertion != NULL)
311         *pAssertion = NULL;
312
313     saml = static_cast<const gss_eap_saml_assertion_provider *>
314         (m_manager->getProvider(ATTR_TYPE_SAML_ASSERTION));
315     if (saml == NULL)
316         return false;
317
318     if (authenticated != NULL)
319         *authenticated = saml->authenticated();
320     if (pAssertion != NULL)
321         *pAssertion = saml->getAssertion();
322
323     return (saml->getAssertion() != NULL);
324 }
325
326 bool
327 gss_eap_saml_attr_provider::getAttributeTypes(gss_eap_attr_enumeration_cb addAttribute,
328                                               void *data) const
329 {
330     const saml2::Assertion *assertion;
331     bool ret = true;
332     int authenticated;
333
334     if (!getAssertion(&authenticated, &assertion))
335         return true;
336
337     /*
338      * Note: the first prefix is added by the attribute provider manager
339      *
340      * From draft-hartman-gss-eap-naming-00:
341      *
342      *   Each attribute carried in the assertion SHOULD also be a GSS name
343      *   attribute.  The name of this attribute has three parts, all separated
344      *   by an ASCII space character.  The first part is
345      *   urn:ietf:params:gss-eap:saml-attr.  The second part is the URI for
346      *   the SAML attribute name format.  The final part is the name of the
347      *   SAML attribute.  If the mechanism performs an additional attribute
348      *   query, the retrieved attributes SHOULD be GSS-API name attributes
349      *   using the same name syntax.
350      */
351     const vector<saml2::Attribute*>& attrs2 =
352         const_cast<const saml2::AttributeStatement*>(assertion->getAttributeStatements().front())->getAttributes();
353     for (vector<saml2::Attribute*>::const_iterator a = attrs2.begin();
354         a != attrs2.end();
355         ++a)
356     {
357         const XMLCh *attributeName = (*a)->getName();
358         const XMLCh *attributeNameFormat = (*a)->getNameFormat();
359         XMLCh *qualifiedName;
360         XMLCh space[2] = { ' ', 0 };
361         gss_buffer_desc utf8;
362
363         qualifiedName = new XMLCh[XMLString::stringLen(attributeName) + 1 +
364                                   XMLString::stringLen(attributeNameFormat) + 1];
365         XMLString::copyString(qualifiedName, attributeName);
366         XMLString::catString(qualifiedName, space);
367         XMLString::catString(qualifiedName, attributeNameFormat);
368
369         utf8.value = (void *)toUTF8(qualifiedName);
370         utf8.length = strlen((char *)utf8.value);
371
372         ret = addAttribute(this, &utf8, data);
373
374         delete qualifiedName;
375
376         if (!ret)
377             break;
378     }
379
380     return ret;
381 }
382
383 void
384 gss_eap_saml_attr_provider::setAttribute(int complete,
385                                          const gss_buffer_t attr,
386                                          const gss_buffer_t value)
387 {
388 }
389
390 void
391 gss_eap_saml_attr_provider::deleteAttribute(const gss_buffer_t value)
392 {
393 }
394
395 static BaseRefVectorOf<XMLCh> *
396 decomposeAttributeName(const gss_buffer_t attr)
397 {
398     XMLCh *qualifiedAttr = new XMLCh[attr->length + 1];
399     XMLString::transcode((const char *)attr->value, qualifiedAttr, attr->length);
400
401     BaseRefVectorOf<XMLCh> *components = XMLString::tokenizeString(qualifiedAttr);
402
403     delete qualifiedAttr;
404
405     return components;
406 }
407
408 bool
409 gss_eap_saml_attr_provider::getAttribute(const gss_buffer_t attr,
410                                          int *authenticated,
411                                          int *complete,
412                                          const saml2::Attribute **pAttribute) const
413 {
414     const saml2::Assertion *assertion;
415
416     if (authenticated != NULL)
417         *authenticated = false;
418     if (complete != NULL)
419         *complete = true;
420     *pAttribute = NULL;
421
422     if (!getAssertion(authenticated, &assertion) ||
423         assertion->getAttributeStatements().size() == 0)
424         return false;
425
426     /* Check the attribute name consists of name format | whsp | name */
427     BaseRefVectorOf<XMLCh> *components = decomposeAttributeName(attr);
428     if (components == NULL || components->size() != 2) {
429         delete components;
430         return false;
431     }
432
433     /* For each attribute statement, look for an attribute match */
434     const vector <saml2::AttributeStatement *>&statements =
435         assertion->getAttributeStatements();
436     const saml2::Attribute *ret = NULL;
437
438     for (vector<saml2::AttributeStatement *>::const_iterator s = statements.begin();
439         s != statements.end();
440         ++s) {
441         const vector<saml2::Attribute*>& attrs =
442             const_cast<const saml2::AttributeStatement*>(*s)->getAttributes();
443
444         for (vector<saml2::Attribute*>::const_iterator a = attrs.begin(); a != attrs.end(); ++a) {
445             if (XMLString::equals((*a)->getNameFormat(), components->elementAt(0)) &&
446                 XMLString::equals((*a)->getName(), components->elementAt(1))) {
447                 ret = *a;
448                 break;
449             }
450         }
451
452         if (ret != NULL)
453             break;
454     }
455
456     delete components;
457
458     *pAttribute = ret;
459
460     return (ret != NULL);
461 }
462
463 bool
464 gss_eap_saml_attr_provider::getAttribute(const gss_buffer_t attr,
465                                          int *authenticated,
466                                          int *complete,
467                                          gss_buffer_t value,
468                                          gss_buffer_t display_value,
469                                          int *more) const
470 {
471     const saml2::Attribute *a;
472     const saml2::AttributeValue *av;
473     int nvalues, i = *more;
474
475     *more = 0;
476
477     if (!getAttribute(attr, authenticated, complete, &a))
478         return false;
479
480     nvalues = a->getAttributeValues().size();
481
482     if (i == -1)
483         i = 0;
484     else if (i >= nvalues)
485         return false;
486     av = dynamic_cast<const saml2::AttributeValue *>(a->getAttributeValues().at(i)
487 );
488     if (av != NULL) {
489         if (value != NULL) {
490             value->value = toUTF8(av->getTextContent(), true);
491             value->length = strlen((char *)value->value);
492         }
493         if (display_value != NULL) {
494             display_value->value = toUTF8(av->getTextContent(), true);
495             display_value->length = strlen((char *)value->value);
496         }
497     }
498
499     if (nvalues > ++i)
500         *more = i;
501
502     return true;
503 }
504
505 gss_any_t
506 gss_eap_saml_attr_provider::mapToAny(int authenticated,
507                                      gss_buffer_t type_id) const
508 {
509     return (gss_any_t)NULL;
510 }
511
512 void
513 gss_eap_saml_attr_provider::releaseAnyNameMapping(gss_buffer_t type_id,
514                                                   gss_any_t input) const
515 {
516 }
517
518 void
519 gss_eap_saml_attr_provider::exportToBuffer(gss_buffer_t buffer) const
520 {
521     buffer->length = 0;
522     buffer->value = NULL;
523 }
524
525 bool
526 gss_eap_saml_attr_provider::initFromBuffer(const gss_eap_attr_ctx *ctx,
527                                            const gss_buffer_t buffer)
528 {
529     return gss_eap_attr_provider::initFromBuffer(ctx, buffer);
530 }
531
532 bool
533 gss_eap_saml_attr_provider::init(void)
534 {
535     gss_eap_attr_ctx::registerProvider(ATTR_TYPE_SAML,
536                                        "urn:ietf:params:gss-eap:saml-attr",
537                                        gss_eap_saml_attr_provider::createAttrContext);
538     return true;
539 }
540
541 void
542 gss_eap_saml_attr_provider::finalize(void)
543 {
544     gss_eap_attr_ctx::unregisterProvider(ATTR_TYPE_SAML);
545 }
546
547 gss_eap_attr_provider *
548 gss_eap_saml_attr_provider::createAttrContext(void)
549 {
550     return new gss_eap_saml_attr_provider;
551 }