Add verify() to CertificateChain.
[libdcp.git] / src / certificates.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
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.
8
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.
13
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.
17
18 */
19
20 /** @file  src/certificates.cc
21  *  @brief Certificate and CertificateChain classes.
22  */
23
24 #include "KM_util.h"
25 #include "certificates.h"
26 #include "compose.hpp"
27 #include "exceptions.h"
28 #include "util.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>
35 #include <cerrno>
36
37 using std::list;
38 using std::string;
39 using boost::shared_ptr;
40 using namespace dcp;
41
42 /** @param c X509 certificate, which this object will take ownership of */
43 Certificate::Certificate (X509* c)
44         : _certificate (c)
45         , _public_key (0)
46 {
47         
48 }
49
50 /** Load an X509 certificate from a file.
51  *  @param filename File to load.
52  */
53 Certificate::Certificate (boost::filesystem::path filename)
54         : _certificate (0)
55         , _public_key (0)
56 {
57         FILE* f = fopen_boost (filename, "r");
58         if (!f) {
59                 throw FileError ("could not open file", filename, errno);
60         }
61         
62         if (!PEM_read_X509 (f, &_certificate, 0, 0)) {
63                 throw MiscError ("could not read X509 certificate");
64         }
65 }
66
67 /** Load an X509 certificate from a string.
68  *  @param cert String to read from.
69  */
70 Certificate::Certificate (string cert)
71         : _certificate (0)
72         , _public_key (0)
73 {
74         read_string (cert);
75 }
76
77 /** Copy constructor.
78  *  @param other Certificate to copy.
79  */
80 Certificate::Certificate (Certificate const & other)
81         : _certificate (0)
82         , _public_key (0)
83 {
84         read_string (other.certificate (true));
85 }
86
87 /** Read a certificate from a string.
88  *  @param cert String to read.
89  */
90 void
91 Certificate::read_string (string cert)
92 {
93         BIO* bio = BIO_new_mem_buf (const_cast<char *> (cert.c_str ()), -1);
94         if (!bio) {
95                 throw MiscError ("could not create memory BIO");
96         }
97
98         _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
99         if (!_certificate) {
100                 throw MiscError ("could not read X509 certificate from memory BIO");
101         }
102
103         BIO_free (bio);
104 }
105
106 /** Destructor */
107 Certificate::~Certificate ()
108 {
109         X509_free (_certificate);
110         RSA_free (_public_key);
111 }
112
113 /** operator= for Certificate.
114  *  @param other Certificate to read from.
115  */
116 Certificate &
117 Certificate::operator= (Certificate const & other)
118 {
119         if (this == &other) {
120                 return *this;
121         }
122
123         X509_free (_certificate);
124         _certificate = 0;
125         RSA_free (_public_key);
126         _public_key = 0;
127         
128         read_string (other.certificate ());
129
130         return *this;
131 }
132
133 /** Return the certificate as a string.
134  *  @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
135  *  @return Certificate string.
136  */
137 string
138 Certificate::certificate (bool with_begin_end) const
139 {
140         assert (_certificate);
141         
142         BIO* bio = BIO_new (BIO_s_mem ());
143         if (!bio) {
144                 throw MiscError ("could not create memory BIO");
145         }
146         
147         PEM_write_bio_X509 (bio, _certificate);
148
149         string s;
150         char* data;
151         long int const data_length = BIO_get_mem_data (bio, &data);
152         for (long int i = 0; i < data_length; ++i) {
153                 s += data[i];
154         }
155
156         BIO_free (bio);
157
158         if (!with_begin_end) {
159                 boost::replace_all (s, "-----BEGIN CERTIFICATE-----\n", "");
160                 boost::replace_all (s, "\n-----END CERTIFICATE-----\n", "");
161         }
162         
163         return s;
164 }
165
166 /** @return Certificate's issuer, in the form
167  *  dnqualifier=&lt;dnQualififer&gt;,CN=&lt;commonName&gt;,OU=&lt;organizationalUnitName&gt,O=&lt;organizationName&gt;
168  *  and with + signs escaped to \+
169  */
170 string
171 Certificate::issuer () const
172 {
173         assert (_certificate);
174         return name_for_xml (X509_get_issuer_name (_certificate));
175 }
176
177 string
178 Certificate::asn_to_utf8 (ASN1_STRING* s)
179 {
180         unsigned char* buf = 0;
181         ASN1_STRING_to_UTF8 (&buf, s);
182         string const u (reinterpret_cast<char *> (buf));
183         OPENSSL_free (buf);
184         return u;
185 }
186
187 string
188 Certificate::get_name_part (X509_NAME* n, int nid)
189 {
190         int p = -1;
191         p = X509_NAME_get_index_by_NID (n, nid, p);
192         assert (p != -1);
193         return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
194 }
195         
196
197 string
198 Certificate::name_for_xml (X509_NAME * n)
199 {
200         assert (n);
201
202         string s = String::compose (
203                 "dnQualifier=%1,CN=%2,OU=%3,O=%4",
204                 get_name_part (n, NID_dnQualifier),
205                 get_name_part (n, NID_commonName),
206                 get_name_part (n, NID_organizationalUnitName),
207                 get_name_part (n, NID_organizationName)
208                 );
209         
210         boost::replace_all (s, "+", "\\+");
211         return s;
212 }
213
214 string
215 Certificate::subject () const
216 {
217         assert (_certificate);
218
219         return name_for_xml (X509_get_subject_name (_certificate));
220 }
221
222 string
223 Certificate::common_name () const
224 {
225         assert (_certificate);
226
227         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
228 }
229
230 string
231 Certificate::serial () const
232 {
233         assert (_certificate);
234
235         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
236         assert (s);
237         
238         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
239         char* c = BN_bn2dec (b);
240         BN_free (b);
241         
242         string st (c);
243         OPENSSL_free (c);
244
245         return st;
246 }
247
248 string
249 Certificate::thumbprint () const
250 {
251         assert (_certificate);
252         
253         uint8_t buffer[8192];
254         uint8_t* p = buffer;
255         i2d_X509_CINF (_certificate->cert_info, &p);
256         int const length = p - buffer;
257         if (length > 8192) {
258                 throw MiscError ("buffer too small to generate thumbprint");
259         }
260
261         SHA_CTX sha;
262         SHA1_Init (&sha);
263         SHA1_Update (&sha, buffer, length);
264         uint8_t digest[20];
265         SHA1_Final (digest, &sha);
266
267         char digest_base64[64];
268         return Kumu::base64encode (digest, 20, digest_base64, 64);
269 }
270
271 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
272 RSA *
273 Certificate::public_key () const
274 {
275         assert (_certificate);
276
277         if (_public_key) {
278                 return _public_key;
279         }
280
281         EVP_PKEY* key = X509_get_pubkey (_certificate);
282         if (!key) {
283                 throw MiscError ("could not get public key from certificate");
284         }
285
286         _public_key = EVP_PKEY_get1_RSA (key);
287         if (!_public_key) {
288                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
289         }
290
291         return _public_key;
292 }
293
294 /** @return Root certificate */
295 shared_ptr<Certificate>
296 CertificateChain::root () const
297 {
298         assert (!_certificates.empty());
299         return _certificates.front ();
300 }
301
302 /** @return Leaf certificate */
303 shared_ptr<Certificate>
304 CertificateChain::leaf () const
305 {
306         assert (_certificates.size() >= 2);
307         return _certificates.back ();
308 }
309
310 /** @return Certificates in order from leaf to root */
311 list<shared_ptr<Certificate> >
312 CertificateChain::leaf_to_root () const
313 {
314         list<shared_ptr<Certificate> > c = _certificates;
315         c.reverse ();
316         return c;
317 }
318
319 /** Add a certificate to the end of the chain.
320  *  @param c Certificate to add.
321  */
322 void
323 CertificateChain::add (shared_ptr<Certificate> c)
324 {
325         _certificates.push_back (c);
326 }
327
328 /** Verify the chain.
329  *  @return true if it's ok, false if not.
330  */
331 bool
332 CertificateChain::verify () const
333 {
334         X509_STORE* store = X509_STORE_new ();
335         if (!store) {
336                 return false;
337         }
338         
339         for (list<shared_ptr<Certificate> >::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
340                 list<shared_ptr<Certificate> >::const_iterator j = i;
341                 ++j;
342                 if (j ==  _certificates.end ()) {
343                         break;
344                 }
345
346                 if (!X509_STORE_add_cert (store, (*i)->x509 ())) {
347                         X509_STORE_free (store);
348                         return false;
349                 }
350
351                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
352                 if (!ctx) {
353                         X509_STORE_free (store);
354                         return false;
355                 }
356
357                 X509_STORE_set_flags (store, 0);
358                 if (!X509_STORE_CTX_init (ctx, store, (*j)->x509 (), 0)) {
359                         X509_STORE_CTX_free (ctx);
360                         X509_STORE_free (store);
361                         return false;
362                 }
363
364                 int v = X509_verify_cert (ctx);
365                 X509_STORE_CTX_free (ctx);
366
367                 if (v == 0) {
368                         X509_STORE_free (store);
369                         return false;
370                 }
371         }
372
373         X509_STORE_free (store);
374         return true;
375 }