Try again to fix Windows build of previous.
[libdcp.git] / src / certificate_chain.cc
index d6b8a7a04d0103366bd88c37ee979b2c14ae29af..ce8d14aa5e98e94b3dfcec874872d9180b1154e3 100644 (file)
@@ -186,6 +186,9 @@ CertificateChain::CertificateChain (
        string leaf_common_name
        )
 {
+       /* Valid for 40 years */
+       int const days = 365 * 40;
+
        boost::filesystem::path directory = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
        boost::filesystem::create_directories (directory);
 
@@ -201,6 +204,7 @@ CertificateChain::CertificateChain (
                f << "[ req ]\n"
                  << "distinguished_name = req_distinguished_name\n"
                  << "x509_extensions   = v3_ca\n"
+                 << "string_mask = nombstr\n"
                  << "[ v3_ca ]\n"
                  << "basicConstraints = critical,CA:true,pathlen:3\n"
                  << "keyUsage = keyCertSign,cRLSign\n"
@@ -220,9 +224,9 @@ CertificateChain::CertificateChain (
        {
                command (
                        String::compose (
-                               "%1 req -new -x509 -sha256 -config ca.cnf -days 3650 -set_serial 5"
-                               " -subj \"%2\" -key ca.key -outform PEM -out ca.self-signed.pem",
-                               quoted_openssl, ca_subject
+                               "%1 req -new -x509 -sha256 -config ca.cnf -days %2 -set_serial 5"
+                               " -subj \"%3\" -key ca.key -outform PEM -out ca.self-signed.pem",
+                               quoted_openssl, days, ca_subject
                                )
                        );
        }
@@ -234,6 +238,7 @@ CertificateChain::CertificateChain (
                f << "[ default ]\n"
                  << "distinguished_name = req_distinguished_name\n"
                  << "x509_extensions = v3_ca\n"
+                 << "string_mask = nombstr\n"
                  << "[ v3_ca ]\n"
                  << "basicConstraints = critical,CA:true,pathlen:2\n"
                  << "keyUsage = keyCertSign,cRLSign\n"
@@ -253,16 +258,18 @@ CertificateChain::CertificateChain (
        {
                command (
                        String::compose (
-                               "%1 req -new -config intermediate.cnf -days 3649 -subj \"%2\" -key intermediate.key -out intermediate.csr",
-                               quoted_openssl, inter_subject
+                               "%1 req -new -config intermediate.cnf -days %2 -subj \"%3\" -key intermediate.key -out intermediate.csr",
+                               quoted_openssl, days - 1, inter_subject
                                )
                        );
        }
 
        command (
-               quoted_openssl +
-               " x509 -req -sha256 -days 3649 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
-               " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem"
+               String::compose (
+                       "%1 x509 -req -sha256 -days %2 -CA ca.self-signed.pem -CAkey ca.key -set_serial 6"
+                       " -in intermediate.csr -extfile intermediate.cnf -extensions v3_ca -out intermediate.signed.pem",
+                       quoted_openssl, days - 1
+                       )
                );
 
        command (quoted_openssl + " genrsa -out leaf.key 2048");
@@ -272,6 +279,7 @@ CertificateChain::CertificateChain (
                f << "[ default ]\n"
                  << "distinguished_name = req_distinguished_name\n"
                  << "x509_extensions   = v3_ca\n"
+                 << "string_mask = nombstr\n"
                  << "[ v3_ca ]\n"
                  << "basicConstraints = critical,CA:false\n"
                  << "keyUsage = digitalSignature,keyEncipherment\n"
@@ -291,16 +299,18 @@ CertificateChain::CertificateChain (
        {
                command (
                        String::compose (
-                               "%1 req -new -config leaf.cnf -days 3648 -subj \"%2\" -key leaf.key -outform PEM -out leaf.csr",
-                               quoted_openssl, leaf_subject
+                               "%1 req -new -config leaf.cnf -days %2 -subj \"%3\" -key leaf.key -outform PEM -out leaf.csr",
+                               quoted_openssl, days - 2, leaf_subject
                                )
                        );
        }
 
        command (
-               quoted_openssl +
-               " x509 -req -sha256 -days 3648 -CA intermediate.signed.pem -CAkey intermediate.key"
-               " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem"
+               String::compose (
+                       "%1 x509 -req -sha256 -days %2 -CA intermediate.signed.pem -CAkey intermediate.key"
+                       " -set_serial 7 -in leaf.csr -extfile leaf.cnf -extensions v3_ca -out leaf.signed.pem",
+                       quoted_openssl, days - 2
+                       )
                );
 
        boost::filesystem::current_path (cwd);
@@ -327,9 +337,8 @@ CertificateChain::CertificateChain (string s)
                }
        }
 
-       if (!attempt_reorder ()) {
-               throw MiscError ("could not find certificate chain order");
-       }
+       /* This will throw an exception if the chain cannot be ordered */
+       leaf_to_root ();
 }
 
 /** @return Root certificate */
@@ -337,7 +346,7 @@ Certificate
 CertificateChain::root () const
 {
        DCP_ASSERT (!_certificates.empty());
-       return _certificates.front ();
+       return root_to_leaf().front ();
 }
 
 /** @return Leaf certificate */
@@ -345,26 +354,25 @@ Certificate
 CertificateChain::leaf () const
 {
        DCP_ASSERT (!_certificates.empty());
-       return _certificates.back ();
+       return root_to_leaf().back ();
 }
 
-/** @return Certificates in order from root to leaf */
+/** @return Certificates in order from leaf to root */
 CertificateChain::List
-CertificateChain::root_to_leaf () const
+CertificateChain::leaf_to_root () const
 {
-       return _certificates;
+       List l = root_to_leaf ();
+       l.reverse ();
+       return l;
 }
 
-/** @return Certificates in order from leaf to root */
 CertificateChain::List
-CertificateChain::leaf_to_root () const
+CertificateChain::unordered () const
 {
-       List c = _certificates;
-       c.reverse ();
-       return c;
+       return _certificates;
 }
 
-/** Add a certificate to the end of the chain.
+/** Add a certificate to the chain.
  *  @param c Certificate to add.
  */
 void
@@ -399,40 +407,49 @@ CertificateChain::remove (int i)
        }
 }
 
-/** Check to see if the chain is valid (i.e. root signs the intermediate, intermediate
+bool
+CertificateChain::chain_valid () const
+{
+       return chain_valid (_certificates);
+}
+
+/** Check to see if a chain is valid (i.e. root signs the intermediate, intermediate
  *  signs the leaf and so on) and that the private key (if there is one) matches the
  *  leaf certificate.
- *  @param valid if non-0 and the CertificateChain is not valid, this is filled in with
- *  an explanation.
  *  @return true if it's ok, false if not.
  */
 bool
-CertificateChain::valid (string* reason) const
+CertificateChain::chain_valid (List const & chain) const
 {
-       /* Check the certificate chain */
+        /* 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.
+       */
 
        X509_STORE* store = X509_STORE_new ();
        if (!store) {
                throw MiscError ("could not create X509 store");
        }
 
-       int n = 1;
-       for (List::const_iterator i = _certificates.begin(); i != _certificates.end(); ++i) {
+       /* Put all the certificates into the store */
+       for (List::const_iterator i = chain.begin(); i != chain.end(); ++i) {
+               if (!X509_STORE_add_cert (store, i->x509 ())) {
+                       X509_STORE_free (store);
+                       return false;
+               }
+       }
+
+       /* Verify each one */
+       for (List::const_iterator i = chain.begin(); i != chain.end(); ++i) {
 
                List::const_iterator j = i;
                ++j;
-               if (j ==  _certificates.end ()) {
+               if (j == chain.end ()) {
                        break;
                }
 
-               if (!X509_STORE_add_cert (store, i->x509 ())) {
-                       X509_STORE_free (store);
-                       if (reason) {
-                               *reason = "X509_STORE_add_cert failed";
-                       }
-                       return false;
-               }
-
                X509_STORE_CTX* ctx = X509_STORE_CTX_new ();
                if (!ctx) {
                        X509_STORE_free (store);
@@ -443,34 +460,47 @@ CertificateChain::valid (string* reason) const
                if (!X509_STORE_CTX_init (ctx, store, j->x509(), 0)) {
                        X509_STORE_CTX_free (ctx);
                        X509_STORE_free (store);
-                       if (reason) {
-                               *reason = "X509_STORE_CTX_init failed";
-                       }
-                       return false;
+                       throw MiscError ("could not initialise X509 store context");
                }
 
-               int v = X509_verify_cert (ctx);
+               int const v = X509_verify_cert (ctx);
                X509_STORE_CTX_free (ctx);
 
-               if (v == 0) {
+               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);
-                       if (reason) {
-                               *reason = String::compose ("X509_verify_cert failed for certificate number %1", n);
-                       }
                        return false;
                }
 
-               ++n;
        }
 
        X509_STORE_free (store);
 
-       /* Check that the leaf certificate matches the private key, if there is one */
+       return true;
+}
 
-       if (!_key) {
+/** Check that there is a valid private key for the leaf certificate.
+ *  Will return true if there are no certificates.
+ */
+bool
+CertificateChain::private_key_valid () const
+{
+       if (_certificates.empty ()) {
                return true;
        }
 
+       if (!_key) {
+               return false;
+       }
+
        BIO* bio = BIO_new_mem_buf (const_cast<char *> (_key->c_str ()), -1);
        if (!bio) {
                throw MiscError ("could not create memory BIO");
@@ -480,7 +510,6 @@ CertificateChain::valid (string* reason) const
        RSA* public_key = leaf().public_key ();
 
 #if OPENSSL_VERSION_NUMBER > 0x10100000L
-#warning "Using new OpenSSL API"
        BIGNUM const * private_key_n;
        RSA_get0_key(private_key, &private_key_n, 0, 0);
        BIGNUM const * public_key_n;
@@ -491,29 +520,44 @@ CertificateChain::valid (string* reason) const
 #endif
        BIO_free (bio);
 
-       if (!valid && reason) {
-               *reason = "leaf certificate does not match private key";
-       }
-
        return valid;
 }
 
-/** @return true if the chain is now in order from root to leaf,
- *  false if no correct order was found.
- */
 bool
-CertificateChain::attempt_reorder ()
+CertificateChain::valid (string* reason) const
 {
-       List original = _certificates;
-       _certificates.sort ();
+       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;
+}
+
+/** @return Certificates in order from root to leaf */
+CertificateChain::List
+CertificateChain::root_to_leaf () const
+{
+       List rtl = _certificates;
+       rtl.sort ();
        do {
-               if (valid ()) {
-                       return true;
+               if (chain_valid (rtl)) {
+                       return rtl;
                }
-       } while (std::next_permutation (_certificates.begin(), _certificates.end ()));
+       } while (std::next_permutation (rtl.begin(), rtl.end()));
 
-       _certificates = original;
-       return false;
+       throw CertificateChainError ("certificate chain is not consistent");
 }
 
 /** Add a &lt;Signer&gt; and &lt;ds:Signature&gt; nodes to an XML node.
@@ -525,16 +569,24 @@ CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
 {
        /* <Signer> */
 
+       parent->add_child_text("  ");
        xmlpp::Element* signer = parent->add_child("Signer");
+       signer->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
        xmlpp::Element* data = signer->add_child("X509Data", "dsig");
        xmlpp::Element* 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> */
 
-       xmlpp::Element* signature = parent->add_child("Signature", "dsig");
+       parent->add_child_text("\n  ");
+       xmlpp::Element* 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");
 
        xmlpp::Element* 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");
@@ -559,7 +611,7 @@ CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
 
        signature->add_child("SignatureValue", "dsig");
        signature->add_child("KeyInfo", "dsig");
-       add_signature_value (signature, "dsig");
+       add_signature_value (signature, "dsig", true);
 }
 
 
@@ -569,7 +621,7 @@ CertificateChain::sign (xmlpp::Element* parent, Standard standard) const
  *  @param ns Namespace to use for the signature XML nodes.
  */
 void
-CertificateChain::add_signature_value (xmlpp::Node* parent, string ns) const
+CertificateChain::add_signature_value (xmlpp::Element* parent, string ns, bool add_indentation) const
 {
        cxml::Node cp (parent);
        xmlpp::Node* key_info = cp.node_child("KeyInfo")->node ();
@@ -600,11 +652,9 @@ CertificateChain::add_signature_value (xmlpp::Node* parent, string ns) const
                throw runtime_error ("could not read private key");
        }
 
-       /* XXX: set key name to the PEM string: this can't be right! */
-       if (xmlSecKeySetName (signature_context->signKey, reinterpret_cast<const xmlChar *> (_key->c_str())) < 0) {
-               throw MiscError ("could not set key name");
+       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));