68bc3beba6352b6357d149feef3fdf263b1b99ad
[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/resolver/ResolutionContext.h>
58 #include <shibsp/handler/AssertionConsumerService.h>
59 #include <shibsp/metadata/MetadataProviderCriteria.h>
60 #include <shibsp/util/SPConstants.h>
61
62 #include <saml/saml1/core/Assertions.h>
63 #include <saml/saml2/core/Assertions.h>
64 #include <saml/saml2/metadata/Metadata.h>
65 #include <xercesc/util/XMLUniDefs.hpp>
66 #include <xmltooling/XMLToolingConfig.h>
67 #include <xmltooling/util/XMLHelper.h>
68
69 using namespace shibsp;
70 using namespace opensaml::saml2md;
71 using namespace opensaml;
72 using namespace xmltooling::logging;
73 using namespace xmltooling;
74 using namespace xercesc;
75 using namespace std;
76
77 class GSSEAPResolver : public shibsp::AssertionConsumerService
78 {
79 public:
80     GSSEAPResolver(const DOMElement *e, const char *appId)
81         : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".GSSEAPResolver")) {
82     }
83     virtual ~GSSEAPResolver() {}
84
85     ResolutionContext* resolveAttributes (
86         const Application& application,
87         const RoleDescriptor* issuer,
88         const XMLCh* protocol,
89         const saml1::NameIdentifier* v1nameid,
90         const saml2::NameID* nameid,
91         const XMLCh* authncontext_class,
92         const XMLCh* authncontext_decl,
93         const vector<const Assertion*>* tokens
94         ) const {
95             return shibsp::AssertionConsumerService::resolveAttributes(
96                     application, issuer, protocol, v1nameid,
97                     nameid, authncontext_class, authncontext_decl, tokens
98             );
99     }
100
101 private:
102     void implementProtocol(
103         const Application& application,
104         const HTTPRequest& httpRequest,
105         HTTPResponse& httpResponse,
106         SecurityPolicy& policy,
107         const PropertySet* settings,
108         const XMLObject& xmlObject
109         ) const {
110             throw FatalProfileException("Should never be called.");
111     }
112 };
113
114 class SHIBSP_DLLLOCAL DummyContext : public ResolutionContext
115 {
116 public:
117     DummyContext(const vector<Attribute*>& attributes) : m_attributes(attributes) {
118     }
119
120     virtual ~DummyContext() {
121         for_each(m_attributes.begin(), m_attributes.end(), xmltooling::cleanup<Attribute>());
122     }
123
124     vector<Attribute*>& getResolvedAttributes() {
125         return m_attributes;
126     }
127     vector<Assertion*>& getResolvedAssertions() {
128         return m_tokens;
129     }
130
131 private:
132     vector<Attribute*> m_attributes;
133     static vector<Assertion*> m_tokens; // never any tokens, so just share an empty vector
134 };
135
136 struct eap_gss_saml_attr_ctx {
137     ResolutionContext *resCtx;
138 };
139
140 static OM_uint32
141 samlAllocAttrContext(OM_uint32 *minor,
142                      struct eap_gss_saml_attr_ctx **pCtx)
143 {
144     struct eap_gss_saml_attr_ctx *ctx;
145
146     ctx = (struct eap_gss_saml_attr_ctx *)GSSEAP_CALLOC(1, sizeof(*ctx));
147     if (ctx == NULL) {
148         *minor = ENOMEM;
149         return GSS_S_FAILURE;
150     }
151
152     *pCtx = ctx;
153     *minor = 0;
154     return GSS_S_COMPLETE;
155 }
156
157 static OM_uint32
158 samlImportAssertion(OM_uint32 *minor,
159                     gss_buffer_t buffer,
160                     saml2::Assertion **pAssertion)
161 {
162     *pAssertion = NULL;
163
164     try {
165         DOMDocument *doc;
166         const XMLObjectBuilder *b;
167         DOMElement *elem;
168         XMLObject *xobj;
169         string samlBuf((char *)buffer->value, buffer->length);
170         istringstream samlIn(samlBuf);
171
172         doc = XMLToolingConfig::getConfig().getParser().parse(samlIn);
173         b = XMLObjectBuilder::getDefaultBuilder();
174         elem = doc->getDocumentElement();
175         xobj = b->buildOneFromElement(elem, true);
176
177         *pAssertion = dynamic_cast<saml2::Assertion *>(xobj);
178         if (*pAssertion == NULL) {
179             /* TODO minor_status */
180             return GSS_S_BAD_NAME;
181         }
182     } catch (exception &e){
183         /* TODO minor_status */
184         return GSS_S_BAD_NAME;
185     }
186
187     *minor = 0;
188     return GSS_S_COMPLETE;
189 }
190
191 OM_uint32
192 samlDuplicateAttrContext(OM_uint32 *minor,
193                          const struct eap_gss_saml_attr_ctx *in,
194                          struct eap_gss_saml_attr_ctx **out)
195 {
196     OM_uint32 major, tmpMinor;
197     struct eap_gss_saml_attr_ctx *ctx;
198
199     major = samlAllocAttrContext(minor, &ctx);
200     if (GSS_ERROR(major))
201         goto cleanup;
202
203     ctx->resCtx = new DummyContext(in->resCtx->getResolvedAttributes());
204
205 cleanup:
206     if (GSS_ERROR(major))
207         samlReleaseAttrContext(&tmpMinor, &ctx);
208
209     return major;
210 }
211
212 OM_uint32
213 samlReleaseAttrContext(OM_uint32 *minor,
214                        struct eap_gss_saml_attr_ctx **pCtx)
215 {
216     struct eap_gss_saml_attr_ctx *ctx = *pCtx;
217
218     if (ctx != NULL) {
219         delete ctx->resCtx;
220         GSSEAP_FREE(ctx);
221         *pCtx = NULL;
222     }
223
224     *minor = 0;
225     return GSS_S_COMPLETE;
226 }
227
228 OM_uint32
229 samlCreateAttrContext(OM_uint32 *minor,
230                       gss_buffer_t buffer,
231                       gss_name_t acceptorName,
232                       struct eap_gss_saml_attr_ctx **pCtx)
233 {
234     OM_uint32 major, tmpMinor;
235     struct eap_gss_saml_attr_ctx *ctx;
236     SPConfig &conf = SPConfig::getConfig();
237     ServiceProvider *sp;
238     const Application *app;
239     MetadataProvider *m;
240     gss_buffer_desc nameBuf;
241     const XMLCh *issuer = NULL;
242     saml2::NameID *subjectName = NULL;
243     saml2::Assertion *assertion;
244
245     nameBuf.length = 0;
246     nameBuf.value = NULL;
247
248     conf.setFeatures(SPConfig::Metadata             |
249                      SPConfig::Trust                |
250                      SPConfig::AttributeResolution  |
251                      SPConfig::Credentials          |
252                      SPConfig::OutOfProcess);
253     if (!conf.init())
254         return GSS_S_FAILURE;
255     if (!conf.instantiate())
256         return GSS_S_FAILURE;
257
258     sp = conf.getServiceProvider();
259     sp->lock();
260
261     major = gss_display_name(minor, acceptorName, &nameBuf, NULL);
262     if (GSS_ERROR(major))
263         goto cleanup;
264
265     app = sp->getApplication((const char *)nameBuf.value);
266     if (app == NULL) {
267         major = GSS_S_FAILURE;
268         goto cleanup;
269     }
270
271     major = samlAllocAttrContext(minor, &ctx);
272     if (GSS_ERROR(major))
273         goto cleanup;
274
275     major = samlImportAssertion(minor, buffer, &assertion);
276     if (GSS_ERROR(major))
277         goto cleanup;
278
279     if (assertion->getIssuer() != NULL)
280         issuer = assertion->getIssuer()->getName();
281     if (assertion->getSubject() != NULL)
282         subjectName = assertion->getSubject()->getNameID();
283
284     try {
285         m = app->getMetadataProvider();
286         xmltooling::Locker mlocker(m);
287         MetadataProviderCriteria mc(*app, issuer,
288                                     &IDPSSODescriptor::ELEMENT_QNAME,
289                                     samlconstants::SAML20P_NS);
290         pair<const EntityDescriptor *, const RoleDescriptor *> site =
291             m->getEntityDescriptor(mc);
292         if (!site.first) {
293             auto_ptr_char temp(issuer);
294             throw MetadataException("Unable to locate metadata for IdP ($1).",
295                                     params(1,temp.get()));
296         }
297         vector<const Assertion*> tokens(1, assertion);
298         GSSEAPResolver gssResolver(NULL, (const char *)nameBuf.value);
299         ctx->resCtx = gssResolver.resolveAttributes(*app, site.second,
300                                                     samlconstants::SAML20P_NS,
301                                                     NULL, subjectName, NULL,
302                                                     NULL, &tokens);
303     } catch (exception &ex) {
304         major = GSS_S_BAD_NAME;
305         goto cleanup;
306     }
307
308     major = GSS_S_COMPLETE;
309     *pCtx = ctx;
310
311 cleanup:
312     sp->unlock();
313     conf.term();
314
315     if (GSS_ERROR(major))
316         samlReleaseAttrContext(&tmpMinor, &ctx);
317     gss_release_buffer(&tmpMinor, &nameBuf);
318
319     return major;
320 }
321
322 OM_uint32
323 samlGetAttributeTypes(OM_uint32 *minor,
324                       const struct eap_gss_saml_attr_ctx *ctx,
325                       void *data,
326                       OM_uint32 (*addAttribute)(OM_uint32 *, void *, gss_buffer_t))
327 {
328     OM_uint32 major = GSS_S_COMPLETE;
329
330     if (ctx == NULL)
331         return GSS_S_COMPLETE;
332
333     for (vector<Attribute*>::const_iterator a = ctx->resCtx->getResolvedAttributes().begin();
334         a != ctx->resCtx->getResolvedAttributes().end();
335         ++a)
336     {
337         gss_buffer_desc attribute;
338
339         attribute.value = (void *)((*a)->getId());
340         attribute.length = strlen((char *)attribute.value);
341
342         major = addAttribute(minor, data, &attribute);
343         if (GSS_ERROR(major))
344             break;
345     }
346
347     return major;
348 }
349
350 /*
351  * SAML implementation of gss_get_name_attribute
352  */
353 OM_uint32
354 samlGetAttribute(OM_uint32 *minor,
355                  const struct eap_gss_saml_attr_ctx *ctx,
356                  gss_buffer_t attr,
357                  int *authenticated,
358                  int *complete,
359                  gss_buffer_t value,
360                  gss_buffer_t display_value,
361                  int *more)
362 {
363     OM_uint32 major;
364     Attribute *shibAttr = NULL;
365     gss_buffer_desc buf;
366
367     if (ctx == NULL)
368         return GSS_S_UNAVAILABLE;
369
370     for (vector<Attribute *>::const_iterator a = ctx->resCtx->getResolvedAttributes().begin();
371          a != ctx->resCtx->getResolvedAttributes().end();
372          ++a) {
373         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
374              s != (*a)->getAliases().end();
375              ++s) {
376             if (attr->length == strlen((*s).c_str()) &&
377                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
378                 shibAttr = *a;
379                 break;
380             }
381         }
382         if (shibAttr != NULL)
383             break;
384     }
385
386     if (shibAttr == NULL)
387         return GSS_S_UNAVAILABLE;
388
389     if (*more == -1) {
390         *more = 0;
391     } else if (*more >= (int)shibAttr->valueCount()) {
392         *more = 0;
393         return GSS_S_COMPLETE;
394     }
395
396     buf.value = (void *)shibAttr->getString(*more);
397     buf.length = strlen((char *)buf.value);
398
399     major = duplicateBuffer(minor, &buf, value);
400     if (GSS_ERROR(major))
401         return major;
402  
403     *authenticated = TRUE;
404     *complete = FALSE;
405
406     return GSS_S_COMPLETE;
407 }
408
409 /*
410  * No plans to support gss_set_name_attribute at this time.
411  */
412 OM_uint32
413 samlSetAttribute(OM_uint32 *minor,
414                  struct eap_gss_saml_attr_ctx *ctx,
415                  int complete,
416                  gss_buffer_t attr,
417                  gss_buffer_t value)
418 {
419     return GSS_S_UNAVAILABLE;
420 }
421
422 /*
423  * In order to implement gss_export_name and gss_export_sec_context,
424  * we need to serialise a resolved attribute context to a buffer.
425  */
426 OM_uint32
427 samlExportAttrContext(OM_uint32 *minor,
428                       struct eap_gss_saml_attr_ctx *ctx,
429                       gss_buffer_t buffer)
430 {
431     GSSEAP_NOT_IMPLEMENTED;
432 }
433
434 /*
435  * In order to implement gss_import_name and gss_import_sec_context,
436  * we need to deserialise a resolved attribute context from a buffer.
437  */
438 OM_uint32
439 samlImportAttrContext(OM_uint32 *minor,
440                       gss_buffer_t buffer,
441                       struct eap_gss_saml_attr_ctx **ppCtx)
442 {
443     GSSEAP_NOT_IMPLEMENTED;
444 }