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