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 "dcp_assert.h"
30 #include <libxml++/nodes/element.h>
31 #include <openssl/x509.h>
32 #include <openssl/ssl.h>
33 #include <openssl/asn1.h>
34 #include <openssl/err.h>
35 #include <boost/algorithm/string.hpp>
44 /** @param c X509 certificate, which this object will take ownership of */
45 Certificate::Certificate (X509* c)
52 /** Load an X509 certificate from a string.
53 * @param cert String to read from.
55 Certificate::Certificate (string cert)
63 * @param other Certificate to copy.
65 Certificate::Certificate (Certificate const & other)
69 read_string (other.certificate (true));
72 /** Read a certificate from a string.
73 * @param cert String to read.
76 Certificate::read_string (string cert)
78 BIO* bio = BIO_new_mem_buf (const_cast<char *> (cert.c_str ()), -1);
80 throw MiscError ("could not create memory BIO");
83 _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
85 throw MiscError ("could not read X509 certificate from memory BIO");
92 Certificate::~Certificate ()
94 X509_free (_certificate);
95 RSA_free (_public_key);
98 /** operator= for Certificate.
99 * @param other Certificate to read from.
102 Certificate::operator= (Certificate const & other)
104 if (this == &other) {
108 X509_free (_certificate);
110 RSA_free (_public_key);
113 read_string (other.certificate (true));
118 /** Return the certificate as a string.
119 * @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
120 * @return Certificate string.
123 Certificate::certificate (bool with_begin_end) const
125 DCP_ASSERT (_certificate);
127 BIO* bio = BIO_new (BIO_s_mem ());
129 throw MiscError ("could not create memory BIO");
132 PEM_write_bio_X509 (bio, _certificate);
136 long int const data_length = BIO_get_mem_data (bio, &data);
137 for (long int i = 0; i < data_length; ++i) {
143 if (!with_begin_end) {
144 boost::replace_all (s, "-----BEGIN CERTIFICATE-----\n", "");
145 boost::replace_all (s, "\n-----END CERTIFICATE-----\n", "");
151 /** @return Certificate's issuer, in the form
152 * dnqualifier=<dnQualififer>,CN=<commonName>,OU=<organizationalUnitName>,O=<organizationName>
153 * and with + signs escaped to \+
156 Certificate::issuer () const
158 DCP_ASSERT (_certificate);
159 return name_for_xml (X509_get_issuer_name (_certificate));
163 Certificate::asn_to_utf8 (ASN1_STRING* s)
165 unsigned char* buf = 0;
166 ASN1_STRING_to_UTF8 (&buf, s);
167 string const u (reinterpret_cast<char *> (buf));
173 Certificate::get_name_part (X509_NAME* n, int nid)
176 p = X509_NAME_get_index_by_NID (n, nid, p);
177 DCP_ASSERT (p != -1);
178 return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
182 Certificate::name_for_xml (X509_NAME* name)
186 BIO* bio = BIO_new (BIO_s_mem ());
188 throw MiscError ("could not create memory BIO");
191 X509_NAME_print_ex (bio, name, 0, XN_FLAG_RFC2253);
192 int n = BIO_pending (bio);
193 char* result = new char[n + 1];
194 n = BIO_read (bio, result, n);
206 Certificate::subject () const
208 DCP_ASSERT (_certificate);
210 return name_for_xml (X509_get_subject_name (_certificate));
214 Certificate::subject_common_name () const
216 DCP_ASSERT (_certificate);
218 return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
222 Certificate::subject_organization_name () const
224 DCP_ASSERT (_certificate);
226 return get_name_part (X509_get_subject_name (_certificate), NID_organizationName);
230 Certificate::subject_organizational_unit_name () const
232 DCP_ASSERT (_certificate);
234 return get_name_part (X509_get_subject_name (_certificate), NID_organizationalUnitName);
238 Certificate::serial () const
240 DCP_ASSERT (_certificate);
242 ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
245 BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
246 char* c = BN_bn2dec (b);
256 Certificate::thumbprint () const
258 DCP_ASSERT (_certificate);
260 uint8_t buffer[8192];
262 i2d_X509_CINF (_certificate->cert_info, &p);
263 unsigned int const length = p - buffer;
264 if (length > sizeof (buffer)) {
265 throw MiscError ("buffer too small to generate thumbprint");
270 SHA1_Update (&sha, buffer, length);
272 SHA1_Final (digest, &sha);
274 char digest_base64[64];
275 return Kumu::base64encode (digest, 20, digest_base64, 64);
278 /** @return RSA public key from this Certificate. Caller must not free the returned value. */
280 Certificate::public_key () const
282 DCP_ASSERT (_certificate);
288 EVP_PKEY* key = X509_get_pubkey (_certificate);
290 throw MiscError ("could not get public key from certificate");
293 _public_key = EVP_PKEY_get1_RSA (key);
295 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
302 dcp::operator== (Certificate const & a, Certificate const & b)
304 return a.certificate() == b.certificate();
308 dcp::operator< (Certificate const & a, Certificate const & b)
310 return a.certificate() < b.certificate();
314 dcp::operator<< (ostream& s, Certificate const & c)
316 s << c.certificate();
320 /** @return Root certificate */
322 CertificateChain::root () const
324 DCP_ASSERT (!_certificates.empty());
325 return _certificates.front ();
328 /** @return Leaf certificate */
330 CertificateChain::leaf () const
332 DCP_ASSERT (_certificates.size() >= 2);
333 return _certificates.back ();
336 /** @return Certificates in order from root to leaf */
337 CertificateChain::List
338 CertificateChain::root_to_leaf () const
340 return _certificates;
343 /** @return Certificates in order from leaf to root */
344 CertificateChain::List
345 CertificateChain::leaf_to_root () const
347 List c = _certificates;
352 /** Add a certificate to the end of the chain.
353 * @param c Certificate to add.
356 CertificateChain::add (Certificate c)
358 _certificates.push_back (c);
361 /** Remove a certificate from the chain.
362 * @param c Certificate to remove.
365 CertificateChain::remove (Certificate c)
367 _certificates.remove (c);
370 /** Remove the i'th certificate in the list, as listed
374 CertificateChain::remove (int i)
376 List::iterator j = _certificates.begin ();
377 while (j != _certificates.end () && i > 0) {
382 if (j != _certificates.end ()) {
383 _certificates.erase (j);
387 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
388 * signs the leaf and so on).
389 * @return true if it's ok, false if not.
392 CertificateChain::valid () const
394 X509_STORE* store = X509_STORE_new ();
399 for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
401 List::const_iterator j = i;
403 if (j == _certificates.end ()) {
407 if (!X509_STORE_add_cert (store, i->x509 ())) {
408 X509_STORE_free (store);
412 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
414 X509_STORE_free (store);
418 X509_STORE_set_flags (store, 0);
419 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
420 X509_STORE_CTX_free (ctx);
421 X509_STORE_free (store);
425 int v = X509_verify_cert (ctx);
426 X509_STORE_CTX_free (ctx);
429 X509_STORE_free (store);
434 X509_STORE_free (store);
438 /** @return true if the chain is now in order from root to leaf,
439 * false if no correct order was found.
442 CertificateChain::attempt_reorder ()
444 List original = _certificates;
445 _certificates.sort ();
450 } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
452 _certificates = original;