9fda0b06cda247dddea7706c46cc187db0e0afa9
[shibboleth/cpp-xmltooling.git] / xmltooling / security / impl / BasicX509Credential.cpp
1 /*
2  *  Copyright 2001-2010 Internet2
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * BasicX509Credential.cpp
19  *
20  * Wraps an X.509-based Credential by storing key/cert objects inside.
21  */
22
23 #include "internal.h"
24 #include "security/BasicX509Credential.h"
25 #include "security/KeyInfoCredentialContext.h"
26 #include "security/OpenSSLCredential.h"
27 #include "security/SecurityHelper.h"
28 #include "security/XSECCryptoX509CRL.h"
29 #include "signature/KeyInfo.h"
30
31 #include <algorithm>
32 #include <openssl/x509v3.h>
33 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
34 #include <xercesc/util/Base64.hpp>
35
36 using namespace xmlsignature;
37 using namespace xmltooling;
38 using namespace xercesc;
39 using namespace std;
40
41 Credential::Credential()
42 {
43 }
44
45 Credential::~Credential()
46 {
47 }
48
49 const CredentialContext* Credential::getCredentalContext() const
50 {
51     return nullptr;
52 }
53
54 X509Credential::X509Credential()
55 {
56 }
57
58 X509Credential::~X509Credential()
59 {
60 }
61
62 OpenSSLCredential::OpenSSLCredential()
63 {
64 }
65
66 OpenSSLCredential::~OpenSSLCredential()
67 {
68 }
69
70 CredentialContext::CredentialContext()
71 {
72 }
73
74 CredentialContext::~CredentialContext()
75 {
76 }
77
78 KeyInfoCredentialContext::KeyInfoCredentialContext(const KeyInfo* keyInfo) : m_keyInfo(keyInfo), m_nativeKeyInfo(nullptr)
79 {
80 }
81
82 KeyInfoCredentialContext::KeyInfoCredentialContext(DSIGKeyInfoList* keyInfo) : m_keyInfo(nullptr), m_nativeKeyInfo(keyInfo)
83 {
84 }
85
86 KeyInfoCredentialContext::~KeyInfoCredentialContext()
87 {
88 }
89
90 const KeyInfo* KeyInfoCredentialContext::getKeyInfo() const
91 {
92     return m_keyInfo;
93 }
94
95 DSIGKeyInfoList* KeyInfoCredentialContext::getNativeKeyInfo() const
96 {
97     return m_nativeKeyInfo;
98 }
99
100 BasicX509Credential::BasicX509Credential(bool ownCerts) : m_key(nullptr), m_ownCerts(ownCerts), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
101 {
102 }
103
104 BasicX509Credential::BasicX509Credential(XSECCryptoKey* key, const vector<XSECCryptoX509*>& certs, XSECCryptoX509CRL* crl)
105     : m_key(key), m_xseccerts(certs), m_ownCerts(true), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
106 {
107     if (crl)
108         m_crls.push_back(crl);
109 }
110
111 BasicX509Credential::BasicX509Credential(XSECCryptoKey* key, const vector<XSECCryptoX509*>& certs, const vector<XSECCryptoX509CRL*>& crls)
112     : m_key(key), m_xseccerts(certs), m_ownCerts(true), m_crls(crls), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
113 {
114 }
115
116 BasicX509Credential::~BasicX509Credential()
117 {
118     delete m_key;
119     if (m_ownCerts)
120         for_each(m_xseccerts.begin(), m_xseccerts.end(), xmltooling::cleanup<XSECCryptoX509>());
121     for_each(m_crls.begin(), m_crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
122     delete m_keyInfo;
123     delete m_compactKeyInfo;
124 }
125
126 void BasicX509Credential::initKeyInfo(unsigned int types)
127 {
128     delete m_keyInfo;
129     m_keyInfo = nullptr;
130     delete m_compactKeyInfo;
131     m_compactKeyInfo = nullptr;
132
133     // Default will disable X509IssuerSerial due to schema validation issues.
134     if (types == 0)
135         types = KEYINFO_KEY_VALUE | KEYINFO_KEY_NAME | KEYINFO_X509_CERTIFICATE | KEYINFO_X509_SUBJECTNAME | KEYINFO_X509_DIGEST;
136
137     if (types & KEYINFO_KEY_NAME) {
138         const set<string>& names = getKeyNames();
139         if (!names.empty()) {
140             m_compactKeyInfo = KeyInfoBuilder::buildKeyInfo();
141             VectorOf(KeyName) knames = m_compactKeyInfo->getKeyNames();
142             for (set<string>::const_iterator n = names.begin(); n!=names.end(); ++n) {
143                 if (*n == m_subjectName)
144                     continue;
145                 auto_ptr_XMLCh wide(n->c_str());
146                 KeyName* kname = KeyNameBuilder::buildKeyName();
147                 kname->setName(wide.get());
148                 knames.push_back(kname);
149             }
150         }
151     }
152
153     if (types & KEYINFO_X509_SUBJECTNAME || types & KEYINFO_X509_ISSUERSERIAL) {
154         if (!m_subjectName.empty() || (!m_issuerName.empty() && !m_serial.empty())) {
155             if (!m_compactKeyInfo)
156                 m_compactKeyInfo = KeyInfoBuilder::buildKeyInfo();
157             X509Data* x509Data=X509DataBuilder::buildX509Data();
158             m_compactKeyInfo->getX509Datas().push_back(x509Data);
159             if (types & KEYINFO_X509_SUBJECTNAME && !m_subjectName.empty()) {
160                 X509SubjectName* sn = X509SubjectNameBuilder::buildX509SubjectName();
161                 auto_ptr_XMLCh wide(m_subjectName.c_str());
162                 sn->setName(wide.get());
163                 x509Data->getX509SubjectNames().push_back(sn);
164             }
165
166             if (types & KEYINFO_X509_ISSUERSERIAL && !m_issuerName.empty() && !m_serial.empty()) {
167                 X509IssuerSerial* is = X509IssuerSerialBuilder::buildX509IssuerSerial();
168                 X509IssuerName* in = X509IssuerNameBuilder::buildX509IssuerName();
169                 auto_ptr_XMLCh wide(m_issuerName.c_str());
170                 in->setName(wide.get());
171                 is->setX509IssuerName(in);
172                 X509SerialNumber* ser = X509SerialNumberBuilder::buildX509SerialNumber();
173                 auto_ptr_XMLCh wide2(m_serial.c_str());
174                 ser->setSerialNumber(wide2.get());
175                 is->setX509SerialNumber(ser);
176                 x509Data->getX509IssuerSerials().push_back(is);
177             }
178         }
179     }
180
181     if (types & KEYINFO_X509_CERTIFICATE && !m_xseccerts.empty()) {
182         m_keyInfo = m_compactKeyInfo ? m_compactKeyInfo->cloneKeyInfo() : KeyInfoBuilder::buildKeyInfo();
183         if (m_keyInfo->getX509Datas().empty())
184             m_keyInfo->getX509Datas().push_back(X509DataBuilder::buildX509Data());
185         for (vector<XSECCryptoX509*>::const_iterator x = m_xseccerts.begin(); x!=m_xseccerts.end(); ++x) {
186             safeBuffer& buf=(*x)->getDEREncodingSB();
187             X509Certificate* x509=X509CertificateBuilder::buildX509Certificate();
188             x509->setValue(buf.sbStrToXMLCh());
189             m_keyInfo->getX509Datas().front()->getX509Certificates().push_back(x509);
190         }
191     }
192
193     if (types & KEYINFO_X509_DIGEST && !m_xseccerts.empty()) {
194         if (!m_compactKeyInfo)
195             m_compactKeyInfo = KeyInfoBuilder::buildKeyInfo();
196         if (m_compactKeyInfo->getX509Datas().empty())
197             m_compactKeyInfo->getX509Datas().push_back(X509DataBuilder::buildX509Data());
198         safeBuffer& buf=m_xseccerts.front()->getDEREncodingSB();
199         xsecsize_t x;
200         XMLByte* decoded = Base64::decode(reinterpret_cast<const XMLByte*>(buf.rawCharBuffer()), &x);
201         if (decoded) {
202             string xdig = SecurityHelper::doHash("SHA1", reinterpret_cast<char*>(decoded), x);
203 #ifdef XMLTOOLING_XERCESC_HAS_XMLBYTE_RELEASE
204             XMLString::release(&decoded);
205 #else
206             XMLString::release((char**)&decoded);
207 #endif
208             XMLByte* encoded = Base64::encode(reinterpret_cast<const XMLByte*>(xdig.c_str()), xdig.length(), &x);
209             if (encoded) {
210                 auto_ptr_XMLCh widenit(reinterpret_cast<char*>(encoded));
211 #ifdef XMLTOOLING_XERCESC_HAS_XMLBYTE_RELEASE
212                 XMLString::release(&encoded);
213 #else
214                 XMLString::release((char**)&encoded);
215 #endif
216                 X509Digest* x509dig = X509DigestBuilder::buildX509Digest();
217                 x509dig->setValue(widenit.get());
218                 m_compactKeyInfo->getX509Datas().front()->getX509Digests().push_back(x509dig);
219             }
220         }
221     }
222 }
223
224 unsigned int BasicX509Credential::getUsage() const
225 {
226     return UNSPECIFIED_CREDENTIAL;
227 }
228
229 const char* BasicX509Credential::getAlgorithm() const
230 {
231     if (m_key) {
232         switch (m_key->getKeyType()) {
233             case XSECCryptoKey::KEY_RSA_PRIVATE:
234             case XSECCryptoKey::KEY_RSA_PUBLIC:
235             case XSECCryptoKey::KEY_RSA_PAIR:
236                 return "RSA";
237
238             case XSECCryptoKey::KEY_DSA_PRIVATE:
239             case XSECCryptoKey::KEY_DSA_PUBLIC:
240             case XSECCryptoKey::KEY_DSA_PAIR:
241                 return "DSA";
242
243 #ifdef XMLTOOLING_XMLSEC_ECC
244             case XSECCryptoKey::KEY_EC_PRIVATE:
245             case XSECCryptoKey::KEY_EC_PUBLIC:
246             case XSECCryptoKey::KEY_EC_PAIR:
247                 return "EC";
248 #endif
249
250             case XSECCryptoKey::KEY_HMAC:
251                 return "HMAC";
252
253             case XSECCryptoKey::KEY_SYMMETRIC: {
254                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
255                     case XSECCryptoSymmetricKey::KEY_3DES_192:
256                         return "DESede";
257                     case XSECCryptoSymmetricKey::KEY_AES_128:
258                         return "AES";
259                     case XSECCryptoSymmetricKey::KEY_AES_192:
260                         return "AES";
261                     case XSECCryptoSymmetricKey::KEY_AES_256:
262                         return "AES";
263                 }
264             }
265         }
266     }
267     return nullptr;
268 }
269
270 unsigned int BasicX509Credential::getKeySize() const
271 {
272     if (m_key) {
273         switch (m_key->getKeyType()) {
274             case XSECCryptoKey::KEY_RSA_PRIVATE:
275             case XSECCryptoKey::KEY_RSA_PUBLIC:
276             case XSECCryptoKey::KEY_RSA_PAIR: {
277                 XSECCryptoKeyRSA* rkey = static_cast<XSECCryptoKeyRSA*>(m_key);
278                 return 8 * rkey->getLength();
279             }
280
281             case XSECCryptoKey::KEY_SYMMETRIC: {
282                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
283                     case XSECCryptoSymmetricKey::KEY_3DES_192:
284                         return 192;
285                     case XSECCryptoSymmetricKey::KEY_AES_128:
286                         return 128;
287                     case XSECCryptoSymmetricKey::KEY_AES_192:
288                         return 192;
289                     case XSECCryptoSymmetricKey::KEY_AES_256:
290                         return 256;
291                 }
292             }
293         }
294     }
295     return 0;
296 }
297
298 XSECCryptoKey* BasicX509Credential::getPrivateKey() const
299 {
300     if (m_key) {
301         XSECCryptoKey::KeyType type = m_key->getKeyType();
302         if (type != XSECCryptoKey::KEY_RSA_PUBLIC && type != XSECCryptoKey::KEY_DSA_PUBLIC
303 #ifdef XMLTOOLING_XMLSEC_ECC
304             && type != XSECCryptoKey::KEY_EC_PUBLIC
305 #endif
306             )
307             return m_key;
308     }
309     return nullptr;
310 }
311
312 XSECCryptoKey* BasicX509Credential::getPublicKey() const
313 {
314     if (m_key) {
315         XSECCryptoKey::KeyType type = m_key->getKeyType();
316         if (type != XSECCryptoKey::KEY_RSA_PRIVATE && type != XSECCryptoKey::KEY_DSA_PRIVATE
317 #ifdef XMLTOOLING_XMLSEC_ECC
318             && type != XSECCryptoKey::KEY_EC_PRIVATE
319 #endif
320             )
321             return m_key;
322     }
323     return nullptr;
324 }
325
326 const set<string>& BasicX509Credential::getKeyNames() const
327 {
328     return m_keyNames;
329 }
330
331 KeyInfo* BasicX509Credential::getKeyInfo(bool compact) const
332 {
333     if (compact || !m_keyInfo)
334         return m_compactKeyInfo ? m_compactKeyInfo->cloneKeyInfo() : nullptr;
335     return m_keyInfo->cloneKeyInfo();
336 }
337
338 const vector<XSECCryptoX509*>& BasicX509Credential::getEntityCertificateChain() const
339 {
340     return m_xseccerts;
341 }
342
343 XSECCryptoX509CRL* BasicX509Credential::getCRL() const
344 {
345     return m_crls.empty() ? nullptr : m_crls.front();
346 }
347
348 const vector<XSECCryptoX509CRL*>& BasicX509Credential::getCRLs() const
349 {
350     return m_crls;
351 }
352
353 const char* BasicX509Credential::getSubjectName() const
354 {
355     return m_subjectName.c_str();
356 }
357
358 const char* BasicX509Credential::getIssuerName() const
359 {
360     return m_issuerName.c_str();
361 }
362
363 const char* BasicX509Credential::getSerialNumber() const
364 {
365     return m_serial.c_str();
366 }
367
368 void BasicX509Credential::extract()
369 {
370     XSECCryptoX509* x509 = m_xseccerts.empty() ? nullptr : m_xseccerts.front();
371     if (!x509 || x509->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL)
372         return;
373     X509* cert = static_cast<OpenSSLCryptoX509*>(x509)->getOpenSSLX509();
374     if (!cert)
375         return;
376
377     X509_NAME* issuer=X509_get_issuer_name(cert);
378     if (issuer) {
379         BIO* b = BIO_new(BIO_s_mem());
380         X509_NAME_print_ex(b,issuer,0,XN_FLAG_RFC2253);
381         BIO_flush(b);
382         BUF_MEM* bptr=nullptr;
383         BIO_get_mem_ptr(b, &bptr);
384         m_issuerName.erase();
385         m_issuerName.append(bptr->data, bptr->length);
386         BIO_free(b);
387     }
388
389     ASN1_INTEGER* serialASN = X509_get_serialNumber(cert);
390     BIGNUM* serialBN = ASN1_INTEGER_to_BN(serialASN, nullptr);
391     if (serialBN) {
392         char* serial = BN_bn2dec(serialBN);
393         if (serial) {
394             m_serial = serial;
395             OPENSSL_free(serial);
396         }
397         BN_free(serialBN);
398     }
399
400     X509_NAME* subject=X509_get_subject_name(cert);
401     if (subject) {
402         BIO* b = BIO_new(BIO_s_mem());
403         X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
404         BIO_flush(b);
405         BUF_MEM* bptr=nullptr;
406         BIO_get_mem_ptr(b, &bptr);
407         m_subjectName.erase();
408         m_subjectName.append(bptr->data, bptr->length);
409         m_keyNames.insert(m_subjectName);
410         BIO_free(b);
411         
412         // Fetch the last CN RDN.
413         char* peer_CN = nullptr;
414         int j,i = -1;
415         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
416             i = j;
417         if (i >= 0) {
418             ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
419             // Copied in from libcurl.
420             /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
421                is already UTF-8 encoded. We check for this case and copy the raw
422                string manually to avoid the problem. */
423             if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
424                 j = ASN1_STRING_length(tmp);
425                 if(j >= 0) {
426                     peer_CN = (char*)OPENSSL_malloc(j + 1);
427                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
428                     peer_CN[j] = '\0';
429                 }
430             }
431             else /* not a UTF8 name */ {
432                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
433             }
434             
435             if (j > 0)
436                 m_keyNames.insert(string(peer_CN, j));
437             if(peer_CN)
438                 OPENSSL_free(peer_CN);
439         }
440
441         STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr);
442         if (altnames) {
443             int numalts = sk_GENERAL_NAME_num(altnames);
444             for (int an=0; an<numalts; an++) {
445                 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
446                 if (check->type==GEN_DNS || check->type==GEN_URI) {
447                     const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
448                     const int altlen = ASN1_STRING_length(check->d.ia5);
449                     if (altlen > 0)
450                         m_keyNames.insert(string(altptr, altlen));
451                 }
452             }
453         }
454         GENERAL_NAMES_free(altnames);
455     }
456 }