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