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