Allow certificates with preamble before BEGIN CERTIFICATE (dcpomatic #774).
[libdcp.git] / src / certificate.cc
1 /*
2     Copyright (C) 2012-2015 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/certificate.cc
21  *  @brief Certificate class.
22  */
23
24 #include "KM_util.h"
25 #include "certificate.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 std::min;
43 using std::stringstream;
44 using namespace dcp;
45
46 static string const begin_certificate = "-----BEGIN CERTIFICATE-----";
47 static string const end_certificate = "-----END CERTIFICATE-----";
48
49 /** @param c X509 certificate, which this object will take ownership of */
50 Certificate::Certificate (X509* c)
51         : _certificate (c)
52         , _public_key (0)
53 {
54
55 }
56
57 /** Load an X509 certificate from a string.
58  *  @param cert String to read from.
59  */
60 Certificate::Certificate (string cert)
61         : _certificate (0)
62         , _public_key (0)
63 {
64         read_string (cert);
65 }
66
67 /** Copy constructor.
68  *  @param other Certificate to copy.
69  */
70 Certificate::Certificate (Certificate const & other)
71         : _certificate (0)
72         , _public_key (0)
73 {
74         if (other._certificate) {
75                 read_string (other.certificate (true));
76         }
77 }
78
79 /** Read a certificate from a string.
80  *  @param cert String to read.
81  */
82 void
83 Certificate::read_string (string cert)
84 {
85         /* Reformat cert so that it has line breaks every 64 characters.
86            See http://comments.gmane.org/gmane.comp.encryption.openssl.user/55593
87         */
88
89         stringstream s (cert);
90         string line;
91
92         /* BEGIN */
93         do {
94                 getline (s, line);
95                 boost::algorithm::trim (line);
96         } while (s.good() && line != begin_certificate);
97
98         if (line != begin_certificate) {
99                 throw MiscError ("missing BEGIN line in certificate");
100         }
101
102         /* The base64 data */
103         bool got_end = false;
104         string base64 = "";
105         while (getline (s, line)) {
106                 boost::algorithm::trim (line);
107                 if (line == end_certificate) {
108                         got_end = true;
109                         break;
110                 }
111                 base64 += line;
112         }
113
114         if (!got_end) {
115                 throw MiscError ("missing END line in certificate");
116         }
117
118         /* Make up the fixed version */
119
120         string fixed = begin_certificate + "\n";
121         while (!base64.empty ()) {
122                 size_t const t = min (size_t(64), base64.length());
123                 fixed += base64.substr (0, t) + "\n";
124                 base64 = base64.substr (t, base64.length() - t);
125         }
126
127         fixed += end_certificate;
128
129         BIO* bio = BIO_new_mem_buf (const_cast<char *> (fixed.c_str ()), -1);
130         if (!bio) {
131                 throw MiscError ("could not create memory BIO");
132         }
133
134         _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
135         if (!_certificate) {
136                 throw MiscError ("could not read X509 certificate from memory BIO");
137         }
138
139         BIO_free (bio);
140 }
141
142 /** Destructor */
143 Certificate::~Certificate ()
144 {
145         X509_free (_certificate);
146         RSA_free (_public_key);
147 }
148
149 /** operator= for Certificate.
150  *  @param other Certificate to read from.
151  */
152 Certificate &
153 Certificate::operator= (Certificate const & other)
154 {
155         if (this == &other) {
156                 return *this;
157         }
158
159         X509_free (_certificate);
160         _certificate = 0;
161         RSA_free (_public_key);
162         _public_key = 0;
163
164         read_string (other.certificate (true));
165
166         return *this;
167 }
168
169 /** Return the certificate as a string.
170  *  @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
171  *  @return Certificate string.
172  */
173 string
174 Certificate::certificate (bool with_begin_end) const
175 {
176         DCP_ASSERT (_certificate);
177
178         BIO* bio = BIO_new (BIO_s_mem ());
179         if (!bio) {
180                 throw MiscError ("could not create memory BIO");
181         }
182
183         PEM_write_bio_X509 (bio, _certificate);
184
185         string s;
186         char* data;
187         long int const data_length = BIO_get_mem_data (bio, &data);
188         for (long int i = 0; i < data_length; ++i) {
189                 s += data[i];
190         }
191
192         BIO_free (bio);
193
194         if (!with_begin_end) {
195                 boost::replace_all (s, begin_certificate + "\n", "");
196                 boost::replace_all (s, "\n" + end_certificate + "\n", "");
197         }
198
199         return s;
200 }
201
202 /** @return Certificate's issuer, in the form
203  *  dnqualifier=&lt;dnQualififer&gt;,CN=&lt;commonName&gt;,OU=&lt;organizationalUnitName&gt,O=&lt;organizationName&gt;
204  *  and with + signs escaped to \+
205  */
206 string
207 Certificate::issuer () const
208 {
209         DCP_ASSERT (_certificate);
210         return name_for_xml (X509_get_issuer_name (_certificate));
211 }
212
213 string
214 Certificate::asn_to_utf8 (ASN1_STRING* s)
215 {
216         unsigned char* buf = 0;
217         ASN1_STRING_to_UTF8 (&buf, s);
218         string const u (reinterpret_cast<char *> (buf));
219         OPENSSL_free (buf);
220         return u;
221 }
222
223 string
224 Certificate::get_name_part (X509_NAME* n, int nid)
225 {
226         int p = -1;
227         p = X509_NAME_get_index_by_NID (n, nid, p);
228         if (p == -1) {
229                 return "";
230         }
231         return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
232 }
233
234 string
235 Certificate::name_for_xml (X509_NAME* name)
236 {
237         assert (name);
238
239         BIO* bio = BIO_new (BIO_s_mem ());
240         if (!bio) {
241                 throw MiscError ("could not create memory BIO");
242         }
243
244         X509_NAME_print_ex (bio, name, 0, XN_FLAG_RFC2253);
245         int n = BIO_pending (bio);
246         char* result = new char[n + 1];
247         n = BIO_read (bio, result, n);
248         result[n] = '\0';
249
250         BIO_free (bio);
251
252         string s = result;
253         delete[] result;
254
255         return s;
256 }
257
258 string
259 Certificate::subject () const
260 {
261         DCP_ASSERT (_certificate);
262
263         return name_for_xml (X509_get_subject_name (_certificate));
264 }
265
266 string
267 Certificate::subject_common_name () const
268 {
269         DCP_ASSERT (_certificate);
270
271         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
272 }
273
274 string
275 Certificate::subject_organization_name () const
276 {
277         DCP_ASSERT (_certificate);
278
279         return get_name_part (X509_get_subject_name (_certificate), NID_organizationName);
280 }
281
282 string
283 Certificate::subject_organizational_unit_name () const
284 {
285         DCP_ASSERT (_certificate);
286
287         return get_name_part (X509_get_subject_name (_certificate), NID_organizationalUnitName);
288 }
289
290 string
291 Certificate::serial () const
292 {
293         DCP_ASSERT (_certificate);
294
295         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
296         DCP_ASSERT (s);
297
298         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
299         char* c = BN_bn2dec (b);
300         BN_free (b);
301
302         string st (c);
303         OPENSSL_free (c);
304
305         return st;
306 }
307
308 string
309 Certificate::thumbprint () const
310 {
311         DCP_ASSERT (_certificate);
312
313         uint8_t buffer[8192];
314         uint8_t* p = buffer;
315         i2d_X509_CINF (_certificate->cert_info, &p);
316         unsigned int const length = p - buffer;
317         if (length > sizeof (buffer)) {
318                 throw MiscError ("buffer too small to generate thumbprint");
319         }
320
321         SHA_CTX sha;
322         SHA1_Init (&sha);
323         SHA1_Update (&sha, buffer, length);
324         uint8_t digest[20];
325         SHA1_Final (digest, &sha);
326
327         char digest_base64[64];
328         return Kumu::base64encode (digest, 20, digest_base64, 64);
329 }
330
331 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
332 RSA *
333 Certificate::public_key () const
334 {
335         DCP_ASSERT (_certificate);
336
337         if (_public_key) {
338                 return _public_key;
339         }
340
341         EVP_PKEY* key = X509_get_pubkey (_certificate);
342         if (!key) {
343                 throw MiscError ("could not get public key from certificate");
344         }
345
346         _public_key = EVP_PKEY_get1_RSA (key);
347         if (!_public_key) {
348                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
349         }
350
351         return _public_key;
352 }
353
354 bool
355 dcp::operator== (Certificate const & a, Certificate const & b)
356 {
357         return a.certificate() == b.certificate();
358 }
359
360 bool
361 dcp::operator< (Certificate const & a, Certificate const & b)
362 {
363         return a.certificate() < b.certificate();
364 }
365
366 ostream&
367 dcp::operator<< (ostream& s, Certificate const & c)
368 {
369         s << c.certificate();
370         return s;
371 }