Use std::runtime_error instead of our own StringError as
[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 "compose.hpp"
30 #include <libcxml/cxml.h>
31 #include <libxml++/libxml++.h>
32 #include <xmlsec/xmldsig.h>
33 #include <xmlsec/dl.h>
34 #include <xmlsec/app.h>
35 #include <xmlsec/crypto.h>
36 #include <openssl/sha.h>
37 #include <openssl/bio.h>
38 #include <openssl/evp.h>
39 #include <openssl/pem.h>
40 #include <boost/filesystem.hpp>
41 #include <boost/algorithm/string.hpp>
42 #include <boost/foreach.hpp>
43 #include <fstream>
44 #include <sstream>
45
46 using std::string;
47 using std::ofstream;
48 using std::ifstream;
49 using std::runtime_error;
50 using std::stringstream;
51 using namespace dcp;
52
53 /** Run a shell command.
54  *  @param cmd Command to run (UTF8-encoded).
55  */
56 static void
57 command (string cmd)
58 {
59 #ifdef LIBDCP_WINDOWS
60         /* We need to use CreateProcessW on Windows so that the UTF-8/16 mess
61            is handled correctly.
62         */
63         int const wn = MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, 0, 0);
64         wchar_t* buffer = new wchar_t[wn];
65         if (MultiByteToWideChar (CP_UTF8, 0, cmd.c_str(), -1, buffer, wn) == 0) {
66                 delete[] buffer;
67                 return;
68         }
69
70         int code = 1;
71
72         STARTUPINFOW startup_info;
73         memset (&startup_info, 0, sizeof (startup_info));
74         startup_info.cb = sizeof (startup_info);
75         PROCESS_INFORMATION process_info;
76
77         /* XXX: this doesn't actually seem to work; failing commands end up with
78            a return code of 0
79         */
80         if (CreateProcessW (0, buffer, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
81                 WaitForSingleObject (process_info.hProcess, INFINITE);
82                 DWORD c;
83                 if (GetExitCodeProcess (process_info.hProcess, &c)) {
84                         code = c;
85                 }
86                 CloseHandle (process_info.hProcess);
87                 CloseHandle (process_info.hThread);
88         }
89
90         delete[] buffer;
91 #else
92         cmd += " 2> /dev/null";
93         int const r = system (cmd.c_str ());
94         int const code = WEXITSTATUS (r);
95 #endif
96         if (code) {
97                 stringstream s;
98                 s << "error " << code << " in " << cmd << " within " << boost::filesystem::current_path();
99                 throw dcp::MiscError (s.str());
100         }
101 }
102
103 /** Extract a public key from a private key and create a SHA1 digest of it.
104  *  @param private_key Private key
105  *  @param openssl openssl binary name (or full path if openssl is not on the system path).
106  *  @return SHA1 digest of corresponding public key, with escaped / characters.
107  */
108 static string
109 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
110 {
111         boost::filesystem::path public_name = private_key.string() + ".public";
112
113         /* Create the public key from the private key */
114         stringstream s;
115         s << "\"" << openssl.string() << "\" rsa -outform PEM -pubout -in " << private_key.string() << " -out " << public_name.string ();
116         command (s.str().c_str ());
117
118         /* Read in the public key from the file */
119
120         string pub;
121         ifstream f (public_name.string().c_str ());
122         if (!f.good ()) {
123                 throw dcp::MiscError ("public key not found");
124         }
125
126         bool read = false;
127         while (f.good ()) {
128                 string line;
129                 getline (f, line);
130                 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
131                         read = true;
132                 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
133                         break;
134                 } else if (read) {
135                         pub += line;
136                 }
137         }
138
139         /* Decode the base64 of the public key */
140
141         unsigned char buffer[512];
142         int const N = dcp::base64_decode (pub, buffer, 1024);
143
144         /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
145
146         SHA_CTX context;
147         if (!SHA1_Init (&context)) {
148                 throw dcp::MiscError ("could not init SHA1 context");
149         }
150
151         if (!SHA1_Update (&context, buffer + 24, N - 24)) {
152                 throw dcp::MiscError ("could not update SHA1 digest");
153         }
154
155         unsigned char digest[SHA_DIGEST_LENGTH];
156         if (!SHA1_Final (digest, &context)) {
157                 throw dcp::MiscError ("could not finish SHA1 digest");
158         }
159
160         char digest_base64[64];
161         string dig = Kumu::base64encode (digest, SHA_DIGEST_LENGTH, digest_base64, 64);
162 #ifdef LIBDCP_WINDOWS
163         boost::replace_all (dig, "/", "\\/");
164 #else
165         boost::replace_all (dig, "/", "\\\\/");
166 #endif
167         return dig;
168 }
169
170 CertificateChain::CertificateChain (
171         boost::filesystem::path openssl,
172         string organisation,
173         string organisational_unit,
174         string root_common_name,
175         string intermediate_common_name,
176         string leaf_common_name
177         )
178 {
179         boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
180         boost::filesystem::create_directories (directory);
181
182         boost::filesystem::path const cwd = boost::filesystem::current_path ();
183         boost::filesystem::current_path (directory);
184
185         string quoted_openssl = "\"" + openssl.string() + "\"";
186
187         command (quoted_openssl + " genrsa -out ca.key 2048");
188
189         {
190                 ofstream f ("ca.cnf");
191                 f << "[ req ]\n"
192                   << "distinguished_name = req_distinguished_name\n"
193                   << "x509_extensions   = v3_ca\n"
194                   << "[ v3_ca ]\n"
195                   << "basicConstraints = critical,CA:true,pathlen:3\n"
196                   << "keyUsage = keyCertSign,cRLSign\n"
197                   << "subjectKeyIdentifier = hash\n"
198                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
199                   << "[ req_distinguished_name ]\n"
200                   << "O = Unique organization name\n"
201                   << "OU = Organization unit\n"
202                   << "CN = Entity and dnQualifier\n";
203         }
204
205         string const ca_subject = "/O=" + organisation +
206                 "/OU=" + organisational_unit +
207                 "/CN=" + root_common_name +
208                 "/dnQualifier=" + public_key_digest ("ca.key", openssl);
209
210         {
211                 stringstream c;
212                 c << quoted_openssl
213                   << " req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
214                   << " -subj \"" << ca_subject << "\" -key ca.key -outform PEM -out ca.self-signed.pem";
215                 command (c.str().c_str());
216         }
217
218         command (quoted_openssl + " genrsa -out intermediate.key 2048");
219
220         {
221                 ofstream f ("intermediate.cnf");
222                 f << "[ default ]\n"
223                   << "distinguished_name = req_distinguished_name\n"
224                   << "x509_extensions = v3_ca\n"
225                   << "[ v3_ca ]\n"
226                   << "basicConstraints = critical,CA:true,pathlen:2\n"
227                   << "keyUsage = keyCertSign,cRLSign\n"
228                   << "subjectKeyIdentifier = hash\n"
229                   << "authorityKeyIdentifier = keyid:always,issuer:always\n"
230                   << "[ req_distinguished_name ]\n"
231                   << "O = Unique organization name\n"
232                   << "OU = Organization unit\n"
233                   << "CN = Entity and dnQualifier\n";
234         }
235
236         string const inter_subject = "/O=" + organisation +
237                 "/OU=" + organisational_unit +
238                 "/CN=" + intermediate_common_name +
239                 "/dnQualifier=" + public_key_digest ("intermediate.key", openssl);
240
241         {
242                 stringstream s;
243                 s << quoted_openssl
244                   << " req -new -config intermediate.cnf -days 3649 -subj \"" << inter_subject << "\" -key intermediate.key -out intermediate.csr";
245                 command (s.str().c_str());
246         }
247
248
249         command (
250                 quoted_openssl +
251                 " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
252                 " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
253                 );
254
255         command (quoted_openssl + " genrsa -out leaf.key 2048");
256
257         {
258                 ofstream f ("leaf.cnf");
259                 f << "[ default ]\n"
260                   << "distinguished_name = req_distinguished_name\n"
261                   << "x509_extensions   = v3_ca\n"
262                   << "[ v3_ca ]\n"
263                   << "basicConstraints = critical,CA:false\n"
264                   << "keyUsage = digitalSignature,keyEncipherment\n"
265                   << "subjectKeyIdentifier = hash\n"
266                   << "authorityKeyIdentifier = keyid,issuer:always\n"
267                   << "[ req_distinguished_name ]\n"
268                   << "O = Unique organization name\n"
269                   << "OU = Organization unit\n"
270                   << "CN = Entity and dnQualifier\n";
271         }
272
273         string const leaf_subject = "/O=" + organisation +
274                 "/OU=" + organisational_unit +
275                 "/CN=" + leaf_common_name +
276                 "/dnQualifier=" + public_key_digest ("leaf.key", openssl);
277
278         {
279                 stringstream s;
280                 s << quoted_openssl << " req -new -config leaf.cnf -days 3648 -subj \"" << leaf_subject << "\" -key leaf.key -outform PEM -out leaf.csr";
281                 command (s.str().c_str());
282         }
283
284         command (
285                 quoted_openssl +
286                 " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
287                 " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
288                 );
289
290         boost::filesystem::current_path (cwd);
291
292         _certificates.push_back (dcp::Certificate (dcp::file_to_string (directory / "ca.self-signed.pem")));
293         _certificates.push_back (dcp::Certificate (dcp::file_to_string (directory / "intermediate.signed.pem")));
294         _certificates.push_back (dcp::Certificate (dcp::file_to_string (directory / "leaf.signed.pem")));
295
296         _key = dcp::file_to_string (directory / "leaf.key");
297
298         boost::filesystem::remove_all (directory);
299 }
300
301 /** @return Root certificate */
302 Certificate
303 CertificateChain::root () const
304 {
305         DCP_ASSERT (!_certificates.empty());
306         return _certificates.front ();
307 }
308
309 /** @return Leaf certificate */
310 Certificate
311 CertificateChain::leaf () const
312 {
313         DCP_ASSERT (_certificates.size() >= 2);
314         return _certificates.back ();
315 }
316
317 /** @return Certificates in order from root to leaf */
318 CertificateChain::List
319 CertificateChain::root_to_leaf () const
320 {
321         return _certificates;
322 }
323
324 /** @return Certificates in order from leaf to root */
325 CertificateChain::List
326 CertificateChain::leaf_to_root () const
327 {
328         List c = _certificates;
329         c.reverse ();
330         return c;
331 }
332
333 /** Add a certificate to the end of the chain.
334  *  @param c Certificate to add.
335  */
336 void
337 CertificateChain::add (Certificate c)
338 {
339         _certificates.push_back (c);
340 }
341
342 /** Remove a certificate from the chain.
343  *  @param c Certificate to remove.
344  */
345 void
346 CertificateChain::remove (Certificate c)
347 {
348         _certificates.remove (c);
349 }
350
351 /** Remove the i'th certificate in the list, as listed
352  *  from root to leaf.
353  */
354 void
355 CertificateChain::remove (int i)
356 {
357         List::iterator j = _certificates.begin ();
358         while (j != _certificates.end () && i > 0) {
359                 --i;
360                 ++j;
361         }
362
363         if (j != _certificates.end ()) {
364                 _certificates.erase (j);
365         }
366 }
367
368 /** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
369  *  signs the leaf and so on) and that the private key (if there is one) matches the
370  *  leaf certificate.
371  *  @return true if it's ok, false if not.
372  */
373 bool
374 CertificateChain::valid () const
375 {
376         /* Check the certificate chain */
377
378         X509_STORE* store = X509_STORE_new ();
379         if (!store) {
380                 return false;
381         }
382
383         for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
384
385                 List::const_iterator j = i;
386                 ++j;
387                 if (j ==  _certificates.end ()) {
388                         break;
389                 }
390
391                 if (!X509_STORE_add_cert (store, i->x509 ())) {
392                         X509_STORE_free (store);
393                         return false;
394                 }
395
396                 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
397                 if (!ctx) {
398                         X509_STORE_free (store);
399                         return false;
400                 }
401
402                 X509_STORE_set_flags (store, 0);
403                 if (!X509_STORE_CTX_init (ctx, store, j->x509 (), 0)) {
404                         X509_STORE_CTX_free (ctx);
405                         X509_STORE_free (store);
406                         return false;
407                 }
408
409                 int v = X509_verify_cert (ctx);
410                 X509_STORE_CTX_free (ctx);
411
412                 if (v == 0) {
413                         X509_STORE_free (store);
414                         return false;
415                 }
416         }
417
418         X509_STORE_free (store);
419
420         /* Check that the leaf certificate matches the private key, if there is one */
421
422         if (!_key) {
423                 return true;
424         }
425
426         BIO* bio = BIO_new_mem_buf (const_cast<char *> (_key->c_str ()), -1);
427         if (!bio) {
428                 throw MiscError ("could not create memory BIO");
429         }
430
431         RSA* private_key = PEM_read_bio_RSAPrivateKey (bio, 0, 0, 0);
432         RSA* public_key = leaf().public_key ();
433         bool const valid = !BN_cmp (private_key->n, public_key->n);
434         BIO_free (bio);
435
436         return valid;
437 }
438
439 /** @return true if the chain is now in order from root to leaf,
440  *  false if no correct order was found.
441  */
442 bool
443 CertificateChain::attempt_reorder ()
444 {
445         List original = _certificates;
446         _certificates.sort ();
447         do {
448                 if (valid ()) {
449                         return true;
450                 }
451         } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
452
453         _certificates = original;
454         return false;
455 }
456
457 /** Add a &lt;Signer&gt; and &lt;ds:Signature&gt; nodes to an XML node.
458  *  @param parent XML node to add to.
459  *  @param standard INTEROP or SMPTE.
460  */
461 void
462 CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
463 {
464         /* <Signer> */
465
466         xmlpp::Element* signer = parent->add_child("Signer");
467         xmlpp::Element* data = signer->add_child("X509Data", "dsig");
468         xmlpp::Element* serial_element = data->add_child("X509IssuerSerial", "dsig");
469         serial_element->add_child("X509IssuerName", "dsig")->add_child_text (leaf().issuer());
470         serial_element->add_child("X509SerialNumber", "dsig")->add_child_text (leaf().serial());
471         data->add_child("X509SubjectName", "dsig")->add_child_text (leaf().subject());
472
473         /* <Signature> */
474
475         xmlpp::Element* signature = parent->add_child("Signature", "dsig");
476
477         xmlpp::Element* signed_info = signature->add_child ("SignedInfo", "dsig");
478         signed_info->add_child("CanonicalizationMethod", "dsig")->set_attribute ("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
479
480         if (standard == INTEROP) {
481                 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1");
482         } else {
483                 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
484         }
485
486         xmlpp::Element* reference = signed_info->add_child("Reference", "dsig");
487         reference->set_attribute ("URI", "");
488
489         xmlpp::Element* transforms = reference->add_child("Transforms", "dsig");
490         transforms->add_child("Transform", "dsig")->set_attribute (
491                 "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
492                 );
493
494         reference->add_child("DigestMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
495         /* This will be filled in by the signing later */
496         reference->add_child("DigestValue", "dsig");
497
498         signature->add_child("SignatureValue", "dsig");
499         signature->add_child("KeyInfo", "dsig");
500         add_signature_value (signature, "dsig");
501 }
502
503
504 /** Sign an XML node.
505  *
506  *  @param parent Node to sign.
507  *  @param ns Namespace to use for the signature XML nodes.
508  */
509 void
510 CertificateChain::add_signature_value (xmlpp::Node* parent, string ns) const
511 {
512         cxml::Node cp (parent);
513         xmlpp::Node* key_info = cp.node_child("KeyInfo")->node ();
514
515         /* Add the certificate chain to the KeyInfo child node of parent */
516         CertificateChain::List c = leaf_to_root ();
517         BOOST_FOREACH (Certificate const & i, leaf_to_root ()) {
518                 xmlpp::Element* data = key_info->add_child("X509Data", ns);
519
520                 {
521                         xmlpp::Element* serial = data->add_child("X509IssuerSerial", ns);
522                         serial->add_child("X509IssuerName", ns)->add_child_text (i.issuer ());
523                         serial->add_child("X509SerialNumber", ns)->add_child_text (i.serial ());
524                 }
525
526                 data->add_child("X509Certificate", ns)->add_child_text (i.certificate());
527         }
528
529         xmlSecDSigCtxPtr signature_context = xmlSecDSigCtxCreate (0);
530         if (signature_context == 0) {
531                 throw MiscError ("could not create signature context");
532         }
533
534         signature_context->signKey = xmlSecCryptoAppKeyLoadMemory (
535                 reinterpret_cast<const unsigned char *> (_key->c_str()), _key->size(), xmlSecKeyDataFormatPem, 0, 0, 0
536                 );
537
538         if (signature_context->signKey == 0) {
539                 throw runtime_error ("could not read private key");
540         }
541
542         /* XXX: set key name to the PEM string: this can't be right! */
543         if (xmlSecKeySetName (signature_context->signKey, reinterpret_cast<const xmlChar *> (_key->c_str())) < 0) {
544                 throw MiscError ("could not set key name");
545         }
546
547         int const r = xmlSecDSigCtxSign (signature_context, parent->cobj ());
548         if (r < 0) {
549                 throw MiscError (String::compose ("could not sign (%1)", r));
550         }
551
552         xmlSecDSigCtxDestroy (signature_context);
553 }