Fix x509v3_cache_extensions error-handling.

This imports https://github.com/openssl/openssl/pull/10756 from upstream
with a number of changes:

- Add tests.

- Rather than blindly return false in cert_self_signed, make that
  function a tri-state return. This gives better error-reporting when the
  leaf certificate has a bad extension and reduces the risk of confusing
  the verifier.

- Give x509v3_cache_extensions a return value rather than expecting
  everyone to check EXFLAG_INVALID. Switch X509_check_purpose calls to
  it when applicable.

- Rather than setting EXFLAG_INVALID on bad CRLs, fail the parse
  altogether. We're already in the d2i callback. (Nothing checks
  EXFLAG_INVALID on CRLs.)

- I've intentionally left the error unchecked in X509_cmp. OpenSSL's
  strategy is to return -2, but that's not a consistent comparison
  and may mess up sorts that depend on transitivity. This retains the
  current behavior where we consider all undigestable certs as equal
  to each other (modulo the opportunistic TBSCertificate double-check
  which should work most of the time). This is terrible, so I've filed
  https://crbug.com/boringssl/355 to track fixes here.

That last fix caught that I misread the spec when I generated
kKnownCriticalCRL and kUnknownCriticalCRL2. This fixes those and uses
the old kKnownCriticalCRL as a test for invalid extensions. (Those CRLs
were assembled by hand, so they don't indicate any software has been
encoding them wrong.)

Update-Note: The X.509 verifier now correctly rejects syntax errors in
important certificate extensions. This may break some malformed
certificates which were incorrectly accepted before.

Bug: 345
Change-Id: Ifb3a98ba62cd296920546bc718fda524bd55c024
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/41745
Reviewed-by: Adam Langley <agl@google.com>
Commit-Queue: David Benjamin <davidben@google.com>
diff --git a/crypto/x509/test/invalid_extension_intermediate_subject_key_identifier.pem b/crypto/x509/test/invalid_extension_intermediate_subject_key_identifier.pem
new file mode 100644
index 0000000..a440757
--- /dev/null
+++ b/crypto/x509/test/invalid_extension_intermediate_subject_key_identifier.pem
@@ -0,0 +1,11 @@
+-----BEGIN CERTIFICATE-----
+MIIBhTCCASugAwIBAgIBAjAKBggqhkjOPQQDAjAiMSAwHgYDVQQDExdJbnZhbGlk
+IEV4dGVuc2lvbnMgUm9vdDAgFw0wMDAxMDEwMDAwMDBaGA8yMTAwMDEwMTAwMDAw
+MFowKjEoMCYGA1UEAxMfSW52YWxpZCBFeHRlbnNpb25zIEludGVybWVkaWF0ZTBZ
+MBMGByqGSM49AgEGCCqGSM49AwEHA0IABOI6fKiM3jFLkLyAn88cvlw4SwxuygRj
+opP3FFBKHyUQvh3VVvfqSpSCSmp50QiajQ6Dg7CTpVZVVH+bguT7JTCjSDBGMA4G
+A1UdDwEB/wQEAwICBDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTAD
+AQH/MA4GA1UdDgQHSU5WQUxJRDAKBggqhkjOPQQDAgNIADBFAiBXToga6ILFNSXj
+FiwI/ZaZvJubBHzMcrEXtIv85ybV3wIhAL3DMOezrq+dSjf+RdshlTDKwvTY8QYX
+ehvRzctnYHTd
+-----END CERTIFICATE-----