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