+ _certificates.push_back (dcp::Certificate(dcp::file_to_string(directory / "ca.self-signed.pem")));
+ _certificates.push_back (dcp::Certificate(dcp::file_to_string(directory / "intermediate.signed.pem")));
+ _certificates.push_back (dcp::Certificate(dcp::file_to_string(directory / "leaf.signed.pem")));
+
+ _key = dcp::file_to_string (directory / "leaf.key");
+
+ boost::filesystem::remove_all (directory);
+}
+
+
+CertificateChain::CertificateChain (string s)
+{
+ while (true) {
+ try {
+ Certificate c;
+ s = c.read_string (s);
+ _certificates.push_back (c);
+ } catch (MiscError& e) {
+ /* Failed to read a certificate, just stop */
+ break;
+ }
+ }
+
+ /* This will throw an exception if the chain cannot be ordered */
+ leaf_to_root ();
+}
+
+
+Certificate
+CertificateChain::root () const
+{
+ DCP_ASSERT (!_certificates.empty());
+ return root_to_leaf().front();
+}
+
+
+Certificate
+CertificateChain::leaf () const
+{
+ DCP_ASSERT (!_certificates.empty());
+ return root_to_leaf().back();
+}
+
+
+CertificateChain::List
+CertificateChain::leaf_to_root () const
+{
+ auto l = root_to_leaf ();
+ std::reverse (l.begin(), l.end());
+ return l;
+}
+
+
+CertificateChain::List
+CertificateChain::unordered () const
+{
+ return _certificates;
+}
+
+
+void
+CertificateChain::add (Certificate c)
+{
+ _certificates.push_back (c);
+}
+
+
+void
+CertificateChain::remove (Certificate c)
+{
+ auto i = std::find(_certificates.begin(), _certificates.end(), c);
+ if (i != _certificates.end()) {
+ _certificates.erase (i);
+ }
+}
+
+
+void
+CertificateChain::remove (int i)
+{
+ auto j = _certificates.begin ();
+ while (j != _certificates.end () && i > 0) {
+ --i;
+ ++j;
+ }
+
+ if (j != _certificates.end ()) {
+ _certificates.erase (j);
+ }
+}
+
+
+bool
+CertificateChain::chain_valid () const
+{
+ return chain_valid (_certificates);
+}
+
+
+bool
+CertificateChain::chain_valid (List const & chain) const
+{
+ /* Here I am taking a chain of certificates A/B/C/D and checking validity of B wrt A,
+ C wrt B and D wrt C. It also appears necessary to check the issuer of B/C/D matches
+ the subject of A/B/C; I don't understand why. I'm sure there's a better way of doing
+ this with OpenSSL but the documentation does not appear not likely to reveal it
+ any time soon.
+ */
+
+ auto store = X509_STORE_new ();
+ if (!store) {
+ throw MiscError ("could not create X509 store");
+ }
+
+ /* Put all the certificates into the store */
+ for (auto const& i: chain) {
+ if (!X509_STORE_add_cert(store, i.x509())) {
+ X509_STORE_free(store);
+ return false;
+ }
+ }
+
+ /* Verify each one */
+ for (auto i = chain.begin(); i != chain.end(); ++i) {
+
+ auto j = i;
+ ++j;
+ if (j == chain.end ()) {
+ break;
+ }
+
+ auto ctx = X509_STORE_CTX_new ();
+ if (!ctx) {
+ X509_STORE_free (store);
+ throw MiscError ("could not create X509 store context");
+ }
+
+ X509_STORE_set_flags (store, 0);
+ if (!X509_STORE_CTX_init (ctx, store, j->x509(), 0)) {
+ X509_STORE_CTX_free (ctx);
+ X509_STORE_free (store);
+ throw MiscError ("could not initialise X509 store context");
+ }
+
+ int const v = X509_verify_cert (ctx);
+ X509_STORE_CTX_free (ctx);
+
+ if (v != 1) {
+ X509_STORE_free (store);
+ return false;
+ }
+
+ /* I don't know why OpenSSL doesn't check this stuff
+ in verify_cert, but without these checks the
+ certificates_validation8 test fails.
+ */
+ if (j->issuer() != i->subject() || j->subject() == i->subject()) {
+ X509_STORE_free (store);
+ return false;
+ }
+
+ }
+
+ X509_STORE_free (store);
+
+ return true;
+}
+
+
+bool
+CertificateChain::private_key_valid () const
+{
+ if (_certificates.empty ()) {
+ return true;
+ }
+
+ if (!_key) {
+ return false;
+ }
+
+ auto bio = BIO_new_mem_buf (const_cast<char *> (_key->c_str ()), -1);
+ if (!bio) {
+ throw MiscError ("could not create memory BIO");
+ }
+
+ auto private_key = PEM_read_bio_RSAPrivateKey (bio, 0, 0, 0);
+ if (!private_key) {
+ return false;
+ }
+
+ auto public_key = leaf().public_key ();
+
+#if OPENSSL_VERSION_NUMBER > 0x10100000L
+ BIGNUM const * private_key_n;
+ RSA_get0_key(private_key, &private_key_n, 0, 0);
+ BIGNUM const * public_key_n;
+ RSA_get0_key(public_key, &public_key_n, 0, 0);
+ if (!private_key_n || !public_key_n) {
+ return false;
+ }
+ bool const valid = !BN_cmp (private_key_n, public_key_n);
+#else
+ bool const valid = !BN_cmp (private_key->n, public_key->n);
+#endif
+ BIO_free (bio);
+
+ return valid;
+}
+
+
+bool
+CertificateChain::valid (string* reason) const
+{
+ try {
+ root_to_leaf ();
+ } catch (CertificateChainError& e) {
+ if (reason) {
+ *reason = "certificates do not form a chain";
+ }
+ return false;
+ }
+
+ if (!private_key_valid ()) {
+ if (reason) {
+ *reason = "private key does not exist, or does not match leaf certificate";
+ }
+ return false;
+ }
+
+ return true;
+}
+
+
+CertificateChain::List
+CertificateChain::root_to_leaf () const
+{
+ auto rtl = _certificates;
+ std::sort (rtl.begin(), rtl.end());
+ do {
+ if (chain_valid (rtl)) {
+ return rtl;
+ }
+ } while (std::next_permutation (rtl.begin(), rtl.end()));
+
+ throw CertificateChainError ("certificate chain is not consistent");
+}
+
+
+void
+CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
+{
+ /* <Signer> */
+
+ parent->add_child_text(" ");
+ auto signer = parent->add_child("Signer");
+ signer->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
+ auto data = signer->add_child("X509Data", "dsig");
+ auto serial_element = data->add_child("X509IssuerSerial", "dsig");
+ serial_element->add_child("X509IssuerName", "dsig")->add_child_text (leaf().issuer());
+ serial_element->add_child("X509SerialNumber", "dsig")->add_child_text (leaf().serial());
+ data->add_child("X509SubjectName", "dsig")->add_child_text (leaf().subject());
+
+ indent (signer, 2);
+
+ /* <Signature> */
+
+ parent->add_child_text("\n ");
+ auto signature = parent->add_child("Signature");
+ signature->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
+ signature->set_namespace ("dsig");
+ parent->add_child_text("\n");
+
+ auto signed_info = signature->add_child ("SignedInfo", "dsig");
+ signed_info->add_child("CanonicalizationMethod", "dsig")->set_attribute ("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
+
+ if (standard == Standard::INTEROP) {
+ signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1");
+ } else {
+ signed_info->add_child("SignatureMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256");
+ }
+
+ auto reference = signed_info->add_child("Reference", "dsig");
+ reference->set_attribute ("URI", "");
+
+ auto transforms = reference->add_child("Transforms", "dsig");
+ transforms->add_child("Transform", "dsig")->set_attribute (
+ "Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
+ );
+
+ reference->add_child("DigestMethod", "dsig")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
+ /* This will be filled in by the signing later */
+ reference->add_child("DigestValue", "dsig");
+
+ signature->add_child("SignatureValue", "dsig");
+ signature->add_child("KeyInfo", "dsig");
+ add_signature_value (signature, "dsig", true);
+}
+
+
+void
+CertificateChain::add_signature_value (xmlpp::Element* parent, string ns, bool add_indentation) const
+{
+ cxml::Node cp (parent);
+ auto key_info = cp.node_child("KeyInfo")->node();
+
+ /* Add the certificate chain to the KeyInfo child node of parent */
+ for (auto const& i: leaf_to_root()) {
+ auto data = key_info->add_child("X509Data", ns);
+
+ {
+ auto serial = data->add_child("X509IssuerSerial", ns);
+ serial->add_child("X509IssuerName", ns)->add_child_text (i.issuer ());
+ serial->add_child("X509SerialNumber", ns)->add_child_text (i.serial ());
+ }
+
+ data->add_child("X509Certificate", ns)->add_child_text (i.certificate());
+ }
+
+ auto signature_context = xmlSecDSigCtxCreate (0);
+ if (signature_context == 0) {
+ throw MiscError ("could not create signature context");
+ }
+
+ signature_context->signKey = xmlSecCryptoAppKeyLoadMemory (
+ reinterpret_cast<const unsigned char *> (_key->c_str()), _key->size(), xmlSecKeyDataFormatPem, 0, 0, 0
+ );
+
+ if (signature_context->signKey == 0) {
+ throw runtime_error ("could not read private key");
+ }
+
+ if (add_indentation) {
+ indent (parent, 2);
+ }
+ int const r = xmlSecDSigCtxSign (signature_context, parent->cobj ());
+ if (r < 0) {
+ throw MiscError (String::compose ("could not sign (%1)", r));
+ }
+
+ xmlSecDSigCtxDestroy (signature_context);
+}
+
+
+string
+CertificateChain::chain () const
+{
+ string o;
+ for (auto const& i: root_to_leaf()) {
+ o += i.certificate(true);
+ }
+
+ return o;