Convert from NULL macro to nullptr.
[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/XSECCryptoX509CRL.h"
28 #include "signature/KeyInfo.h"
29
30 #include <algorithm>
31 #include <openssl/x509v3.h>
32 #include <xsec/enc/OpenSSL/OpenSSLCryptoX509.hpp>
33
34 using namespace xmlsignature;
35 using namespace xmltooling;
36 using namespace std;
37
38 Credential::Credential()
39 {
40 }
41
42 Credential::~Credential()
43 {
44 }
45
46 const CredentialContext* Credential::getCredentalContext() const
47 {
48     return nullptr;
49 }
50
51 X509Credential::X509Credential()
52 {
53 }
54
55 X509Credential::~X509Credential()
56 {
57 }
58
59 OpenSSLCredential::OpenSSLCredential()
60 {
61 }
62
63 OpenSSLCredential::~OpenSSLCredential()
64 {
65 }
66
67 CredentialContext::CredentialContext()
68 {
69 }
70
71 CredentialContext::~CredentialContext()
72 {
73 }
74
75 KeyInfoCredentialContext::KeyInfoCredentialContext(const KeyInfo* keyInfo) : m_keyInfo(keyInfo), m_nativeKeyInfo(nullptr)
76 {
77 }
78
79 KeyInfoCredentialContext::KeyInfoCredentialContext(DSIGKeyInfoList* keyInfo) : m_keyInfo(nullptr), m_nativeKeyInfo(keyInfo)
80 {
81 }
82
83 KeyInfoCredentialContext::~KeyInfoCredentialContext()
84 {
85 }
86
87 const KeyInfo* KeyInfoCredentialContext::getKeyInfo() const
88 {
89     return m_keyInfo;
90 }
91
92 DSIGKeyInfoList* KeyInfoCredentialContext::getNativeKeyInfo() const
93 {
94     return m_nativeKeyInfo;
95 }
96
97 BasicX509Credential::BasicX509Credential(bool ownCerts) : m_key(nullptr), m_ownCerts(ownCerts), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
98 {
99 }
100
101 BasicX509Credential::BasicX509Credential(XSECCryptoKey* key, const vector<XSECCryptoX509*>& certs, XSECCryptoX509CRL* crl)
102     : m_key(key), m_xseccerts(certs), m_ownCerts(true), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
103 {
104     if (crl)
105         m_crls.push_back(crl);
106 }
107
108 BasicX509Credential::BasicX509Credential(XSECCryptoKey* key, const vector<XSECCryptoX509*>& certs, const vector<XSECCryptoX509CRL*>& crls)
109     : m_key(key), m_xseccerts(certs), m_ownCerts(true), m_crls(crls), m_keyInfo(nullptr), m_compactKeyInfo(nullptr)
110 {
111 }
112
113 BasicX509Credential::~BasicX509Credential()
114 {
115     delete m_key;
116     if (m_ownCerts)
117         for_each(m_xseccerts.begin(), m_xseccerts.end(), xmltooling::cleanup<XSECCryptoX509>());
118     for_each(m_crls.begin(), m_crls.end(), xmltooling::cleanup<XSECCryptoX509CRL>());
119     delete m_keyInfo;
120     delete m_compactKeyInfo;
121 }
122
123 void BasicX509Credential::initKeyInfo(unsigned int types)
124 {
125     delete m_keyInfo;
126     m_keyInfo = nullptr;
127     delete m_compactKeyInfo;
128     m_compactKeyInfo = nullptr;
129
130     if (types == 0)
131         types = KEYINFO_KEY_VALUE | KEYINFO_KEY_NAME | KEYINFO_X509_CERTIFICATE | KEYINFO_X509_SUBJECTNAME | KEYINFO_X509_ISSUERSERIAL;
132
133     if (types & KEYINFO_KEY_NAME) {
134         const set<string>& names = getKeyNames();
135         if (!names.empty()) {
136             m_compactKeyInfo = KeyInfoBuilder::buildKeyInfo();
137             VectorOf(KeyName) knames = m_compactKeyInfo->getKeyNames();
138             for (set<string>::const_iterator n = names.begin(); n!=names.end(); ++n) {
139                 if (*n == m_subjectName)
140                     continue;
141                 auto_ptr_XMLCh wide(n->c_str());
142                 KeyName* kname = KeyNameBuilder::buildKeyName();
143                 kname->setName(wide.get());
144                 knames.push_back(kname);
145             }
146         }
147     }
148
149     if (types & KEYINFO_X509_SUBJECTNAME || types & KEYINFO_X509_ISSUERSERIAL) {
150         if (!m_subjectName.empty() || (!m_issuerName.empty() && !m_serial.empty())) {
151             if (!m_compactKeyInfo)
152                 m_compactKeyInfo = KeyInfoBuilder::buildKeyInfo();
153             X509Data* x509Data=X509DataBuilder::buildX509Data();
154             m_compactKeyInfo->getX509Datas().push_back(x509Data);
155             if (types & KEYINFO_X509_SUBJECTNAME && !m_subjectName.empty()) {
156                 X509SubjectName* sn = X509SubjectNameBuilder::buildX509SubjectName();
157                 auto_ptr_XMLCh wide(m_subjectName.c_str());
158                 sn->setName(wide.get());
159                 x509Data->getX509SubjectNames().push_back(sn);
160             }
161
162             if (types & KEYINFO_X509_ISSUERSERIAL && !m_issuerName.empty() && !m_serial.empty()) {
163                 X509IssuerSerial* is = X509IssuerSerialBuilder::buildX509IssuerSerial();
164                 X509IssuerName* in = X509IssuerNameBuilder::buildX509IssuerName();
165                 auto_ptr_XMLCh wide(m_issuerName.c_str());
166                 in->setName(wide.get());
167                 is->setX509IssuerName(in);
168                 X509SerialNumber* ser = X509SerialNumberBuilder::buildX509SerialNumber();
169                 auto_ptr_XMLCh wide2(m_serial.c_str());
170                 ser->setSerialNumber(wide2.get());
171                 is->setX509SerialNumber(ser);
172                 x509Data->getX509IssuerSerials().push_back(is);
173             }
174         }
175     }
176
177     if (types & KEYINFO_X509_CERTIFICATE && !m_xseccerts.empty()) {
178         m_keyInfo = m_compactKeyInfo ? m_compactKeyInfo->cloneKeyInfo() : KeyInfoBuilder::buildKeyInfo();
179         if (m_keyInfo->getX509Datas().empty())
180             m_keyInfo->getX509Datas().push_back(X509DataBuilder::buildX509Data());
181         for (vector<XSECCryptoX509*>::const_iterator x = m_xseccerts.begin(); x!=m_xseccerts.end(); ++x) {
182             safeBuffer& buf=(*x)->getDEREncodingSB();
183             X509Certificate* x509=X509CertificateBuilder::buildX509Certificate();
184             x509->setValue(buf.sbStrToXMLCh());
185             m_keyInfo->getX509Datas().front()->getX509Certificates().push_back(x509);
186         }
187     }
188 }
189
190 unsigned int BasicX509Credential::getUsage() const
191 {
192     return UNSPECIFIED_CREDENTIAL;
193 }
194
195 const char* BasicX509Credential::getAlgorithm() const
196 {
197     if (m_key) {
198         switch (m_key->getKeyType()) {
199             case XSECCryptoKey::KEY_RSA_PRIVATE:
200             case XSECCryptoKey::KEY_RSA_PUBLIC:
201             case XSECCryptoKey::KEY_RSA_PAIR:
202                 return "RSA";
203
204             case XSECCryptoKey::KEY_DSA_PRIVATE:
205             case XSECCryptoKey::KEY_DSA_PUBLIC:
206             case XSECCryptoKey::KEY_DSA_PAIR:
207                 return "DSA";
208
209             case XSECCryptoKey::KEY_HMAC:
210                 return "HMAC";
211
212             case XSECCryptoKey::KEY_SYMMETRIC: {
213                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
214                     case XSECCryptoSymmetricKey::KEY_3DES_192:
215                         return "DESede";
216                     case XSECCryptoSymmetricKey::KEY_AES_128:
217                         return "AES";
218                     case XSECCryptoSymmetricKey::KEY_AES_192:
219                         return "AES";
220                     case XSECCryptoSymmetricKey::KEY_AES_256:
221                         return "AES";
222                 }
223             }
224         }
225     }
226     return nullptr;
227 }
228
229 unsigned int BasicX509Credential::getKeySize() 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                 XSECCryptoKeyRSA* rkey = static_cast<XSECCryptoKeyRSA*>(m_key);
237                 return rkey->getLength();
238             }
239
240             case XSECCryptoKey::KEY_SYMMETRIC: {
241                 switch (static_cast<XSECCryptoSymmetricKey*>(m_key)->getSymmetricKeyType()) {
242                     case XSECCryptoSymmetricKey::KEY_3DES_192:
243                         return 192;
244                     case XSECCryptoSymmetricKey::KEY_AES_128:
245                         return 128;
246                     case XSECCryptoSymmetricKey::KEY_AES_192:
247                         return 192;
248                     case XSECCryptoSymmetricKey::KEY_AES_256:
249                         return 256;
250                 }
251             }
252         }
253     }
254     return 0;
255 }
256
257 XSECCryptoKey* BasicX509Credential::getPrivateKey() const
258 {
259     if (m_key) {
260         XSECCryptoKey::KeyType type = m_key->getKeyType();
261         if (type!=XSECCryptoKey::KEY_RSA_PUBLIC && type!=XSECCryptoKey::KEY_DSA_PUBLIC)
262             return m_key;
263     }
264     return nullptr;
265 }
266
267 XSECCryptoKey* BasicX509Credential::getPublicKey() const
268 {
269     if (m_key) {
270         XSECCryptoKey::KeyType type = m_key->getKeyType();
271         if (type!=XSECCryptoKey::KEY_RSA_PRIVATE && type!=XSECCryptoKey::KEY_DSA_PRIVATE)
272             return m_key;
273     }
274     return nullptr;
275 }
276
277 const set<string>& BasicX509Credential::getKeyNames() const
278 {
279     return m_keyNames;
280 }
281
282 KeyInfo* BasicX509Credential::getKeyInfo(bool compact) const
283 {
284     if (compact || !m_keyInfo)
285         return m_compactKeyInfo ? m_compactKeyInfo->cloneKeyInfo() : nullptr;
286     return m_keyInfo->cloneKeyInfo();
287 }
288
289 const vector<XSECCryptoX509*>& BasicX509Credential::getEntityCertificateChain() const
290 {
291     return m_xseccerts;
292 }
293
294 XSECCryptoX509CRL* BasicX509Credential::getCRL() const
295 {
296     return m_crls.empty() ? nullptr : m_crls.front();
297 }
298
299 const vector<XSECCryptoX509CRL*>& BasicX509Credential::getCRLs() const
300 {
301     return m_crls;
302 }
303
304 const char* BasicX509Credential::getSubjectName() const
305 {
306     return m_subjectName.c_str();
307 }
308
309 const char* BasicX509Credential::getIssuerName() const
310 {
311     return m_issuerName.c_str();
312 }
313
314 const char* BasicX509Credential::getSerialNumber() const
315 {
316     return m_serial.c_str();
317 }
318
319 void BasicX509Credential::extract()
320 {
321     XSECCryptoX509* x509 = m_xseccerts.empty() ? nullptr : m_xseccerts.front();
322     if (!x509 || x509->getProviderName()!=DSIGConstants::s_unicodeStrPROVOpenSSL)
323         return;
324     X509* cert = static_cast<OpenSSLCryptoX509*>(x509)->getOpenSSLX509();
325     if (!cert)
326         return;
327
328     X509_NAME* issuer=X509_get_issuer_name(cert);
329     if (issuer) {
330         BIO* b = BIO_new(BIO_s_mem());
331         X509_NAME_print_ex(b,issuer,0,XN_FLAG_RFC2253);
332         BIO_flush(b);
333         BUF_MEM* bptr=nullptr;
334         BIO_get_mem_ptr(b, &bptr);
335         m_issuerName.erase();
336         m_issuerName.append(bptr->data, bptr->length);
337         BIO_free(b);
338     }
339
340     ASN1_INTEGER* serialASN = X509_get_serialNumber(cert);
341     BIGNUM* serialBN = ASN1_INTEGER_to_BN(serialASN, nullptr);
342     if (serialBN) {
343         char* serial = BN_bn2dec(serialBN);
344         if (serial) {
345             m_serial = serial;
346             OPENSSL_free(serial);
347         }
348         BN_free(serialBN);
349     }
350
351     X509_NAME* subject=X509_get_subject_name(cert);
352     if (subject) {
353         BIO* b = BIO_new(BIO_s_mem());
354         X509_NAME_print_ex(b,subject,0,XN_FLAG_RFC2253);
355         BIO_flush(b);
356         BUF_MEM* bptr=nullptr;
357         BIO_get_mem_ptr(b, &bptr);
358         m_subjectName.erase();
359         m_subjectName.append(bptr->data, bptr->length);
360         m_keyNames.insert(m_subjectName);
361         BIO_free(b);
362         
363         // Fetch the last CN RDN.
364         char* peer_CN = nullptr;
365         int j,i = -1;
366         while ((j=X509_NAME_get_index_by_NID(subject, NID_commonName, i)) >= 0)
367             i = j;
368         if (i >= 0) {
369             ASN1_STRING* tmp = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, i));
370             // Copied in from libcurl.
371             /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
372                is already UTF-8 encoded. We check for this case and copy the raw
373                string manually to avoid the problem. */
374             if(tmp && ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
375                 j = ASN1_STRING_length(tmp);
376                 if(j >= 0) {
377                     peer_CN = (char*)OPENSSL_malloc(j + 1);
378                     memcpy(peer_CN, ASN1_STRING_data(tmp), j);
379                     peer_CN[j] = '\0';
380                 }
381             }
382             else /* not a UTF8 name */ {
383                 j = ASN1_STRING_to_UTF8(reinterpret_cast<unsigned char**>(&peer_CN), tmp);
384             }
385             
386             if (j > 0)
387                 m_keyNames.insert(string(peer_CN, j));
388             if(peer_CN)
389                 OPENSSL_free(peer_CN);
390         }
391
392         STACK_OF(GENERAL_NAME)* altnames=(STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, nullptr);
393         if (altnames) {
394             int numalts = sk_GENERAL_NAME_num(altnames);
395             for (int an=0; an<numalts; an++) {
396                 const GENERAL_NAME* check = sk_GENERAL_NAME_value(altnames, an);
397                 if (check->type==GEN_DNS || check->type==GEN_URI) {
398                     const char* altptr = (char*)ASN1_STRING_data(check->d.ia5);
399                     const int altlen = ASN1_STRING_length(check->d.ia5);
400                     if (altlen > 0)
401                         m_keyNames.insert(string(altptr, altlen));
402                 }
403             }
404         }
405         GENERAL_NAMES_free(altnames);
406     }
407 }