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