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