From e9d0955c442a39ebef4b9a46f2ebcf28a9d5eabb Mon Sep 17 00:00:00 2001 From: qmuntal Date: Wed, 13 Nov 2024 10:26:42 +0100 Subject: [PATCH] add SetFIPS tests --- export_test.go | 11 ++++++++--- openssl.go | 3 +++ openssl_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/export_test.go b/export_test.go index b6f27d62..f55857d0 100644 --- a/export_test.go +++ b/export_test.go @@ -5,8 +5,13 @@ import "sync" var ErrOpen = errOpen var SymCryptProviderAvailable = sync.OnceValue(func() bool { - if vMajor == 1 { - return false - } return isProviderAvailable("symcryptprovider") }) + +var FIPSProviderAvailable = sync.OnceValue(func() bool { + return isProviderAvailable("fips") +}) + +var DefaultProviderAvailable = sync.OnceValue(func() bool { + return isProviderAvailable("default") +}) diff --git a/openssl.go b/openssl.go index 45dedb20..145b082f 100644 --- a/openssl.go +++ b/openssl.go @@ -137,6 +137,9 @@ func FIPS() bool { // isProviderAvailable checks if the provider with the given name is available. // This function is used in export_test.go, but must be defined here as test files can't access C functions. func isProviderAvailable(name string) bool { + if vMajor == 1 { + return false + } providerName := C.CString(name) defer C.free(unsafe.Pointer(providerName)) return C.go_openssl_OSSL_PROVIDER_available(nil, providerName) == 1 diff --git a/openssl_test.go b/openssl_test.go index 182fc7b8..4c723fce 100644 --- a/openssl_test.go +++ b/openssl_test.go @@ -91,3 +91,45 @@ func compareCurrentVersion(v string) int { ver := strings.TrimPrefix(runtime.Version(), "devel ") return version.Compare(ver, v) } + +func TestSetFIPS(t *testing.T) { + fipsEnabled := openssl.FIPS() + t.Cleanup(func() { + // Restore the previous FIPS mode. + err := openssl.SetFIPS(fipsEnabled) + if err != nil { + t.Fatal(err) + } + }) + + if err := openssl.SetFIPS(fipsEnabled); err != nil { + // Test that we can set FIPS mode to the current state + // without error. + t.Fatalf("SetFIPS(%v) failed: %v", fipsEnabled, err) + } + if got := openssl.FIPS(); got != fipsEnabled { + // Test that the FIPS mode hasn't been changed by the + // previous SetFIPS call. + t.Fatalf("FIPS mode mismatch: want %v, got %v", fipsEnabled, got) + } + + if fipsEnabled && + openssl.DefaultProviderAvailable() { + // Test that we can disable FIPS mode if it was enabled + // when the built-in provider is available. + err := openssl.SetFIPS(false) + if err != nil { + t.Fatalf("SetFIPS(false) failed: %v", err) + } + } else if !fipsEnabled && + (openssl.SymCryptProviderAvailable() || openssl.FIPSProviderAvailable()) { + // Test that we can enable FIPS mode if it was disabled + // when the provider is known to support FIPS mode. + err := openssl.SetFIPS(true) + if err != nil { + t.Fatalf("SetFIPS(true) failed: %v", err) + } + } else { + t.Skip("FIPS mode is not supported") + } +}