MessageEncoder, ArtifactMap, and SAML 1.x encoder classes.
[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/MessageEncoder.h"
28 #include "binding/SAMLArtifact.h"
29 #include "saml1/core/Assertions.h"
30 #include "saml1/core/Protocols.h"
31 #include "saml2/core/Protocols.h"
32 #include "saml2/metadata/Metadata.h"
33 #include "saml2/metadata/MetadataProvider.h"
34 #include "security/TrustEngine.h"
35 #include "util/SAMLConstants.h"
36
37 #include <xmltooling/XMLToolingConfig.h>
38 #include <xmltooling/signature/Signature.h>
39 #include <xmltooling/util/NDC.h>
40
41 #include <log4cpp/Category.hh>
42 #include <xsec/enc/XSECCryptoException.hpp>
43 #include <xsec/enc/XSECCryptoProvider.hpp>
44 #include <xsec/utils/XSECPlatformUtils.hpp>
45 #include <openssl/err.h>
46
47 using namespace opensaml;
48 using namespace xmlsignature;
49 using namespace xmltooling;
50 using namespace log4cpp;
51 using namespace std;
52
53 // Expose entry points when used as an extension library
54
55 extern "C" int SAML_API xmltooling_extension_init(void*)
56 {
57     if (SAMLConfig::getConfig().init(false))
58         return 0;
59     return -1;
60 }
61
62 extern "C" void SAML_API xmltooling_extension_term()
63 {
64     SAMLConfig::getConfig().term(false);
65 }
66
67 DECL_EXCEPTION_FACTORY(ArtifactException,opensaml);
68 DECL_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
69 DECL_EXCEPTION_FACTORY(BindingException,opensaml);
70
71 namespace opensaml {
72    SAMLInternalConfig g_config;
73 }
74
75 SAMLConfig& SAMLConfig::getConfig()
76 {
77     return g_config;
78 }
79
80 SAMLInternalConfig& SAMLInternalConfig::getInternalConfig()
81 {
82     return g_config;
83 }
84
85 bool SAMLInternalConfig::init(bool initXMLTooling)
86 {
87 #ifdef _DEBUG
88     xmltooling::NDC ndc("init");
89 #endif
90     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
91     log.debug("library initialization started");
92
93     if (initXMLTooling) {
94         XMLToolingConfig::getConfig().init();
95         log.debug("XMLTooling library initialized");
96     }
97
98     REGISTER_EXCEPTION_FACTORY(ArtifactException,opensaml);
99     REGISTER_EXCEPTION_FACTORY(MetadataFilterException,opensaml::saml2md);
100     REGISTER_EXCEPTION_FACTORY(BindingException,opensaml);
101
102     registerMessageEncoders();
103     registerSAMLArtifacts();
104     saml1::registerAssertionClasses();
105     saml1p::registerProtocolClasses();
106     saml2::registerAssertionClasses();
107     saml2p::registerProtocolClasses();
108     saml2md::registerMetadataClasses();
109     saml2md::registerMetadataProviders();
110     saml2md::registerMetadataFilters();
111     registerTrustEngines();
112
113     log.info("library initialization complete");
114     return true;
115 }
116
117 void SAMLInternalConfig::term(bool termXMLTooling)
118 {
119 #ifdef _DEBUG
120     xmltooling::NDC ndc("term");
121 #endif
122     Category& log=Category::getInstance(SAML_LOGCAT".SAMLConfig");
123
124     saml1::AssertionSchemaValidators.destroyValidators();
125     saml1p::ProtocolSchemaValidators.destroyValidators();
126     saml2::AssertionSchemaValidators.destroyValidators();
127     saml2md::MetadataSchemaValidators.destroyValidators();
128     
129     TrustEngineManager.deregisterFactories();
130     MetadataFilterManager.deregisterFactories();
131     MetadataProviderManager.deregisterFactories();
132     SAMLArtifactManager.deregisterFactories();
133     MessageEncoderManager.deregisterFactories();
134
135     delete m_artifactMap;
136     m_artifactMap = NULL;
137
138     if (termXMLTooling) {
139         XMLToolingConfig::getConfig().term();
140         log.debug("XMLTooling library shut down");
141     }
142     log.info("library shutdown complete");
143 }
144
145 void SAMLInternalConfig::generateRandomBytes(void* buf, unsigned int len)
146 {
147     try {
148         if (XSECPlatformUtils::g_cryptoProvider->getRandom(reinterpret_cast<unsigned char*>(buf),len)<len)
149             throw XMLSecurityException("Unable to generate random data; was PRNG seeded?");
150     }
151     catch (XSECCryptoException& e) {
152         throw XMLSecurityException("Unable to generate random data: $1",params(1,e.getMsg()));
153     }
154 }
155
156 void SAMLInternalConfig::generateRandomBytes(std::string& buf, unsigned int len)
157 {
158     buf.erase();
159     auto_ptr<unsigned char> hold(new unsigned char[len]);
160     generateRandomBytes(hold.get(),len);
161     for (unsigned int i=0; i<len; i++)
162         buf+=(hold.get())[i];
163 }
164
165 XMLCh* SAMLInternalConfig::generateIdentifier()
166 {
167     unsigned char key[17];
168     generateRandomBytes(key,16);
169     
170     char hexform[34];
171     sprintf(hexform,"_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
172             key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7],
173             key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15]);
174     hexform[33]=0;
175     return XMLString::transcode(hexform);
176 }
177
178 string SAMLInternalConfig::hashSHA1(const char* s, bool toHex)
179 {
180     static char DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
181
182     auto_ptr<XSECCryptoHash> hasher(XSECPlatformUtils::g_cryptoProvider->hashSHA1());
183     if (hasher.get()) {
184         auto_ptr<char> dup(strdup(s));
185         unsigned char buf[21];
186         hasher->hash(reinterpret_cast<unsigned char*>(dup.get()),strlen(dup.get()));
187         if (hasher->finish(buf,20)==20) {
188             string ret;
189             if (toHex) {
190                 for (unsigned int i=0; i<20; i++) {
191                     ret+=(DIGITS[((unsigned char)(0xF0 & buf[i])) >> 4 ]);
192                     ret+=(DIGITS[0x0F & buf[i]]);
193                 }
194             }
195             else {
196                 for (unsigned int i=0; i<20; i++) {
197                     ret+=buf[i];
198                 }
199             }
200             return ret;
201         }
202     }
203     throw XMLSecurityException("Unable to generate SHA-1 hash.");
204 }
205
206 void opensaml::log_openssl()
207 {
208     const char* file;
209     const char* data;
210     int flags,line;
211
212     unsigned long code=ERR_get_error_line_data(&file,&line,&data,&flags);
213     while (code) {
214         Category& log=Category::getInstance("OpenSSL");
215         log.errorStream() << "error code: " << code << " in " << file << ", line " << line << CategoryStream::ENDLINE;
216         if (data && (flags & ERR_TXT_STRING))
217             log.errorStream() << "error data: " << data << CategoryStream::ENDLINE;
218         code=ERR_get_error_line_data(&file,&line,&data,&flags);
219     }
220 }