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