Add halign to SubtitleString's operator<< and use it for dcpinfo.
[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
182 string
183 Certificate::name_for_xml (X509_NAME * n)
184 {
185         DCP_ASSERT (n);
186
187         string s = String::compose (
188                 "O=%1,OU=%2,CN=%3,dnQualifier=%4",
189                 get_name_part (n, NID_organizationName),
190                 get_name_part (n, NID_organizationalUnitName),
191                 get_name_part (n, NID_commonName),
192                 get_name_part (n, NID_dnQualifier)
193                 );
194         
195         boost::replace_all (s, "+", "\\+");
196         return s;
197 }
198
199 string
200 Certificate::subject () const
201 {
202         DCP_ASSERT (_certificate);
203
204         return name_for_xml (X509_get_subject_name (_certificate));
205 }
206
207 string
208 Certificate::common_name () const
209 {
210         DCP_ASSERT (_certificate);
211
212         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
213 }
214
215 string
216 Certificate::serial () const
217 {
218         DCP_ASSERT (_certificate);
219
220         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
221         DCP_ASSERT (s);
222         
223         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
224         char* c = BN_bn2dec (b);
225         BN_free (b);
226         
227         string st (c);
228         OPENSSL_free (c);
229
230         return st;
231 }
232
233 string
234 Certificate::thumbprint () const
235 {
236         DCP_ASSERT (_certificate);
237         
238         uint8_t buffer[8192];
239         uint8_t* p = buffer;
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");
244         }
245
246         SHA_CTX sha;
247         SHA1_Init (&sha);
248         SHA1_Update (&sha, buffer, length);
249         uint8_t digest[20];
250         SHA1_Final (digest, &sha);
251
252         char digest_base64[64];
253         return Kumu::base64encode (digest, 20, digest_base64, 64);
254 }
255
256 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
257 RSA *
258 Certificate::public_key () const
259 {
260         DCP_ASSERT (_certificate);
261
262         if (_public_key) {
263                 return _public_key;
264         }
265
266         EVP_PKEY* key = X509_get_pubkey (_certificate);
267         if (!key) {
268                 throw MiscError ("could not get public key from certificate");
269         }
270
271         _public_key = EVP_PKEY_get1_RSA (key);
272         if (!_public_key) {
273                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
274         }
275
276         return _public_key;
277 }
278
279 bool
280 dcp::operator== (Certificate const & a, Certificate const & b)
281 {
282         return a.certificate() == b.certificate();
283 }
284
285 bool
286 dcp::operator< (Certificate const & a, Certificate const & b)
287 {
288         return a.certificate() < b.certificate();
289 }
290
291 ostream&
292 dcp::operator<< (ostream& s, Certificate const & c)
293 {
294         s << c.certificate();
295         return s;
296 }
297
298 /** @return Root certificate */
299 Certificate
300 CertificateChain::root () const
301 {
302         DCP_ASSERT (!_certificates.empty());
303         return _certificates.front ();
304 }
305
306 /** @return Leaf certificate */
307 Certificate
308 CertificateChain::leaf () const
309 {
310         DCP_ASSERT (_certificates.size() >= 2);
311         return _certificates.back ();
312 }
313
314 /** @return Certificates in order from root to leaf */
315 CertificateChain::List
316 CertificateChain::root_to_leaf () const
317 {
318         return _certificates;
319 }
320
321 /** @return Certificates in order from leaf to root */
322 CertificateChain::List
323 CertificateChain::leaf_to_root () const
324 {
325         List c = _certificates;
326         c.reverse ();
327         return c;
328 }
329
330 /** Add a certificate to the end of the chain.
331  *  @param c Certificate to add.
332  */
333 void
334 CertificateChain::add (Certificate c)
335 {
336         _certificates.push_back (c);
337 }
338
339 /** Remove a certificate from the chain.
340  *  @param c Certificate to remove.
341  */
342 void
343 CertificateChain::remove (Certificate c)
344 {
345         _certificates.remove (c);
346 }
347
348 /** Remove the i'th certificate in the list, as listed
349  *  from root to leaf.
350  */
351 void
352 CertificateChain::remove (int i)
353 {
354         List::iterator j = _certificates.begin ();
355         while (j != _certificates.end () && i > 0) {
356                 --i;
357                 ++j;
358         }
359
360         if (j != _certificates.end ()) {
361                 _certificates.erase (j);
362         }
363 }
364
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.
368  */
369 bool
370 CertificateChain::valid () const
371 {
372         X509_STORE* store = X509_STORE_new ();
373         if (!store) {
374                 return false;
375         }
376
377         for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
378
379                 List::const_iterator j = i;
380                 ++j;
381                 if (j ==  _certificates.end ()) {
382                         break;
383                 }
384
385                 if (!X509_STORE_add_cert (store, i->x509 ())) {
386                         X509_STORE_free (store);
387                         return false;
388                 }
389
390                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
391                 if (!ctx) {
392                         X509_STORE_free (store);
393                         return false;
394                 }
395
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);
400                         return false;
401                 }
402
403                 int v = X509_verify_cert (ctx);
404                 X509_STORE_CTX_free (ctx);
405
406                 if (v == 0) {
407                         X509_STORE_free (store);
408                         return false;
409                 }
410         }
411
412         X509_STORE_free (store);
413         return true;
414 }
415
416 /** @return true if the chain is now in order from root to leaf,
417  *  false if no correct order was found.
418  */
419 bool
420 CertificateChain::attempt_reorder ()
421 {
422         List original = _certificates;
423         _certificates.sort ();
424         do {
425                 if (valid ()) {
426                         return true;
427                 }
428         } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
429
430         _certificates = original;
431         return false;
432 }