Moved URLEncoder into separate header, made it a global service.
[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/MessageEncoder.h"
29 #include "binding/SAMLArtifact.h"
30 #include "binding/URLEncoder.h"
31 #include "saml1/core/Assertions.h"
32 #include "saml1/core/Protocols.h"
33 #include "saml2/core/Protocols.h"
34 #include "saml2/metadata/Metadata.h"
35 #include "saml2/metadata/MetadataProvider.h"
36 #include "security/TrustEngine.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     registerMessageEncoders();
117     registerSAMLArtifacts();
118     saml1::registerAssertionClasses();
119     saml1p::registerProtocolClasses();
120     saml2::registerAssertionClasses();
121     saml2p::registerProtocolClasses();
122     saml2md::registerMetadataClasses();
123     saml2md::registerMetadataProviders();
124     saml2md::registerMetadataFilters();
125     registerTrustEngines();
126     
127     m_urlEncoder = new URLEncoder();
128
129     log.info("library initialization complete");
130     return true;
131 }
132
133 void SAMLInternalConfig::term(bool termXMLTooling)
134 {
135 #ifdef _DEBUG
136     xmltooling::NDC ndc("term");
137 #endif
138     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
139
140     saml1::AssertionSchemaValidators.destroyValidators();
141     saml1p::ProtocolSchemaValidators.destroyValidators();
142     saml2::AssertionSchemaValidators.destroyValidators();
143     saml2md::MetadataSchemaValidators.destroyValidators();
144     
145     TrustEngineManager.deregisterFactories();
146     MetadataFilterManager.deregisterFactories();
147     MetadataProviderManager.deregisterFactories();
148     SAMLArtifactManager.deregisterFactories();
149     MessageEncoderManager.deregisterFactories();
150
151     delete m_artifactMap;
152     m_artifactMap = NULL;
153     delete m_urlEncoder;
154     m_urlEncoder = NULL;
155
156     if (termXMLTooling) {
157         XMLToolingConfig::getConfig().term();
158         log.debug("XMLTooling library shut down");
159     }
160     log.info("library shutdown complete");
161 }
162
163 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
164 {
165     try {
166         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
167             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
168     }
169     catch (XSECCryptoException& e) {
170         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
171     }
172 }
173
174 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
175 {
176     buf.erase();
177     auto_ptr<unsigned char> hold(new unsigned char[len]);
178     generateRandomBytes(hold.get(),len);
179     for (unsigned int i=0; i<len; i++)
180         buf+=(hold.get())[i];
181 }
182
183 XMLCh* SAMLInternalConfig::generateIdentifier()
184 {
185     unsigned char key[17];
186     generateRandomBytes(key,16);
187     
188     char hexform[34];
189     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
190             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
191             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
192     hexform[33]=0;
193     return XMLString::transcode(hexform);
194 }
195
196 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
197 {
198     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
199
200     auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
201     if (hasher.get()) {
202         auto_ptr<char> dup(strdup(s));
203         unsigned char buf[21];
204         hasher->hash(reinterpret_cast<unsigned char*>(dup.get()),strlen(dup.get()));
205         if (hasher->finish(buf,20)==20) {
206             string ret;
207             if (toHex) {
208                 for (unsigned int i=0; i<20; i++) {
209                     ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
210                     ret+=(DIGITS[0x0F & buf[i]]);
211                 }
212             }
213             else {
214                 for (unsigned int i=0; i<20; i++) {
215                     ret+=buf[i];
216                 }
217             }
218             return ret;
219         }
220     }
221     throw XMLSecurityException("Unable to generate SHA-1 hash.");
222 }
223
224 void opensaml::log_openssl()
225 {
226     const char* file;
227     const char* data;
228     int flags,line;
229
230     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
231     while (code) {
232         Category& log=Category::getInstance("OpenSSL");
233         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
234         if (data && (flags & ERR_TXT_STRING))
235             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
236         code=ERR_get_error_line_data(&file,&line,&data,&flags);
237     }
238 }