blob: 19cdb92814082f150300361cd8977545f421488a [file] [log] [blame]
Nikhil Namjoshida6e5572023-03-13 10:52:53 -07001#include "bej_common_test.hpp"
kasunathe8946af2022-05-23 12:32:09 -07002#include "bej_decoder_json.hpp"
Brandon Kim07abbf82025-06-23 21:03:07 +00003#include "bej_encoder_json.hpp"
kasunathe8946af2022-05-23 12:32:09 -07004
kasunathe8946af2022-05-23 12:32:09 -07005#include <memory>
kasunathe8946af2022-05-23 12:32:09 -07006#include <string_view>
Brandon Kim07abbf82025-06-23 21:03:07 +00007#include <vector>
kasunathe8946af2022-05-23 12:32:09 -07008
9#include <gmock/gmock-matchers.h>
10#include <gmock/gmock.h>
11#include <gtest/gtest.h>
12
13namespace libbej
14{
15
kasunathe8946af2022-05-23 12:32:09 -070016struct BejDecoderTestParams
17{
18 const std::string testName;
19 const BejTestInputFiles inputFiles;
20};
21
Brian Maa46f9852024-09-27 16:57:20 +080022void PrintTo(const BejDecoderTestParams& params, std::ostream* os)
23{
24 *os << params.testName;
25}
26
kasunathe8946af2022-05-23 12:32:09 -070027using BejDecoderTest = testing::TestWithParam<BejDecoderTestParams>;
28
29const BejTestInputFiles driveOemTestFiles = {
30 .jsonFile = "../test/json/drive_oem.json",
31 .schemaDictionaryFile = "../test/dictionaries/drive_oem_dict.bin",
32 .annotationDictionaryFile = "../test/dictionaries/annotation_dict.bin",
33 .errorDictionaryFile = "",
34 .encodedStreamFile = "../test/encoded/drive_oem_enc.bin",
35};
36
37const BejTestInputFiles circuitTestFiles = {
38 .jsonFile = "../test/json/circuit.json",
39 .schemaDictionaryFile = "../test/dictionaries/circuit_dict.bin",
40 .annotationDictionaryFile = "../test/dictionaries/annotation_dict.bin",
41 .errorDictionaryFile = "",
42 .encodedStreamFile = "../test/encoded/circuit_enc.bin",
43};
44
45const BejTestInputFiles storageTestFiles = {
46 .jsonFile = "../test/json/storage.json",
47 .schemaDictionaryFile = "../test/dictionaries/storage_dict.bin",
48 .annotationDictionaryFile = "../test/dictionaries/annotation_dict.bin",
49 .errorDictionaryFile = "",
50 .encodedStreamFile = "../test/encoded/storage_enc.bin",
51};
52
53const BejTestInputFiles dummySimpleTestFiles = {
54 .jsonFile = "../test/json/dummysimple.json",
55 .schemaDictionaryFile = "../test/dictionaries/dummy_simple_dict.bin",
56 .annotationDictionaryFile = "../test/dictionaries/annotation_dict.bin",
57 .errorDictionaryFile = "",
58 .encodedStreamFile = "../test/encoded/dummy_simple_enc.bin",
59};
60
kasunathe8946af2022-05-23 12:32:09 -070061TEST_P(BejDecoderTest, Decode)
62{
63 const BejDecoderTestParams& test_case = GetParam();
64 auto inputsOrErr = loadInputs(test_case.inputFiles);
65 EXPECT_TRUE(inputsOrErr);
66
67 BejDictionaries dictionaries = {
68 .schemaDictionary = inputsOrErr->schemaDictionary,
69 .annotationDictionary = inputsOrErr->annotationDictionary,
70 .errorDictionary = inputsOrErr->errorDictionary,
71 };
72
73 BejDecoderJson decoder;
74 EXPECT_THAT(decoder.decode(dictionaries, inputsOrErr->encodedStream), 0);
75 std::string decoded = decoder.getOutput();
76 nlohmann::json jsonDecoded = nlohmann::json::parse(decoded);
77
78 // Just comparing nlohmann::json types could lead to errors. It compares the
79 // byte values. So int64 and unit64 comparisons might be incorrect. Eg:
80 // bytes values for -5 and 18446744073709551611 are the same. So compare the
81 // string values.
82 EXPECT_TRUE(jsonDecoded.dump() == inputsOrErr->expectedJson.dump());
83}
84
Brandon Kim07abbf82025-06-23 21:03:07 +000085TEST(BejDecoderSecurityTest, MaxOperationsLimit)
86{
87 auto inputsOrErr = loadInputs(dummySimpleTestFiles);
88 ASSERT_TRUE(inputsOrErr);
89
90 BejDictionaries dictionaries = {
91 .schemaDictionary = inputsOrErr->schemaDictionary,
92 .annotationDictionary = inputsOrErr->annotationDictionary,
93 .errorDictionary = inputsOrErr->errorDictionary,
94 };
95
96 // Each array element below consists of a set and two properties, resulting
97 // in 3 operations. 400,000 elements will result in 1,200,000 operations,
98 // which should exceed the limit of 1,000,000.
99 constexpr int numElements = 400000;
100
101 auto root = std::make_unique<RedfishPropertyParent>();
102 bejTreeInitSet(root.get(), "DummySimple");
103
104 auto childArray = std::make_unique<RedfishPropertyParent>();
105 bejTreeInitArray(childArray.get(), "ChildArrayProperty");
106 bejTreeLinkChildToParent(root.get(), childArray.get());
107
108 std::vector<std::unique_ptr<RedfishPropertyParent>> sets;
109 std::vector<std::unique_ptr<RedfishPropertyLeafBool>> bools;
110 std::vector<std::unique_ptr<RedfishPropertyLeafEnum>> enums;
111 sets.reserve(numElements);
112 bools.reserve(numElements);
113 enums.reserve(numElements);
114
115 for (int i = 0; i < numElements; ++i)
116 {
117 auto chArraySet = std::make_unique<RedfishPropertyParent>();
118 bejTreeInitSet(chArraySet.get(), nullptr);
119
120 auto chArraySetBool = std::make_unique<RedfishPropertyLeafBool>();
121 bejTreeAddBool(chArraySet.get(), chArraySetBool.get(), "AnotherBoolean",
122 true);
123
124 auto chArraySetLs = std::make_unique<RedfishPropertyLeafEnum>();
125 bejTreeAddEnum(chArraySet.get(), chArraySetLs.get(), "LinkStatus",
126 "NoLink");
127
128 bejTreeLinkChildToParent(childArray.get(), chArraySet.get());
129
130 sets.push_back(std::move(chArraySet));
131 bools.push_back(std::move(chArraySetBool));
132 enums.push_back(std::move(chArraySetLs));
133 }
134
135 libbej::BejEncoderJson encoder;
136 encoder.encode(&dictionaries, bejMajorSchemaClass, root.get());
137 std::vector<uint8_t> outputBuffer = encoder.getOutput();
138
139 BejDecoderJson decoder;
140 EXPECT_THAT(decoder.decode(dictionaries, std::span(outputBuffer)),
Brandon Kimef01d4c2025-06-23 21:13:04 +0000141 bejErrorNotSupported);
Brandon Kim07abbf82025-06-23 21:03:07 +0000142}
143
Brandon Kim9eb01172025-06-23 21:26:59 +0000144TEST(BejDecoderSecurityTest, RealWithTooManyLeadingZeros)
145{
146 auto inputsOrErr = loadInputs(dummySimpleTestFiles);
147 ASSERT_TRUE(inputsOrErr);
148
149 BejDictionaries dictionaries = {
150 .schemaDictionary = inputsOrErr->schemaDictionary,
151 .annotationDictionary = inputsOrErr->annotationDictionary,
152 .errorDictionary = inputsOrErr->errorDictionary,
153 };
154
155 auto root = std::make_unique<RedfishPropertyParent>();
156 bejTreeInitSet(root.get(), "DummySimple");
157
158 // 1.003 was randomely chosen
159 auto real = std::make_unique<RedfishPropertyLeafReal>();
160 bejTreeAddReal(root.get(), real.get(), "SampleRealProperty", 1.003);
161
162 libbej::BejEncoderJson encoder;
163 encoder.encode(&dictionaries, bejMajorSchemaClass, root.get());
164 std::vector<uint8_t> outputBuffer = encoder.getOutput();
165
166 // Manually tamper with the encoded stream to create the attack vector.
167 // We will find the `bejReal` property and overwrite its `zeroCount`.
168 // The property "SampleRealProperty" has sequence number 4. The encoded
169 // sequence number is `(4 << 1) | 0 = 8`. The nnint for 8 is `0x01, 0x08`.
170 const std::vector<uint8_t> realPropSeqNum = {0x01, 0x08};
171 auto it = std::search(outputBuffer.begin(), outputBuffer.end(),
172 realPropSeqNum.begin(), realPropSeqNum.end());
173 ASSERT_NE(it, outputBuffer.end()) << "Could not find bejReal property";
174
175 // The structure of a bejReal SFLV is: S(nnint) F(u8) L(nnint) V(...)
176 // The structure of V is: nnint(len(whole)), int(whole), nnint(zeroCount)...
177 // Find the start of the value (V) by skipping S, F, and L.
178 size_t sflvOffset = std::distance(outputBuffer.begin(), it);
179 const uint8_t* streamPtr = outputBuffer.data() + sflvOffset;
180 // Skip S
181 streamPtr += bejGetNnintSize(streamPtr);
182 // Skip F
183 streamPtr++;
184 // Skip L
185 const uint8_t* valuePtr = streamPtr + bejGetNnintSize(streamPtr);
186
187 // Find the start of zeroCount within V.
188 const uint8_t* zeroCountPtr = valuePtr + bejGetNnintSize(valuePtr);
189 zeroCountPtr += bejGetNnint(valuePtr); // Skip int(whole)
190
191 // The original zeroCount for 1.003 is 2. nnint(2) is `0x01, 0x02`.
192 // We replace it with a zeroCount of 101, which exceeds the limit.
193 // nnint(101) is `0x01, 101`. The size is the same (2 bytes), so we don't
194 // need to update the SFLV length field (L).
195 ASSERT_EQ(bejGetNnint(zeroCountPtr), 2);
196 size_t zeroCountOffset = zeroCountPtr - outputBuffer.data();
197 // nnint value for 101
198 outputBuffer[zeroCountOffset + 1] = 101;
199
200 BejDecoderJson decoder;
201 EXPECT_THAT(decoder.decode(dictionaries, std::span(outputBuffer)),
202 bejErrorInvalidSize);
203}
204
kasunathe8946af2022-05-23 12:32:09 -0700205/**
206 * TODO: Add more test cases.
207 * - Test Enums inside array elemets
208 * - Array inside an array: is this a valid case?
209 * - Real numbers with exponent part
210 * - Every type inside an array.
211 */
212INSTANTIATE_TEST_SUITE_P(
213 , BejDecoderTest,
214 testing::ValuesIn<BejDecoderTestParams>({
215 {"DriveOEM", driveOemTestFiles},
216 {"Circuit", circuitTestFiles},
217 {"Storage", storageTestFiles},
218 {"DummySimple", dummySimpleTestFiles},
219 }),
220 [](const testing::TestParamInfo<BejDecoderTest::ParamType>& info) {
Patrick Williamsbe27f2e2024-08-16 15:22:35 -0400221 return info.param.testName;
222 });
kasunathe8946af2022-05-23 12:32:09 -0700223
224} // namespace libbej