4e4c7ce0cc38a0f8d8e922c0609084f550435590
[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/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"
40
41 #include <xmltooling/XMLToolingConfig.h>
42 #include <xmltooling/signature/Signature.h>
43 #include <xmltooling/util/NDC.h>
44
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>
50
51 using namespace opensaml;
52 using namespace xmlsignature;
53 using namespace xmltooling;
54 using namespace log4cpp;
55 using namespace std;
56
57 // Expose entry points when used as an extension library
58
59 extern "C" int SAML_API xmltooling_extension_init(void*)
60 {
61     if (SAMLConfig::getConfig().init(false))
62         return 0;
63     return -1;
64 }
65
66 extern "C" void SAML_API xmltooling_extension_term()
67 {
68     SAMLConfig::getConfig().term(false);
69 }
70
71 DECL_EXCEPTION_FACTORY(ArtifactException,opensaml);
72 DECL_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
73 DECL_EXCEPTION_FACTORY(BindingException,opensaml);
74
75 namespace opensaml {
76    SAMLInternalConfig g_config;
77 }
78
79 SAMLConfig& SAMLConfig::getConfig()
80 {
81     return g_config;
82 }
83
84 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
85 {
86     return g_config;
87 }
88
89 void SAMLConfig::setArtifactMap(ArtifactMap* artifactMap)
90 {
91     delete m_artifactMap;
92     m_artifactMap = artifactMap;
93 }
94
95 void SAMLConfig::setURLEncoder(URLEncoder* urlEncoder)
96 {
97     delete m_urlEncoder;
98     m_urlEncoder = urlEncoder;
99 }
100
101 void SAMLConfig::setReplayCache(ReplayCache* replayCache)
102 {
103     delete m_replayCache;
104     m_replayCache = replayCache;
105 }
106
107 bool SAMLInternalConfig::init(bool initXMLTooling)
108 {
109 #ifdef _DEBUG
110     xmltooling::NDC ndc("init");
111 #endif
112     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
113     log.debug("library initialization started");
114
115     if (initXMLTooling) {
116         XMLToolingConfig::getConfig().init();
117         log.debug("XMLTooling library initialized");
118     }
119
120     REGISTER_EXCEPTION_FACTORY(ArtifactException,opensaml);
121     REGISTER_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
122     REGISTER_EXCEPTION_FACTORY(BindingException,opensaml);
123
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();
135     
136     m_urlEncoder = new URLEncoder();
137
138     log.info("library initialization complete");
139     return true;
140 }
141
142 void SAMLInternalConfig::term(bool termXMLTooling)
143 {
144 #ifdef _DEBUG
145     xmltooling::NDC ndc("term");
146 #endif
147     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
148
149     MessageDecoderManager.deregisterFactories();
150     MessageEncoderManager.deregisterFactories();
151     TrustEngineManager.deregisterFactories();
152     SAMLArtifactManager.deregisterFactories();
153     MetadataFilterManager.deregisterFactories();
154     MetadataProviderManager.deregisterFactories();
155
156     delete m_artifactMap;
157     m_artifactMap = NULL;
158     delete m_urlEncoder;
159     m_urlEncoder = NULL;
160     delete m_replayCache;
161     m_replayCache = NULL;
162
163     if (termXMLTooling) {
164         XMLToolingConfig::getConfig().term();
165         log.debug("XMLTooling library shut down");
166     }
167     log.info("library shutdown complete");
168 }
169
170 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
171 {
172     try {
173         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
174             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
175     }
176     catch (XSECCryptoException& e) {
177         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
178     }
179 }
180
181 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
182 {
183     buf.erase();
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];
188 }
189
190 XMLCh* SAMLInternalConfig::generateIdentifier()
191 {
192     unsigned char key[17];
193     generateRandomBytes(key,16);
194     
195     char hexform[34];
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]);
199     hexform[33]=0;
200     return XMLString::transcode(hexform);
201 }
202
203 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
204 {
205     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
206
207     auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
208     if (hasher.get()) {
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) {
213             string ret;
214             if (toHex) {
215                 for (unsigned int i=0; i<20; i++) {
216                     ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
217                     ret+=(DIGITS[0x0F & buf[i]]);
218                 }
219             }
220             else {
221                 for (unsigned int i=0; i<20; i++) {
222                     ret+=buf[i];
223                 }
224             }
225             return ret;
226         }
227     }
228     throw XMLSecurityException("Unable to generate SHA-1 hash.");
229 }
230
231 void opensaml::log_openssl()
232 {
233     const char* file;
234     const char* data;
235     int flags,line;
236
237     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
238     while (code) {
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);
244     }
245 }
246
247 using namespace saml2md;
248
249 void opensaml::annotateException(XMLToolingException* e, const EntityDescriptor* entity, bool rethrow)
250 {
251     if (entity) {
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());
270                         }
271                         else if (first.get())
272                             e->addProperty("contactName",first.get());
273                         else if (last.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());
278                             if (email.get())
279                                 e->addProperty("contactEmail",email.get());
280                         }
281                         break;
282                     }
283                 }
284                 if (e->getProperty("contactName") || e->getProperty("contactEmail")) {
285                     auto_ptr_char eurl(role->getErrorURL());
286                     if (eurl.get()) {
287                         e->addProperty("errorURL",eurl.get());
288                     }
289                 }
290                 break;
291             }
292         }
293     }
294     
295     if (rethrow)
296         e->raise();
297 }
298
299 void opensaml::annotateException(XMLToolingException* e, const RoleDescriptor* role, bool rethrow)
300 {
301     if (role) {
302         auto_ptr_char id(dynamic_cast<EntityDescriptor*>(role->getParent())->getEntityID());
303         e->addProperty("entityID",id.get());
304
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());
317                 }
318                 else if (first.get())
319                     e->addProperty("contactName",first.get());
320                 else if (last.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());
325                     if (email.get())
326                         e->addProperty("contactEmail",email.get());
327                 }
328                 break;
329             }
330         }
331
332         auto_ptr_char eurl(role->getErrorURL());
333         if (eurl.get()) {
334             e->addProperty("errorURL",eurl.get());
335         }
336     }
337     
338     if (rethrow)
339         e->raise();
340 }