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>
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 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 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);
178 return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
183 Certificate::name_for_xml (X509_NAME * n)
187 string s = String::compose (
188 "dnQualifier=%1,CN=%2,OU=%3,O=%4",
189 get_name_part (n, NID_dnQualifier),
190 get_name_part (n, NID_commonName),
191 get_name_part (n, NID_organizationalUnitName),
192 get_name_part (n, NID_organizationName)
195 boost::replace_all (s, "+", "\\+");
200 Certificate::subject () const
202 assert (_certificate);
204 return name_for_xml (X509_get_subject_name (_certificate));
208 Certificate::common_name () const
210 assert (_certificate);
212 return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
216 Certificate::serial () const
218 assert (_certificate);
220 ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
223 BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
224 char* c = BN_bn2dec (b);
234 Certificate::thumbprint () const
236 assert (_certificate);
238 uint8_t buffer[8192];
240 i2d_X509_CINF (_certificate->cert_info, &p);
241 unsigned int const length = p - buffer;
242 if (length > sizeof (buffer)) {
243 throw MiscError ("buffer too small to generate thumbprint");
248 SHA1_Update (&sha, buffer, length);
250 SHA1_Final (digest, &sha);
252 char digest_base64[64];
253 return Kumu::base64encode (digest, 20, digest_base64, 64);
256 /** @return RSA public key from this Certificate. Caller must not free the returned value. */
258 Certificate::public_key () const
260 assert (_certificate);
266 EVP_PKEY* key = X509_get_pubkey (_certificate);
268 throw MiscError ("could not get public key from certificate");
271 _public_key = EVP_PKEY_get1_RSA (key);
273 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
280 dcp::operator== (Certificate const & a, Certificate const & b)
282 return a.certificate() == b.certificate();
286 dcp::operator< (Certificate const & a, Certificate const & b)
288 return a.certificate() < b.certificate();
292 dcp::operator<< (ostream& s, Certificate const & c)
294 s << c.certificate();
298 /** @return Root certificate */
300 CertificateChain::root () const
302 assert (!_certificates.empty());
303 return _certificates.front ();
306 /** @return Leaf certificate */
308 CertificateChain::leaf () const
310 assert (_certificates.size() >= 2);
311 return _certificates.back ();
314 /** @return Certificates in order from root to leaf */
315 CertificateChain::List
316 CertificateChain::root_to_leaf () const
318 return _certificates;
321 /** @return Certificates in order from leaf to root */
322 CertificateChain::List
323 CertificateChain::leaf_to_root () const
325 List c = _certificates;
330 /** Add a certificate to the end of the chain.
331 * @param c Certificate to add.
334 CertificateChain::add (Certificate c)
336 _certificates.push_back (c);
339 /** Remove a certificate from the chain.
340 * @param c Certificate to remove.
343 CertificateChain::remove (Certificate c)
345 _certificates.remove (c);
348 /** Remove the i'th certificate in the list, as listed
352 CertificateChain::remove (int i)
354 List::iterator j = _certificates.begin ();
355 while (j != _certificates.end () && i > 0) {
360 if (j != _certificates.end ()) {
361 _certificates.erase (j);
365 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
366 * signs the leaf and so on).
367 * @return true if it's ok, false if not.
370 CertificateChain::valid () const
372 X509_STORE* store = X509_STORE_new ();
377 for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
379 List::const_iterator j = i;
381 if (j == _certificates.end ()) {
385 if (!X509_STORE_add_cert (store, i->x509 ())) {
386 X509_STORE_free (store);
390 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
392 X509_STORE_free (store);
396 X509_STORE_set_flags (store, 0);
397 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
398 X509_STORE_CTX_free (ctx);
399 X509_STORE_free (store);
403 int v = X509_verify_cert (ctx);
404 X509_STORE_CTX_free (ctx);
407 X509_STORE_free (store);
412 X509_STORE_free (store);
416 /** @return true if the chain is now in order from root to leaf,
417 * false if no correct order was found.
420 CertificateChain::attempt_reorder ()
422 List original = _certificates;
423 _certificates.sort ();
428 } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
430 _certificates = original;