1c0ef98431e2571714845cc1f1385eb23758da20
[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 "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>
36 #include <cerrno>
37 #include <algorithm>
38
39 using std::list;
40 using std::string;
41 using std::ostream;
42 using namespace dcp;
43
44 /** @param c X509 certificate, which this object will take ownership of */
45 Certificate::Certificate (X509* c)
46         : _certificate (c)
47         , _public_key (0)
48 {
49         
50 }
51
52 /** Load an X509 certificate from a string.
53  *  @param cert String to read from.
54  */
55 Certificate::Certificate (string cert)
56         : _certificate (0)
57         , _public_key (0)
58 {
59         read_string (cert);
60 }
61
62 /** Copy constructor.
63  *  @param other Certificate to copy.
64  */
65 Certificate::Certificate (Certificate const & other)
66         : _certificate (0)
67         , _public_key (0)
68 {
69         read_string (other.certificate (true));
70 }
71
72 /** Read a certificate from a string.
73  *  @param cert String to read.
74  */
75 void
76 Certificate::read_string (string cert)
77 {
78         BIO* bio = BIO_new_mem_buf (const_cast<char *> (cert.c_str ()), -1);
79         if (!bio) {
80                 throw MiscError ("could not create memory BIO");
81         }
82
83         _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
84         if (!_certificate) {
85                 throw MiscError ("could not read X509 certificate from memory BIO");
86         }
87
88         BIO_free (bio);
89 }
90
91 /** Destructor */
92 Certificate::~Certificate ()
93 {
94         X509_free (_certificate);
95         RSA_free (_public_key);
96 }
97
98 /** operator= for Certificate.
99  *  @param other Certificate to read from.
100  */
101 Certificate &
102 Certificate::operator= (Certificate const & other)
103 {
104         if (this == &other) {
105                 return *this;
106         }
107
108         X509_free (_certificate);
109         _certificate = 0;
110         RSA_free (_public_key);
111         _public_key = 0;
112         
113         read_string (other.certificate (true));
114
115         return *this;
116 }
117
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.
121  */
122 string
123 Certificate::certificate (bool with_begin_end) const
124 {
125         DCP_ASSERT (_certificate);
126         
127         BIO* bio = BIO_new (BIO_s_mem ());
128         if (!bio) {
129                 throw MiscError ("could not create memory BIO");
130         }
131         
132         PEM_write_bio_X509 (bio, _certificate);
133
134         string s;
135         char* data;
136         long int const data_length = BIO_get_mem_data (bio, &data);
137         for (long int i = 0; i < data_length; ++i) {
138                 s += data[i];
139         }
140
141         BIO_free (bio);
142
143         if (!with_begin_end) {
144                 boost::replace_all (s, "-----BEGIN CERTIFICATE-----\n", "");
145                 boost::replace_all (s, "\n-----END CERTIFICATE-----\n", "");
146         }
147         
148         return s;
149 }
150
151 /** @return Certificate's issuer, in the form
152  *  dnqualifier=&lt;dnQualififer&gt;,CN=&lt;commonName&gt;,OU=&lt;organizationalUnitName&gt,O=&lt;organizationName&gt;
153  *  and with + signs escaped to \+
154  */
155 string
156 Certificate::issuer () const
157 {
158         DCP_ASSERT (_certificate);
159         return name_for_xml (X509_get_issuer_name (_certificate));
160 }
161
162 string
163 Certificate::asn_to_utf8 (ASN1_STRING* s)
164 {
165         unsigned char* buf = 0;
166         ASN1_STRING_to_UTF8 (&buf, s);
167         string const u (reinterpret_cast<char *> (buf));
168         OPENSSL_free (buf);
169         return u;
170 }
171
172 string
173 Certificate::get_name_part (X509_NAME* n, int nid)
174 {
175         int p = -1;
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)));
179 }
180         
181 string
182 Certificate::name_for_xml (X509_NAME* name)
183 {
184         assert (name);
185
186         BIO* bio = BIO_new (BIO_s_mem ());
187         if (!bio) {
188                 throw MiscError ("could not create memory BIO");
189         }
190
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);
195         result[n] = '\0';
196
197         BIO_free (bio);
198
199         string s = result;
200         delete[] result;
201
202         return s;
203 }
204
205 string
206 Certificate::subject () const
207 {
208         DCP_ASSERT (_certificate);
209
210         return name_for_xml (X509_get_subject_name (_certificate));
211 }
212
213 string
214 Certificate::common_name () const
215 {
216         DCP_ASSERT (_certificate);
217
218         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
219 }
220
221 string
222 Certificate::serial () const
223 {
224         DCP_ASSERT (_certificate);
225
226         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
227         DCP_ASSERT (s);
228         
229         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
230         char* c = BN_bn2dec (b);
231         BN_free (b);
232         
233         string st (c);
234         OPENSSL_free (c);
235
236         return st;
237 }
238
239 string
240 Certificate::thumbprint () const
241 {
242         DCP_ASSERT (_certificate);
243         
244         uint8_t buffer[8192];
245         uint8_t* p = buffer;
246         i2d_X509_CINF (_certificate->cert_info, &p);
247         unsigned int const length = p - buffer;
248         if (length > sizeof (buffer)) {
249                 throw MiscError ("buffer too small to generate thumbprint");
250         }
251
252         SHA_CTX sha;
253         SHA1_Init (&sha);
254         SHA1_Update (&sha, buffer, length);
255         uint8_t digest[20];
256         SHA1_Final (digest, &sha);
257
258         char digest_base64[64];
259         return Kumu::base64encode (digest, 20, digest_base64, 64);
260 }
261
262 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
263 RSA *
264 Certificate::public_key () const
265 {
266         DCP_ASSERT (_certificate);
267
268         if (_public_key) {
269                 return _public_key;
270         }
271
272         EVP_PKEY* key = X509_get_pubkey (_certificate);
273         if (!key) {
274                 throw MiscError ("could not get public key from certificate");
275         }
276
277         _public_key = EVP_PKEY_get1_RSA (key);
278         if (!_public_key) {
279                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
280         }
281
282         return _public_key;
283 }
284
285 bool
286 dcp::operator== (Certificate const & a, Certificate const & b)
287 {
288         return a.certificate() == b.certificate();
289 }
290
291 bool
292 dcp::operator< (Certificate const & a, Certificate const & b)
293 {
294         return a.certificate() < b.certificate();
295 }
296
297 ostream&
298 dcp::operator<< (ostream& s, Certificate const & c)
299 {
300         s << c.certificate();
301         return s;
302 }
303
304 /** @return Root certificate */
305 Certificate
306 CertificateChain::root () const
307 {
308         DCP_ASSERT (!_certificates.empty());
309         return _certificates.front ();
310 }
311
312 /** @return Leaf certificate */
313 Certificate
314 CertificateChain::leaf () const
315 {
316         DCP_ASSERT (_certificates.size() >= 2);
317         return _certificates.back ();
318 }
319
320 /** @return Certificates in order from root to leaf */
321 CertificateChain::List
322 CertificateChain::root_to_leaf () const
323 {
324         return _certificates;
325 }
326
327 /** @return Certificates in order from leaf to root */
328 CertificateChain::List
329 CertificateChain::leaf_to_root () const
330 {
331         List c = _certificates;
332         c.reverse ();
333         return c;
334 }
335
336 /** Add a certificate to the end of the chain.
337  *  @param c Certificate to add.
338  */
339 void
340 CertificateChain::add (Certificate c)
341 {
342         _certificates.push_back (c);
343 }
344
345 /** Remove a certificate from the chain.
346  *  @param c Certificate to remove.
347  */
348 void
349 CertificateChain::remove (Certificate c)
350 {
351         _certificates.remove (c);
352 }
353
354 /** Remove the i'th certificate in the list, as listed
355  *  from root to leaf.
356  */
357 void
358 CertificateChain::remove (int i)
359 {
360         List::iterator j = _certificates.begin ();
361         while (j != _certificates.end () && i > 0) {
362                 --i;
363                 ++j;
364         }
365
366         if (j != _certificates.end ()) {
367                 _certificates.erase (j);
368         }
369 }
370
371 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
372  *  signs the leaf and so on).
373  *  @return true if it's ok, false if not.
374  */
375 bool
376 CertificateChain::valid () const
377 {
378         X509_STORE* store = X509_STORE_new ();
379         if (!store) {
380                 return false;
381         }
382
383         for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
384
385                 List::const_iterator j = i;
386                 ++j;
387                 if (j ==  _certificates.end ()) {
388                         break;
389                 }
390
391                 if (!X509_STORE_add_cert (store, i->x509 ())) {
392                         X509_STORE_free (store);
393                         return false;
394                 }
395
396                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
397                 if (!ctx) {
398                         X509_STORE_free (store);
399                         return false;
400                 }
401
402                 X509_STORE_set_flags (store, 0);
403                 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
404                         X509_STORE_CTX_free (ctx);
405                         X509_STORE_free (store);
406                         return false;
407                 }
408
409                 int v = X509_verify_cert (ctx);
410                 X509_STORE_CTX_free (ctx);
411
412                 if (v == 0) {
413                         X509_STORE_free (store);
414                         return false;
415                 }
416         }
417
418         X509_STORE_free (store);
419         return true;
420 }
421
422 /** @return true if the chain is now in order from root to leaf,
423  *  false if no correct order was found.
424  */
425 bool
426 CertificateChain::attempt_reorder ()
427 {
428         List original = _certificates;
429         _certificates.sort ();
430         do {
431                 if (valid ()) {
432                         return true;
433                 }
434         } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
435
436         _certificates = original;
437         return false;
438 }