diff --git a/mock-bpa-test/_test_util.py b/mock-bpa-test/_test_util.py index e664e0ef..0d3a923f 100644 --- a/mock-bpa-test/_test_util.py +++ b/mock-bpa-test/_test_util.py @@ -19,10 +19,17 @@ # the prime contract 80NM0018D0004 between the Caltech and NASA under # subcontract 1700763. # +import contextlib +import json +import logging +import tempfile +from collections.abc import Generator from dataclasses import dataclass from enum import IntEnum, unique from typing import Any, Optional +LOGGER = logging.getLogger(__name__) + @unique class DataFormat(IntEnum): @@ -71,3 +78,38 @@ class _TestCase: use_bcb_rng: bool = False """ If true, test will use custom rng callback for BCB testing """ + + +@contextlib.contextmanager +def sc_config_modifier(orig: str, modify: dict[str, Any]) -> Generator[str, None, None]: + """A context for modifying baseline configurations + + :param orig: The original file path, relative to this directory. + :param modify: Updates to the context parameters, either modifying or adding. + :return: A generator for temporary files which exist for the duration + of this context. + """ + with tempfile.NamedTemporaryFile("w+", suffix=".json") as polfile: + with open(orig, "r") as infile: + poldata = json.load(infile) + + params = poldata["policyrule_set"][0]["policyrule"]["spec"]["sc_parms"] + LOGGER.debug("Original params:\n%s", params) + if isinstance(params, dict): + params |= modify + elif isinstance(params, list): + # replace existing + for pair in params: + key = pair["id"] + if key in modify: + pair["value"] = str(modify.pop(key)) + # add remaining + for key, val in modify.items(): + params.append({"id": key, "value": str(val)}) + else: + raise TypeError(f"bad type {type(params)}") + LOGGER.debug("Modified params:\n%s", params) + + json.dump(poldata, polfile) + polfile.flush() + yield polfile.name diff --git a/mock-bpa-test/data/default-scs/keyset-1.json b/mock-bpa-test/data/default-scs/keyset-1.json new file mode 100644 index 00000000..7d49301c --- /dev/null +++ b/mock-bpa-test/data/default-scs/keyset-1.json @@ -0,0 +1,19 @@ +{ + "keys": [ + { + "kty": "oct", + "kid": "ExampleA.1", + "k": "GisaKxorGisaKxorGisaKw==" + }, + { + "kty": "oct", + "kid": "ExampleA.2-cek", + "k": "cXdlcnR5dWlvcGFzZGZnaA==" + }, + { + "kty": "oct", + "kid": "ExampleA.2", + "k": "YWJjZGVmZ2hpamtsbW5vcA==" + } + ] +} diff --git a/mock-bpa-test/data/default-scs/policy-exA.1-accept.json b/mock-bpa-test/data/default-scs/policy-exA.1-accept.json new file mode 100644 index 00000000..3030e9c5 --- /dev/null +++ b/mock-bpa-test/data/default-scs/policy-exA.1-accept.json @@ -0,0 +1,27 @@ +{ + "policyrule_set": [ + { + "policyrule": { + "desc": "Integrity accept rule", + "filter": { + "rule_id": "1", + "role": "a", + "tgt": 1, + "loc": "appout", + "sc_id": 1 + }, + "spec": { + "svc": "bib", + "sc_id": 1, + "sc_parms": { + "key_name": "ExampleA.1", + "sha_variant": 7, + "scope_flags": 0, + "key_wrap": 0 + } + }, + "policy_action_on_fail": "delete_bundle" + } + } + ] +} diff --git a/mock-bpa-test/data/default-scs/policy-exA.1-source.json b/mock-bpa-test/data/default-scs/policy-exA.1-source.json new file mode 100644 index 00000000..b3ddf5b7 --- /dev/null +++ b/mock-bpa-test/data/default-scs/policy-exA.1-source.json @@ -0,0 +1,27 @@ +{ + "policyrule_set": [ + { + "policyrule": { + "desc": "Integrity source rule", + "filter": { + "rule_id": "1", + "role": "s", + "tgt": 1, + "loc": "appin", + "sc_id": 1 + }, + "spec": { + "svc": "bib", + "sc_id": 1, + "sc_parms": { + "key_name": "ExampleA.1", + "sha_variant": 7, + "scope_flags": 0, + "key_wrap": 0 + } + }, + "policy_action_on_fail": "delete_bundle" + } + } + ] +} diff --git a/mock-bpa-test/data/default-scs/policy-exA.2-accept.json b/mock-bpa-test/data/default-scs/policy-exA.2-accept.json new file mode 100644 index 00000000..86afe94c --- /dev/null +++ b/mock-bpa-test/data/default-scs/policy-exA.2-accept.json @@ -0,0 +1,27 @@ +{ + "policyrule_set": [ + { + "policyrule": { + "desc": "Confidentiality accept rule", + "filter": { + "rule_id": "1", + "role": "a", + "tgt": 1, + "loc": "appout", + "sc_id": 2 + }, + "spec": { + "svc": "bcb", + "sc_id": 2, + "sc_parms": { + "key_name": "ExampleA.2", + "aes_variant": 1, + "aad_scope": 0, + "key_wrap": 1 + } + }, + "policy_action_on_fail": "delete_bundle" + } + } + ] +} diff --git a/mock-bpa-test/data/default-scs/policy-exA.2-cek-source.json b/mock-bpa-test/data/default-scs/policy-exA.2-cek-source.json new file mode 100644 index 00000000..a2723367 --- /dev/null +++ b/mock-bpa-test/data/default-scs/policy-exA.2-cek-source.json @@ -0,0 +1,27 @@ +{ + "policyrule_set": [ + { + "policyrule": { + "desc": "Confidentiality source rule", + "filter": { + "rule_id": "1", + "role": "s", + "tgt": 1, + "loc": "appin", + "sc_id": 2 + }, + "spec": { + "svc": "bcb", + "sc_id": 2, + "sc_parms": { + "key_name": "ExampleA.2-cek", + "aes_variant": 1, + "aad_scope": 0, + "key_wrap": 0 + } + }, + "policy_action_on_fail": "delete_bundle" + } + } + ] +} diff --git a/mock-bpa-test/data/default-scs/policy-exA.2-source.json b/mock-bpa-test/data/default-scs/policy-exA.2-source.json new file mode 100644 index 00000000..99451abd --- /dev/null +++ b/mock-bpa-test/data/default-scs/policy-exA.2-source.json @@ -0,0 +1,27 @@ +{ + "policyrule_set": [ + { + "policyrule": { + "desc": "Confidentiality source rule", + "filter": { + "rule_id": "1", + "role": "s", + "tgt": 1, + "loc": "appin", + "sc_id": 2 + }, + "spec": { + "svc": "bcb", + "sc_id": 2, + "sc_parms": { + "key_name": "ExampleA.2", + "aes_variant": 1, + "aad_scope": 0, + "key_wrap": 1 + } + }, + "policy_action_on_fail": "delete_bundle" + } + } + ] +} diff --git a/mock-bpa-test/test_bpa.py b/mock-bpa-test/test_bpa.py index d4a47f45..4c5a7a23 100644 --- a/mock-bpa-test/test_bpa.py +++ b/mock-bpa-test/test_bpa.py @@ -91,22 +91,24 @@ def _start(self, testcase: Optional[_TestCase]): sec_src_eid = testcase.sec_src_eid pol_is_json = policy_config.endswith(".json") + if pol_is_json: + policy_config = os.path.join(OWNPATH, policy_config) use_bcb_rng = testcase.use_bcb_rng - key_set = testcase.key_set + key_set = os.path.join(OWNPATH, testcase.key_set) # freshen derived file if key_set.endswith(".cbordiag"): key_file = key_set[:-4] with ( - open(os.path.join(OWNPATH, key_set), "r") as infile, - open(os.path.join(OWNPATH, key_file), "wb") as outfile, + open(key_set, "r") as infile, + open(key_file, "wb") as outfile, ): outfile.write(diag2cbor(infile.read())) key_set = key_file else: policy_config = "0x00" - key_set = "data/key_set_1.json" + key_set = os.path.join(OWNPATH, "data/key_set_1.json") # fmt: off arglist = [ @@ -188,8 +190,6 @@ def _single_test(self, testcase: _TestCase): with self.assertRaises(TimeoutError): self._wait_for(test_sock, timeout=0.1) - LOGGER.warning("Check log output to validate expected error") - err_case_str = testcase.expected_output LOGGER.debug(f"ERR CASE STR: {err_case_str}") diff --git a/mock-bpa-test/test_cose_sc.py b/mock-bpa-test/test_cose_sc.py index bc790dae..4b534b3d 100644 --- a/mock-bpa-test/test_cose_sc.py +++ b/mock-bpa-test/test_cose_sc.py @@ -21,14 +21,10 @@ # """Test Cases utilizing JSON policy definitions with the COSE context""" -import contextlib -import json import logging import os -import tempfile -from typing import Any -from _test_util import BundleDestLoc, DataFormat, _TestCase +from _test_util import BundleDestLoc, DataFormat, _TestCase, sc_config_modifier from test_bpa import TestAgent OWNPATH = os.path.dirname(os.path.abspath(__file__)) @@ -51,6 +47,14 @@ """ """ Bundle with BIB over target #1, adjusted sec block to #2 """ +EXAMPLE_A_EMPTY_PAYLOAD = """\ +[_ + [7, 0, 2, [1, "//dst/svc"], [1, "//src/svc"], [1, "//src/"], [813110400000, 0], 1000000, h'82A081C9'], + [1, 1, 0, 2, h''] +] +""" +""" Example A input bundle adjusted to have empty payload """ + EXAMPLE_A_1_WITH_BIB_ADDL_UHDR = """\ [_ [7, 0, 2, [1, "//dst/svc"], [1, "//src/svc"], [1, "//src/"], [813110400000, 0], 1000000, h'82A081C9'], @@ -148,23 +152,6 @@ """ Bundle with BIB over target #1 """ -@contextlib.contextmanager -def sc_config_modifier(orig: str, modify: dict[str, Any]): - """A context for modifying baseline configurations""" - with tempfile.NamedTemporaryFile("w+", suffix=".json") as polfile: - with open(os.path.join(OWNPATH, orig), "r") as infile: - poldata = json.load(infile) - - params: dict = poldata["policyrule_set"][0]["policyrule"]["spec"]["sc_parms"] - LOGGER.debug("Original params:\n%s", params) - params |= modify - LOGGER.debug("Modified params:\n%s", params) - - json.dump(poldata, polfile) - polfile.flush() - yield polfile - - class TestCoseScMac0(TestAgent): def test_exampleA_1_source(self): self._single_test( @@ -210,14 +197,15 @@ def test_exampleA_1_acceptor_valid_addl_uhdr(self): def test_exampleA_1_acceptor_valid_strict_target_alg(self): with sc_config_modifier( - "data/cose-sc/policy-any-bib-accept.json", {"target_alg": 6} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bib-accept.json"), + modify={"target_alg": 6}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_1_WITH_BIB, expected_output=EXAMPLE_A_NO_SEC, sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -227,14 +215,15 @@ def test_exampleA_1_acceptor_valid_strict_target_alg(self): def test_exampleA_1_acceptor_valid_strict_aad_scope(self): with sc_config_modifier( - "data/cose-sc/policy-any-bib-accept.json", {"aad_scope": {"0": 1, "-1": 1}} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bib-accept.json"), + modify={"aad_scope": {"0": 1, "-1": 1}}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_1_WITH_BIB, expected_output=EXAMPLE_A_NO_SEC, sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -244,14 +233,15 @@ def test_exampleA_1_acceptor_valid_strict_aad_scope(self): def test_exampleA_1_acceptor_failure_key_disallow(self): with sc_config_modifier( - "data/cose-sc/policy-any-bib-accept.json", {"key_id": "ExampleA.5"} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bib-accept.json"), + modify={"key_id": "ExampleA.5"}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_1_WITH_BIB, expected_output=".*.* Mismatched key ID value", sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -261,14 +251,15 @@ def test_exampleA_1_acceptor_failure_key_disallow(self): def test_exampleA_1_acceptor_failure_aad_mismatch(self): with sc_config_modifier( - "data/cose-sc/policy-any-bib-accept.json", {"aad_scope": {"0": 1, "-1": 2}} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bib-accept.json"), + modify={"aad_scope": {"0": 1, "-1": 2}}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_1_WITH_BIB, expected_output=".*.* Mismatch of AAD Scope parameter", sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -427,14 +418,15 @@ def test_exampleA_4_acceptor_valid_addl_uhdr(self): def test_exampleA_4_acceptor_valid_strict_key_id(self): with sc_config_modifier( - "data/cose-sc/policy-any-bcb-accept.json", {"key_id": "ExampleA.4"} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bcb-accept.json"), + modify={"key_id": "ExampleA.4"}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_4_WITH_BCB, expected_output=EXAMPLE_A_NO_SEC, sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -444,14 +436,15 @@ def test_exampleA_4_acceptor_valid_strict_key_id(self): def test_exampleA_4_acceptor_valid_strict_target_alg(self): with sc_config_modifier( - "data/cose-sc/policy-any-bcb-accept.json", {"target_alg": 3} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bcb-accept.json"), + modify={"target_alg": 3}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_4_WITH_BCB, expected_output=EXAMPLE_A_NO_SEC, sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, @@ -461,14 +454,15 @@ def test_exampleA_4_acceptor_valid_strict_target_alg(self): def test_exampleA_4_acceptor_valid_strict_aad_scope(self): with sc_config_modifier( - "data/cose-sc/policy-any-bcb-accept.json", {"aad_scope": {"0": 1, "-1": 1}} - ) as polfile: + orig=os.path.join(OWNPATH, "data/cose-sc/policy-any-bcb-accept.json"), + modify={"aad_scope": {"0": 1, "-1": 1}}, + ) as polfile_path: self._single_test( _TestCase( input_data=EXAMPLE_A_4_WITH_BCB, expected_output=EXAMPLE_A_NO_SEC, sec_src_eid="dtn://dst/", - policy_config=polfile.name, + policy_config=polfile_path, bundle_dest_loc=BundleDestLoc.APPIN, key_set="data/cose-sc/keyset-1.cbordiag", input_data_format=DataFormat.CBORDIAG, diff --git a/mock-bpa-test/test_default_scs.py b/mock-bpa-test/test_default_scs.py new file mode 100644 index 00000000..9a7f6963 --- /dev/null +++ b/mock-bpa-test/test_default_scs.py @@ -0,0 +1,282 @@ +# +# Copyright (c) 2025-2026 The Johns Hopkins University Applied Physics +# Laboratory LLC. +# +# This file is part of the Bundle Protocol Security Library (BSL). +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# This work was performed for the Jet Propulsion Laboratory, California +# Institute of Technology, sponsored by the United States Government under +# the prime contract 80NM0018D0004 between the Caltech and NASA under +# subcontract 1700763. +# +"""Test Cases utilizing JSON policy definitions with the default contexts""" + +import logging +import os +import unittest + +from _test_util import BundleDestLoc, DataFormat, _TestCase, sc_config_modifier +from test_bpa import TestAgent + +OWNPATH = os.path.dirname(os.path.abspath(__file__)) +LOGGER = logging.getLogger(__name__) + +EXAMPLE_A_NO_SEC = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [1, 1, 0, 0, h'526561647920746F2067656E657261746520612033322D62797465207061796C6F6164'] +] +""" +""" Example A input bundle with no security blocks """ + +EXAMPLE_A_1_WITH_BIB = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [11, 2, 0, 0, << [1], 1, 1, [2, [2, 1]], [[1, 7], [3, 0]], [[[1, h'3BDC69B3A34A2B5D3A8554368BD1E808F606219D2A10A846EAE3886AE4ECC83C4EE550FDFB1CC636B904E2F1A73E303DCD4B6CCECE003E95E8164DCC89A156E1']]] >>], + [1, 1, 0, 0, h'526561647920746F2067656E657261746520612033322D62797465207061796C6F6164'] +] +""" +""" Bundle with BIB over target #1, adjusted sec block to #2 """ + +EXAMPLE_A_2_WITH_BCB = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [12, 2, 1, 0, << [1], 2, 1, [2, [2, 1]], [[1, h'5477656C7665313231323132'], [2, 1], [3, h'69C411276FECDDC4780DF42C8A2AF89296FABF34D7FAE700'], [4, 0]], [[[1, h'EFA4B5AC0108E3816C5606479801BC04']]] >>], + [1, 1, 0, 0, h'3A09C1E63FE23A7F66A59C7303837241E070B02619FC59C5214A22F08CD70795E73E9A'] +] +""" +""" Bundle with BCB over target #1, adjusted sec block to #2 with flags 0x1""" + +EXAMPLE_EMPTY_PAYLOAD = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [1, 1, 0, 0, h''] +] +""" +""" Example A input bundle adjusted to have empty payload """ + +EXAMPLE_EMPTY_PAYLOAD_WITH_BIB = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [11, 2, 0, 0, << [1], 1, 1, [2, [2, 1]], [[1, 7], [3, 0]], [[[1, h'97F2168D91EA3BC9BE02FDC225AD2DCF70DD823BA4E13E11E599D8ACFB364502014F25220DFA5FFFDFF98C0C1BE7B235CA53A0B09B2F0D1776220F2E7A8DF372']]] >>], + [1, 1, 0, 0, h''] +] +""" +""" Bundle with BIB over target #1 """ + +EXAMPLE_EMPTY_PAYLOAD_WITH_BCB = """\ +[_ + [7, 0, 0, [2, [1, 2]], [2, [2, 1]], [2, [2, 1]], [0, 40], 1000000], + [12, 2, 1, 0, << [1], 2, 1, [2, [2, 1]], [[1, h'5477656C7665313231323132'], [2, 1], [3, h'69C411276FECDDC4780DF42C8A2AF89296FABF34D7FAE700'], [4, 0]], [[[1, h'EFA4B5AC0108E3816C5606479801BC04']]] >>], + [1, 1, 0, 0, h''] +] +""" +""" Bundle with BCB over target #1 """ + + +class TestBibHmacSha(TestAgent): + def test_exampleA_1_source(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_A_NO_SEC, + expected_output=EXAMPLE_A_1_WITH_BIB, + sec_src_eid="ipn:2.1", + policy_config="data/default-scs/policy-exA.1-source.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.CBORDIAG, + ) + ) + + def test_exampleA_1_acceptor_valid_match(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_A_1_WITH_BIB, + expected_output=EXAMPLE_A_NO_SEC, + sec_src_eid="ipn:1.0", + policy_config="data/default-scs/policy-exA.1-accept.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.CBORDIAG, + ) + ) + + def test_exampleA_1_acceptor_failure_key_mismatch(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.1-accept.json"), + modify={"key_name": "ExampleA.2"}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_1_WITH_BIB, + expected_output=".*.* Auth tag result mismatched", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + def test_exampleA_1_acceptor_failure_sha_variant(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.1-accept.json"), + modify={"sha_variant": 6}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_1_WITH_BIB, + expected_output=".*.* SHA variant mismatch, needed 6 got 7", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + @unittest.skip("the operation still proceeds after mismatch") + def test_exampleA_1_acceptor_failure_aad_mismatch(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.1-accept.json"), + modify={"scope_flags": 0x1}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_1_WITH_BIB, + expected_output=".*.* IPPT Scope mismatch, needed 1 got 0", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + def test_empty_target_source(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_EMPTY_PAYLOAD, + expected_output=EXAMPLE_EMPTY_PAYLOAD_WITH_BIB, + sec_src_eid="ipn:2.1", + policy_config="data/default-scs/policy-exA.1-source.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.CBORDIAG, + ) + ) + + +class TestBcbAesGcm(TestAgent): + def test_exampleA_2_source(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_A_NO_SEC, + expected_output=None, # non-deterministic BTSD + sec_src_eid="ipn:2.1", + policy_config="data/default-scs/policy-exA.2-source.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ANYCBOR, + ) + ) + + def test_exampleA_2_acceptor_valid_match(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_A_2_WITH_BCB, + expected_output=EXAMPLE_A_NO_SEC, + sec_src_eid="ipn:1.0", + policy_config="data/default-scs/policy-exA.2-accept.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.CBORDIAG, + ) + ) + + def test_exampleA_2_acceptor_failure_key_mismatch(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.2-accept.json"), + modify={"key_name": "ExampleA.1"}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_2_WITH_BCB, + expected_output=".*.* Failed to unwrap AES key", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + def test_exampleA_2_acceptor_failure_aes_variant(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.2-accept.json"), + modify={"aes_variant": 2}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_2_WITH_BCB, + expected_output=".*.* AES variant mismatch, needed 2 got 1", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + @unittest.skip("the operation still proceeds after mismatch") + def test_exampleA_2_acceptor_failure_aad_mismatch(self): + with sc_config_modifier( + orig=os.path.join(OWNPATH, "data/default-scs/policy-exA.2-accept.json"), + modify={"aad_scope": 0x1}, + ) as polfile_path: + self._single_test( + _TestCase( + input_data=EXAMPLE_A_2_WITH_BCB, + expected_output=".*.* AAD Scope mismatch, needed 1 got 0", + sec_src_eid="ipn:1.0", + policy_config=polfile_path, + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ERR, + ) + ) + + def test_empty_target_source(self): + self._single_test( + _TestCase( + input_data=EXAMPLE_EMPTY_PAYLOAD, + expected_output=None, # non-deterministic BTSD + sec_src_eid="ipn:2.1", + policy_config="data/default-scs/policy-exA.2-cek-source.json", + bundle_dest_loc=BundleDestLoc.APPIN, + key_set="data/default-scs/keyset-1.json", + input_data_format=DataFormat.CBORDIAG, + expected_output_format=DataFormat.ANYCBOR, + ) + ) diff --git a/src/bsl/crypto/CryptoInterface.c b/src/bsl/crypto/CryptoInterface.c index fcd12035..d709ef17 100644 --- a/src/bsl/crypto/CryptoInterface.c +++ b/src/bsl/crypto/CryptoInterface.c @@ -312,7 +312,8 @@ int BSL_Crypto_KDF(BSL_Crypto_KeyHandle_t kdk_handle, BSL_Crypto_KDFVariant_t fu CHK_PRECONDITION(BSL_SUCCESS == BSL_KeyStore_State.get_keymat(kdk_handle, &kdk_view)); BSL_Data_t cek_keymat; - if (BSL_SUCCESS != BSL_Data_InitBuffer(&cek_keymat, keylen)) + res = BSL_Data_InitBuffer(&cek_keymat, keylen); + if (BSL_SUCCESS != res) { retval = BSL_ERR_SECURITY_CONTEXT_CRYPTO_FAILED; } @@ -446,7 +447,7 @@ int BSL_AuthCtx_Init(BSL_AuthCtx_t *hmac_ctx, BSL_Crypto_KeyHandle_t keyhandle, // GCOV_EXCL_STOP res = BSL_Data_InitBuffer(&hmac_ctx->in_buf, hmac_ctx->block_size); - CHK_PROPERTY(!res); + CHK_PROPERTY(BSL_SUCCESS == res); BSL_KeyStore_State.update_stats(keyhandle, 1, 0); @@ -605,10 +606,9 @@ int BSL_Cipher_Init(BSL_Cipher_t *cipher_ctx, BSL_CipherMode_e enc, BSL_Crypto_A CHK_PROPERTY(res == 1); res = BSL_Data_InitBuffer(&cipher_ctx->in_buf, cipher_ctx->block_size); - CHK_PROPERTY(!res); - + CHK_PROPERTY(BSL_SUCCESS == res); res = BSL_Data_InitBuffer(&cipher_ctx->out_buf, cipher_ctx->block_size); - CHK_PROPERTY(!res); + CHK_PROPERTY(BSL_SUCCESS == res); BSL_KeyStore_State.update_stats(cipher_ctx->keyhandle, 1, 0); diff --git a/src/bsl/crypto/KeyStore.c b/src/bsl/crypto/KeyStore.c index 0c267e23..3f9c8e2d 100644 --- a/src/bsl/crypto/KeyStore.c +++ b/src/bsl/crypto/KeyStore.c @@ -98,8 +98,11 @@ int BSL_Crypto_GenKey(size_t key_length, BSL_Crypto_KeyHandle_t *key_out) int retval = BSL_SUCCESS; BSL_Data_t keymat; - BSL_Data_InitBuffer(&keymat, key_length); - if (BSL_SUCCESS != BSL_Crypto_GenIV(&keymat)) // FIXME rename for clarity + int res = BSL_Data_InitBuffer(&keymat, key_length); + CHK_PROPERTY(BSL_SUCCESS == res); + + res = BSL_Crypto_GenIV(&keymat); + if (BSL_SUCCESS != res) { BSL_Data_Deinit(&keymat); return BSL_ERR_FAILURE; diff --git a/src/bsl/default_sc/BCB_AES_GCM.c b/src/bsl/default_sc/BCB_AES_GCM.c index e9da5b3d..2214eeee 100644 --- a/src/bsl/default_sc/BCB_AES_GCM.c +++ b/src/bsl/default_sc/BCB_AES_GCM.c @@ -392,7 +392,6 @@ int BSLX_BCB_GetOptions(const BSL_BundleRef_t *bundle, BSLX_BCB_t *bcb_context, int res; CHK_PRECONDITION(bcb_context->target_block.block_num > 0); - CHK_PRECONDITION(bcb_context->target_block.btsd_len > 0); bcb_context->keywrap = -1; @@ -503,7 +502,6 @@ int BSLX_BCB_Init(BSLX_BCB_t *bcb_context, BSL_BundleRef_t *bundle, const BSL_Se } CHK_POSTCONDITION(bcb_context->target_block.block_num > 0); - CHK_POSTCONDITION(bcb_context->target_block.btsd_len > 0); return BSL_SUCCESS; } diff --git a/src/bsl/default_sc/BIB_HMAC_SHA2.c b/src/bsl/default_sc/BIB_HMAC_SHA2.c index 25b561db..c490d886 100644 --- a/src/bsl/default_sc/BIB_HMAC_SHA2.c +++ b/src/bsl/default_sc/BIB_HMAC_SHA2.c @@ -248,20 +248,33 @@ int BSLX_BIB_GenIPPT(const BSLX_BIB_t *self, BSL_Data_t *ippt_space) if (self->target_block.block_num > 0) { - // IPPT needs the whole data now BSL_Data_t btsd_copy; - BSL_Data_InitBuffer(&btsd_copy, self->target_block.btsd_len); + // IPPT needs the whole data now + int res = BSL_Data_InitBuffer(&btsd_copy, self->target_block.btsd_len); + CHK_PROPERTY(BSL_SUCCESS == res); - BSL_SeqReader_t *btsd_read = BSL_BundleCtx_ReadBTSD(self->bundle, self->target_block.block_num); - if (!btsd_read) - { - BSL_LOG_ERR("Failed to open BTSD reader on block %" PRIu64, self->target_block.block_num); - } - BSL_SeqReader_Get(btsd_read, btsd_copy.ptr, &btsd_copy.len); - BSL_SeqReader_Destroy(btsd_read); - if (btsd_copy.len != self->target_block.btsd_len) + // only copy data if the destination is real, not just size calculation + if (ippt_space->ptr) { - BSL_LOG_ERR("Failed to read all %zu BTSD, got only %zu", self->target_block.btsd_len, btsd_copy.len); + int retval = BSL_SUCCESS; + + BSL_SeqReader_t *btsd_read = BSL_BundleCtx_ReadBTSD(self->bundle, self->target_block.block_num); + if (!btsd_read) + { + BSL_LOG_ERR("Failed to open BTSD reader on block %" PRIu64, self->target_block.block_num); + retval = BSL_ERR_FAILURE; + } + BSL_SeqReader_Get(btsd_read, btsd_copy.ptr, &btsd_copy.len); + if (btsd_copy.len != self->target_block.btsd_len) + { + BSL_LOG_ERR("Failed to read all %zu BTSD, got only %zu", self->target_block.btsd_len, btsd_copy.len); + retval = BSL_ERR_FAILURE; + } + BSL_SeqReader_Destroy(btsd_read); + if (BSL_SUCCESS != retval) + { + return retval; + } } QCBOREncode_AddBytes(&encoder, UsefulBufC_FROM_BSL_Data(btsd_copy)); @@ -495,9 +508,9 @@ int BSLX_BIB_Execute(BSL_LibCtx_t *lib, BSL_BundleRef_t *bundle, BSL_SecOper_t * BSL_LOG_WARNING("Failed to get security block data"); } - // first determine the size needed, then encode actual IPPT BSL_Data_t ippt_space = BSL_DATA_INIT_NULL; - int ippt_len = BSLX_BIB_GenIPPT(&bib_context, &ippt_space); + // first determine the size needed, then encode actual IPPT + int ippt_len = BSLX_BIB_GenIPPT(&bib_context, &ippt_space); if (ippt_len <= 0) { BSL_LOG_ERR("GenIPPT returned %d", ippt_len); @@ -505,7 +518,9 @@ int BSLX_BIB_Execute(BSL_LibCtx_t *lib, BSL_BundleRef_t *bundle, BSL_SecOper_t * BSL_Data_Deinit(&ippt_space); return BSL_ERR_SECURITY_CONTEXT_FAILED; } - BSL_Data_InitBuffer(&ippt_space, ippt_len); + int res = BSL_Data_InitBuffer(&ippt_space, ippt_len); + CHK_PROPERTY(BSL_SUCCESS == res); + ippt_len = BSLX_BIB_GenIPPT(&bib_context, &ippt_space); if (ippt_len <= 0) { diff --git a/src/bsl/dynamic/PublicInterfaceImpl.c b/src/bsl/dynamic/PublicInterfaceImpl.c index b6192c63..ecc7b4f4 100644 --- a/src/bsl/dynamic/PublicInterfaceImpl.c +++ b/src/bsl/dynamic/PublicInterfaceImpl.c @@ -174,7 +174,8 @@ int BSL_API_QuerySecurity(BSL_LibCtx_t *bsl, BSL_SecurityActionSet_t *output_act // ASB decoder needs the whole BTSD now BSL_Data_t btsd_copy; - BSL_Data_InitBuffer(&btsd_copy, block.btsd_len); + int res = BSL_Data_InitBuffer(&btsd_copy, block.btsd_len); + CHK_PROPERTY(BSL_SUCCESS == res); BSL_SeqReader_t *btsd_read = BSL_BundleCtx_ReadBTSD(bundle, block.block_num); BSL_SeqReader_Get(btsd_read, btsd_copy.ptr, &btsd_copy.len); @@ -182,7 +183,8 @@ int BSL_API_QuerySecurity(BSL_LibCtx_t *bsl, BSL_SecurityActionSet_t *output_act BSL_AbsSecBlock_t *asb = BSL_calloc(1, BSL_AbsSecBlock_Sizeof()); BSL_AbsSecBlock_Init(asb); - if (BSL_SUCCESS == BSL_CBOR_Decode(&btsd_copy, (BSL_CBOR_Decode_f)&BSL_AbsSecBlock_Decode, asb)) + res = BSL_CBOR_Decode(&btsd_copy, (BSL_CBOR_Decode_f)&BSL_AbsSecBlock_Decode, asb); + if (BSL_SUCCESS == res) { if (BSL_AbsSecBlock_ContainsTarget(asb, sec_oper->target_block_num)) { diff --git a/src/bsl/dynamic/SecurityContext.c b/src/bsl/dynamic/SecurityContext.c index a886f60f..c3b721cf 100644 --- a/src/bsl/dynamic/SecurityContext.c +++ b/src/bsl/dynamic/SecurityContext.c @@ -213,7 +213,8 @@ static int BSL_ExecAnyVerifierAcceptor_Pre(BSL_LibCtx_t *lib, const BSL_BundleRe // ASB decoder needs the whole BTSD now BSL_Data_t btsd_copy; - BSL_Data_InitBuffer(&btsd_copy, sec_blk.btsd_len); + res = BSL_Data_InitBuffer(&btsd_copy, sec_blk.btsd_len); + CHK_PROPERTY(BSL_SUCCESS == res); BSL_SeqReader_t *btsd_read = BSL_BundleCtx_ReadBTSD(bundle, sec_blk.block_num); BSL_SeqReader_Get(btsd_read, btsd_copy.ptr, &btsd_copy.len); diff --git a/src/bsl/front/Data.c b/src/bsl/front/Data.c index 5fed69d8..0435edbe 100644 --- a/src/bsl/front/Data.c +++ b/src/bsl/front/Data.c @@ -30,19 +30,17 @@ #include +/// Internal state reset to default static void bsl_data_int_reset(BSL_Data_t *data) { - ASSERT_ARG_NONNULL(data); - data->owned = false; data->ptr = NULL; data->len = 0; } +/// Internal free of owned data without changing state static void bsl_data_int_free(BSL_Data_t *data) { - ASSERT_ARG_NONNULL(data); - if (data->owned && data->ptr) { BSL_free(data->ptr); @@ -58,28 +56,35 @@ void BSL_Data_Init(BSL_Data_t *data) int BSL_Data_InitBuffer(BSL_Data_t *data, size_t bytelen) { ASSERT_ARG_NONNULL(data); - CHK_ARG_EXPR(bytelen > 0); - bsl_data_int_reset(data); + + if (bytelen == 0) + { + // nothing to do + return BSL_SUCCESS; + } + + data->owned = true; data->ptr = BSL_malloc(bytelen); data->len = bytelen; - data->owned = true; if (data->ptr) { memset(data->ptr, 0, bytelen); + return BSL_SUCCESS; + } + else + { + return BSL_ERR_INSUFFICIENT_SPACE; } - - CHK_POSTCONDITION(data->ptr != NULL); - return BSL_SUCCESS; } void BSL_Data_InitView(BSL_Data_t *data, size_t len, const BSL_DataPtr_t src) { ASSERT_ARG_NONNULL(data); + bsl_data_int_reset(data); - data->owned = false; - data->ptr = src; - data->len = len; + data->ptr = src; + data->len = len; } void BSL_Data_InitMove(BSL_Data_t *data, BSL_Data_t *src) diff --git a/src/bsl/mock_bpa/agent.c b/src/bsl/mock_bpa/agent.c index ba5771c4..039973d6 100644 --- a/src/bsl/mock_bpa/agent.c +++ b/src/bsl/mock_bpa/agent.c @@ -182,10 +182,13 @@ static int MockBPA_ReadBTSD_Read(void *user_data, void *buf, size_t *bufsize) ASSERT_ARG_NONNULL(obj); CHK_ARG_NONNULL(buf); CHK_ARG_NONNULL(bufsize); - ASSERT_PRECONDITION(obj->file); - const size_t got = fread(buf, 1, *bufsize, obj->file); - obj->curs += got; + size_t got = 0; + if (obj->file) + { + got = fread(buf, 1, *bufsize, obj->file); + obj->curs += got; + } BSL_LOG_DEBUG("reading up to %zd bytes, got %zd", *bufsize, got); *bufsize = got; return 0; @@ -195,9 +198,11 @@ static void MockBPA_ReadBTSD_Deinit(void *user_data) { struct MockBPA_BTSD_Data_s *obj = user_data; ASSERT_ARG_NONNULL(obj); - ASSERT_PRECONDITION(obj->file); - fclose(obj->file); + if (obj->file) + { + fclose(obj->file); + } // buffer is external data, no cleanup BSL_free(obj); } @@ -221,7 +226,7 @@ static struct BSL_SeqReader_s *MockBPA_ReadBTSD(const BSL_BundleRef_t *bundle_re obj->block = found_block; obj->ptr = found_block->btsd; obj->size = found_block->btsd_len; - obj->file = fmemopen(obj->ptr, obj->size, "rb"); + obj->file = (obj->ptr) ? fmemopen(obj->ptr, obj->size, "rb") : NULL; obj->curs = 0; BSL_SeqReader_t *reader = BSL_calloc(1, sizeof(BSL_SeqReader_t)); diff --git a/test/test_AbsSecBlock.c b/test/test_AbsSecBlock.c index d3a64afe..39cf3c37 100644 --- a/test/test_AbsSecBlock.c +++ b/test/test_AbsSecBlock.c @@ -73,9 +73,11 @@ void TestASBDecodeEncodeClosure(uint8_t *asb_cbor, size_t asb_cbor_bytelen, int6 // Confirm that when we encode it, we get the original. BSL_Data_t encoded_cbor; - BSL_Data_InitBuffer(&encoded_cbor, asb_cbor_bytelen); - int res = BSL_CBOR_Encode_Twopass(&encoded_cbor, (BSL_CBOR_Encode_f)&BSL_AbsSecBlock_Encode, asb); + int res = BSL_Data_InitBuffer(&encoded_cbor, asb_cbor_bytelen); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); + + res = BSL_CBOR_Encode_Twopass(&encoded_cbor, (BSL_CBOR_Encode_f)&BSL_AbsSecBlock_Encode, asb); TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); // Make sure the lengths match and then make sure the bytes match diff --git a/test/test_CryptoInterface.c b/test/test_CryptoInterface.c index 4a95eaee..df448db8 100644 --- a/test/test_CryptoInterface.c +++ b/test/test_CryptoInterface.c @@ -201,7 +201,7 @@ static uint8_t test_256[32] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, void suiteSetUp(void) { - TEST_ASSERT_EQUAL_INT(0, BSL_HostDescriptors_Set(MockBPA_Agent_Descriptors(NULL))); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_HostDescriptors_Set(MockBPA_Agent_Descriptors(NULL))); mock_bpa_LogOpen(); mock_bpa_LogSetLeastSeverity(LOG_ERR); } @@ -214,7 +214,7 @@ int suiteTearDown(int failures) void setUp(void) { - TEST_ASSERT_EQUAL(0, BSL_API_InitLib(&bsl)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_API_InitLib(&bsl)); MockBPA_KeyStore_Init(); @@ -242,7 +242,7 @@ void setUp(void) void tearDown(void) { MockBPA_KeyStore_Deinit(); - TEST_ASSERT_EQUAL(0, BSL_API_DeinitLib(&bsl)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_API_DeinitLib(&bsl)); } void test_SeqReader_flat(void) @@ -255,12 +255,12 @@ void test_SeqReader_flat(void) uint8_t buf[3]; size_t bufsize = sizeof(buf); // first 3 bytes - TEST_ASSERT_EQUAL_INT(0, BSL_SeqReader_Get(reader, buf, &bufsize)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_SeqReader_Get(reader, buf, &bufsize)); TEST_ASSERT_EQUAL_INT(3, bufsize); TEST_ASSERT_EQUAL_MEMORY(source, buf, 3); // next 2 bytes bufsize = sizeof(buf); - TEST_ASSERT_EQUAL_INT(0, BSL_SeqReader_Get(reader, buf, &bufsize)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_SeqReader_Get(reader, buf, &bufsize)); TEST_ASSERT_EQUAL_INT(2, bufsize); TEST_ASSERT_EQUAL_MEMORY(source + 3, buf, 2); @@ -278,10 +278,10 @@ void test_SeqWriter_flat(void) uint8_t buf[3] = { 0x01, 0x02, 0x03 }; size_t bufsize = sizeof(buf); // first 3 bytes - TEST_ASSERT_EQUAL_INT(0, BSL_SeqWriter_Put(writer, buf, bufsize)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_SeqWriter_Put(writer, buf, bufsize)); // next 2 bytes bufsize = sizeof(buf) - 1; - TEST_ASSERT_EQUAL_INT(0, BSL_SeqWriter_Put(writer, buf, bufsize)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_SeqWriter_Put(writer, buf, bufsize)); TEST_ASSERT_NULL(dest); TEST_ASSERT_EQUAL_size_t(0, dest_size); @@ -340,10 +340,10 @@ void test_hmac_in(int input_case, const char *keyid, BSL_Crypto_SHAVariant_e sha "BSL_TestUtils_DecodeBase16_cstr() failed"); BSL_Crypto_KeyHandle_t keyhandle; - TEST_ASSERT_EQUAL(0, BSL_Crypto_GetRegistryKeyName(keyid, &keyhandle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName(keyid, &keyhandle)); BSL_AuthCtx_t hmac; - TEST_ASSERT_EQUAL(0, BSL_AuthCtx_Init(&hmac, keyhandle, sha_var)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_AuthCtx_Init(&hmac, keyhandle, sha_var)); BSL_Crypto_ReleaseKeyHandle(keyhandle); switch (input_case) @@ -353,13 +353,13 @@ void test_hmac_in(int input_case, const char *keyid, BSL_Crypto_SHAVariant_e sha BSL_SeqReader_t *reader = BSL_TestUtils_FlatReader(pt_in_data.ptr, pt_in_data.len); TEST_ASSERT_NOT_NULL(reader); - TEST_ASSERT_EQUAL(0, BSL_AuthCtx_DigestSeq(&hmac, reader)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_AuthCtx_DigestSeq(&hmac, reader)); BSL_SeqReader_Destroy(reader); break; } case 1: - TEST_ASSERT_EQUAL(0, BSL_AuthCtx_DigestBuffer(&hmac, (void *)pt_in_data.ptr, pt_in_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_AuthCtx_DigestBuffer(&hmac, (void *)pt_in_data.ptr, pt_in_data.len)); break; default: TEST_ABORT(); @@ -382,7 +382,7 @@ void test_hmac_in(int input_case, const char *keyid, BSL_Crypto_SHAVariant_e sha BSL_Data_t tag; BSL_Data_Init(&tag); - TEST_ASSERT_EQUAL(0, BSL_AuthCtx_Finalize(&hmac, &tag)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_AuthCtx_Finalize(&hmac, &tag)); TEST_ASSERT_EQUAL(expect_hmac_sz, tag.len); TEST_ASSERT_TRUE(BSL_TestUtils_IsB16StrEqualTo(expected, tag)); @@ -401,9 +401,11 @@ void test_encrypt(const char *plaintext_in, const char *keyid) int res; BSL_Data_t iv; - BSL_Data_InitBuffer(&iv, 16); + + res = BSL_Data_InitBuffer(&iv, 16); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Crypto_GenIV(&iv); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); size_t pt_size = strlen(plaintext_in); BSL_SeqReader_t *reader = BSL_TestUtils_FlatReader((const void *)plaintext_in, pt_size); @@ -417,28 +419,28 @@ void test_encrypt(const char *plaintext_in, const char *keyid) int aes_var = (0 == strcmp(keyid, "Key8")) ? BSL_CRYPTO_AES_256 : BSL_CRYPTO_AES_128; BSL_Crypto_KeyHandle_t ekey; - TEST_ASSERT_EQUAL(0, BSL_Crypto_GetRegistryKeyName(keyid, &ekey)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName(keyid, &ekey)); BSL_Cipher_t ctx; res = BSL_Cipher_Init(&ctx, BSL_CRYPTO_ENCRYPT, aes_var, &iv, ekey); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); uint8_t aad[2] = { 0x00, 0x01 }; - res = BSL_Cipher_AddAadBuffer(&ctx, aad, 2); - TEST_ASSERT_EQUAL(0, res); + res = BSL_Cipher_AddAadBuffer(&ctx, aad, sizeof(aad)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Cipher_AddSeq(&ctx, reader, writer, pt_size); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); BSL_Data_t tag; BSL_Data_Init(&tag); res = BSL_Cipher_FinalizeSeq(&ctx, writer); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); BSL_SeqWriter_Destroy(writer, true); res = BSL_Cipher_GetTag(&ctx, &tag); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); TEST_ASSERT_NOT_NULL(tag.ptr); TEST_ASSERT_EQUAL_size_t(16, tag.len); @@ -476,10 +478,11 @@ void test_decrypt(const char *plaintext_in, const char *keyid) int res; BSL_Data_t iv; - BSL_Data_InitBuffer(&iv, 16); + res = BSL_Data_InitBuffer(&iv, 16); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Crypto_GenIV(&iv); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); uint8_t aad[2] = { 0x00, 0x01 }; @@ -506,23 +509,24 @@ void test_decrypt(const char *plaintext_in, const char *keyid) int aes_var = (0 == strcmp(keyid, "Key8")) ? BSL_CRYPTO_AES_256 : BSL_CRYPTO_AES_128; BSL_Crypto_KeyHandle_t ckey; - TEST_ASSERT_EQUAL(0, BSL_Crypto_GetRegistryKeyName(keyid, &ckey)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName(keyid, &ckey)); BSL_Cipher_t ctx; res = BSL_Cipher_Init(&ctx, BSL_CRYPTO_DECRYPT, aes_var, &iv, ckey); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Cipher_AddAadBuffer(&ctx, aad, 2); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Cipher_AddSeq(&ctx, reader, writer, ciphertext_len); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); res = BSL_Cipher_SetTag(&ctx, &tag); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); + BSL_Data_Deinit(&tag); res = BSL_Cipher_FinalizeSeq(&ctx, writer); - TEST_ASSERT_EQUAL(0, res); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); BSL_SeqWriter_Destroy(writer, true); @@ -544,10 +548,12 @@ TEST_RANGE(<6, 18, 1>) void test_crypto_generate_iv(int iv_len) { BSL_Data_t buf; - BSL_Data_InitBuffer(&buf, iv_len); - int res = BSL_Crypto_GenIV(&buf); - TEST_ASSERT_EQUAL(0, res); + int res = BSL_Data_InitBuffer(&buf, iv_len); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); + + res = BSL_Crypto_GenIV(&buf); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, res); BSL_Data_Deinit(&buf); } @@ -572,24 +578,24 @@ void test_key_wrap(const char *kek, const char *cek, const char *expected) // convert strings to bytedata BSL_Data_t kek_data; BSL_Data_Init(&kek_data); - TEST_ASSERT_EQUAL(0, BSL_TestUtils_DecodeBase16_cstr(&kek_data, kek)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&kek_data, kek)); BSL_Data_t cek_data; BSL_Data_Init(&cek_data); - TEST_ASSERT_EQUAL(0, BSL_TestUtils_DecodeBase16_cstr(&cek_data, cek)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&cek_data, cek)); // convert bytedata to keyhandles - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("kek", kek_data.ptr, kek_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("kek", kek_data.ptr, kek_data.len)); BSL_Crypto_KeyHandle_t kek_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("kek", &kek_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("kek", &kek_handle)); - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("cek", cek_data.ptr, cek_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("cek", cek_data.ptr, cek_data.len)); BSL_Crypto_KeyHandle_t cek_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("cek", &cek_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("cek", &cek_handle)); BSL_Data_t wrapped_key; BSL_Data_InitBuffer(&wrapped_key, cek_data.len + 8); - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_WrapKey(kek_handle, cek_handle, &wrapped_key)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_WrapKey(kek_handle, cek_handle, &wrapped_key)); TEST_ASSERT_TRUE(BSL_TestUtils_IsB16StrEqualTo(expected, wrapped_key)); @@ -638,16 +644,16 @@ void test_key_unwrap(const char *kek, const char *expected_cek, const char *wrap TEST_ASSERT_EQUAL(BSL_TestUtils_DecodeBase16_cstr(&wrapped_key_data, wrapped_key), 0); // convert bytedata to keyhandles - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("kek", kek_data.ptr, kek_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("kek", kek_data.ptr, kek_data.len)); BSL_Crypto_KeyHandle_t kek_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("kek", &kek_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("kek", &kek_handle)); - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("expect", cek_data.ptr, cek_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("expect", cek_data.ptr, cek_data.len)); BSL_Crypto_KeyHandle_t expect_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("expect", &expect_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("expect", &expect_handle)); BSL_Crypto_KeyHandle_t cek_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_UnwrapKey(kek_handle, &wrapped_key_data, &cek_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_UnwrapKey(kek_handle, &wrapped_key_data, &cek_handle)); TEST_ASSERT_TRUE(BSL_Crypto_CompareKeys(expect_handle, cek_handle)); @@ -677,31 +683,31 @@ void test_kdf(const char *kdk_hex, int func, const char *salt_hex, const char *i { BSL_Data_t kdk_data; BSL_Data_Init(&kdk_data); - TEST_ASSERT_EQUAL(0, BSL_TestUtils_DecodeBase16_cstr(&kdk_data, kdk_hex)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&kdk_data, kdk_hex)); BSL_Data_t salt_data; BSL_Data_Init(&salt_data); - TEST_ASSERT_EQUAL(0, BSL_TestUtils_DecodeBase16_cstr(&salt_data, salt_hex)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&salt_data, salt_hex)); BSL_Data_t info_data; BSL_Data_Init(&info_data); - TEST_ASSERT_EQUAL_INT(0, BSL_TestUtils_DecodeBase16_cstr(&info_data, info_hex)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&info_data, info_hex)); BSL_Data_t expect_data; BSL_Data_Init(&expect_data); - TEST_ASSERT_EQUAL_INT(0, BSL_TestUtils_DecodeBase16_cstr(&expect_data, expect_hex)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_TestUtils_DecodeBase16_cstr(&expect_data, expect_hex)); // convert bytedata to keyhandles - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("kdk", kdk_data.ptr, kdk_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("kdk", kdk_data.ptr, kdk_data.len)); BSL_Crypto_KeyHandle_t kdk_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("kdk", &kdk_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("kdk", &kdk_handle)); - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_AddRegistryKeyName("expect", expect_data.ptr, expect_data.len)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName("expect", expect_data.ptr, expect_data.len)); BSL_Crypto_KeyHandle_t expect_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_GetRegistryKeyName("expect", &expect_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_GetRegistryKeyName("expect", &expect_handle)); BSL_Crypto_KeyHandle_t cek_handle; - TEST_ASSERT_EQUAL_INT(0, BSL_Crypto_KDF(kdk_handle, func, &salt_data, &info_data, keylen, &cek_handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_KDF(kdk_handle, func, &salt_data, &info_data, keylen, &cek_handle)); TEST_ASSERT_TRUE(BSL_Crypto_CompareKeys(expect_handle, cek_handle)); @@ -805,7 +811,7 @@ void test_get_key_concurrency(void) 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF }; for (size_t i = 0; i < TEST_THREADS; i++) { - TEST_ASSERT_EQUAL(0, BSL_Crypto_AddRegistryKeyName(names[i], key_bytes, sizeof(key_bytes))); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, BSL_Crypto_AddRegistryKeyName(names[i], key_bytes, sizeof(key_bytes))); } for (size_t i = 0; i < TEST_THREADS; i++) @@ -834,7 +840,7 @@ void test_key_stats(void) BSL_Crypto_KeyHandle_t handle; BSL_Crypto_LoadKey(test_128, sizeof(test_128), &handle); TEST_ASSERT_NOT_NULL(handle); - TEST_ASSERT_EQUAL_INT(0, MockBPA_KeyStore_AddKey(&key_id, handle)); + TEST_ASSERT_EQUAL_INT(BSL_SUCCESS, MockBPA_KeyStore_AddKey(&key_id, handle)); test_encrypt("hello world!", "testkeystats");