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