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