8682b831e119ca7954573ac465c5a0dee2b43ea8
[libdcp.git] / src / certificates.cc
1 /*
2     Copyright (C) 2012 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 #include <sstream>
21 #include <vector>
22 #include <cerrno>
23 #include <boost/algorithm/string.hpp>
24 #include <openssl/x509.h>
25 #include <openssl/ssl.h>
26 #include <openssl/asn1.h>
27 #include <openssl/err.h>
28 #include <libxml++/nodes/element.h>
29 #include "KM_util.h"
30 #include "certificates.h"
31 #include "compose.hpp"
32 #include "exceptions.h"
33 #include "util.h"
34
35 using std::list;
36 using std::string;
37 using std::stringstream;
38 using std::vector;
39 using boost::shared_ptr;
40 using namespace libdcp;
41
42 /** @param c X509 certificate, which this object will take ownership of */
43 Certificate::Certificate (X509* c)
44         : _certificate (c)
45         , _public_key (0)
46 {
47         
48 }
49
50 Certificate::Certificate (boost::filesystem::path filename)
51         : _certificate (0)
52         , _public_key (0)
53 {
54         FILE* f = fopen_boost (filename, "r");
55         if (!f) {
56                 throw FileError ("could not open file", filename, errno);
57         }
58         
59         if (!PEM_read_X509 (f, &_certificate, 0, 0)) {
60                 throw MiscError ("could not read X509 certificate");
61         }
62 }
63
64 Certificate::Certificate (string cert)
65         : _certificate (0)
66         , _public_key (0)
67 {
68         read_string (cert);
69 }
70
71 Certificate::Certificate (Certificate const & other)
72         : _certificate (0)
73         , _public_key (0)
74 {
75         read_string (other.certificate (true));
76 }
77
78 void
79 Certificate::read_string (string cert)
80 {
81         BIO* bio = BIO_new_mem_buf (const_cast<char *> (cert.c_str ()), -1);
82         if (!bio) {
83                 throw MiscError ("could not create memory BIO");
84         }
85
86         _certificate = PEM_read_bio_X509 (bio, 0, 0, 0);
87         if (!_certificate) {
88                 throw MiscError ("could not read X509 certificate from memory BIO");
89         }
90
91         BIO_free (bio);
92 }
93
94 Certificate::~Certificate ()
95 {
96         X509_free (_certificate);
97         RSA_free (_public_key);
98 }
99
100 Certificate &
101 Certificate::operator= (Certificate const & other)
102 {
103         if (this == &other) {
104                 return *this;
105         }
106
107         X509_free (_certificate);
108         _certificate = 0;
109         RSA_free (_public_key);
110         _public_key = 0;
111         
112         read_string (other.certificate ());
113
114         return *this;
115 }
116
117 string
118 Certificate::certificate (bool with_begin_end) const
119 {
120         assert (_certificate);
121         
122         BIO* bio = BIO_new (BIO_s_mem ());
123         if (!bio) {
124                 throw MiscError ("could not create memory BIO");
125         }
126         
127         PEM_write_bio_X509 (bio, _certificate);
128
129         string s;
130         char* data;
131         long int const data_length = BIO_get_mem_data (bio, &data);
132         for (long int i = 0; i < data_length; ++i) {
133                 s += data[i];
134         }
135
136         BIO_free (bio);
137
138         if (!with_begin_end) {
139                 boost::replace_all (s, "-----BEGIN CERTIFICATE-----\n", "");
140                 boost::replace_all (s, "\n-----END CERTIFICATE-----\n", "");
141         }
142         
143         return s;
144 }
145
146 string
147 Certificate::issuer () const
148 {
149         assert (_certificate);
150         return name_for_xml (X509_get_issuer_name (_certificate));
151 }
152
153 string
154 Certificate::asn_to_utf8 (ASN1_STRING* s)
155 {
156         unsigned char* buf = 0;
157         ASN1_STRING_to_UTF8 (&buf, s);
158         string const u (reinterpret_cast<char *> (buf));
159         OPENSSL_free (buf);
160         return u;
161 }
162
163 string
164 Certificate::get_name_part (X509_NAME* n, int nid)
165 {
166         int p = -1;
167         p = X509_NAME_get_index_by_NID (n, nid, p);
168         assert (p != -1);
169         return asn_to_utf8 (X509_NAME_ENTRY_get_data (X509_NAME_get_entry (n, p)));
170 }
171
172 string
173 Certificate::name_for_xml (X509_NAME* name)
174 {
175         assert (name);
176
177         BIO* bio = BIO_new (BIO_s_mem ());
178         if (!bio) {
179                 throw MiscError ("could not create memory BIO");
180         }
181
182         X509_NAME_print_ex (bio, name, 0, XN_FLAG_RFC2253);
183         int n = BIO_pending (bio);
184         char* result = new char[n + 1];
185         n = BIO_read (bio, result, n);
186         result[n] = '\0';
187
188         BIO_free (bio);
189
190         string s = result;
191         delete[] result;
192
193         return s;
194 }
195
196 string
197 Certificate::subject () const
198 {
199         assert (_certificate);
200
201         return name_for_xml (X509_get_subject_name (_certificate));
202 }
203
204 string
205 Certificate::common_name () const
206 {
207         assert (_certificate);
208
209         return get_name_part (X509_get_subject_name (_certificate), NID_commonName);
210 }
211
212 string
213 Certificate::serial () const
214 {
215         assert (_certificate);
216
217         ASN1_INTEGER* s = X509_get_serialNumber (_certificate);
218         assert (s);
219         
220         BIGNUM* b = ASN1_INTEGER_to_BN (s, 0);
221         char* c = BN_bn2dec (b);
222         BN_free (b);
223         
224         string st (c);
225         OPENSSL_free (c);
226
227         return st;
228 }
229
230 string
231 Certificate::thumbprint () const
232 {
233         assert (_certificate);
234         
235         uint8_t buffer[8192];
236         uint8_t* p = buffer;
237         i2d_X509_CINF (_certificate->cert_info, &p);
238         int const length = p - buffer;
239         if (length > 8192) {
240                 throw MiscError ("buffer too small to generate thumbprint");
241         }
242
243         SHA_CTX sha;
244         SHA1_Init (&sha);
245         SHA1_Update (&sha, buffer, length);
246         uint8_t digest[20];
247         SHA1_Final (digest, &sha);
248
249         char digest_base64[64];
250         return Kumu::base64encode (digest, 20, digest_base64, 64);
251 }
252
253 RSA *
254 Certificate::public_key () const
255 {
256         assert (_certificate);
257
258         if (_public_key) {
259                 return _public_key;
260         }
261
262         EVP_PKEY* key = X509_get_pubkey (_certificate);
263         if (!key) {
264                 throw MiscError ("could not get public key from certificate");
265         }
266
267         _public_key = EVP_PKEY_get1_RSA (key);
268         if (!_public_key) {
269                 throw MiscError (String::compose ("could not get RSA public key (%1)", ERR_error_string (ERR_get_error(), 0)));
270         }
271
272         return _public_key;
273 }
274
275 shared_ptr<Certificate>
276 CertificateChain::root () const
277 {
278         assert (!_certificates.empty());
279         return _certificates.front ();
280 }
281
282 shared_ptr<Certificate>
283 CertificateChain::leaf () const
284 {
285         assert (_certificates.size() >= 2);
286         return _certificates.back ();
287 }
288
289 list<shared_ptr<Certificate> >
290 CertificateChain::leaf_to_root () const
291 {
292         list<shared_ptr<Certificate> > c = _certificates;
293         c.reverse ();
294         return c;
295 }
296
297 void
298 CertificateChain::add (shared_ptr<Certificate> c)
299 {
300         _certificates.push_back (c);
301 }