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