Merge branch '1.0' of ssh://main.carlh.net/home/carl/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 <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         getline (s, line);
94         boost::algorithm::trim (line);
95         if (line != begin_certificate) {
96                 throw MiscError ("missing BEGIN line in certificate");
97         }
98
99         /* The base64 data */
100         bool got_end = false;
101         string base64 = "";
102         while (getline (s, line)) {
103                 boost::algorithm::trim (line);
104                 if (line == end_certificate) {
105                         got_end = true;
106                         break;
107                 }
108                 base64 += line;
109         }
110
111         if (!got_end) {
112                 throw MiscError ("missing END line in certificate");
113         }
114
115         /* Make up the fixed version */
116
117         string fixed = begin_certificate + "\n";
118         while (!base64.empty ()) {
119                 size_t const t = min (size_t(64), base64.length());
120                 fixed += base64.substr (0, t) + "\n";
121                 base64 = base64.substr (t, base64.length() - t);
122         }
123
124         fixed += end_certificate;
125
126         BIO* bio = BIO_new_mem_buf (const_cast<char *> (fixed.c_str ()), -1);
127         if (!bio) {
128                 throw MiscError ("could not create memory BIO");
129         }
130
131         _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
132         if (!_certificate) {
133                 throw MiscError ("could not read X509 certificate from memory BIO");
134         }
135
136         BIO_free (bio);
137 }
138
139 /** Destructor */
140 Certificate::~Certificate ()
141 {
142         X509_free (_certificate);
143         RSA_free (_public_key);
144 }
145
146 /** operator= for Certificate.
147  *  @param other Certificate to read from.
148  */
149 Certificate &
150 Certificate::operator= (Certificate const & other)
151 {
152         if (this == &other) {
153                 return *this;
154         }
155
156         X509_free (_certificate);
157         _certificate = 0;
158         RSA_free (_public_key);
159         _public_key = 0;
160
161         read_string (other.certificate (true));
162
163         return *this;
164 }
165
166 /** Return the certificate as a string.
167  *  @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
168  *  @return Certificate string.
169  */
170 string
171 Certificate::certificate (bool with_begin_end) const
172 {
173         DCP_ASSERT (_certificate);
174
175         BIO* bio = BIO_new (BIO_s_mem ());
176         if (!bio) {
177                 throw MiscError ("could not create memory BIO");
178         }
179
180         PEM_write_bio_X509 (bio, _certificate);
181
182         string s;
183         char* data;
184         long int const data_length = BIO_get_mem_data (bio, &data);
185         for (long int i = 0; i < data_length; ++i) {
186                 s += data[i];
187         }
188
189         BIO_free (bio);
190
191         if (!with_begin_end) {
192                 boost::replace_all (s, begin_certificate + "\n", "");
193                 boost::replace_all (s, "\n" + end_certificate + "\n", "");
194         }
195
196         return s;
197 }
198
199 /** @return Certificate's issuer, in the form
200  *  dnqualifier=&lt;dnQualififer&gt;,CN=&lt;commonName&gt;,OU=&lt;organizationalUnitName&gt,O=&lt;organizationName&gt;
201  *  and with + signs escaped to \+
202  */
203 string
204 Certificate::issuer () const
205 {
206         DCP_ASSERT (_certificate);
207         return name_for_xml (X509_get_issuer_name (_certificate));
208 }
209
210 string
211 Certificate::asn_to_utf8 (ASN1_STRING* s)
212 {
213         unsigned char* buf = 0;
214         ASN1_STRING_to_UTF8 (&buf, s);
215         string const u (reinterpret_cast<char *> (buf));
216         OPENSSL_free (buf);
217         return u;
218 }
219
220 string
221 Certificate::get_name_part (X509_NAME* n, int nid)
222 {
223         int p = -1;
224         p = X509_NAME_get_index_by_NID (n, nid, p);
225         if (p == -1) {
226                 return "";
227         }
228         return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
229 }
230
231 string
232 Certificate::name_for_xml (X509_NAME* name)
233 {
234         assert (name);
235
236         BIO* bio = BIO_new (BIO_s_mem ());
237         if (!bio) {
238                 throw MiscError ("could not create memory BIO");
239         }
240
241         X509_NAME_print_ex (bio, name, 0, XN_FLAG_RFC2253);
242         int n = BIO_pending (bio);
243         char* result = new char[n + 1];
244         n = BIO_read (bio, result, n);
245         result[n] = '\0';
246
247         BIO_free (bio);
248
249         string s = result;
250         delete[] result;
251
252         return s;
253 }
254
255 string
256 Certificate::subject () const
257 {
258         DCP_ASSERT (_certificate);
259
260         return name_for_xml (X509_get_subject_name (_certificate));
261 }
262
263 string
264 Certificate::subject_common_name () const
265 {
266         DCP_ASSERT (_certificate);
267
268         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
269 }
270
271 string
272 Certificate::subject_organization_name () const
273 {
274         DCP_ASSERT (_certificate);
275
276         return get_name_part (X509_get_subject_name (_certificate), NID_organizationName);
277 }
278
279 string
280 Certificate::subject_organizational_unit_name () const
281 {
282         DCP_ASSERT (_certificate);
283
284         return get_name_part (X509_get_subject_name (_certificate), NID_organizationalUnitName);
285 }
286
287 string
288 Certificate::serial () const
289 {
290         DCP_ASSERT (_certificate);
291
292         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
293         DCP_ASSERT (s);
294
295         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
296         char* c = BN_bn2dec (b);
297         BN_free (b);
298
299         string st (c);
300         OPENSSL_free (c);
301
302         return st;
303 }
304
305 string
306 Certificate::thumbprint () const
307 {
308         DCP_ASSERT (_certificate);
309
310         uint8_t buffer[8192];
311         uint8_t* p = buffer;
312         i2d_X509_CINF (_certificate->cert_info, &p);
313         unsigned int const length = p - buffer;
314         if (length > sizeof (buffer)) {
315                 throw MiscError ("buffer too small to generate thumbprint");
316         }
317
318         SHA_CTX sha;
319         SHA1_Init (&sha);
320         SHA1_Update (&sha, buffer, length);
321         uint8_t digest[20];
322         SHA1_Final (digest, &sha);
323
324         char digest_base64[64];
325         return Kumu::base64encode (digest, 20, digest_base64, 64);
326 }
327
328 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
329 RSA *
330 Certificate::public_key () const
331 {
332         DCP_ASSERT (_certificate);
333
334         if (_public_key) {
335                 return _public_key;
336         }
337
338         EVP_PKEY* key = X509_get_pubkey (_certificate);
339         if (!key) {
340                 throw MiscError ("could not get public key from certificate");
341         }
342
343         _public_key = EVP_PKEY_get1_RSA (key);
344         if (!_public_key) {
345                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
346         }
347
348         return _public_key;
349 }
350
351 bool
352 dcp::operator== (Certificate const & a, Certificate const & b)
353 {
354         return a.certificate() == b.certificate();
355 }
356
357 bool
358 dcp::operator< (Certificate const & a, Certificate const & b)
359 {
360         return a.certificate() < b.certificate();
361 }
362
363 ostream&
364 dcp::operator<< (ostream& s, Certificate const & c)
365 {
366         s << c.certificate();
367         return s;
368 }