https://issues.shibboleth.net/jira/browse/CPPXT-90
[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, false);
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                 x509dig->setAlgorithm(DSIGConstants::s_unicodeStrURISHA1);
223                 m_compactKeyInfo->getX509Datas().front()->getX509Digests().push_back(x509dig);
224             }
225         }
226     }
227 }
228
229 unsigned int BasicX509Credential::getUsage() const
230 {
231     return UNSPECIFIED_CREDENTIAL;
232 }
233
234 const char* BasicX509Credential::getAlgorithm() const
235 {
236     if (m_key) {
237         switch (m_key->getKeyType()) {
238             case XSECCryptoKey::KEY_RSA_PRIVATE:
239             case XSECCryptoKey::KEY_RSA_PUBLIC:
240             case XSECCryptoKey::KEY_RSA_PAIR:
241                 return "RSA";
242
243             case XSECCryptoKey::KEY_DSA_PRIVATE:
244             case XSECCryptoKey::KEY_DSA_PUBLIC:
245             case XSECCryptoKey::KEY_DSA_PAIR:
246                 return "DSA";
247
248 #ifdef XMLTOOLING_XMLSEC_ECC
249             case XSECCryptoKey::KEY_EC_PRIVATE:
250             case XSECCryptoKey::KEY_EC_PUBLIC:
251             case XSECCryptoKey::KEY_EC_PAIR:
252                 return "EC";
253 #endif
254
255             case XSECCryptoKey::KEY_HMAC:
256                 return "HMAC";
257
258             case XSECCryptoKey::KEY_SYMMETRIC: {
259                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
260                     case XSECCryptoSymmetricKey::KEY_3DES_192:
261                         return "DESede";
262                     case XSECCryptoSymmetricKey::KEY_AES_128:
263                         return "AES";
264                     case XSECCryptoSymmetricKey::KEY_AES_192:
265                         return "AES";
266                     case XSECCryptoSymmetricKey::KEY_AES_256:
267                         return "AES";
268                 }
269             }
270         }
271     }
272     return nullptr;
273 }
274
275 unsigned int BasicX509Credential::getKeySize() const
276 {
277     if (m_key) {
278         switch (m_key->getKeyType()) {
279             case XSECCryptoKey::KEY_RSA_PRIVATE:
280             case XSECCryptoKey::KEY_RSA_PUBLIC:
281             case XSECCryptoKey::KEY_RSA_PAIR: {
282                 XSECCryptoKeyRSA* rkey = static_cast<XSECCryptoKeyRSA*>(m_key);
283                 return 8 * rkey->getLength();
284             }
285
286             case XSECCryptoKey::KEY_SYMMETRIC: {
287                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
288                     case XSECCryptoSymmetricKey::KEY_3DES_192:
289                         return 192;
290                     case XSECCryptoSymmetricKey::KEY_AES_128:
291                         return 128;
292                     case XSECCryptoSymmetricKey::KEY_AES_192:
293                         return 192;
294                     case XSECCryptoSymmetricKey::KEY_AES_256:
295                         return 256;
296                 }
297             }
298         }
299     }
300     return 0;
301 }
302
303 XSECCryptoKey* BasicX509Credential::getPrivateKey() const
304 {
305     if (m_key) {
306         XSECCryptoKey::KeyType type = m_key->getKeyType();
307         if (type != XSECCryptoKey::KEY_RSA_PUBLIC && type != XSECCryptoKey::KEY_DSA_PUBLIC
308 #ifdef XMLTOOLING_XMLSEC_ECC
309             && type != XSECCryptoKey::KEY_EC_PUBLIC
310 #endif
311             )
312             return m_key;
313     }
314     return nullptr;
315 }
316
317 XSECCryptoKey* BasicX509Credential::getPublicKey() const
318 {
319     if (m_key) {
320         XSECCryptoKey::KeyType type = m_key->getKeyType();
321         if (type != XSECCryptoKey::KEY_RSA_PRIVATE && type != XSECCryptoKey::KEY_DSA_PRIVATE
322 #ifdef XMLTOOLING_XMLSEC_ECC
323             && type != XSECCryptoKey::KEY_EC_PRIVATE
324 #endif
325             )
326             return m_key;
327     }
328     return nullptr;
329 }
330
331 const set<string>& BasicX509Credential::getKeyNames() const
332 {
333     return m_keyNames;
334 }
335
336 KeyInfo* BasicX509Credential::getKeyInfo(bool compact) const
337 {
338     if (compact || !m_keyInfo)
339         return m_compactKeyInfo ? m_compactKeyInfo->cloneKeyInfo() : nullptr;
340     return m_keyInfo->cloneKeyInfo();
341 }
342
343 const vector<XSECCryptoX509*>& BasicX509Credential::getEntityCertificateChain() const
344 {
345     return m_xseccerts;
346 }
347
348 XSECCryptoX509CRL* BasicX509Credential::getCRL() const
349 {
350     return m_crls.empty() ? nullptr : m_crls.front();
351 }
352
353 const vector<XSECCryptoX509CRL*>& BasicX509Credential::getCRLs() const
354 {
355     return m_crls;
356 }
357
358 const char* BasicX509Credential::getSubjectName() const
359 {
360     return m_subjectName.c_str();
361 }
362
363 const char* BasicX509Credential::getIssuerName() const
364 {
365     return m_issuerName.c_str();
366 }
367
368 const char* BasicX509Credential::getSerialNumber() const
369 {
370     return m_serial.c_str();
371 }
372
373 void BasicX509Credential::extract()
374 {
375     XSECCryptoX509* x509 = m_xseccerts.empty() ? nullptr : m_xseccerts.front();
376     if (!x509 || x509->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL)
377         return;
378     X509* cert = static_cast<OpenSSLCryptoX509*>(x509)->getOpenSSLX509();
379     if (!cert)
380         return;
381
382     X509_NAME* issuer=X509_get_issuer_name(cert);
383     if (issuer) {
384         BIO* b = BIO_new(BIO_s_mem());
385         X509_NAME_print_ex(b,issuer,0,XN_FLAG_RFC2253);
386         BIO_flush(b);
387         BUF_MEM* bptr=nullptr;
388         BIO_get_mem_ptr(b, &bptr);
389         m_issuerName.erase();
390         m_issuerName.append(bptr->data, bptr->length);
391         BIO_free(b);
392     }
393
394     ASN1_INTEGER* serialASN = X509_get_serialNumber(cert);
395     BIGNUM* serialBN = ASN1_INTEGER_to_BN(serialASN, nullptr);
396     if (serialBN) {
397         char* serial = BN_bn2dec(serialBN);
398         if (serial) {
399             m_serial = serial;
400             OPENSSL_free(serial);
401         }
402         BN_free(serialBN);
403     }
404
405     X509_NAME* subject=X509_get_subject_name(cert);
406     if (subject) {
407         BIO* b = BIO_new(BIO_s_mem());
408         X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
409         BIO_flush(b);
410         BUF_MEM* bptr=nullptr;
411         BIO_get_mem_ptr(b, &bptr);
412         m_subjectName.erase();
413         m_subjectName.append(bptr->data, bptr->length);
414         m_keyNames.insert(m_subjectName);
415         BIO_free(b);
416         
417         // Fetch the last CN RDN.
418         char* peer_CN = nullptr;
419         int j,i = -1;
420         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
421             i = j;
422         if (i >= 0) {
423             ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
424             // Copied in from libcurl.
425             /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
426                is already UTF-8 encoded. We check for this case and copy the raw
427                string manually to avoid the problem. */
428             if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
429                 j = ASN1_STRING_length(tmp);
430                 if(j >= 0) {
431                     peer_CN = (char*)OPENSSL_malloc(j + 1);
432                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
433                     peer_CN[j] = '\0';
434                 }
435             }
436             else /* not a UTF8 name */ {
437                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
438             }
439             
440             if (j > 0)
441                 m_keyNames.insert(string(peer_CN, j));
442             if(peer_CN)
443                 OPENSSL_free(peer_CN);
444         }
445
446         STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr);
447         if (altnames) {
448             int numalts = sk_GENERAL_NAME_num(altnames);
449             for (int an=0; an<numalts; an++) {
450                 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
451                 if (check->type==GEN_DNS || check->type==GEN_URI) {
452                     const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
453                     const int altlen = ASN1_STRING_length(check->d.ia5);
454                     if (altlen > 0)
455                         m_keyNames.insert(string(altptr, altlen));
456                 }
457             }
458         }
459         GENERAL_NAMES_free(altnames);
460     }
461 }