Remove some unnecessary includes.
[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         line.clear ();
146         if (s.good ()) {
147                 getline (s, line);
148         }
149         return !line.empty();
150 }
151
152 /** Destructor */
153 Certificate::~Certificate ()
154 {
155         X509_free (_certificate);
156         RSA_free (_public_key);
157 }
158
159 /** operator= for Certificate.
160  *  @param other Certificate to read from.
161  */
162 Certificate &
163 Certificate::operator= (Certificate const & other)
164 {
165         if (this == &other) {
166                 return *this;
167         }
168
169         X509_free (_certificate);
170         _certificate = 0;
171         RSA_free (_public_key);
172         _public_key = 0;
173         _extra_data = other._extra_data;
174
175         read_string (other.certificate (true));
176
177         return *this;
178 }
179
180 /** Return the certificate as a string.
181  *  @param with_begin_end true to include the -----BEGIN CERTIFICATE--- / -----END CERTIFICATE----- markers.
182  *  @return Certificate string.
183  */
184 string
185 Certificate::certificate (bool with_begin_end) const
186 {
187         DCP_ASSERT (_certificate);
188
189         BIO* bio = BIO_new (BIO_s_mem ());
190         if (!bio) {
191                 throw MiscError ("could not create memory BIO");
192         }
193
194         PEM_write_bio_X509 (bio, _certificate);
195
196         string s;
197         char* data;
198         long int const data_length = BIO_get_mem_data (bio, &data);
199         for (long int i = 0; i < data_length; ++i) {
200                 s += data[i];
201         }
202
203         BIO_free (bio);
204
205         if (!with_begin_end) {
206                 boost::replace_all (s, begin_certificate + "\n", "");
207                 boost::replace_all (s, "\n" + end_certificate + "\n", "");
208         }
209
210         return s;
211 }
212
213 /** @return Certificate's issuer, in the form
214  *  dnqualifier=&lt;dnQualififer&gt;,CN=&lt;commonName&gt;,OU=&lt;organizationalUnitName&gt,O=&lt;organizationName&gt;
215  *  and with + signs escaped to \+
216  */
217 string
218 Certificate::issuer () const
219 {
220         DCP_ASSERT (_certificate);
221         return name_for_xml (X509_get_issuer_name (_certificate));
222 }
223
224 string
225 Certificate::asn_to_utf8 (ASN1_STRING* s)
226 {
227         unsigned char* buf = 0;
228         ASN1_STRING_to_UTF8 (&buf, s);
229         string const u (reinterpret_cast<char *> (buf));
230         OPENSSL_free (buf);
231         return u;
232 }
233
234 string
235 Certificate::get_name_part (X509_NAME* n, int nid)
236 {
237         int p = -1;
238         p = X509_NAME_get_index_by_NID (n, nid, p);
239         if (p == -1) {
240                 return "";
241         }
242         return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
243 }
244
245 string
246 Certificate::name_for_xml (X509_NAME* name)
247 {
248         assert (name);
249
250         BIO* bio = BIO_new (BIO_s_mem ());
251         if (!bio) {
252                 throw MiscError ("could not create memory BIO");
253         }
254
255         X509_NAME_print_ex (bio, name, 0, XN_FLAG_RFC2253);
256         int n = BIO_pending (bio);
257         char* result = new char[n + 1];
258         n = BIO_read (bio, result, n);
259         result[n] = '\0';
260
261         BIO_free (bio);
262
263         string s = result;
264         delete[] result;
265
266         return s;
267 }
268
269 string
270 Certificate::subject () const
271 {
272         DCP_ASSERT (_certificate);
273
274         return name_for_xml (X509_get_subject_name (_certificate));
275 }
276
277 string
278 Certificate::subject_common_name () const
279 {
280         DCP_ASSERT (_certificate);
281
282         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
283 }
284
285 string
286 Certificate::subject_organization_name () const
287 {
288         DCP_ASSERT (_certificate);
289
290         return get_name_part (X509_get_subject_name (_certificate), NID_organizationName);
291 }
292
293 string
294 Certificate::subject_organizational_unit_name () const
295 {
296         DCP_ASSERT (_certificate);
297
298         return get_name_part (X509_get_subject_name (_certificate), NID_organizationalUnitName);
299 }
300
301 string
302 Certificate::serial () const
303 {
304         DCP_ASSERT (_certificate);
305
306         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
307         DCP_ASSERT (s);
308
309         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
310         char* c = BN_bn2dec (b);
311         BN_free (b);
312
313         string st (c);
314         OPENSSL_free (c);
315
316         return st;
317 }
318
319 string
320 Certificate::thumbprint () const
321 {
322         DCP_ASSERT (_certificate);
323
324         uint8_t buffer[8192];
325         uint8_t* p = buffer;
326         i2d_X509_CINF (_certificate->cert_info, &p);
327         unsigned int const length = p - buffer;
328         if (length > sizeof (buffer)) {
329                 throw MiscError ("buffer too small to generate thumbprint");
330         }
331
332         SHA_CTX sha;
333         SHA1_Init (&sha);
334         SHA1_Update (&sha, buffer, length);
335         uint8_t digest[20];
336         SHA1_Final (digest, &sha);
337
338         char digest_base64[64];
339         return Kumu::base64encode (digest, 20, digest_base64, 64);
340 }
341
342 /** @return RSA public key from this Certificate.  Caller must not free the returned value. */
343 RSA *
344 Certificate::public_key () const
345 {
346         DCP_ASSERT (_certificate);
347
348         if (_public_key) {
349                 return _public_key;
350         }
351
352         EVP_PKEY* key = X509_get_pubkey (_certificate);
353         if (!key) {
354                 throw MiscError ("could not get public key from certificate");
355         }
356
357         _public_key = EVP_PKEY_get1_RSA (key);
358         if (!_public_key) {
359                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
360         }
361
362         return _public_key;
363 }
364
365 bool
366 dcp::operator== (Certificate const & a, Certificate const & b)
367 {
368         return a.certificate() == b.certificate();
369 }
370
371 bool
372 dcp::operator< (Certificate const & a, Certificate const & b)
373 {
374         return a.certificate() < b.certificate();
375 }
376
377 ostream&
378 dcp::operator<< (ostream& s, Certificate const & c)
379 {
380         s << c.certificate();
381         return s;
382 }