xref: /aosp_15_r20/external/tink/cc/internal/fips_utils.cc (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 
17 #include "tink/internal/fips_utils.h"
18 
19 #include <atomic>
20 
21 #include "absl/base/attributes.h"
22 #include "absl/status/status.h"
23 #include "openssl/crypto.h"
24 #include "tink/util/status.h"
25 
26 namespace crypto {
27 namespace tink {
28 namespace internal {
29 
30 #ifdef TINK_USE_ONLY_FIPS
31 ABSL_CONST_INIT const bool kUseOnlyFips = true;
32 #else
33 ABSL_CONST_INIT const bool kUseOnlyFips = false;
34 #endif
35 
36 static std::atomic<bool> is_fips_restricted(false);
37 
SetFipsRestricted()38 void SetFipsRestricted() { is_fips_restricted = true; }
39 
UnSetFipsRestricted()40 void UnSetFipsRestricted() { is_fips_restricted = false; }
41 
IsFipsModeEnabled()42 bool IsFipsModeEnabled() { return kUseOnlyFips || is_fips_restricted; }
43 
IsFipsEnabledInSsl()44 bool IsFipsEnabledInSsl() {
45 #ifdef OPENSSL_IS_BORINGSSL
46   return FIPS_mode();
47 #else
48   return false;
49 #endif
50 }
51 
ChecksFipsCompatibility(FipsCompatibility fips_status)52 util::Status ChecksFipsCompatibility(FipsCompatibility fips_status) {
53   switch (fips_status) {
54     case FipsCompatibility::kNotFips:
55       if (IsFipsModeEnabled()) {
56         return util::Status(absl::StatusCode::kInternal,
57                             "Primitive not available in FIPS only mode.");
58       } else {
59         return util::OkStatus();
60       }
61     case FipsCompatibility::kRequiresBoringCrypto:
62       if ((IsFipsModeEnabled()) && !IsFipsEnabledInSsl()) {
63         return util::Status(
64             absl::StatusCode::kInternal,
65             "BoringSSL not built with the BoringCrypto module. If you want to "
66             "use FIPS only mode you have to build BoringSSL in FIPS Mode.");
67 
68       } else {
69         return util::OkStatus();
70       }
71     default:
72       return util::Status(absl::StatusCode::kInternal,
73                           "Could not determine FIPS status.");
74   }
75 }
76 
77 }  // namespace internal
78 }  // namespace tink
79 }  // namespace crypto
80