From 8d7abff29035508b6208b4742bfaaed42f78ac43 Mon Sep 17 00:00:00 2001
From: rpm-build <rpm-build>
Date: Wed, 6 Mar 2024 19:17:15 +0100
Subject: [PATCH 08/59] RH: Add Kernel FIPS mode flag support - FIXSTYLE

Patch-name: 0009-Add-Kernel-FIPS-mode-flag-support.patch
Patch-id: 9
Patch-status: |
    # # Add check to see if fips flag is enabled in kernel
From-dist-git-commit: 4334bc837fbc64d14890fdc51679a80770d498ce
---
 crypto/context.c            | 35 +++++++++++++++++++++++++++++++++++
 include/internal/provider.h |  3 +++
 2 files changed, 38 insertions(+)

diff --git a/crypto/context.c b/crypto/context.c
index f15bc3d755..614c8a2c88 100644
--- a/crypto/context.c
+++ b/crypto/context.c
@@ -7,6 +7,7 @@
  * https://www.openssl.org/source/license.html
  */
 
+#define _GNU_SOURCE /* needed for secure_getenv */
 #include "crypto/cryptlib.h"
 #include <openssl/conf.h>
 #include <openssl/trace.h>
@@ -19,6 +20,38 @@
 #include "crypto/decoder.h"
 #include "crypto/context.h"
 
+# include <sys/types.h>
+# include <sys/stat.h>
+# include <fcntl.h>
+# include <unistd.h>
+# include <openssl/evp.h>
+
+# define FIPS_MODE_SWITCH_FILE "/proc/sys/crypto/fips_enabled"
+
+static int kernel_fips_flag;
+
+static void read_kernel_fips_flag(void)
+{
+    char buf[2] = "0";
+    int fd;
+
+    if (secure_getenv("OPENSSL_FORCE_FIPS_MODE") != NULL) {
+        buf[0] = '1';
+    } else if ((fd = open(FIPS_MODE_SWITCH_FILE, O_RDONLY)) >= 0) {
+        while (read(fd, buf, sizeof(buf)) < 0 && errno == EINTR) ;
+        close(fd);
+    }
+
+    if (buf[0] == '1') {
+        kernel_fips_flag = 1;
+    }
+}
+
+int ossl_get_kernel_fips_flag()
+{
+    return kernel_fips_flag;
+}
+
 struct ossl_lib_ctx_st {
     CRYPTO_RWLOCK *lock;
     OSSL_EX_DATA_GLOBAL global;
@@ -393,6 +426,8 @@ static int default_context_inited = 0;
 
 DEFINE_RUN_ONCE_STATIC(default_context_do_init)
 {
+    read_kernel_fips_flag();
+
     if (!CRYPTO_THREAD_init_local(&default_context_thread_local, NULL))
         goto err;
 
diff --git a/include/internal/provider.h b/include/internal/provider.h
index 7d94346155..c0f1d00da9 100644
--- a/include/internal/provider.h
+++ b/include/internal/provider.h
@@ -114,6 +114,9 @@ int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx,
                                 const OSSL_DISPATCH *in);
 void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx);
 
+/* FIPS flag access */
+int ossl_get_kernel_fips_flag(void);
+
 # ifdef __cplusplus
 }
 # endif
-- 
2.51.0

