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