Only write self test flag files if an environment variable is set.

Prevents arbitrary processes linked against libcrypto, which run
before the self test binaries, from triggering SELinux audit logs.

Fails safe. I.e. default is not to write a flag file which in turn
will mean all processes loading libcrypto run a full set of KAT tests
until the variable is set.

Alternative considered:  Use a weak gloabl symbol containing the flag
(defaulting to "don't write") and override in the self test binaries.
However at the very least this would need to be in a separate object
file other than bcm.o to prevent local symbol resolution, so unsure
if that would be acceptable.

Change-Id: I32b20699bdd7ecaff06fc5f79b213d9a9d5f6253
Reviewed-by: Adam Langley <>
Commit-Queue: Adam Langley <>
diff --git a/crypto/fipsmodule/self_check/self_check.c b/crypto/fipsmodule/self_check/self_check.c
index 3d47e69..71d1c18 100644
--- a/crypto/fipsmodule/self_check/self_check.c
+++ b/crypto/fipsmodule/self_check/self_check.c
@@ -15,6 +15,7 @@
 #include <openssl/crypto.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <openssl/aead.h>
 #include <openssl/aes.h>
@@ -36,12 +37,18 @@
 #if !defined(_MSC_VER)
 #if defined(BORINGSSL_FIPS) && defined(OPENSSL_ANDROID)
-// FIPS builds on Android will attempt to write flag files to
-// /dev/boringssl/selftest/ named after the module hash. If the flag file
-// exists, it's assumed that self-tests have already passed and thus do not need
-// to be repeated.
+// FIPS builds on Android will test for flag files, named after the module hash,
+// in /dev/boringssl/selftest/. If such a flag file exists, it's assumed that
+// self-tests have already passed and thus do not need to be repeated. (The
+// integrity tests always run, however.)
+// If self-tests complete successfully and the environment variable named in
+// |kFlagWriteEnableEnvVar| is present, then the flag file will be created. The
+// flag file isn't written without the environment variable being set in order
+// to avoid SELinux violations on Android.
 static const char kFlagPrefix[] = "/dev/boringssl/selftest/";
+static const char kFlagWriteEnableEnvVar[] = "BORINGSSL_SELF_TEST_CREATE_FLAG";
 static void hexdump(const uint8_t *in, size_t len) {
@@ -611,7 +618,7 @@
   // Tests were successful. Write flag file if requested.
-  if (flag_path_valid) {
+  if (flag_path_valid && getenv(kFlagWriteEnableEnvVar) != NULL) {
     const int fd = open(flag_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
     if (fd >= 0) {