Rename exception macros to avoid conflicts.
[shibboleth/cpp-opensaml.git] / saml / SAMLConfig.cpp
1
2 /*
3  *  Copyright 2001-2006 Internet2
4  * 
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 /**
19  * SAMLConfig.cpp
20  * 
21  * Library configuration 
22  */
23
24 #include "internal.h"
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/SAMLArtifact.h"
31 #include "binding/SecurityPolicyRule.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 "util/SAMLConstants.h"
39
40 #include <xmltooling/XMLToolingConfig.h>
41 #include <xmltooling/signature/Signature.h>
42 #include <xmltooling/util/NDC.h>
43
44 #include <log4cpp/Category.hh>
45 #include <xsec/enc/XSECCryptoException.hpp>
46 #include <xsec/enc/XSECCryptoProvider.hpp>
47 #include <xsec/utils/XSECPlatformUtils.hpp>
48 #include <openssl/err.h>
49
50 using namespace opensaml;
51 using namespace xmlsignature;
52 using namespace xmltooling;
53 using namespace log4cpp;
54 using namespace std;
55
56 // Expose entry points when used as an extension library
57
58 extern "C" int SAML_API xmltooling_extension_init(void*)
59 {
60     if (SAMLConfig::getConfig().init(false))
61         return 0;
62     return -1;
63 }
64
65 extern "C" void SAML_API xmltooling_extension_term()
66 {
67     SAMLConfig::getConfig().term(false);
68 }
69
70 DECL_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
71 DECL_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
72 DECL_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
73
74 namespace opensaml {
75    SAMLInternalConfig g_config;
76 }
77
78 SAMLConfig& SAMLConfig::getConfig()
79 {
80     return g_config;
81 }
82
83 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
84 {
85     return g_config;
86 }
87
88 void SAMLConfig::setArtifactMap(ArtifactMap* artifactMap)
89 {
90     delete m_artifactMap;
91     m_artifactMap = artifactMap;
92 }
93
94 void SAMLConfig::setURLEncoder(URLEncoder* urlEncoder)
95 {
96     delete m_urlEncoder;
97     m_urlEncoder = urlEncoder;
98 }
99
100 bool SAMLInternalConfig::init(bool initXMLTooling)
101 {
102 #ifdef _DEBUG
103     xmltooling::NDC ndc("init");
104 #endif
105     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
106     log.debug("library initialization started");
107
108     if (initXMLTooling) {
109         XMLToolingConfig::getConfig().init();
110         log.debug("XMLTooling library initialized");
111     }
112
113     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(ArtifactException,opensaml);
114     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
115     REGISTER_XMLTOOLING_EXCEPTION_FACTORY(BindingException,opensaml);
116
117     saml1::registerAssertionClasses();
118     saml1p::registerProtocolClasses();
119     saml2::registerAssertionClasses();
120     saml2p::registerProtocolClasses();
121     saml2md::registerMetadataClasses();
122     saml2md::registerMetadataProviders();
123     saml2md::registerMetadataFilters();
124     registerSAMLArtifacts();
125     registerMessageEncoders();
126     registerMessageDecoders();
127     registerSecurityPolicyRules();
128     
129     m_urlEncoder = new URLEncoder();
130
131     log.info("library initialization complete");
132     return true;
133 }
134
135 void SAMLInternalConfig::term(bool termXMLTooling)
136 {
137 #ifdef _DEBUG
138     xmltooling::NDC ndc("term");
139 #endif
140     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
141
142     MessageDecoderManager.deregisterFactories();
143     MessageEncoderManager.deregisterFactories();
144     SecurityPolicyRuleManager.deregisterFactories();
145     SAMLArtifactManager.deregisterFactories();
146     MetadataFilterManager.deregisterFactories();
147     MetadataProviderManager.deregisterFactories();
148
149     delete m_artifactMap;
150     m_artifactMap = NULL;
151     delete m_urlEncoder;
152     m_urlEncoder = NULL;
153
154     if (termXMLTooling) {
155         XMLToolingConfig::getConfig().term();
156         log.debug("XMLTooling library shut down");
157     }
158     log.info("library shutdown complete");
159 }
160
161 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
162 {
163     try {
164         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
165             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
166     }
167     catch (XSECCryptoException& e) {
168         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
169     }
170 }
171
172 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
173 {
174     buf.erase();
175     auto_ptr<unsigned char> hold(new unsigned char[len]);
176     generateRandomBytes(hold.get(),len);
177     for (unsigned int i=0; i<len; i++)
178         buf+=(hold.get())[i];
179 }
180
181 XMLCh* SAMLInternalConfig::generateIdentifier()
182 {
183     unsigned char key[17];
184     generateRandomBytes(key,16);
185     
186     char hexform[34];
187     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
188             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
189             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
190     hexform[33]=0;
191     return XMLString::transcode(hexform);
192 }
193
194 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
195 {
196     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
197
198     auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
199     if (hasher.get()) {
200         unsigned char buf[21];
201         hasher->hash(reinterpret_cast<unsigned char*>(const_cast<char*>(s)),strlen(s));
202         if (hasher->finish(buf,20)==20) {
203             string ret;
204             if (toHex) {
205                 for (unsigned int i=0; i<20; i++) {
206                     ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
207                     ret+=(DIGITS[0x0F & buf[i]]);
208                 }
209             }
210             else {
211                 for (unsigned int i=0; i<20; i++) {
212                     ret+=buf[i];
213                 }
214             }
215             return ret;
216         }
217     }
218     throw XMLSecurityException("Unable to generate SHA-1 hash.");
219 }
220
221 void opensaml::log_openssl()
222 {
223     const char* file;
224     const char* data;
225     int flags,line;
226
227     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
228     while (code) {
229         Category& log=Category::getInstance("OpenSSL");
230         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
231         if (data && (flags & ERR_TXT_STRING))
232             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
233         code=ERR_get_error_line_data(&file,&line,&data,&flags);
234     }
235 }
236
237 using namespace saml2md;
238
239 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, bool rethrow)
240 {
241     if (entity) {
242         auto_ptr_char id(entity->getEntityID());
243         e->addProperty("entityID",id.get());
244         const list<XMLObject*>& roles=entity->getOrderedChildren();
245         for (list<XMLObject*>::const_iterator child=roles.begin(); child!=roles.end(); ++child) {
246             const RoleDescriptor* role=dynamic_cast<RoleDescriptor*>(*child);
247             if (role && role->isValid()) {
248                 const vector<ContactPerson*>& contacts=role->getContactPersons();
249                 for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
250                     const XMLCh* ctype=(*c)->getContactType();
251                     if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
252                             || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
253                         GivenName* fname=(*c)->getGivenName();
254                         SurName* lname=(*c)->getSurName();
255                         auto_ptr_char first(fname ? fname->getName() : NULL);
256                         auto_ptr_char last(lname ? lname->getName() : NULL);
257                         if (first.get() && last.get()) {
258                             string contact=string(first.get()) + ' ' + last.get();
259                             e->addProperty("contactName",contact.c_str());
260                         }
261                         else if (first.get())
262                             e->addProperty("contactName",first.get());
263                         else if (last.get())
264                             e->addProperty("contactName",last.get());
265                         const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
266                         if (!emails.empty()) {
267                             auto_ptr_char email(emails.front()->getAddress());
268                             if (email.get())
269                                 e->addProperty("contactEmail",email.get());
270                         }
271                         break;
272                     }
273                 }
274                 if (e->getProperty("contactName") || e->getProperty("contactEmail")) {
275                     auto_ptr_char eurl(role->getErrorURL());
276                     if (eurl.get()) {
277                         e->addProperty("errorURL",eurl.get());
278                     }
279                 }
280                 break;
281             }
282         }
283     }
284     
285     if (rethrow)
286         e->raise();
287 }
288
289 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, bool rethrow)
290 {
291     if (role) {
292         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
293         e->addProperty("entityID",id.get());
294
295         const vector<ContactPerson*>& contacts=role->getContactPersons();
296         for (vector<ContactPerson*>::const_iterator c=contacts.begin(); c!=contacts.end(); ++c) {
297             const XMLCh* ctype=(*c)->getContactType();
298             if (ctype && (XMLString::equals(ctype,ContactPerson::CONTACT_SUPPORT)
299                     || XMLString::equals(ctype,ContactPerson::CONTACT_TECHNICAL))) {
300                 GivenName* fname=(*c)->getGivenName();
301                 SurName* lname=(*c)->getSurName();
302                 auto_ptr_char first(fname ? fname->getName() : NULL);
303                 auto_ptr_char last(lname ? lname->getName() : NULL);
304                 if (first.get() && last.get()) {
305                     string contact=string(first.get()) + ' ' + last.get();
306                     e->addProperty("contactName",contact.c_str());
307                 }
308                 else if (first.get())
309                     e->addProperty("contactName",first.get());
310                 else if (last.get())
311                     e->addProperty("contactName",last.get());
312                 const vector<EmailAddress*>& emails=const_cast<const ContactPerson*>(*c)->getEmailAddresss();
313                 if (!emails.empty()) {
314                     auto_ptr_char email(emails.front()->getAddress());
315                     if (email.get())
316                         e->addProperty("contactEmail",email.get());
317                 }
318                 break;
319             }
320         }
321
322         auto_ptr_char eurl(role->getErrorURL());
323         if (eurl.get()) {
324             e->addProperty("errorURL",eurl.get());
325         }
326     }
327     
328     if (rethrow)
329         e->raise();
330 }