2 Copyright (C) 2013-2015 Carl Hetherington <cth@carlh.net>
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.
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.
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.
20 /** @file src/signer_chain.cc
21 * @brief Functions to make signer chains.
24 #include "certificate_chain.h"
25 #include "exceptions.h"
27 #include "dcp_assert.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>
49 using std::stringstream;
52 /** Run a shell command.
53 * @param cmd Command to run (UTF8-encoded).
59 /* We need to use CreateProcessW on Windows so that the UTF-8/16 mess
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) {
71 STARTUPINFOW startup_info;
72 memset (&startup_info, 0, sizeof (startup_info));
73 startup_info.cb = sizeof (startup_info);
74 PROCESS_INFORMATION process_info;
76 /* XXX: this doesn't actually seem to work; failing commands end up with
79 if (CreateProcessW (0, buffer, 0, 0, FALSE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
80 WaitForSingleObject (process_info.hProcess, INFINITE);
82 if (GetExitCodeProcess (process_info.hProcess, &c)) {
85 CloseHandle (process_info.hProcess);
86 CloseHandle (process_info.hThread);
91 cmd += " 2> /dev/null";
92 int const r = system (cmd.c_str ());
93 int const code = WEXITSTATUS (r);
97 s << "error " << code << " in " << cmd << " within " << boost::filesystem::current_path();
98 throw dcp::MiscError (s.str());
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.
108 public_key_digest (boost::filesystem::path private_key, boost::filesystem::path openssl)
110 boost::filesystem::path public_name = private_key.string() + ".public";
112 /* Create the public key from the private key */
114 s << "\"" << openssl.string() << "\" rsa -outform PEM -pubout -in " << private_key.string() << " -out " << public_name.string ();
115 command (s.str().c_str ());
117 /* Read in the public key from the file */
120 ifstream f (public_name.string().c_str ());
122 throw dcp::MiscError ("public key not found");
129 if (line.length() >= 10 && line.substr(0, 10) == "-----BEGIN") {
131 } else if (line.length() >= 8 && line.substr(0, 8) == "-----END") {
138 /* Decode the base64 of the public key */
140 unsigned char buffer[512];
141 int const N = dcp::base64_decode (pub, buffer, 1024);
143 /* Hash it with SHA1 (without the first 24 bytes, for reasons that are not entirely clear) */
146 if (!SHA1_Init (&context)) {
147 throw dcp::MiscError ("could not init SHA1 context");
150 if (!SHA1_Update (&context, buffer + 24, N - 24)) {
151 throw dcp::MiscError ("could not update SHA1 digest");
154 unsigned char digest[SHA_DIGEST_LENGTH];
155 if (!SHA1_Final (digest, &context)) {
156 throw dcp::MiscError ("could not finish SHA1 digest");
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, "/", "\\/");
164 boost::replace_all (dig, "/", "\\\\/");
169 CertificateChain::CertificateChain (
170 boost::filesystem::path openssl,
172 string organisational_unit,
173 string root_common_name,
174 string intermediate_common_name,
175 string leaf_common_name
178 boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
179 boost::filesystem::create_directories (directory);
181 boost::filesystem::path const cwd = boost::filesystem::current_path ();
182 boost::filesystem::current_path (directory);
184 string quoted_openssl = "\"" + openssl.string() + "\"";
186 command (quoted_openssl + " genrsa -out ca.key 2048");
189 ofstream f ("ca.cnf");
191 << "distinguished_name = req_distinguished_name\n"
192 << "x509_extensions = 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";
204 string const ca_subject = "/O=" + organisation +
205 "/OU=" + organisational_unit +
206 "/CN=" + root_common_name +
207 "/dnQualifier=" + public_key_digest ("ca.key", 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());
217 command (quoted_openssl + " genrsa -out intermediate.key 2048");
220 ofstream f ("intermediate.cnf");
222 << "distinguished_name = req_distinguished_name\n"
223 << "x509_extensions = 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";
235 string const inter_subject = "/O=" + organisation +
236 "/OU=" + organisational_unit +
237 "/CN=" + intermediate_common_name +
238 "/dnQualifier=" + public_key_digest ("intermediate.key", openssl);
243 << " req -new -config intermediate.cnf -days 3649 -subj \"" << inter_subject << "\" -key intermediate.key -out intermediate.csr";
244 command (s.str().c_str());
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"
254 command (quoted_openssl + " genrsa -out leaf.key 2048");
257 ofstream f ("leaf.cnf");
259 << "distinguished_name = req_distinguished_name\n"
260 << "x509_extensions = 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";
272 string const leaf_subject = "/O=" + organisation +
273 "/OU=" + organisational_unit +
274 "/CN=" + leaf_common_name +
275 "/dnQualifier=" + public_key_digest ("leaf.key", openssl);
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());
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"
289 boost::filesystem::current_path (cwd);
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")));
295 _key = dcp::file_to_string (directory / "leaf.key");
297 boost::filesystem::remove_all (directory);
300 /** @return Root certificate */
302 CertificateChain::root () const
304 DCP_ASSERT (!_certificates.empty());
305 return _certificates.front ();
308 /** @return Leaf certificate */
310 CertificateChain::leaf () const
312 DCP_ASSERT (_certificates.size() >= 2);
313 return _certificates.back ();
316 /** @return Certificates in order from root to leaf */
317 CertificateChain::List
318 CertificateChain::root_to_leaf () const
320 return _certificates;
323 /** @return Certificates in order from leaf to root */
324 CertificateChain::List
325 CertificateChain::leaf_to_root () const
327 List c = _certificates;
332 /** Add a certificate to the end of the chain.
333 * @param c Certificate to add.
336 CertificateChain::add (Certificate c)
338 _certificates.push_back (c);
341 /** Remove a certificate from the chain.
342 * @param c Certificate to remove.
345 CertificateChain::remove (Certificate c)
347 _certificates.remove (c);
350 /** Remove the i'th certificate in the list, as listed
354 CertificateChain::remove (int i)
356 List::iterator j = _certificates.begin ();
357 while (j != _certificates.end () && i > 0) {
362 if (j != _certificates.end ()) {
363 _certificates.erase (j);
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
370 * @return true if it's ok, false if not.
373 CertificateChain::valid () const
375 /* Check the certificate chain */
377 X509_STORE* store = X509_STORE_new ();
382 for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
384 List::const_iterator j = i;
386 if (j == _certificates.end ()) {
390 if (!X509_STORE_add_cert (store, i->x509 ())) {
391 X509_STORE_free (store);
395 X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
397 X509_STORE_free (store);
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);
408 int v = X509_verify_cert (ctx);
409 X509_STORE_CTX_free (ctx);
412 X509_STORE_free (store);
417 X509_STORE_free (store);
419 /* Check that the leaf certificate matches the private key, if there is one */
425 BIO* bio = BIO_new_mem_buf (const_cast<char *> (_key->c_str ()), -1);
427 throw MiscError ("could not create memory BIO");
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);
438 /** @return true if the chain is now in order from root to leaf,
439 * false if no correct order was found.
442 CertificateChain::attempt_reorder ()
444 List original = _certificates;
445 _certificates.sort ();
450 } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
452 _certificates = original;
456 /** Add a <Signer> and <ds:Signature> nodes to an XML node.
457 * @param parent XML node to add to.
458 * @param standard INTEROP or SMPTE.
461 CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
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());
474 xmlpp::Element* signature = parent->add_child("Signature", "dsig");
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");
479 if (standard == INTEROP) {
480 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1");
482 signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
485 xmlpp::Element* reference = signed_info->add_child("Reference", "dsig");
486 reference->set_attribute ("URI", "");
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"
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");
497 signature->add_child("SignatureValue", "dsig");
498 signature->add_child("KeyInfo", "dsig");
499 add_signature_value (signature, "dsig");
503 /** Sign an XML node.
505 * @param parent Node to sign.
506 * @param ns Namespace to use for the signature XML nodes.
509 CertificateChain::add_signature_value (xmlpp::Node* parent, string ns) const
511 cxml::Node cp (parent);
512 xmlpp::Node* key_info = cp.node_child("KeyInfo")->node ();
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);
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 ());
525 data->add_child("X509Certificate", ns)->add_child_text (i.certificate());
528 xmlSecDSigCtxPtr signature_context = xmlSecDSigCtxCreate (0);
529 if (signature_context == 0) {
530 throw MiscError ("could not create signature context");
533 signature_context->signKey = xmlSecCryptoAppKeyLoadMemory (
534 reinterpret_cast<const unsigned char *> (_key->c_str()), _key->size(), xmlSecKeyDataFormatPem, 0, 0, 0
537 if (signature_context->signKey == 0) {
538 throw StringError ("could not read private key");
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");
546 int const r = xmlSecDSigCtxSign (signature_context, parent->cobj ());
548 throw MiscError (String::compose ("could not sign (%1)", r));
551 xmlSecDSigCtxDestroy (signature_context);