2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /** @file src/certificates.cc
21 * @brief Certificate and CertificateChain classes.
25 #include "certificates.h"
26 #include "compose.hpp"
27 #include "exceptions.h"
29 #include <libxml++/nodes/element.h>
30 #include <openssl/x509.h>
31 #include <openssl/ssl.h>
32 #include <openssl/asn1.h>
33 #include <openssl/err.h>
34 #include <boost/algorithm/string.hpp>
41 using boost::shared_ptr;
44 /** @param c X509 certificate, which this object will take ownership of */
45 Certificate::Certificate (X509* c)
52 /** Load an X509 certificate from a file.
53 * @param filename File to load.
55 Certificate::Certificate (boost::filesystem::path filename)
59 FILE* f = fopen_boost (filename, "r");
61 throw FileError ("could not open file", filename, errno);
64 if (!PEM_read_X509 (f, &_certificate, 0, 0)) {
65 throw MiscError ("could not read X509 certificate");
69 /** Load an X509 certificate from a string.
70 * @param cert String to read from.
72 Certificate::Certificate (string cert)
80 * @param other Certificate to copy.
82 Certificate::Certificate (Certificate const & other)
86 read_string (other.certificate (true));
89 /** Read a certificate from a string.
90 * @param cert String to read.
93 Certificate::read_string (string cert)
95 BIO* bio = BIO_new_mem_buf (const_cast<char *> (cert.c_str ()), -1);
97 throw MiscError ("could not create memory BIO");
100 _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
102 throw MiscError ("could not read X509 certificate from memory BIO");
109 Certificate::~Certificate ()
111 X509_free (_certificate);
112 RSA_free (_public_key);
115 /** operator= for Certificate.
116 * @param other Certificate to read from.
119 Certificate::operator= (Certificate const & other)
121 if (this == &other) {
125 X509_free (_certificate);
127 RSA_free (_public_key);
130 read_string (other.certificate ());
135 /** Return the certificate as a string.
136 * @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
137 * @return Certificate string.
140 Certificate::certificate (bool with_begin_end) const
142 assert (_certificate);
144 BIO* bio = BIO_new (BIO_s_mem ());
146 throw MiscError ("could not create memory BIO");
149 PEM_write_bio_X509 (bio, _certificate);
153 long int const data_length = BIO_get_mem_data (bio, &data);
154 for (long int i = 0; i < data_length; ++i) {
160 if (!with_begin_end) {
161 boost::replace_all (s, "-----BEGIN CERTIFICATE-----\n", "");
162 boost::replace_all (s, "\n-----END CERTIFICATE-----\n", "");
168 /** @return Certificate's issuer, in the form
169 * dnqualifier=<dnQualififer>,CN=<commonName>,OU=<organizationalUnitName>,O=<organizationName>
170 * and with + signs escaped to \+
173 Certificate::issuer () const
175 assert (_certificate);
176 return name_for_xml (X509_get_issuer_name (_certificate));
180 Certificate::asn_to_utf8 (ASN1_STRING* s)
182 unsigned char* buf = 0;
183 ASN1_STRING_to_UTF8 (&buf, s);
184 string const u (reinterpret_cast<char *> (buf));
190 Certificate::get_name_part (X509_NAME* n, int nid)
193 p = X509_NAME_get_index_by_NID (n, nid, p);
195 return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
200 Certificate::name_for_xml (X509_NAME * n)
204 string s = String::compose (
205 "dnQualifier=%1,CN=%2,OU=%3,O=%4",
206 get_name_part (n, NID_dnQualifier),
207 get_name_part (n, NID_commonName),
208 get_name_part (n, NID_organizationalUnitName),
209 get_name_part (n, NID_organizationName)
212 boost::replace_all (s, "+", "\\+");
217 Certificate::subject () const
219 assert (_certificate);
221 return name_for_xml (X509_get_subject_name (_certificate));
225 Certificate::common_name () const
227 assert (_certificate);
229 return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
233 Certificate::serial () const
235 assert (_certificate);
237 ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
240 BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
241 char* c = BN_bn2dec (b);
251 Certificate::thumbprint () const
253 assert (_certificate);
255 uint8_t buffer[8192];
257 i2d_X509_CINF (_certificate->cert_info, &p);
258 int const length = p - buffer;
260 throw MiscError ("buffer too small to generate thumbprint");
265 SHA1_Update (&sha, buffer, length);
267 SHA1_Final (digest, &sha);
269 char digest_base64[64];
270 return Kumu::base64encode (digest, 20, digest_base64, 64);
273 /** @return RSA public key from this Certificate. Caller must not free the returned value. */
275 Certificate::public_key () const
277 assert (_certificate);
283 EVP_PKEY* key = X509_get_pubkey (_certificate);
285 throw MiscError ("could not get public key from certificate");
288 _public_key = EVP_PKEY_get1_RSA (key);
290 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
296 /** @return Root certificate */
297 shared_ptr<const Certificate>
298 CertificateChain::root () const
300 assert (!_certificates.empty());
301 return _certificates.front ();
304 /** @return Leaf certificate */
305 shared_ptr<const Certificate>
306 CertificateChain::leaf () const
308 assert (_certificates.size() >= 2);
309 return _certificates.back ();
312 /** @return Certificates in order from root to leaf */
313 CertificateChain::List
314 CertificateChain::root_to_leaf () const
316 return _certificates;
319 /** @return Certificates in order from leaf to root */
320 CertificateChain::List
321 CertificateChain::leaf_to_root () const
323 List c = _certificates;
328 /** Add a certificate to the end of the chain.
329 * @param c Certificate to add.
332 CertificateChain::add (shared_ptr<const Certificate> c)
334 _certificates.push_back (c);
338 CertificateChain::remove (shared_ptr<const Certificate> c)
340 _certificates.remove (c);
343 /** Remove the i'th certificate in the list, as listed
347 CertificateChain::remove (int i)
349 List::iterator j = _certificates.begin ();
350 while (j != _certificates.end () && i > 0) {
355 if (j != _certificates.end ()) {
356 _certificates.erase (j);
360 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
361 * signs the leaf and so on).
362 * @return true if it's ok, false if not.
365 CertificateChain::valid () const
367 X509_STORE* store = X509_STORE_new ();
372 for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
374 List::const_iterator j = i;
376 if (j == _certificates.end ()) {
380 if (!X509_STORE_add_cert (store, (*i)->x509 ())) {
381 X509_STORE_free (store);
385 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
387 X509_STORE_free (store);
391 X509_STORE_set_flags (store, 0);
392 if (!X509_STORE_CTX_init (ctx, store, (*j)->x509 (), 0)) {
393 X509_STORE_CTX_free (ctx);
394 X509_STORE_free (store);
398 int v = X509_verify_cert (ctx);
399 X509_STORE_CTX_free (ctx);
402 X509_STORE_free (store);
407 X509_STORE_free (store);
411 /** @return true if the chain is now in order from root to leaf,
412 * false if no correct order was found.
415 CertificateChain::attempt_reorder ()
417 List original = _certificates;
418 _certificates.sort ();
423 } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
425 _certificates = original;