Move CertificateChain into the right header.
[libdcp.git] / src / certificate_chain.cc
1 /*
2     Copyright (C) 2013-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/signer_chain.cc
21  *  @brief Functions to make signer chains.
22  */
23
24 #include "certificate_chain.h"
25 #include "exceptions.h"
26 #include "util.h"
27 #include "dcp_assert.h"
28 #include "KM_util.h"
29 #include <openssl/sha.h>
30 #include <openssl/bio.h>
31 #include <openssl/evp.h>
32 #include <boost/filesystem.hpp>
33 #include <boost/algorithm/string.hpp>
34 #include <fstream>
35 #include <sstream>
36
37 using std::string;
38 using std::ofstream;
39 using std::ifstream;
40 using std::stringstream;
41 using namespace dcp;
42
43 /** Run a shell command.
44  *  @param cmd Command to run (UTF8-encoded).
45  */
46 static void
47 command (string cmd)
48 {
49 #ifdef LIBDCP_WINDOWS
50         /* We need to use CreateProcessW on Windows so that the UTF-8/16 mess
51            is handled correctly.
52         */
53         int const wn = MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, 0, 0);
54         wchar_t* buffer = new wchar_t[wn];
55         if (MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, buffer, wn) == 0) {
56                 delete[] buffer;
57                 return;
58         }
59
60         int code = 1;
61
62         STARTUPINFOW startup_info;
63         memset (&startup_info, 0, sizeof (startup_info));
64         startup_info.cb = sizeof (startup_info);
65         PROCESS_INFORMATION process_info;
66
67         /* XXX: this doesn't actually seem to work; failing commands end up with
68            a return code of 0
69         */
70         if (CreateProcessW (0, buffer, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
71                 WaitForSingleObject (process_info.hProcess, INFINITE);
72                 DWORD c;
73                 if (GetExitCodeProcess (process_info.hProcess, &c)) {
74                         code = c;
75                 }
76                 CloseHandle (process_info.hProcess);
77                 CloseHandle (process_info.hThread);
78         }
79
80         delete[] buffer;
81 #else
82         cmd += " 2> /dev/null";
83         int const r = system (cmd.c_str ());
84         int const code = WEXITSTATUS (r);
85 #endif
86         if (code) {
87                 stringstream s;
88                 s << "error " << code << " in " << cmd << " within " << boost::filesystem::current_path();
89                 throw dcp::MiscError (s.str());
90         }
91 }
92
93 /** Extract a public key from a private key and create a SHA1 digest of it.
94  *  @param private_key Private key
95  *  @param openssl openssl binary name (or full path if openssl is not on the system path).
96  *  @return SHA1 digest of corresponding public key, with escaped / characters.
97  */
98 static string
99 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
100 {
101         boost::filesystem::path public_name = private_key.string() + ".public";
102
103         /* Create the public key from the private key */
104         stringstream s;
105         s << "\"" << openssl.string() << "\" rsa -outform PEM -pubout -in " << private_key.string() << " -out " << public_name.string ();
106         command (s.str().c_str ());
107
108         /* Read in the public key from the file */
109
110         string pub;
111         ifstream f (public_name.string().c_str ());
112         if (!f.good ()) {
113                 throw dcp::MiscError ("public key not found");
114         }
115
116         bool read = false;
117         while (f.good ()) {
118                 string line;
119                 getline (f, line);
120                 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
121                         read = true;
122                 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
123                         break;
124                 } else if (read) {
125                         pub += line;
126                 }
127         }
128
129         /* Decode the base64 of the public key */
130
131         unsigned char buffer[512];
132         int const N = dcp::base64_decode (pub, buffer, 1024);
133
134         /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
135
136         SHA_CTX context;
137         if (!SHA1_Init (&context)) {
138                 throw dcp::MiscError ("could not init SHA1 context");
139         }
140
141         if (!SHA1_Update (&context, buffer + 24, N - 24)) {
142                 throw dcp::MiscError ("could not update SHA1 digest");
143         }
144
145         unsigned char digest[SHA_DIGEST_LENGTH];
146         if (!SHA1_Final (digest, &context)) {
147                 throw dcp::MiscError ("could not finish SHA1 digest");
148         }
149
150         char digest_base64[64];
151         string dig = Kumu::base64encode (digest, SHA_DIGEST_LENGTH, digest_base64, 64);
152 #ifdef LIBDCP_WINDOWS
153         boost::replace_all (dig, "/", "\\/");
154 #else
155         boost::replace_all (dig, "/", "\\\\/");
156 #endif
157         return dig;
158 }
159
160 boost::filesystem::path
161 dcp::make_certificate_chain (
162         boost::filesystem::path openssl,
163         string organisation,
164         string organisational_unit,
165         string root_common_name,
166         string intermediate_common_name,
167         string leaf_common_name
168         )
169 {
170         boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
171         boost::filesystem::create_directories (directory);
172
173         boost::filesystem::path const cwd = boost::filesystem::current_path ();
174         boost::filesystem::current_path (directory);
175
176         string quoted_openssl = "\"" + openssl.string() + "\"";
177
178         command (quoted_openssl + " genrsa -out ca.key 2048");
179
180         {
181                 ofstream f ("ca.cnf");
182                 f << "[ req ]\n"
183                   << "distinguished_name = req_distinguished_name\n"
184                   << "x509_extensions   = v3_ca\n"
185                   << "[ v3_ca ]\n"
186                   << "basicConstraints = critical,CA:true,pathlen:3\n"
187                   << "keyUsage = keyCertSign,cRLSign\n"
188                   << "subjectKeyIdentifier = hash\n"
189                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
190                   << "[ req_distinguished_name ]\n"
191                   << "O = Unique organization name\n"
192                   << "OU = Organization unit\n"
193                   << "CN = Entity and dnQualifier\n";
194         }
195
196         string const ca_subject = "/O=" + organisation +
197                 "/OU=" + organisational_unit +
198                 "/CN=" + root_common_name +
199                 "/dnQualifier=" + public_key_digest ("ca.key", openssl);
200
201         {
202                 stringstream c;
203                 c << quoted_openssl
204                   << " req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
205                   << " -subj \"" << ca_subject << "\" -key ca.key -outform PEM -out ca.self-signed.pem";
206                 command (c.str().c_str());
207         }
208
209         command (quoted_openssl + " genrsa -out intermediate.key 2048");
210
211         {
212                 ofstream f ("intermediate.cnf");
213                 f << "[ default ]\n"
214                   << "distinguished_name = req_distinguished_name\n"
215                   << "x509_extensions = v3_ca\n"
216                   << "[ v3_ca ]\n"
217                   << "basicConstraints = critical,CA:true,pathlen:2\n"
218                   << "keyUsage = keyCertSign,cRLSign\n"
219                   << "subjectKeyIdentifier = hash\n"
220                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
221                   << "[ req_distinguished_name ]\n"
222                   << "O = Unique organization name\n"
223                   << "OU = Organization unit\n"
224                   << "CN = Entity and dnQualifier\n";
225         }
226
227         string const inter_subject = "/O=" + organisation +
228                 "/OU=" + organisational_unit +
229                 "/CN=" + intermediate_common_name +
230                 "/dnQualifier=" + public_key_digest ("intermediate.key", openssl);
231
232         {
233                 stringstream s;
234                 s << quoted_openssl
235                   << " req -new -config intermediate.cnf -days 3649 -subj \"" << inter_subject << "\" -key intermediate.key -out intermediate.csr";
236                 command (s.str().c_str());
237         }
238
239
240         command (
241                 quoted_openssl +
242                 " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
243                 " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
244                 );
245
246         command (quoted_openssl + " genrsa -out leaf.key 2048");
247
248         {
249                 ofstream f ("leaf.cnf");
250                 f << "[ default ]\n"
251                   << "distinguished_name = req_distinguished_name\n"
252                   << "x509_extensions   = v3_ca\n"
253                   << "[ v3_ca ]\n"
254                   << "basicConstraints = critical,CA:false\n"
255                   << "keyUsage = digitalSignature,keyEncipherment\n"
256                   << "subjectKeyIdentifier = hash\n"
257                   << "authorityKeyIdentifier = keyid,issuer:always\n"
258                   << "[ req_distinguished_name ]\n"
259                   << "O = Unique organization name\n"
260                   << "OU = Organization unit\n"
261                   << "CN = Entity and dnQualifier\n";
262         }
263
264         string const leaf_subject = "/O=" + organisation +
265                 "/OU=" + organisational_unit +
266                 "/CN=" + leaf_common_name +
267                 "/dnQualifier=" + public_key_digest ("leaf.key", openssl);
268
269         {
270                 stringstream s;
271                 s << quoted_openssl << " req -new -config leaf.cnf -days 3648 -subj \"" << leaf_subject << "\" -key leaf.key -outform PEM -out leaf.csr";
272                 command (s.str().c_str());
273         }
274
275         command (
276                 quoted_openssl +
277                 " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
278                 " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
279                 );
280
281         boost::filesystem::current_path (cwd);
282
283         return directory;
284 }
285
286 /** @return Root certificate */
287 Certificate
288 CertificateChain::root () const
289 {
290         DCP_ASSERT (!_certificates.empty());
291         return _certificates.front ();
292 }
293
294 /** @return Leaf certificate */
295 Certificate
296 CertificateChain::leaf () const
297 {
298         DCP_ASSERT (_certificates.size() >= 2);
299         return _certificates.back ();
300 }
301
302 /** @return Certificates in order from root to leaf */
303 CertificateChain::List
304 CertificateChain::root_to_leaf () const
305 {
306         return _certificates;
307 }
308
309 /** @return Certificates in order from leaf to root */
310 CertificateChain::List
311 CertificateChain::leaf_to_root () const
312 {
313         List c = _certificates;
314         c.reverse ();
315         return c;
316 }
317
318 /** Add a certificate to the end of the chain.
319  *  @param c Certificate to add.
320  */
321 void
322 CertificateChain::add (Certificate c)
323 {
324         _certificates.push_back (c);
325 }
326
327 /** Remove a certificate from the chain.
328  *  @param c Certificate to remove.
329  */
330 void
331 CertificateChain::remove (Certificate c)
332 {
333         _certificates.remove (c);
334 }
335
336 /** Remove the i'th certificate in the list, as listed
337  *  from root to leaf.
338  */
339 void
340 CertificateChain::remove (int i)
341 {
342         List::iterator j = _certificates.begin ();
343         while (j != _certificates.end () && i > 0) {
344                 --i;
345                 ++j;
346         }
347
348         if (j != _certificates.end ()) {
349                 _certificates.erase (j);
350         }
351 }
352
353 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
354  *  signs the leaf and so on).
355  *  @return true if it's ok, false if not.
356  */
357 bool
358 CertificateChain::valid () const
359 {
360         X509_STORE* store = X509_STORE_new ();
361         if (!store) {
362                 return false;
363         }
364
365         for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
366
367                 List::const_iterator j = i;
368                 ++j;
369                 if (j ==  _certificates.end ()) {
370                         break;
371                 }
372
373                 if (!X509_STORE_add_cert (store, i->x509 ())) {
374                         X509_STORE_free (store);
375                         return false;
376                 }
377
378                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
379                 if (!ctx) {
380                         X509_STORE_free (store);
381                         return false;
382                 }
383
384                 X509_STORE_set_flags (store, 0);
385                 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
386                         X509_STORE_CTX_free (ctx);
387                         X509_STORE_free (store);
388                         return false;
389                 }
390
391                 int v = X509_verify_cert (ctx);
392                 X509_STORE_CTX_free (ctx);
393
394                 if (v == 0) {
395                         X509_STORE_free (store);
396                         return false;
397                 }
398         }
399
400         X509_STORE_free (store);
401         return true;
402 }
403
404 /** @return true if the chain is now in order from root to leaf,
405  *  false if no correct order was found.
406  */
407 bool
408 CertificateChain::attempt_reorder ()
409 {
410         List original = _certificates;
411         _certificates.sort ();
412         do {
413                 if (valid ()) {
414                         return true;
415                 }
416         } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
417
418         _certificates = original;
419         return false;
420 }