Fix self-signed handling.

Don't mark a certificate as self-signed if keyUsage is present and
certificate signing is not asserted.

PR#3979

(Imported from upstream's e272f8ef8f63298466494adcd29512797ab1eece.)

Change-Id: I3120832f32455e8e099708fa2491d85d3d4a3930
Reviewed-on: https://boringssl-review.googlesource.com/6341
Reviewed-by: Adam Langley <alangley@gmail.com>
diff --git a/crypto/x509v3/v3_purp.c b/crypto/x509v3/v3_purp.c
index f53c0f1..9a0a7bc 100644
--- a/crypto/x509v3/v3_purp.c
+++ b/crypto/x509v3/v3_purp.c
@@ -70,6 +70,14 @@
 #include "../internal.h"
 
 
+#define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
+#define ku_reject(x, usage) \
+	(((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
+#define xku_reject(x, usage) \
+	(((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage)))
+#define ns_reject(x, usage) \
+	(((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
+
 static void x509v3_cache_extensions(X509 *x);
 
 static int check_ssl_ca(const X509 *x);
@@ -494,7 +502,8 @@
 			{
 			x->ex_flags |= EXFLAG_SI;
 			/* If SKID matches AKID also indicate self signed */
-			if (X509_check_akid(x, x->akid) == X509_V_OK)
+			if (X509_check_akid(x, x->akid) == X509_V_OK &&
+				!ku_reject(x, KU_KEY_CERT_SIGN))
 				x->ex_flags |= EXFLAG_SS;
 			}
 	x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
@@ -531,14 +540,6 @@
  * 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
  */
 
-#define V1_ROOT (EXFLAG_V1|EXFLAG_SS)
-#define ku_reject(x, usage) \
-	(((x)->ex_flags & EXFLAG_KUSAGE) && !((x)->ex_kusage & (usage)))
-#define xku_reject(x, usage) \
-	(((x)->ex_flags & EXFLAG_XKUSAGE) && !((x)->ex_xkusage & (usage)))
-#define ns_reject(x, usage) \
-	(((x)->ex_flags & EXFLAG_NSCERT) && !((x)->ex_nscert & (usage)))
-
 static int check_ca(const X509 *x)
 {
 	/* keyUsage if present should allow cert signing */