Rename a couple of Certificate methods and add accessors for organization and organiz...
[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::subject_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::subject_organization_name () const
223 {
224         DCP_ASSERT (_certificate);
225
226         return get_name_part (X509_get_subject_name (_certificate), NID_organizationName);
227 }
228
229 string
230 Certificate::subject_organizational_unit_name () const
231 {
232         DCP_ASSERT (_certificate);
233
234         return get_name_part (X509_get_subject_name (_certificate), NID_organizationalUnitName);
235 }
236
237 string
238 Certificate::serial () const
239 {
240         DCP_ASSERT (_certificate);
241
242         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
243         DCP_ASSERT (s);
244
245         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
246         char* c = BN_bn2dec (b);
247         BN_free (b);
248
249         string st (c);
250         OPENSSL_free (c);
251
252         return st;
253 }
254
255 string
256 Certificate::thumbprint () const
257 {
258         DCP_ASSERT (_certificate);
259
260         uint8_t buffer[8192];
261         uint8_t* p = buffer;
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");
266         }
267
268         SHA_CTX sha;
269         SHA1_Init (&sha);
270         SHA1_Update (&sha, buffer, length);
271         uint8_t digest[20];
272         SHA1_Final (digest, &sha);
273
274         char digest_base64[64];
275         return Kumu::base64encode (digest, 20, digest_base64, 64);
276 }
277
278 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
279 RSA *
280 Certificate::public_key () const
281 {
282         DCP_ASSERT (_certificate);
283
284         if (_public_key) {
285                 return _public_key;
286         }
287
288         EVP_PKEY* key = X509_get_pubkey (_certificate);
289         if (!key) {
290                 throw MiscError ("could not get public key from certificate");
291         }
292
293         _public_key = EVP_PKEY_get1_RSA (key);
294         if (!_public_key) {
295                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
296         }
297
298         return _public_key;
299 }
300
301 bool
302 dcp::operator== (Certificate const & a, Certificate const & b)
303 {
304         return a.certificate() == b.certificate();
305 }
306
307 bool
308 dcp::operator< (Certificate const & a, Certificate const & b)
309 {
310         return a.certificate() < b.certificate();
311 }
312
313 ostream&
314 dcp::operator<< (ostream& s, Certificate const & c)
315 {
316         s << c.certificate();
317         return s;
318 }
319
320 /** @return Root certificate */
321 Certificate
322 CertificateChain::root () const
323 {
324         DCP_ASSERT (!_certificates.empty());
325         return _certificates.front ();
326 }
327
328 /** @return Leaf certificate */
329 Certificate
330 CertificateChain::leaf () const
331 {
332         DCP_ASSERT (_certificates.size() >= 2);
333         return _certificates.back ();
334 }
335
336 /** @return Certificates in order from root to leaf */
337 CertificateChain::List
338 CertificateChain::root_to_leaf () const
339 {
340         return _certificates;
341 }
342
343 /** @return Certificates in order from leaf to root */
344 CertificateChain::List
345 CertificateChain::leaf_to_root () const
346 {
347         List c = _certificates;
348         c.reverse ();
349         return c;
350 }
351
352 /** Add a certificate to the end of the chain.
353  *  @param c Certificate to add.
354  */
355 void
356 CertificateChain::add (Certificate c)
357 {
358         _certificates.push_back (c);
359 }
360
361 /** Remove a certificate from the chain.
362  *  @param c Certificate to remove.
363  */
364 void
365 CertificateChain::remove (Certificate c)
366 {
367         _certificates.remove (c);
368 }
369
370 /** Remove the i'th certificate in the list, as listed
371  *  from root to leaf.
372  */
373 void
374 CertificateChain::remove (int i)
375 {
376         List::iterator j = _certificates.begin ();
377         while (j != _certificates.end () && i > 0) {
378                 --i;
379                 ++j;
380         }
381
382         if (j != _certificates.end ()) {
383                 _certificates.erase (j);
384         }
385 }
386
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.
390  */
391 bool
392 CertificateChain::valid () const
393 {
394         X509_STORE* store = X509_STORE_new ();
395         if (!store) {
396                 return false;
397         }
398
399         for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
400
401                 List::const_iterator j = i;
402                 ++j;
403                 if (j ==  _certificates.end ()) {
404                         break;
405                 }
406
407                 if (!X509_STORE_add_cert (store, i->x509 ())) {
408                         X509_STORE_free (store);
409                         return false;
410                 }
411
412                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
413                 if (!ctx) {
414                         X509_STORE_free (store);
415                         return false;
416                 }
417
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);
422                         return false;
423                 }
424
425                 int v = X509_verify_cert (ctx);
426                 X509_STORE_CTX_free (ctx);
427
428                 if (v == 0) {
429                         X509_STORE_free (store);
430                         return false;
431                 }
432         }
433
434         X509_STORE_free (store);
435         return true;
436 }
437
438 /** @return true if the chain is now in order from root to leaf,
439  *  false if no correct order was found.
440  */
441 bool
442 CertificateChain::attempt_reorder ()
443 {
444         List original = _certificates;
445         _certificates.sort ();
446         do {
447                 if (valid ()) {
448                         return true;
449                 }
450         } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
451
452         _certificates = original;
453         return false;
454 }