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