2 * Copyright 2010-2011 JANET(UK)
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
20 * An embeddable component interface to Shibboleth SP attribute processing.
25 #ifdef SHIBRESOLVER_HAVE_GSSAPI_NAMINGEXTS
26 # include <gssapi/gssapi_ext.h>
29 #include <shibsp/exceptions.h>
30 #include <shibsp/Application.h>
31 #include <shibsp/GSSRequest.h>
32 #include <shibsp/SPRequest.h>
33 #include <shibsp/ServiceProvider.h>
34 #include <shibsp/attribute/Attribute.h>
35 #include <shibsp/remoting/ListenerService.h>
37 # include <saml/saml2/metadata/Metadata.h>
38 # include <saml/saml2/metadata/MetadataProvider.h>
39 # include <saml/util/SAMLConstants.h>
40 # include <shibsp/attribute/filtering/AttributeFilter.h>
41 # include <shibsp/attribute/filtering/BasicFilteringContext.h>
42 # include <shibsp/attribute/resolver/AttributeExtractor.h>
43 # include <shibsp/attribute/resolver/AttributeResolver.h>
44 # include <shibsp/attribute/resolver/ResolutionContext.h>
45 # include <shibsp/metadata/MetadataProviderCriteria.h>
47 #include <xmltooling/XMLObjectBuilder.h>
48 #include <xmltooling/XMLToolingConfig.h>
49 #include <xmltooling/impl/AnyElement.h>
50 #include <xmltooling/util/ParserPool.h>
51 #include <xmltooling/util/XMLHelper.h>
52 #include <xercesc/util/Base64.hpp>
54 using namespace shibresolver;
55 using namespace shibsp;
57 using namespace opensaml;
58 using namespace opensaml::saml2md;
60 using namespace xmltooling;
63 namespace shibresolver {
64 class SHIBRESOLVER_DLLLOCAL RemotedResolver : public Remoted {
71 for_each(tokens.begin(), tokens.end(), xmltooling::cleanup<XMLObject>());
72 for_each(inputAttrs.begin(), inputAttrs.end(), xmltooling::cleanup<Attribute>());
73 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<Attribute>());
76 vector<const XMLObject*> tokens;
77 vector<Attribute*> inputAttrs;
78 vector<Attribute*> resolvedAttrs;
81 void receive(DDF& in, ostream& out);
83 const Application& app,
85 const vector<const XMLObject*>& tokens,
86 const vector<Attribute*>& inputAttrs,
87 vector <Attribute*>& resolvedAttrs
91 static RemotedResolver g_Remoted;
94 ShibbolethResolver* ShibbolethResolver::create()
96 return new ShibbolethResolver();
99 ShibbolethResolver::ShibbolethResolver() : m_request(NULL), m_sp(NULL)
100 #ifdef SHIBRESOLVER_HAVE_GSSAPI
106 ShibbolethResolver::~ShibbolethResolver()
108 #ifdef SHIBRESOLVER_HAVE_GSSAPI
111 for_each(m_resolvedAttributes.begin(), m_resolvedAttributes.end(), xmltooling::cleanup<Attribute>());
116 void ShibbolethResolver::setRequest(const SPRequest* request)
119 #if defined(SHIBSP_HAVE_GSSAPI) && defined (SHIBRESOLVER_HAVE_GSSAPI)
121 const GSSRequest* gss = dynamic_cast<const GSSRequest*>(request);
123 // TODO: fix API to prevent destruction of contexts
124 gss_ctx_id_t ctx = gss->getGSSContext();
131 void ShibbolethResolver::setApplicationID(const char* appID)
138 void ShibbolethResolver::setIssuer(const char* issuer)
145 void ShibbolethResolver::addToken(const XMLObject* token)
148 m_tokens.push_back(token);
151 #ifdef SHIBRESOLVER_HAVE_GSSAPI
152 void ShibbolethResolver::addToken(gss_ctx_id_t* ctx)
159 if (ctx && *ctx != GSS_C_NO_CONTEXT) {
161 gss_buffer_desc contextbuf = GSS_C_EMPTY_BUFFER;
162 OM_uint32 major = gss_export_sec_context(&minor, ctx, &contextbuf);
163 if (major == GSS_S_COMPLETE) {
165 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf.value), contextbuf.length, &len);
168 s.append(reinterpret_cast<char*>(out), len);
169 auto_ptr_XMLCh temp(s.c_str());
170 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
171 XMLString::release(&out);
173 XMLString::release((char**)&out);
175 static const XMLCh _GSSAPI[] = UNICODE_LITERAL_13(G,S,S,A,P,I,C,o,n,t,e,x,t);
176 m_gsswrapper = new AnyElementImpl(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPI);
177 m_gsswrapper->setTextContent(temp.get());
180 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error while base64-encoding GSS context");
182 gss_release_buffer(&minor, &contextbuf);
185 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error exporting GSS context");
190 #ifdef SHIBRESOLVER_HAVE_GSSAPI_NAMINGEXTS
191 void ShibbolethResolver::addToken(gss_name_t name)
199 gss_buffer_desc namebuf = GSS_C_EMPTY_BUFFER;
200 OM_uint32 major = gss_export_name_composite(&minor, name, &namebuf);
201 if (major == GSS_S_COMPLETE) {
203 gss_release_buffer(&minor, &namebuf);
206 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error exporting GSS name");
211 void ShibbolethResolver::addToken(const gss_buffer_t contextbuf)
219 XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(contextbuf->value), contextbuf->length, &len);
222 s.append(reinterpret_cast<char*>(out), len);
223 auto_ptr_XMLCh temp(s.c_str());
224 #ifdef SHIBSP_XERCESC_HAS_XMLBYTE_RELEASE
225 XMLString::release(&out);
227 XMLString::release((char**)&out);
229 static const XMLCh _GSSAPI[] = UNICODE_LITERAL_10(G,S,S,A,P,I,N,a,m,e);
230 m_gsswrapper = new AnyElementImpl(shibspconstants::SHIB2ATTRIBUTEMAP_NS, _GSSAPI);
231 m_gsswrapper->setTextContent(temp.get());
234 Category::getInstance(SHIBRESOLVER_LOGCAT).error("error while base64-encoding GSS name");
240 void ShibbolethResolver::addAttribute(Attribute* attr)
243 m_inputAttributes.push_back(attr);
246 vector<Attribute*>& ShibbolethResolver::getResolvedAttributes()
248 return m_resolvedAttributes;
251 RequestMapper::Settings ShibbolethResolver::getSettings() const
254 throw ConfigurationException("Request settings not available without supplying SPRequest instance.");
255 return m_request->getRequestSettings();
258 void ShibbolethResolver::resolve()
260 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
261 SPConfig& conf = SPConfig::getConfig();
263 m_sp = conf.getServiceProvider();
269 const Application* app = m_request ? &(m_request->getApplication()) : m_sp->getApplication(m_appID.c_str());
271 throw ConfigurationException("Unable to locate application for resolution.");
273 #ifdef SHIBRESOLVER_HAVE_GSSAPI
275 m_tokens.push_back(m_gsswrapper);
278 if (conf.isEnabled(SPConfig::OutOfProcess)) {
288 // When not out of process, we remote all the message processing.
289 DDF out,in = DDF("org.project-moonshot.shibresolver");
290 DDFJanitor jin(in), jout(out);
291 in.addmember("application_id").string(app->getId());
292 if (!m_issuer.empty())
293 in.addmember("issuer").string(m_issuer.c_str());
294 if (!m_tokens.empty()) {
295 DDF& tokens = in.addmember("tokens").list();
296 for (vector<const XMLObject*>::const_iterator t = m_tokens.begin(); t != m_tokens.end(); ++t) {
299 tokens.add(DDF(NULL).string(os.str().c_str()));
302 if (!m_inputAttributes.empty()) {
304 DDF& attrs = in.addmember("attributes").list();
305 for (vector<Attribute*>::const_iterator a = m_inputAttributes.begin(); a != m_inputAttributes.end(); ++a) {
306 attr = (*a)->marshall();
311 out = (m_request ? m_request->getServiceProvider() : (*m_sp)).getListenerService()->send(in);
313 Attribute* attribute;
314 DDF attr = out.first();
315 while (!attr.isnull()) {
317 attribute = Attribute::unmarshall(attr);
318 m_resolvedAttributes.push_back(attribute);
319 if (log.isDebugEnabled())
320 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
321 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
323 catch (AttributeException& ex) {
324 const char* id = attr.first().name();
325 log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());
332 void RemotedResolver::receive(DDF& in, ostream& out)
334 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
337 const char* aid = in["application_id"].string();
338 const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
340 // Something's horribly wrong.
341 log.error("couldn't find application (%s) for resolution", aid ? aid : "(missing)");
342 throw ConfigurationException("Unable to locate application for resolution, deleted?");
346 DDFJanitor jout(ret);
350 DDF tlist = in["tokens"];
351 DDF token = tlist.first();
352 while (token.isstring()) {
353 // Parse and bind the document into an XMLObject.
354 istringstream instr(token.string());
355 DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr);
356 XercesJanitor<DOMDocument> janitor(doc);
357 XMLObject* xmlObject = XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true);
358 t.tokens.push_back(xmlObject);
360 token = tlist.next();
363 DDF alist = in["attributes"];
364 Attribute* attribute;
365 DDF attr = alist.first();
366 while (!attr.isnull()) {
367 attribute = Attribute::unmarshall(attr);
368 t.inputAttrs.push_back(attribute);
369 if (log.isDebugEnabled())
370 log.debug("unmarshalled attribute (ID: %s) with %d value%s",
371 attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");
375 resolve(*app, in["issuer"].string(), t.tokens, t.inputAttrs, t.resolvedAttrs);
377 if (!t.resolvedAttrs.empty()) {
379 for (vector<Attribute*>::const_iterator a = t.resolvedAttrs.begin(); a != t.resolvedAttrs.end(); ++a) {
380 attr = (*a)->marshall();
388 void RemotedResolver::resolve(
389 const Application& app,
391 const vector<const XMLObject*>& tokens,
392 const vector<Attribute*>& inputAttrs,
393 vector <Attribute*>& resolvedAttrs
397 Category& log = Category::getInstance(SHIBRESOLVER_LOGCAT);
398 string issuerstr(issuer ? issuer : "");
399 pair<const EntityDescriptor*,const RoleDescriptor*> entity = make_pair((EntityDescriptor*)NULL, (RoleDescriptor*)NULL);
400 MetadataProvider* m = app.getMetadataProvider(false);
403 log.warn("no metadata providers are configured");
406 if (!issuerstr.empty()) {
407 // Attempt to locate an issuer based on input token.
408 for (vector<const XMLObject*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
409 const saml2::Assertion* assertion = dynamic_cast<const saml2::Assertion*>(*t);
410 if (assertion && assertion->getIssuer()) {
411 auto_ptr_char iss(assertion->getIssuer()->getName());
412 if (iss.get() && *iss.get()) {
413 issuerstr = iss.get();
418 if (!issuerstr.empty()) {
419 log.info("setting issuer based on input token (%s)", issuerstr.c_str());
423 if (!issuerstr.empty()) {
424 // Lookup metadata for the issuer.
425 MetadataProviderCriteria idpmc(app, issuerstr.c_str(), &IDPSSODescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
426 entity = m->getEntityDescriptor(idpmc);
428 log.warn("unable to locate metadata for provider (%s)", issuerstr.c_str());
430 else if (!entity.second) {
431 MetadataProviderCriteria aamc(app, issuerstr.c_str(), &AttributeAuthorityDescriptor::ELEMENT_QNAME, samlconstants::SAML20P_NS);
432 entity = m->getEntityDescriptor(aamc);
433 if (!entity.second) {
434 log.warn("unable to locate SAML 2.0 IdP or AA role for provider (%s)", issuerstr.c_str());
440 vector<const Assertion*> assertions;
442 AttributeExtractor* extractor = app.getAttributeExtractor();
444 Locker extlocker(extractor);
446 pair<bool,const char*> mprefix = app.getString("metadataAttributePrefix");
448 log.debug("extracting metadata-derived attributes...");
450 // We pass NULL for "issuer" because the IdP isn't the one asserting metadata-based attributes.
451 extractor->extractAttributes(app, NULL, *entity.second, resolvedAttrs);
452 for (vector<Attribute*>::iterator a = resolvedAttrs.begin(); a != resolvedAttrs.end(); ++a) {
453 vector<string>& ids = (*a)->getAliases();
454 for (vector<string>::iterator id = ids.begin(); id != ids.end(); ++id)
455 *id = mprefix.second + *id;
458 catch (exception& ex) {
459 log.error("caught exception extracting attributes: %s", ex.what());
463 log.debug("extracting pushed attributes...");
464 for (vector<const XMLObject*>::const_iterator t = tokens.begin(); t!=tokens.end(); ++t) {
466 // Save off any assertions for later use by resolver.
467 const Assertion* assertion = dynamic_cast<const Assertion*>(*t);
469 assertions.push_back(assertion);
470 extractor->extractAttributes(app, entity.second, *(*t), resolvedAttrs);
472 catch (exception& ex) {
473 log.error("caught exception extracting attributes: %s", ex.what());
477 AttributeFilter* filter = app.getAttributeFilter();
478 if (filter && !resolvedAttrs.empty()) {
479 BasicFilteringContext fc(app, resolvedAttrs, entity.second);
480 Locker filtlocker(filter);
482 filter->filterAttributes(fc, resolvedAttrs);
484 catch (exception& ex) {
485 log.error("caught exception filtering attributes: %s", ex.what());
486 log.error("dumping extracted attributes due to filtering exception");
487 for_each(resolvedAttrs.begin(), resolvedAttrs.end(), xmltooling::cleanup<shibsp::Attribute>());
488 resolvedAttrs.clear();
493 log.warn("no AttributeExtractor plugin installed, check log during startup");
497 AttributeResolver* resolver = app.getAttributeResolver();
499 log.debug("resolving attributes...");
501 vector<Attribute*> inputs = inputAttrs;
502 inputs.insert(inputs.end(), resolvedAttrs.begin(), resolvedAttrs.end());
504 Locker locker(resolver);
505 auto_ptr<ResolutionContext> ctx(
506 resolver->createResolutionContext(
509 samlconstants::SAML20P_NS,
517 resolver->resolveAttributes(*ctx.get());
518 if (!ctx->getResolvedAttributes().empty())
519 resolvedAttrs.insert(resolvedAttrs.end(), ctx->getResolvedAttributes().begin(), ctx->getResolvedAttributes().end());
522 catch (exception& ex) {
523 log.error("attribute resolution failed: %s", ex.what());
526 throw ConfigurationException("Cannot process request using lite version of shibsp library.");
530 bool ShibbolethResolver::init(unsigned long features, const char* config, bool rethrow)
532 if (features && SPConfig::OutOfProcess) {
534 features = features | SPConfig::AttributeResolution | SPConfig::Metadata | SPConfig::Trust | SPConfig::Credentials;
536 if (!(features && SPConfig::InProcess))
537 features |= SPConfig::Listener;
539 else if (features && SPConfig::InProcess) {
540 features |= SPConfig::Listener;
542 SPConfig::getConfig().setFeatures(features);
543 if (!SPConfig::getConfig().init())
545 if (!SPConfig::getConfig().instantiate(config, rethrow))
551 * Shuts down runtime.
553 * Each process using the library SHOULD call this function exactly once before terminating itself.
555 void ShibbolethResolver::term()
557 SPConfig::getConfig().term();
561 extern "C" int SHIBRESOLVER_EXPORTS xmltooling_extension_init(void*)
563 #ifdef SHIBRESOLVER_SHIBSP_HAS_REMOTING
564 SPConfig& conf = SPConfig::getConfig();
565 if (conf.isEnabled(SPConfig::OutOfProcess) && !conf.isEnabled(SPConfig::InProcess) && conf.isEnabled(SPConfig::Listener))
566 conf.getServiceProvider()->regListener("org.project-moonshot.shibresolver", &g_Remoted);
568 return 0; // signal success
571 extern "C" void SHIBRESOLVER_EXPORTS xmltooling_extension_term()
573 // Factories normally get unregistered during library shutdown, so no work usually required here.