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