move extracting raw assertion to RADIUS
[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     gss_buffer_desc assertion;
139 };
140
141 static OM_uint32
142 samlAllocAttrContext(OM_uint32 *minor,
143                      struct eap_gss_saml_attr_ctx **pCtx)
144 {
145     struct eap_gss_saml_attr_ctx *ctx;
146
147     ctx = (struct eap_gss_saml_attr_ctx *)GSSEAP_CALLOC(1, sizeof(*ctx));
148     if (ctx == NULL) {
149         *minor = ENOMEM;
150         return GSS_S_FAILURE;
151     }
152
153     *pCtx = ctx;
154     *minor = 0;
155     return GSS_S_COMPLETE;
156 }
157
158 static OM_uint32
159 samlImportAssertion(OM_uint32 *minor,
160                     gss_buffer_t buffer,
161                     saml2::Assertion **pAssertion)
162 {
163     *pAssertion = NULL;
164
165     try {
166         DOMDocument *doc;
167         const XMLObjectBuilder *b;
168         DOMElement *elem;
169         XMLObject *xobj;
170         string samlBuf((char *)buffer->value, buffer->length);
171         istringstream samlIn(samlBuf);
172
173         doc = XMLToolingConfig::getConfig().getParser().parse(samlIn);
174         b = XMLObjectBuilder::getDefaultBuilder();
175         elem = doc->getDocumentElement();
176         xobj = b->buildOneFromElement(elem, true);
177
178         *pAssertion = dynamic_cast<saml2::Assertion *>(xobj);
179         if (*pAssertion == NULL) {
180             /* TODO minor_status */
181             return GSS_S_BAD_NAME;
182         }
183     } catch (exception &e){
184         /* TODO minor_status */
185         return GSS_S_BAD_NAME;
186     }
187
188     *minor = 0;
189     return GSS_S_COMPLETE;
190 }
191
192 OM_uint32
193 samlDuplicateAttrContext(OM_uint32 *minor,
194                          const struct eap_gss_saml_attr_ctx *in,
195                          struct eap_gss_saml_attr_ctx **out)
196 {
197     OM_uint32 major, tmpMinor;
198     struct eap_gss_saml_attr_ctx *ctx;
199
200     major = samlAllocAttrContext(minor, &ctx);
201     if (GSS_ERROR(major))
202         goto cleanup;
203
204     ctx->resCtx = new DummyContext(in->resCtx->getResolvedAttributes());
205
206 cleanup:
207     if (GSS_ERROR(major))
208         samlReleaseAttrContext(&tmpMinor, &ctx);
209
210     return major;
211 }
212
213 OM_uint32
214 samlReleaseAttrContext(OM_uint32 *minor,
215                        struct eap_gss_saml_attr_ctx **pCtx)
216 {
217     struct eap_gss_saml_attr_ctx *ctx = *pCtx;
218
219     if (ctx != NULL) {
220         delete ctx->resCtx;
221         GSSEAP_FREE(ctx);
222         *pCtx = NULL;
223     }
224
225     *minor = 0;
226     return GSS_S_COMPLETE;
227 }
228
229 OM_uint32
230 samlCreateAttrContext(OM_uint32 *minor,
231                       gss_buffer_t buffer,
232                       gss_name_t acceptorName,
233                       struct eap_gss_saml_attr_ctx **pCtx)
234 {
235     OM_uint32 major, tmpMinor;
236     struct eap_gss_saml_attr_ctx *ctx;
237     SPConfig &conf = SPConfig::getConfig();
238     ServiceProvider *sp;
239     const Application *app;
240     MetadataProvider *m;
241     gss_buffer_desc nameBuf;
242     const XMLCh *issuer = NULL;
243     saml2::NameID *subjectName = NULL;
244     saml2::Assertion *assertion;
245
246     nameBuf.length = 0;
247     nameBuf.value = NULL;
248
249     conf.setFeatures(SPConfig::Metadata             |
250                      SPConfig::Trust                |
251                      SPConfig::AttributeResolution  |
252                      SPConfig::Credentials          |
253                      SPConfig::OutOfProcess);
254     if (!conf.init())
255         return GSS_S_FAILURE;
256     if (!conf.instantiate())
257         return GSS_S_FAILURE;
258
259     sp = conf.getServiceProvider();
260     sp->lock();
261
262     major = gss_display_name(minor, acceptorName, &nameBuf, NULL);
263     if (GSS_ERROR(major))
264         goto cleanup;
265
266     app = sp->getApplication((const char *)nameBuf.value);
267     if (app == NULL) {
268         major = GSS_S_FAILURE;
269         goto cleanup;
270     }
271
272     major = samlAllocAttrContext(minor, &ctx);
273     if (GSS_ERROR(major))
274         goto cleanup;
275
276     major = samlImportAssertion(minor, buffer, &assertion);
277     if (GSS_ERROR(major))
278         goto cleanup;
279
280     if (assertion->getIssuer() != NULL)
281         issuer = assertion->getIssuer()->getName();
282     if (assertion->getSubject() != NULL)
283         subjectName = assertion->getSubject()->getNameID();
284
285     try {
286         m = app->getMetadataProvider();
287         xmltooling::Locker mlocker(m);
288         MetadataProviderCriteria mc(*app, issuer,
289                                     &IDPSSODescriptor::ELEMENT_QNAME,
290                                     samlconstants::SAML20P_NS);
291         pair<const EntityDescriptor *, const RoleDescriptor *> site =
292             m->getEntityDescriptor(mc);
293         if (!site.first) {
294             auto_ptr_char temp(issuer);
295             throw MetadataException("Unable to locate metadata for IdP ($1).",
296                                     params(1,temp.get()));
297         }
298         vector<const Assertion*> tokens(1, assertion);
299         GSSEAPResolver gssResolver(NULL, (const char *)nameBuf.value);
300         ctx->resCtx = gssResolver.resolveAttributes(*app, site.second,
301                                                     samlconstants::SAML20P_NS,
302                                                     NULL, subjectName, NULL,
303                                                     NULL, &tokens);
304     } catch (exception &ex) {
305         major = GSS_S_BAD_NAME;
306         goto cleanup;
307     }
308
309     major = GSS_S_COMPLETE;
310     *pCtx = ctx;
311
312 cleanup:
313     sp->unlock();
314     conf.term();
315
316     if (GSS_ERROR(major))
317         samlReleaseAttrContext(&tmpMinor, &ctx);
318     gss_release_buffer(&tmpMinor, &nameBuf);
319
320     return major;
321 }
322
323 OM_uint32
324 samlGetAttributeTypes(OM_uint32 *minor,
325                       const struct eap_gss_saml_attr_ctx *ctx,
326                       void *data,
327                       OM_uint32 (*addAttribute)(OM_uint32 *, void *, gss_buffer_t))
328 {
329     OM_uint32 major = GSS_S_COMPLETE;
330
331     if (ctx == NULL)
332         return GSS_S_COMPLETE;
333
334     for (vector<Attribute*>::const_iterator a = ctx->resCtx->getResolvedAttributes().begin();
335         a != ctx->resCtx->getResolvedAttributes().end();
336         ++a)
337     {
338         gss_buffer_desc attribute;
339
340         attribute.value = (void *)((*a)->getId());
341         attribute.length = strlen((char *)attribute.value);
342
343         major = addAttribute(minor, data, &attribute);
344         if (GSS_ERROR(major))
345             break;
346     }
347
348     return major;
349 }
350
351 OM_uint32
352 samlGetAttribute(OM_uint32 *minor,
353                  const struct eap_gss_saml_attr_ctx *ctx,
354                  gss_buffer_t attr,
355                  int *authenticated,
356                  int *complete,
357                  gss_buffer_t value,
358                  gss_buffer_t display_value,
359                  int *more)
360 {
361     OM_uint32 major;
362     Attribute *shibAttr = NULL;
363     gss_buffer_desc buf;
364
365     if (ctx == NULL)
366         return GSS_S_UNAVAILABLE;
367
368     for (vector<Attribute *>::const_iterator a = ctx->resCtx->getResolvedAttributes().begin();
369          a != ctx->resCtx->getResolvedAttributes().end();
370          ++a) {
371         for (vector<string>::const_iterator s = (*a)->getAliases().begin();
372              s != (*a)->getAliases().end();
373              ++s) {
374             if (attr->length == strlen((*s).c_str()) &&
375                 memcmp((*s).c_str(), attr->value, attr->length) == 0) {
376                 shibAttr = *a;
377                 break;
378             }
379         }
380         if (shibAttr != NULL)
381             break;
382     }
383
384     if (shibAttr == NULL)
385         return GSS_S_UNAVAILABLE;
386
387     if (*more == -1) {
388         *more = 0;
389     } else if (*more >= (int)shibAttr->valueCount()) {
390         *more = 0;
391         return GSS_S_COMPLETE;
392     }
393
394     buf.value = (void *)shibAttr->getString(*more);
395     buf.length = strlen((char *)buf.value);
396
397     major = duplicateBuffer(minor, &buf, value);
398     if (GSS_ERROR(major))
399         return major;
400  
401     *authenticated = TRUE;
402     *complete = FALSE;
403
404     return GSS_S_COMPLETE;
405 }
406
407 OM_uint32
408 samlSetAttribute(OM_uint32 *minor,
409                  struct eap_gss_saml_attr_ctx *ctx,
410                  int complete,
411                  gss_buffer_t attr,
412                  gss_buffer_t value)
413 {
414     return GSS_S_UNAVAILABLE;
415 }
416
417 OM_uint32
418 samlExportAttrContext(OM_uint32 *minor,
419                       struct eap_gss_saml_attr_ctx *ctx,
420                       gss_buffer_t buffer)
421 {
422     GSSEAP_NOT_IMPLEMENTED;
423 }
424
425 OM_uint32
426 samlImportAttrContext(OM_uint32 *minor,
427                       gss_buffer_t buffer,
428                       struct eap_gss_saml_attr_ctx **ppCtx)
429 {
430     GSSEAP_NOT_IMPLEMENTED;
431 }