3 * Copyright 2001-2006 Internet2
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
21 * Library configuration
25 #include "exceptions.h"
26 #include "SAMLConfig.h"
27 #include "binding/ArtifactMap.h"
28 #include "binding/MessageDecoder.h"
29 #include "binding/MessageEncoder.h"
30 #include "binding/ReplayCache.h"
31 #include "binding/SAMLArtifact.h"
32 #include "binding/URLEncoder.h"
33 #include "saml1/core/Assertions.h"
34 #include "saml1/core/Protocols.h"
35 #include "saml2/core/Protocols.h"
36 #include "saml2/metadata/Metadata.h"
37 #include "saml2/metadata/MetadataProvider.h"
38 #include "security/TrustEngine.h"
39 #include "util/SAMLConstants.h"
41 #include <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/signature/Signature.h>
43 #include <xmltooling/util/NDC.h>
45 #include <log4cpp/Category.hh>
46 #include <xsec/enc/XSECCryptoException.hpp>
47 #include <xsec/enc/XSECCryptoProvider.hpp>
48 #include <xsec/utils/XSECPlatformUtils.hpp>
49 #include <openssl/err.h>
51 using namespace opensaml;
52 using namespace xmlsignature;
53 using namespace xmltooling;
54 using namespace log4cpp;
57 // Expose entry points when used as an extension library
59 extern "C" int SAML_API xmltooling_extension_init(void*)
61 if (SAMLConfig::getConfig().init(false))
66 extern "C" void SAML_API xmltooling_extension_term()
68 SAMLConfig::getConfig().term(false);
71 DECL_EXCEPTION_FACTORY(ArtifactException,opensaml);
72 DECL_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
73 DECL_EXCEPTION_FACTORY(BindingException,opensaml);
76 SAMLInternalConfig g_config;
79 SAMLConfig& SAMLConfig::getConfig()
84 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
89 void SAMLConfig::setArtifactMap(ArtifactMap* artifactMap)
92 m_artifactMap = artifactMap;
95 void SAMLConfig::setURLEncoder(URLEncoder* urlEncoder)
98 m_urlEncoder = urlEncoder;
101 void SAMLConfig::setReplayCache(ReplayCache* replayCache)
103 delete m_replayCache;
104 m_replayCache = replayCache;
107 bool SAMLInternalConfig::init(bool initXMLTooling)
110 xmltooling::NDC ndc("init");
112 Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
113 log.debug("library initialization started");
115 if (initXMLTooling) {
116 XMLToolingConfig::getConfig().init();
117 log.debug("XMLTooling library initialized");
120 REGISTER_EXCEPTION_FACTORY(ArtifactException,opensaml);
121 REGISTER_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
122 REGISTER_EXCEPTION_FACTORY(BindingException,opensaml);
124 saml1::registerAssertionClasses();
125 saml1p::registerProtocolClasses();
126 saml2::registerAssertionClasses();
127 saml2p::registerProtocolClasses();
128 saml2md::registerMetadataClasses();
129 saml2md::registerMetadataProviders();
130 saml2md::registerMetadataFilters();
131 registerSAMLArtifacts();
132 registerTrustEngines();
133 registerMessageEncoders();
134 registerMessageDecoders();
136 m_urlEncoder = new URLEncoder();
138 log.info("library initialization complete");
142 void SAMLInternalConfig::term(bool termXMLTooling)
145 xmltooling::NDC ndc("term");
147 Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
149 MessageDecoderManager.deregisterFactories();
150 MessageEncoderManager.deregisterFactories();
151 TrustEngineManager.deregisterFactories();
152 SAMLArtifactManager.deregisterFactories();
153 MetadataFilterManager.deregisterFactories();
154 MetadataProviderManager.deregisterFactories();
156 delete m_artifactMap;
157 m_artifactMap = NULL;
160 delete m_replayCache;
161 m_replayCache = NULL;
163 if (termXMLTooling) {
164 XMLToolingConfig::getConfig().term();
165 log.debug("XMLTooling library shut down");
167 log.info("library shutdown complete");
170 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
173 if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
174 throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
176 catch (XSECCryptoException& e) {
177 throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
181 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
184 auto_ptr<unsigned char> hold(new unsigned char[len]);
185 generateRandomBytes(hold.get(),len);
186 for (unsigned int i=0; i<len; i++)
187 buf+=(hold.get())[i];
190 XMLCh* SAMLInternalConfig::generateIdentifier()
192 unsigned char key[17];
193 generateRandomBytes(key,16);
196 sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
197 key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
198 key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
200 return XMLString::transcode(hexform);
203 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
205 static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
207 auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
209 auto_ptr<char> dup(strdup(s));
210 unsigned char buf[21];
211 hasher->hash(reinterpret_cast<unsigned char*>(dup.get()),strlen(dup.get()));
212 if (hasher->finish(buf,20)==20) {
215 for (unsigned int i=0; i<20; i++) {
216 ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
217 ret+=(DIGITS[0x0F & buf[i]]);
221 for (unsigned int i=0; i<20; i++) {
228 throw XMLSecurityException("Unable to generate SHA-1 hash.");
231 void opensaml::log_openssl()
237 unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
239 Category& log=Category::getInstance("OpenSSL");
240 log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
241 if (data && (flags & ERR_TXT_STRING))
242 log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
243 code=ERR_get_error_line_data(&file,&line,&data,&flags);
247 using namespace saml2md;
249 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, bool rethrow)
252 auto_ptr_char id(entity->getEntityID());
253 e->addProperty("entityID",id.get());
254 const list<XMLObject*>& roles=entity->getOrderedChildren();
255 for (list<XMLObject*>::const_iterator child=roles.begin(); child!=roles.end(); ++child) {
256 const RoleDescriptor* role=dynamic_cast<RoleDescriptor*>(*child);
257 if (role && role->isValid()) {
258 const vector<ContactPerson*>& contacts=role->getContactPersons();
259 for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
260 const XMLCh* ctype=(*c)->getContactType();
261 if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
262 || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
263 GivenName* fname=(*c)->getGivenName();
264 SurName* lname=(*c)->getSurName();
265 auto_ptr_char first(fname ? fname->getName() : NULL);
266 auto_ptr_char last(lname ? lname->getName() : NULL);
267 if (first.get() && last.get()) {
268 string contact=string(first.get()) + ' ' + last.get();
269 e->addProperty("contactName",contact.c_str());
271 else if (first.get())
272 e->addProperty("contactName",first.get());
274 e->addProperty("contactName",last.get());
275 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
276 if (!emails.empty()) {
277 auto_ptr_char email(emails.front()->getAddress());
279 e->addProperty("contactEmail",email.get());
284 if (e->getProperty("contactName") || e->getProperty("contactEmail")) {
285 auto_ptr_char eurl(role->getErrorURL());
287 e->addProperty("errorURL",eurl.get());
299 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, bool rethrow)
302 auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
303 e->addProperty("entityID",id.get());
305 const vector<ContactPerson*>& contacts=role->getContactPersons();
306 for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
307 const XMLCh* ctype=(*c)->getContactType();
308 if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
309 || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
310 GivenName* fname=(*c)->getGivenName();
311 SurName* lname=(*c)->getSurName();
312 auto_ptr_char first(fname ? fname->getName() : NULL);
313 auto_ptr_char last(lname ? lname->getName() : NULL);
314 if (first.get() && last.get()) {
315 string contact=string(first.get()) + ' ' + last.get();
316 e->addProperty("contactName",contact.c_str());
318 else if (first.get())
319 e->addProperty("contactName",first.get());
321 e->addProperty("contactName",last.get());
322 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
323 if (!emails.empty()) {
324 auto_ptr_char email(emails.front()->getAddress());
326 e->addProperty("contactEmail",email.get());
332 auto_ptr_char eurl(role->getErrorURL());
334 e->addProperty("errorURL",eurl.get());