Move test helpers into the framework

Move everything in tests/src and tests/include except for TLS-only
things, the alt-dummy headers and the generated PSA test wrappers.

Signed-off-by: David Horstmann <[email protected]>
This commit is contained in:
David Horstmann
2024-11-14 12:11:06 +00:00
parent 824a8dcde3
commit dfd518f976
987 changed files with 0 additions and 462192 deletions
-26
View File
@@ -1,26 +0,0 @@
*.sln
*.vcxproj
*.log
/test_suite*
/data_files/mpi_write
/data_files/hmac_drbg_seed
/data_files/ctr_drbg_seed
/data_files/entropy_seed
/include/alt-extra/psa/crypto_platform_alt.h
/include/alt-extra/psa/crypto_struct_alt.h
/include/test/instrument_record_status.h
/src/libmbed*
/libtestdriver1/*
###START_GENERATED_FILES###
# Generated source files
/opt-testcases/tls13-compat.sh
/suites/*.generated.data
/suites/test_suite_config.mbedtls_boolean.data
/src/test_keys.h
/src/test_certs.h
###END_GENERATED_FILES###
-1
View File
@@ -1 +0,0 @@
mbedtls.run_job()
-224
View File
@@ -1,224 +0,0 @@
set(libs
${mbedtls_target}
${everest_target}
${CMAKE_THREAD_LIBS_INIT}
)
if(NOT MBEDTLS_PYTHON_EXECUTABLE)
message(FATAL_ERROR "Cannot build test suites without Python 3")
endif()
# generated .data files will go there
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/suites)
# Get base names for generated files
execute_process(
COMMAND
${MBEDTLS_PYTHON_EXECUTABLE}
${MBEDTLS_FRAMEWORK_DIR}/scripts/generate_config_tests.py
--list-for-cmake
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}/..
OUTPUT_VARIABLE
base_config_generated_data_files_raw)
string(REGEX REPLACE "[^;]*/" ""
base_config_generated_data_files_raw "${base_config_generated_data_files_raw}")
# Can be replace by list(FILTER ...) when CI CMake version is >=3.6
foreach(file ${base_config_generated_data_files_raw})
if(${file} MATCHES "mbedtls")
list(APPEND base_config_generated_data_files ${file})
endif()
endforeach()
# Derive generated file paths in the build directory. The generated data
# files go into the suites/ subdirectory.
set(base_generated_data_files
${base_config_generated_data_files})
string(REGEX REPLACE "([^;]+)" "suites/\\1"
all_generated_data_files "${base_generated_data_files}")
set(config_generated_data_files "")
foreach(file ${base_config_generated_data_files})
list(APPEND config_generated_data_files ${CMAKE_CURRENT_BINARY_DIR}/suites/${file})
endforeach()
if(GEN_FILES)
add_custom_command(
OUTPUT
${config_generated_data_files}
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}/..
COMMAND
${MBEDTLS_PYTHON_EXECUTABLE}
${MBEDTLS_FRAMEWORK_DIR}/scripts/generate_config_tests.py
--directory ${CMAKE_CURRENT_BINARY_DIR}/suites
${config_generated_data_files}
DEPENDS
${MBEDTLS_FRAMEWORK_DIR}/scripts/generate_config_tests.py
# Do not declare the configuration files as dependencies: they
# change too often in ways that don't affect the result
# ((un)commenting some options).
)
add_custom_command(
OUTPUT
${CMAKE_CURRENT_SOURCE_DIR}/opt-testcases/tls13-compat.sh
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}/..
COMMAND
"${MBEDTLS_PYTHON_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/../framework/scripts/generate_tls13_compat_tests.py"
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/../framework/scripts/generate_tls13_compat_tests.py
)
add_custom_target(tls13-compat.sh
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/opt-testcases/tls13-compat.sh)
set_target_properties(tls13-compat.sh PROPERTIES EXCLUDE_FROM_ALL NO)
add_dependencies(${ssl_opt_target} tls13-compat.sh)
else()
foreach(file ${all_generated_data_files})
link_to_source(${file})
endforeach()
endif()
# CMake generates sub-makefiles for each target and calls them in subprocesses.
# Without this command, cmake will generate rules in each sub-makefile. As a result,
# they can cause race conditions in parallel builds.
# With this line, only 4 sub-makefiles include the above command, that reduces
# the risk of a race.
add_custom_target(test_suite_config_generated_data DEPENDS ${config_generated_data_files})
# If SKIP_TEST_SUITES is not defined with -D, get it from the environment.
if((NOT DEFINED SKIP_TEST_SUITES) AND (DEFINED ENV{SKIP_TEST_SUITES}))
set(SKIP_TEST_SUITES $ENV{SKIP_TEST_SUITES})
endif()
# Test suites caught by SKIP_TEST_SUITES are built but not executed.
# "foo" as a skip pattern skips "test_suite_foo" and "test_suite_foo.bar"
# but not "test_suite_foobar".
string(REGEX REPLACE "[ ,;]" "|" SKIP_TEST_SUITES_REGEX "${SKIP_TEST_SUITES}")
string(REPLACE "." "\\." SKIP_TEST_SUITES_REGEX "${SKIP_TEST_SUITES_REGEX}")
set(SKIP_TEST_SUITES_REGEX "^(${SKIP_TEST_SUITES_REGEX})(\$|\\.)")
function(add_test_suite suite_name)
if(ARGV1)
set(data_name ${ARGV1})
else()
set(data_name ${suite_name})
endif()
# Get the test names of the tests with generated .data files
# from the generated_data_files list in parent scope.
set(config_generated_data_names "")
foreach(generated_data_file ${config_generated_data_files})
# Get the plain filename
get_filename_component(generated_data_name ${generated_data_file} NAME)
# Remove the ".data" extension
get_name_without_last_ext(generated_data_name ${generated_data_name})
# Remove leading "test_suite_"
string(SUBSTRING ${generated_data_name} 11 -1 generated_data_name)
list(APPEND config_generated_data_names ${generated_data_name})
endforeach()
if(";${config_generated_data_names};" MATCHES ";${data_name};")
set(data_file
${CMAKE_CURRENT_BINARY_DIR}/suites/test_suite_${data_name}.data)
set(dependency test_suite_config_generated_data)
else()
set(data_file
${CMAKE_CURRENT_SOURCE_DIR}/suites/test_suite_${data_name}.data)
set(dependency
test_suite_config_generated_data)
endif()
add_custom_command(
OUTPUT
# The output filename of generate_test_code.py is derived from the -d
# input argument.
test_suite_${data_name}.c
COMMAND
${MBEDTLS_PYTHON_EXECUTABLE}
${MBEDTLS_FRAMEWORK_DIR}/scripts/generate_test_code.py
-f ${CMAKE_CURRENT_SOURCE_DIR}/suites/test_suite_${suite_name}.function
-d ${data_file}
-t ${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/main_test.function
-p ${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/host_test.function
-s ${CMAKE_CURRENT_SOURCE_DIR}/suites
--helpers-file ${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/helpers.function
-o .
DEPENDS
${MBEDTLS_FRAMEWORK_DIR}/scripts/generate_test_code.py
${CMAKE_CURRENT_SOURCE_DIR}/suites/test_suite_${suite_name}.function
${data_file}
${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/main_test.function
${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/host_test.function
${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/tests/suites/helpers.function
${mbedtls_target}
BYPRODUCTS
test_suite_${data_name}.datax
)
add_executable(test_suite_${data_name} test_suite_${data_name}.c
$<TARGET_OBJECTS:mbedtls_test>
$<TARGET_OBJECTS:mbedtls_test_helpers>)
set_base_compile_options(test_suite_${data_name})
target_compile_options(test_suite_${data_name} PRIVATE ${TEST_C_FLAGS})
add_dependencies(test_suite_${data_name} ${dependency})
target_link_libraries(test_suite_${data_name} ${libs})
# Include test-specific header files from ./include and private header
# files (used by some invasive tests) from ../library. Public header
# files are automatically included because the library targets declare
# them as PUBLIC.
target_include_directories(test_suite_${data_name}
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../library
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/core
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../tf-psa-crypto/drivers/builtin/src)
# Request C11, which is needed for memory poisoning tests
set_target_properties(test_suite_${data_name} PROPERTIES C_STANDARD 11)
if(${data_name} MATCHES ${SKIP_TEST_SUITES_REGEX})
message(STATUS "The test suite ${data_name} will not be executed.")
else()
add_test(${data_name}-suite test_suite_${data_name} --verbose)
endif()
endfunction(add_test_suite)
# Enable definition of various functions used throughout the testsuite
# (gethostname, strdup, fileno...) even when compiling with -std=c99. Harmless
# on non-POSIX platforms.
add_definitions("-D_POSIX_C_SOURCE=200809L")
if(CMAKE_COMPILER_IS_CLANG)
set(TEST_C_FLAGS -Wdocumentation -Wno-documentation-deprecated-sync -Wunreachable-code)
endif(CMAKE_COMPILER_IS_CLANG)
if(MSVC)
# If a warning level has been defined, suppress all warnings for test code
set(TEST_C_FLAGS /W0 /WX-)
endif(MSVC)
file(GLOB test_suites RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" suites/*.data)
list(APPEND test_suites ${all_generated_data_files})
# If the generated .data files are present in the source tree, we just added
# them twice, both through GLOB and through ${all_generated_data_files}.
list(REMOVE_DUPLICATES test_suites)
list(SORT test_suites)
foreach(test_suite ${test_suites})
get_filename_component(data_name ${test_suite} NAME)
string(REGEX REPLACE "\\.data\$" "" data_name "${data_name}")
string(REPLACE "test_suite_" "" data_name "${data_name}")
string(REGEX MATCH "[^.]*" function_name "${data_name}")
add_test_suite(${function_name} ${data_name})
endforeach(test_suite)
# Make scripts and data files needed for testing available in an
# out-of-source build.
if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/seedfile")
link_to_source(seedfile)
endif()
link_to_source(Descriptions.txt)
link_to_source(compat.sh)
link_to_source(context-info.sh)
link_to_source(../framework/data_files)
link_to_source(scripts)
link_to_source(ssl-opt.sh)
link_to_source(opt-testcases)
endif()
-22
View File
@@ -1,22 +0,0 @@
test_suites
The various 'test_suite_XXX' programs from the 'tests' directory, executed
using 'make check' (Unix make) or 'make test' (Cmake), include test cases
(reference test vectors, sanity checks, malformed input for parsing
functions, etc.) for all modules except the SSL modules.
selftests
The 'programs/test/selftest' program runs the 'XXX_self_test()' functions
of each individual module. Most of them are included in the respective
test suite, but some slower ones are only included here.
compat
The 'tests/compat.sh' script checks interoperability with OpenSSL and
GnuTLS (and ourselves!) for every common ciphersuite, in every TLS
version, both ways (client/server), using client authentication or not.
For each ciphersuite/version/side/authmode it performs a full handshake
and a small data exchange.
ssl_opt
The 'tests/ssl-opt.sh' script checks various options and/or operations not
covered by compat.sh: session resumption (using session cache or tickets),
renegotiation, SNI, other extensions, etc.
-362
View File
@@ -1,362 +0,0 @@
MBEDTLS_TEST_PATH = .
include ../scripts/common.make
# Set this to -v to see the details of failing test cases
TEST_FLAGS ?= $(if $(filter-out 0 OFF Off off NO No no FALSE False false N n,$(CTEST_OUTPUT_ON_FAILURE)),-v,)
# Also include private headers, for the sake of invasive tests.
LOCAL_CFLAGS += -I$(MBEDTLS_PATH)/library -I$(MBEDTLS_PATH)/tf-psa-crypto/core -I$(MBEDTLS_PATH)/tf-psa-crypto/drivers/builtin/src
# Enable definition of various functions used throughout the testsuite
# (gethostname, strdup, fileno...) even when compiling with -std=c99. Harmless
# on non-POSIX platforms.
LOCAL_CFLAGS += -D_POSIX_C_SOURCE=200809L
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
LOCAL_CFLAGS += -Werror -DRECORD_PSA_STATUS_COVERAGE_LOG
endif
GENERATED_BIGNUM_DATA_FILES := $(addprefix ../tf-psa-crypto/,$(shell \
$(PYTHON) ../framework/scripts/generate_bignum_tests.py --list || \
echo FAILED \
))
ifeq ($(GENERATED_BIGNUM_DATA_FILES),FAILED)
$(error "$(PYTHON) ../framework/scripts/generate_bignum_tests.py --list" failed)
endif
GENERATED_CRYPTO_DATA_FILES += $(GENERATED_BIGNUM_DATA_FILES)
GENERATED_CONFIG_DATA_FILES_RAW := $(patsubst tests/%,%,$(shell \
$(PYTHON) ../framework/scripts/generate_config_tests.py --list || \
echo FAILED \
))
ifeq ($(GENERATED_CONFIG_DATA_FILES),FAILED)
$(error "$(PYTHON) ../framework/scripts/generate_config_tests.py --list" failed)
endif
GENERATED_MBEDTLS_CONFIG_DATA_FILES := $(foreach file,$(GENERATED_CONFIG_DATA_FILES_RAW),$(if $(findstring mbedtls,$(file)),$(file),))
GENERATED_PSA_CONFIG_DATA_FILES := $(foreach file,$(GENERATED_CONFIG_DATA_FILES_RAW),$(if $(findstring psa,$(file)),$(addprefix ../tf-psa-crypto/tests/,$(file)),))
GENERATED_CONFIG_DATA_FILES := $(GENERATED_MBEDTLS_CONFIG_DATA_FILES)$(GENERATED_PSA_CONFIG_DATA_FILES)
GENERATED_DATA_FILES += $(GENERATED_MBEDTLS_CONFIG_DATA_FILES)
GENERATED_CRYPTO_DATA_FILES += $(GENERATED_PSA_CONFIG_DATA_FILES)
GENERATED_ECP_DATA_FILES := $(addprefix ../tf-psa-crypto/,$(shell \
$(PYTHON) ../framework/scripts/generate_ecp_tests.py --list || \
echo FAILED \
))
ifeq ($(GENERATED_ECP_DATA_FILES),FAILED)
$(error "$(PYTHON) ../framework/scripts/generate_ecp_tests.py --list" failed)
endif
GENERATED_CRYPTO_DATA_FILES += $(GENERATED_ECP_DATA_FILES)
GENERATED_PSA_DATA_FILES := $(addprefix ../tf-psa-crypto/,$(shell \
$(PYTHON) ../framework/scripts/generate_psa_tests.py --list || \
echo FAILED \
))
ifeq ($(GENERATED_PSA_DATA_FILES),FAILED)
$(error "$(PYTHON) ../framework/scripts/generate_psa_tests.py --list" failed)
endif
GENERATED_CRYPTO_DATA_FILES += $(GENERATED_PSA_DATA_FILES)
GENERATED_FILES = $(GENERATED_DATA_FILES) $(GENERATED_CRYPTO_DATA_FILES)
GENERATED_FILES += src/test_keys.h src/test_certs.h
# Generated files needed to (fully) run ssl-opt.sh
.PHONY: ssl-opt
opt-testcases/tls13-compat.sh: ../framework/scripts/generate_tls13_compat_tests.py
echo " Gen $@"
$(PYTHON) ../framework/scripts/generate_tls13_compat_tests.py -o $@
GENERATED_FILES += opt-testcases/tls13-compat.sh
ssl-opt: opt-testcases/tls13-compat.sh
.PHONY: generated_files
generated_files: $(GENERATED_FILES)
# generate_bignum_tests.py and generate_psa_tests.py spend more time analyzing
# inputs than generating outputs. Its inputs are the same no matter which files
# are being generated.
# It's rare not to want all the outputs. So always generate all of its outputs.
# Use an intermediate phony dependency so that parallel builds don't run
# a separate instance of the recipe for each output file.
$(GENERATED_BIGNUM_DATA_FILES): $(gen_file_dep) generated_bignum_test_data
generated_bignum_test_data: ../framework/scripts/generate_bignum_tests.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/bignum_common.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/bignum_core.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/bignum_mod_raw.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/bignum_mod.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/test_case.py
generated_bignum_test_data: ../framework/scripts/mbedtls_framework/test_data_generation.py
generated_bignum_test_data:
echo " Gen $(GENERATED_BIGNUM_DATA_FILES)"
$(PYTHON) ../framework/scripts/generate_bignum_tests.py --directory ../tf-psa-crypto/tests/suites
.SECONDARY: generated_bignum_test_data
# We deliberately omit the configuration files (mbedtls_config.h,
# crypto_config.h) from the depenency list because during development
# and on the CI, we often edit those in a way that doesn't change the
# output, to comment out certain options, or even to remove certain
# lines which do affect the output negatively (it will miss the
# corresponding test cases).
$(GENERATED_CONFIG_DATA_FILES): $(gen_file_dep) generated_config_test_data
generated_config_test_data: ../framework/scripts/generate_config_tests.py
generated_config_test_data: ../scripts/config.py
generated_config_test_data: ../framework/scripts/mbedtls_framework/test_case.py
generated_config_test_data: ../framework/scripts/mbedtls_framework/test_data_generation.py
generated_config_test_data:
echo " Gen $(GENERATED_CONFIG_DATA_FILES)"
$(PYTHON) ../framework/scripts/generate_config_tests.py $(GENERATED_MBEDTLS_CONFIG_DATA_FILES)
$(PYTHON) ../framework/scripts/generate_config_tests.py --directory ../tf-psa-crypto/tests/suites $(GENERATED_PSA_CONFIG_DATA_FILES)
.SECONDARY: generated_config_test_data
$(GENERATED_ECP_DATA_FILES): $(gen_file_dep) generated_ecp_test_data
generated_ecp_test_data: ../framework/scripts/generate_ecp_tests.py
generated_ecp_test_data: ../framework/scripts/mbedtls_framework/bignum_common.py
generated_ecp_test_data: ../framework/scripts/mbedtls_framework/ecp.py
generated_ecp_test_data: ../framework/scripts/mbedtls_framework/test_case.py
generated_ecp_test_data: ../framework/scripts/mbedtls_framework/test_data_generation.py
generated_ecp_test_data:
echo " Gen $(GENERATED_ECP_DATA_FILES)"
$(PYTHON) ../framework/scripts/generate_ecp_tests.py --directory ../tf-psa-crypto/tests/suites
.SECONDARY: generated_ecp_test_data
$(GENERATED_PSA_DATA_FILES): $(gen_file_dep) generated_psa_test_data
generated_psa_test_data: ../framework/scripts/generate_psa_tests.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/crypto_data_tests.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/crypto_knowledge.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/macro_collector.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/psa_information.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/psa_storage.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/test_case.py
generated_psa_test_data: ../framework/scripts/mbedtls_framework/test_data_generation.py
## The generated file only depends on the options that are present in
## crypto_config.h, not on which options are set. To avoid regenerating this
## file all the time when switching between configurations, don't declare
## crypto_config.h as a dependency. Remove this file from your working tree
## if you've just added or removed an option in crypto_config.h.
#generated_psa_test_data: ../tf-psa-crypto/include/psa/crypto_config.h
generated_psa_test_data: ../tf-psa-crypto/include/psa/crypto_values.h
generated_psa_test_data: ../tf-psa-crypto/include/psa/crypto_extra.h
generated_psa_test_data: ../tf-psa-crypto/tests/suites/test_suite_psa_crypto_metadata.data
generated_psa_test_data:
echo " Gen $(GENERATED_PSA_DATA_FILES) ..."
$(PYTHON) ../framework/scripts/generate_psa_tests.py --directory ../tf-psa-crypto/tests/suites
.SECONDARY: generated_psa_test_data
# A test application is built for each suites/test_suite_*.data file.
# Application name is same as .data file's base name and can be
# constructed by stripping path 'suites/' and extension .data.
DATA_FILES = $(filter-out $(GENERATED_DATA_FILES), $(wildcard suites/test_suite_*.data))
CRYPTO_DATA_FILES = $(filter-out $(GENERATED_CRYPTO_DATA_FILES), $(wildcard ../tf-psa-crypto/tests/suites/test_suite_*.data))
# Make sure that generated data files are included even if they don't
# exist yet when the makefile is parsed.
DATA_FILES += $(GENERATED_DATA_FILES)
CRYPTO_DATA_FILES += $(GENERATED_CRYPTO_DATA_FILES)
APPS = $(basename $(subst suites/,,$(DATA_FILES)))
CRYPTO_APPS = $(basename $(subst suites/,,$(CRYPTO_DATA_FILES)))
# Construct executable name by adding OS specific suffix $(EXEXT).
BINARIES := $(addsuffix $(EXEXT),$(APPS))
CRYPTO_BINARIES := $(addsuffix $(EXEXT),$(CRYPTO_APPS))
.SILENT:
.PHONY: all check test clean
all: $(BINARIES) $(CRYPTO_BINARIES)
mbedtls_test: $(MBEDTLS_TEST_OBJS)
src/test_certs.h: ../framework/scripts/generate_test_cert_macros.py \
$($(PYTHON) ../framework/scripts/generate_test_cert_macros.py --list-dependencies)
echo " Gen $@"
$(PYTHON) ../framework/scripts/generate_test_cert_macros.py --output $@
src/test_keys.h: ../framework/scripts/generate_test_keys.py
echo " Gen $@"
$(PYTHON) ../framework/scripts/generate_test_keys.py --output $@
TEST_OBJS_DEPS = $(wildcard include/test/*.h include/test/*/*.h)
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
# Explicitly depend on this header because on a clean copy of the source tree,
# it doesn't exist yet and must be generated as part of the build, and
# therefore the wildcard enumeration above doesn't include it.
TEST_OBJS_DEPS += include/test/instrument_record_status.h
endif
TEST_OBJS_DEPS += src/test_certs.h src/test_keys.h
# Rule to compile common test C files in src folder
src/%.o : src/%.c $(TEST_OBJS_DEPS)
echo " CC $<"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
src/drivers/%.o : src/drivers/%.c
echo " CC $<"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
src/test_helpers/%.o : src/test_helpers/%.c
echo " CC $<"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) -o $@ -c $<
C_FILES := $(addsuffix .c,$(APPS)) $(addsuffix .c,$(CRYPTO_APPS))
c: $(C_FILES)
# Wildcard target for test code generation:
# A .c file is generated for each .data file in the suites/ directory. Each .c
# file depends on a .data and .function file from suites/ directory. Following
# nameing convention is followed:
#
# C file | Depends on
#-----------------------------------------------------------------------------
# foo.c | suites/foo.function suites/foo.data
# foo.bar.c | suites/foo.function suites/foo.bar.data
#
# Note above that .c and .data files have same base name.
# However, corresponding .function file's base name is the word before first
# dot in .c file's base name.
#
.SECONDEXPANSION:
# First handle the tf-psa-crypto case, which has different paths from
# the local case. In GNU Make >=3.82, the shortest match applies regardless
# of the order in the makefile. In GNU Make <=3.81, the first matching rule
# applies.
../tf-psa-crypto/tests/%.c: ../tf-psa-crypto/tests/suites/$$(firstword $$(subst ., ,$$*)).function ../tf-psa-crypto/tests/suites/%.data ../framework/scripts/generate_test_code.py ../tf-psa-crypto/tests/suites/helpers.function ../tf-psa-crypto/tests/suites/main_test.function ../tf-psa-crypto/tests/suites/host_test.function
echo " Gen $@"
cd ../tf-psa-crypto/tests && $(PYTHON) ../../framework/scripts/generate_test_code.py -f suites/$(firstword $(subst ., ,$*)).function \
-d suites/$*.data \
-t suites/main_test.function \
-p suites/host_test.function \
-s suites \
--helpers-file suites/helpers.function \
-o .
%.c: suites/$$(firstword $$(subst ., ,$$*)).function suites/%.data ../framework/scripts/generate_test_code.py ../tf-psa-crypto/tests/suites/helpers.function ../tf-psa-crypto/tests/suites/main_test.function ../tf-psa-crypto/tests/suites/host_test.function
echo " Gen $@"
$(PYTHON) ../framework/scripts/generate_test_code.py -f suites/$(firstword $(subst ., ,$*)).function \
-d suites/$*.data \
-t ../tf-psa-crypto/tests/suites/main_test.function \
-p ../tf-psa-crypto/tests/suites/host_test.function \
-s suites \
--helpers-file ../tf-psa-crypto/tests/suites/helpers.function \
-o .
$(BINARIES): %$(EXEXT): %.c $(MBEDLIBS) $(TEST_OBJS_DEPS) $(MBEDTLS_TEST_OBJS)
echo " CC $<"
$(CC) $(LOCAL_CFLAGS) $(CFLAGS) $< $(LOCAL_LDFLAGS) $(LDFLAGS) -o $@
LOCAL_CRYPTO_CFLAGS = $(patsubst -I./include, -I../../tests/include, $(patsubst -I../%,-I../../%, $(LOCAL_CFLAGS)))
LOCAL_CRYPTO_LDFLAGS = $(patsubst -L../library, -L../../library, \
$(patsubst -L../tests/%, -L../../tests/%, \
$(patsubst ./src/%,../../tests/src/%, $(LOCAL_LDFLAGS))))
$(CRYPTO_BINARIES): %$(EXEXT): %.c $(MBEDLIBS) $(TEST_OBJS_DEPS) $(MBEDTLS_TEST_OBJS)
echo " CC $<"
cd ../tf-psa-crypto/tests && $(CC) $(LOCAL_CRYPTO_CFLAGS) $(CFLAGS) $(subst $(EXEXT),,$(@F)).c $(LOCAL_CRYPTO_LDFLAGS) $(LDFLAGS) -o $(@F)
clean:
ifndef WINDOWS
$(MAKE) -C psa-client-server/psasim clean
rm -rf $(BINARIES) *.c *.datax
rm -rf $(CRYPTO_BINARIES) ../tf-psa-crypto/tests/*.c ../tf-psa-crypto/tests/*.datax
rm -f src/*.o src/drivers/*.o src/test_helpers/*.o src/libmbed*
rm -f include/test/instrument_record_status.h
rm -f include/alt-extra/*/*_alt.h
rm -rf libtestdriver1
rm -rf libpsaclient libpsaserver
rm -f ../library/libtestdriver1.a
else
if exist *.c del /Q /F *.c
if exist *.exe del /Q /F *.exe
if exist *.datax del /Q /F *.datax
if exist ../tf-psa-crypto/tests/*.c del /Q /F ../tf-psa-crypto/tests/*.c
if exist ../tf-psa-crypto/tests/*.exe del /Q /F ../tf-psa-crypto/tests/*.exe
if exist ../tf-psa-crypto/tests/*.datax del /Q /F ../tf-psa-crypto/tests/*.datax
if exist src/*.o del /Q /F src/*.o
if exist src/drivers/*.o del /Q /F src/drivers/*.o
if exist src/test_helpers/*.o del /Q /F src/test_helpers/*.o
if exist src/libmbed* del /Q /F src/libmbed*
if exist include/test/instrument_record_status.h del /Q /F include/test/instrument_record_status.h
endif
# Test suites caught by SKIP_TEST_SUITES are built but not executed.
check: $(BINARIES) $(CRYPTO_BINARIES)
perl scripts/run-test-suites.pl $(TEST_FLAGS) --skip=$(SKIP_TEST_SUITES)
test: check
# Generate variants of some headers for testing
include/alt-extra/%_alt.h: ../include/%.h
perl -p -e 's/^(# *(define|ifndef) +\w+_)H\b/$${1}ALT_H/' $< >$@
include/alt-extra/%_alt.h: ../tf-psa-crypto/include/%.h
perl -p -e 's/^(# *(define|ifndef) +\w+_)H\b/$${1}ALT_H/' $< >$@
include/alt-extra/%_alt.h: ../tf-psa-crypto/drivers/builtin/include/%.h
perl -p -e 's/^(# *(define|ifndef) +\w+_)H\b/$${1}ALT_H/' $< >$@
# Generate test library
# Perl code that is executed to transform each original line from a library
# source file into the corresponding line in the test driver copy of the
# library. Add a LIBTESTDRIVER1_/libtestdriver1_ to mbedtls_xxx and psa_xxx
# symbols.
define libtestdriver1_rewrite :=
s!^(\s*#\s*include\s*[\"<])mbedtls/build_info.h!$${1}libtestdriver1/include/mbedtls/build_info.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/mbedtls_config.h!$${1}libtestdriver1/include/mbedtls/mbedtls_config.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/config_adjust_legacy_crypto.h!$${1}libtestdriver1/include/mbedtls/config_adjust_legacy_crypto.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/config_adjust_x509.h!$${1}libtestdriver1/include/mbedtls/config_adjust_x509.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/config_adjust_ssl.h!$${1}libtestdriver1/include/mbedtls/config_adjust_ssl.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/check_config.h!$${1}libtestdriver1/include/mbedtls/check_config.h!; \
s!^(\s*#\s*include\s*[\"<])mbedtls/!$${1}libtestdriver1/tf-psa-crypto/drivers/builtin/include/mbedtls/!; \
s!^(\s*#\s*include\s*[\"<])psa/!$${1}libtestdriver1/tf-psa-crypto/include/psa/!; \
next if /^\s*#\s*include/; \
s/\b(?=MBEDTLS_|PSA_)/LIBTESTDRIVER1_/g; \
s/\b(?=mbedtls_|psa_)/libtestdriver1_/g;
endef
libtestdriver1.a:
rm -Rf ./libtestdriver1
mkdir ./libtestdriver1
mkdir ./libtestdriver1/tf-psa-crypto
mkdir ./libtestdriver1/tf-psa-crypto/drivers
mkdir ./libtestdriver1/tf-psa-crypto/drivers/everest
mkdir ./libtestdriver1/tf-psa-crypto/drivers/p256-m
touch ./libtestdriver1/tf-psa-crypto/drivers/everest/Makefile.inc
touch ./libtestdriver1/tf-psa-crypto/drivers/p256-m/Makefile.inc
cp -Rf ../framework ./libtestdriver1
cp -Rf ../library ./libtestdriver1
cp -Rf ../include ./libtestdriver1
cp -Rf ../tf-psa-crypto/core ./libtestdriver1/tf-psa-crypto
cp -Rf ../tf-psa-crypto/include ./libtestdriver1/tf-psa-crypto
cp -Rf ../tf-psa-crypto/drivers/builtin ./libtestdriver1/tf-psa-crypto/drivers
cp -Rf ../scripts ./libtestdriver1
# Set the test driver base (minimal) configuration.
cp ./include/test/drivers/config_test_driver.h ./libtestdriver1/include/mbedtls/mbedtls_config.h
# Set the PSA cryptography configuration for the test library.
# It is set from the copied include/psa/crypto_config.h of the Mbed TLS
# library the test library is intended to be linked with extended by
# ./include/test/drivers/crypto_config_test_driver_extension.h to
# mirror the PSA_ACCEL_* macros.
mv ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h.bak
head -n -1 ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h.bak > ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h
cat ./include/test/drivers/crypto_config_test_driver_extension.h >> ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h
echo "#endif /* PSA_CRYPTO_CONFIG_H */" >> ./libtestdriver1/tf-psa-crypto/include/psa/crypto_config.h
# Prefix MBEDTLS_* PSA_* symbols with LIBTESTDRIVER1_ as well as
# mbedtls_* psa_* symbols with libtestdriver1_ to avoid symbol clash
# when this test driver library is linked with the Mbed TLS library.
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/library/*.[ch]
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/include/*/*.h
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/tf-psa-crypto/core/*.[ch]
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/tf-psa-crypto/include/*/*.h
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/tf-psa-crypto/drivers/builtin/include/*/*.h
perl -pi -e '$(libtestdriver1_rewrite)' ./libtestdriver1/tf-psa-crypto/drivers/builtin/src/*.[ch]
$(MAKE) -C ./libtestdriver1/library CFLAGS="-I../../ $(CFLAGS)" LDFLAGS="$(LDFLAGS)" libmbedcrypto.a
cp ./libtestdriver1/library/libmbedcrypto.a ../library/libtestdriver1.a
ifdef RECORD_PSA_STATUS_COVERAGE_LOG
include/test/instrument_record_status.h: ../tf-psa-crypto/include/psa/crypto.h Makefile
echo " Gen $@"
sed <../tf-psa-crypto/include/psa/crypto.h >$@ -n 's/^psa_status_t \([A-Za-z0-9_]*\)(.*/#define \1(...) RECORD_STATUS("\1", \1(__VA_ARGS__))/p'
endif
-55
View File
@@ -1,55 +0,0 @@
#!/bin/bash -eu
# compat-in-docker.sh
#
# Purpose
# -------
# This runs compat.sh in a Docker container.
#
# WARNING: the Dockerfile used by this script is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
#
# Notes for users
# ---------------
# If OPENSSL, GNUTLS_CLI, or GNUTLS_SERV are specified the path must
# correspond to an executable inside the Docker container. The special
# values "next" (OpenSSL only) and "legacy" are also allowed as shorthand
# for the installations inside the container.
#
# See also:
# - scripts/docker_env.sh for general Docker prerequisites and other information.
# - compat.sh for notes about invocation of that script.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
source tests/scripts/docker_env.sh
case "${OPENSSL:-default}" in
"legacy") export OPENSSL="/usr/local/openssl-1.0.1j/bin/openssl";;
"next") export OPENSSL="/usr/local/openssl-1.1.1a/bin/openssl";;
*) ;;
esac
case "${GNUTLS_CLI:-default}" in
"legacy") export GNUTLS_CLI="/usr/local/gnutls-3.3.8/bin/gnutls-cli";;
"next") export GNUTLS_CLI="/usr/local/gnutls-3.7.2/bin/gnutls-cli";;
*) ;;
esac
case "${GNUTLS_SERV:-default}" in
"legacy") export GNUTLS_SERV="/usr/local/gnutls-3.3.8/bin/gnutls-serv";;
"next") export GNUTLS_SERV="/usr/local/gnutls-3.7.2/bin/gnutls-serv";;
*) ;;
esac
run_in_docker \
-e M_CLI \
-e M_SRV \
-e GNUTLS_CLI \
-e GNUTLS_SERV \
-e OPENSSL \
-e OSSL_NO_DTLS \
tests/compat.sh \
$@
-1240
View File
File diff suppressed because it is too large Load Diff
-31
View File
@@ -1,31 +0,0 @@
/* MBEDTLS_USER_CONFIG_FILE for testing.
* Only used for a few test configurations.
*
* Typical usage (note multiple levels of quoting):
* make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/* Enable TLS 1.3 and core 1.3 features */
#define MBEDTLS_SSL_PROTO_TLS1_3
#define MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
/* Disable TLS 1.2 and 1.2-specific features */
#undef MBEDTLS_SSL_ENCRYPT_THEN_MAC
#undef MBEDTLS_SSL_EXTENDED_MASTER_SECRET
#undef MBEDTLS_SSL_RENEGOTIATION
#undef MBEDTLS_SSL_PROTO_TLS1_2
#undef MBEDTLS_SSL_PROTO_DTLS
#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY
#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY
#undef MBEDTLS_SSL_DTLS_SRTP
#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
#undef MBEDTLS_SSL_DTLS_CONNECTION_ID
#undef MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT
/* Enable some invasive tests */
#define MBEDTLS_TEST_HOOKS
-29
View File
@@ -1,29 +0,0 @@
/* MBEDTLS_USER_CONFIG_FILE for testing.
* Only used for a few test configurations.
*
* Typical usage (note multiple levels of quoting):
* make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/user-config-for-test.h\"'"
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
/* The #MBEDTLS_PSA_INJECT_ENTROPY feature requires two extra platform
* functions, which must be configured as #MBEDTLS_PLATFORM_NV_SEED_READ_MACRO
* and #MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO. The job of these functions
* is to read and write from the entropy seed file, which is located
* in the PSA ITS file whose uid is #PSA_CRYPTO_ITS_RANDOM_SEED_UID.
* (These could have been provided as library functions, but for historical
* reasons, they weren't, and so each integrator has to provide a copy
* of these functions.)
*
* Provide implementations of these functions for testing. */
#include <stddef.h>
int mbedtls_test_inject_entropy_seed_read(unsigned char *buf, size_t len);
int mbedtls_test_inject_entropy_seed_write(unsigned char *buf, size_t len);
#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_test_inject_entropy_seed_read
#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_test_inject_entropy_seed_write
#endif /* MBEDTLS_PSA_INJECT_ENTROPY */
-22
View File
@@ -1,22 +0,0 @@
/* mbedtls_config.h modifier that forces calloc(0) to return NULL.
* Used for testing.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <stdlib.h>
#ifndef MBEDTLS_PLATFORM_STD_CALLOC
static inline void *custom_calloc(size_t nmemb, size_t size)
{
if (nmemb == 0 || size == 0) {
return NULL;
}
return calloc(nmemb, size);
}
#define MBEDTLS_PLATFORM_MEMORY
#define MBEDTLS_PLATFORM_STD_CALLOC custom_calloc
#endif
@@ -1,17 +0,0 @@
/* mbedtls_config.h modifier that defines mbedtls_platform_zeroize() to be
* memset(), so that the compile can check arguments for us.
* Used for testing.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <string.h>
/* Define _ALT so we don't get the built-in implementation. The test code will
* also need to define MBEDTLS_TEST_DEFINES_ZEROIZE so we don't get the
* declaration. */
#define MBEDTLS_PLATFORM_ZEROIZE_ALT
#define mbedtls_platform_zeroize(buf, len) memset(buf, 0, len)
-428
View File
@@ -1,428 +0,0 @@
#!/bin/sh
# context-info.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# This program is intended for testing the ssl_context_info program
#
set -eu
if ! cd "$(dirname "$0")"; then
exit 125
fi
# Variables
THIS_SCRIPT_NAME=$(basename "$0")
PROG_PATH="../programs/ssl/ssl_context_info"
OUT_FILE="ssl_context_info.log"
IN_DIR="../framework/data_files/base64"
USE_VALGRIND=0
T_COUNT=0
T_PASSED=0
T_FAILED=0
# Functions
print_usage() {
echo "Usage: $0 [options]"
printf " -h|--help\tPrint this help.\n"
printf " -m|--memcheck\tUse valgrind to check the memory.\n"
}
# Print test name <name>
print_name() {
printf "%s %.*s " "$1" $(( 71 - ${#1} )) \
"........................................................................"
}
# Print header to the test output file <test name> <file path> <test command>
print_header()
{
date="$(date)"
echo "******************************************************************" > $2
echo "* File created by: $THIS_SCRIPT_NAME" >> $2
echo "* Test name: $1" >> $2
echo "* Date: $date" >> $2
echo "* Command: $3" >> $2
echo "******************************************************************" >> $2
echo "" >> $2
}
# Print footer at the end of file <file path>
print_footer()
{
echo "" >> $1
echo "******************************************************************" >> $1
echo "* End command" >> $1
echo "******************************************************************" >> $1
echo "" >> $1
}
# Use the arguments of this script
get_options() {
while [ $# -gt 0 ]; do
case "$1" in
-h|--help)
print_usage
exit 0
;;
-m|--memcheck)
USE_VALGRIND=1
;;
*)
echo "Unknown argument: '$1'"
print_usage
exit 1
;;
esac
shift
done
}
# Current test failed
fail()
{
T_FAILED=$(( $T_FAILED + 1))
FAIL_OUT="Fail.$T_FAILED""_$OUT_FILE"
echo "FAIL"
echo " Error: $1"
cp -f "$OUT_FILE" "$FAIL_OUT"
echo "Error: $1" >> "$FAIL_OUT"
}
# Current test passed
pass()
{
T_PASSED=$(( $T_PASSED + 1))
echo "PASS"
}
# Usage: run_test <name> <input file with b64 code> [ -arg <extra arguments for tested program> ] [option [...]]
# Options: -m <pattern that MUST be present in the output of tested program>
# -n <pattern that must NOT be present in the output of tested program>
# -u <pattern that must be UNIQUE in the output of tested program>
run_test()
{
TEST_NAME="$1"
RUN_CMD="$PROG_PATH -f $IN_DIR/$2"
if [ "-arg" = "$3" ]; then
RUN_CMD="$RUN_CMD $4"
shift 4
else
shift 2
fi
# prepend valgrind to our commands if active
if [ "$USE_VALGRIND" -gt 0 ]; then
RUN_CMD="valgrind --leak-check=full $RUN_CMD"
fi
T_COUNT=$(( $T_COUNT + 1))
print_name "$TEST_NAME"
# run tested program
print_header "$TEST_NAME" "$OUT_FILE" "$RUN_CMD"
eval "$RUN_CMD" >> "$OUT_FILE" 2>&1
print_footer "$OUT_FILE"
# check valgrind's results
if [ "$USE_VALGRIND" -gt 0 ]; then
if ! ( grep -F 'All heap blocks were freed -- no leaks are possible' "$OUT_FILE" &&
grep -F 'ERROR SUMMARY: 0 errors from 0 contexts' "$OUT_FILE" ) > /dev/null
then
fail "Memory error detected"
return
fi
fi
# check other assertions
# lines beginning with == are added by valgrind, ignore them, because we already checked them before
# lines with 'Serious error when reading debug info', are valgrind issues as well
# lines beginning with * are added by this script, ignore too
while [ $# -gt 0 ]
do
case $1 in
"-m")
if grep -v '^==' "$OUT_FILE" | grep -v 'Serious error when reading debug info' | grep -v "^*" | grep "$2" >/dev/null; then :; else
fail "pattern '$2' MUST be present in the output"
return
fi
;;
"-n")
if grep -v '^==' "$OUT_FILE" | grep -v 'Serious error when reading debug info' | grep -v "^*" | grep "$2" >/dev/null; then
fail "pattern '$2' MUST NOT be present in the output"
return
fi
;;
"-u")
if [ $(grep -v '^==' "$OUT_FILE"| grep -v 'Serious error when reading debug info' | grep -v "^*" | grep "$2" | wc -l) -ne 1 ]; then
fail "lines following pattern '$2' must be once in the output"
return
fi
;;
*)
echo "Unknown test: $1" >&2
exit 1
esac
shift 2
done
rm -f "$OUT_FILE"
pass
}
get_options "$@"
# Tests
run_test "Default configuration, server" \
"srv_def.txt" \
-n "ERROR" \
-u "major.* 2$" \
-u "minor.* 21$" \
-u "path.* 0$" \
-u "MBEDTLS_HAVE_TIME$" \
-u "MBEDTLS_X509_CRT_PARSE_C$" \
-u "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH$" \
-u "MBEDTLS_SSL_ENCRYPT_THEN_MAC$" \
-u "MBEDTLS_SSL_SESSION_TICKETS$" \
-u "MBEDTLS_SSL_SESSION_TICKETS and client$" \
-u "MBEDTLS_SSL_DTLS_ANTI_REPLAY$" \
-u "MBEDTLS_SSL_ALPN$" \
-u "ciphersuite.* TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256$" \
-u "cipher flags.* 0x00$" \
-u "Message-Digest.* SHA256$" \
-u "compression.* disabled$" \
-u "DTLS datagram packing.* enabled$" \
-n "Certificate" \
-n "bytes left to analyze from context"
run_test "Default configuration, client" \
"cli_def.txt" \
-n "ERROR" \
-u "major.* 2$" \
-u "minor.* 21$" \
-u "path.* 0$" \
-u "MBEDTLS_HAVE_TIME$" \
-u "MBEDTLS_X509_CRT_PARSE_C$" \
-u "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH$" \
-u "MBEDTLS_SSL_ENCRYPT_THEN_MAC$" \
-u "MBEDTLS_SSL_SESSION_TICKETS$" \
-u "MBEDTLS_SSL_SESSION_TICKETS and client$" \
-u "MBEDTLS_SSL_DTLS_ANTI_REPLAY$" \
-u "MBEDTLS_SSL_ALPN$" \
-u "ciphersuite.* TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256$" \
-u "cipher flags.* 0x00$" \
-u "Message-Digest.* SHA256$" \
-u "compression.* disabled$" \
-u "DTLS datagram packing.* enabled$" \
-u "cert. version .* 3$" \
-u "serial number.* 02$" \
-u "issuer name.* C=NL, O=PolarSSL, CN=PolarSSL Test CA$" \
-u "subject name.* C=NL, O=PolarSSL, CN=localhost$" \
-u "issued on.* 2019-02-10 14:44:06$" \
-u "expires on.* 2029-02-10 14:44:06$" \
-u "signed using.* RSA with SHA-256$" \
-u "RSA key size.* 2048 bits$" \
-u "basic constraints.* CA=false$" \
-n "bytes left to analyze from context"
run_test "Ciphersuite TLS-RSA-WITH-AES-256-CCM-8, server" \
"srv_ciphersuite.txt" \
-n "ERROR" \
-u "ciphersuite.* TLS-RSA-WITH-AES-256-CCM-8$" \
run_test "Ciphersuite TLS-RSA-WITH-AES-256-CCM-8, client" \
"cli_ciphersuite.txt" \
-n "ERROR" \
-u "ciphersuite.* TLS-RSA-WITH-AES-256-CCM-8$" \
run_test "No packing, server" \
"srv_no_packing.txt" \
-n "ERROR" \
-u "DTLS datagram packing.* disabled"
run_test "No packing, client" \
"cli_no_packing.txt" \
-n "ERROR" \
-u "DTLS datagram packing.* disabled"
run_test "DTLS CID, server" \
"srv_cid.txt" \
-n "ERROR" \
-u "in CID.* DE AD" \
-u "out CID.* BE EF"
run_test "DTLS CID, client" \
"cli_cid.txt" \
-n "ERROR" \
-u "in CID.* BE EF" \
-u "out CID.* DE AD"
run_test "No MBEDTLS_SSL_MAX_FRAGMENT_LENGTH, server" \
"srv_no_mfl.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH"
run_test "No MBEDTLS_SSL_MAX_FRAGMENT_LENGTH, client" \
"cli_no_mfl.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH"
run_test "No MBEDTLS_SSL_ALPN, server" \
"srv_no_alpn.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_ALPN"
run_test "No MBEDTLS_SSL_ALPN, client" \
"cli_no_alpn.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_ALPN"
run_test "No MBEDTLS_SSL_KEEP_PEER_CERTIFICATE, server" \
"srv_no_keep_cert.txt" \
-arg "--keep-peer-cert=0" \
-u "ciphersuite.* TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256$" \
-u "cipher flags.* 0x00" \
-u "compression.* disabled" \
-u "DTLS datagram packing.* enabled" \
-n "ERROR"
run_test "No MBEDTLS_SSL_KEEP_PEER_CERTIFICATE, client" \
"cli_no_keep_cert.txt" \
-arg "--keep-peer-cert=0" \
-u "ciphersuite.* TLS-ECDHE-RSA-WITH-CHACHA20-POLY1305-SHA256$" \
-u "cipher flags.* 0x00" \
-u "compression.* disabled" \
-u "DTLS datagram packing.* enabled" \
-n "ERROR"
run_test "No MBEDTLS_SSL_KEEP_PEER_CERTIFICATE, negative, server" \
"srv_no_keep_cert.txt" \
-m "Deserializing" \
-m "ERROR"
run_test "No MBEDTLS_SSL_KEEP_PEER_CERTIFICATE, negative, client" \
"cli_no_keep_cert.txt" \
-m "Deserializing" \
-m "ERROR"
run_test "Minimal configuration, server" \
"srv_min_cfg.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH$" \
-n "MBEDTLS_SSL_ENCRYPT_THEN_MAC$" \
-n "MBEDTLS_SSL_SESSION_TICKETS$" \
-n "MBEDTLS_SSL_SESSION_TICKETS and client$" \
-n "MBEDTLS_SSL_DTLS_ANTI_REPLAY$" \
-n "MBEDTLS_SSL_ALPN$" \
run_test "Minimal configuration, client" \
"cli_min_cfg.txt" \
-n "ERROR" \
-n "MBEDTLS_SSL_MAX_FRAGMENT_LENGTH$" \
-n "MBEDTLS_SSL_ENCRYPT_THEN_MAC$" \
-n "MBEDTLS_SSL_SESSION_TICKETS$" \
-n "MBEDTLS_SSL_SESSION_TICKETS and client$" \
-n "MBEDTLS_SSL_DTLS_ANTI_REPLAY$" \
-n "MBEDTLS_SSL_ALPN$" \
run_test "MTU=10000" \
"mtu_10000.txt" \
-n "ERROR" \
-u "MTU.* 10000$"
run_test "MFL=1024" \
"mfl_1024.txt" \
-n "ERROR" \
-u "MFL.* 1024$"
run_test "Older version (v2.19.1)" \
"v2.19.1.txt" \
-n "ERROR" \
-u "major.* 2$" \
-u "minor.* 19$" \
-u "path.* 1$" \
-u "ciphersuite.* TLS-ECDHE-ECDSA-WITH-AES-128-CCM-8$" \
-u "Message-Digest.* SHA256$" \
-u "compression.* disabled$" \
-u "serial number.* 01:70:AF:40:B4:E6$" \
-u "issuer name.* CN=ca$" \
-u "subject name.* L=160001, OU=acc1, CN=device01$" \
-u "issued on.* 2020-03-06 09:50:18$" \
-u "expires on.* 2056-02-26 09:50:18$" \
-u "signed using.* ECDSA with SHA256$" \
-u "lifetime.* 0 sec.$" \
-u "MFL.* none$" \
-u "negotiate truncated HMAC.* disabled$" \
-u "Encrypt-then-MAC.* enabled$" \
-u "DTLS datagram packing.* enabled$" \
-u "verify result.* 0x00000000$" \
-n "bytes left to analyze from context"
run_test "Wrong base64 format" \
"def_bad_b64.txt" \
-m "ERROR" \
-u "The length of the base64 code found should be a multiple of 4" \
-n "bytes left to analyze from context"
run_test "Too much data at the beginning of base64 code" \
"def_b64_too_big_1.txt" \
-m "ERROR" \
-n "The length of the base64 code found should be a multiple of 4" \
run_test "Too much data in the middle of base64 code" \
"def_b64_too_big_2.txt" \
-m "ERROR" \
-n "The length of the base64 code found should be a multiple of 4" \
run_test "Too much data at the end of base64 code" \
"def_b64_too_big_3.txt" \
-m "ERROR" \
-n "The length of the base64 code found should be a multiple of 4" \
-u "bytes left to analyze from context"
run_test "Empty file as input" \
"empty.txt" \
-u "Finished. No valid base64 code found"
run_test "Not empty file without base64 code" \
"../../../tests/context-info.sh" \
-n "Deserializing"
run_test "Binary file instead of text file" \
"../../../programs/ssl/ssl_context_info" \
-m "ERROR" \
-u "Too many bad symbols detected. File check aborted" \
-n "Deserializing"
run_test "Decoder continues past 0xff character" \
"def_b64_ff.bin" \
-n "No valid base64" \
-u "ciphersuite.* TLS-"
# End of tests
echo
if [ $T_FAILED -eq 0 ]; then
echo "PASSED ( $T_COUNT tests )"
else
echo "FAILED ( $T_FAILED / $T_COUNT tests )"
fi
exit $T_FAILED
-158
View File
@@ -1,158 +0,0 @@
# Dockerfile
#
# Purpose
# -------
# Defines a Docker container suitable to build and run all tests (all.sh),
# except for those that use a proprietary toolchain.
#
# WARNING: this Dockerfile is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
ARG MAKEFLAGS_PARALLEL=""
ARG MY_REGISTRY=
FROM ${MY_REGISTRY}ubuntu:bionic
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update \
&& apt-get -y install software-properties-common \
&& rm -rf /var/lib/apt/lists
RUN add-apt-repository -y ppa:team-gcc-arm-embedded/ppa
RUN apt-get update \
&& apt-get -y install \
# mbedtls build/test dependencies
build-essential \
clang \
cmake \
doxygen \
gcc-arm-none-eabi \
gcc-mingw-w64-i686 \
gcc-multilib \
g++-multilib \
gdb \
git \
graphviz \
lsof \
python \
python3-pip \
python3 \
pylint3 \
valgrind \
wget \
# libnettle build dependencies
libgmp-dev \
m4 \
pkg-config \
&& rm -rf /var/lib/apt/lists/*
# Jinja2 is required for driver dispatch code generation.
RUN python3 -m pip install \
jinja2==2.10.1 types-jinja2
# Build a static, legacy openssl from sources with sslv3 enabled
# Based on https://gist.github.com/bmaupin/8caca3a1e8c3c5686141 (build-openssl.sh)
# Note: openssl-1.0.2 and earlier has known build issues with parallel make.
RUN cd /tmp \
&& wget https://www.openssl.org/source/old/1.0.1/openssl-1.0.1j.tar.gz -qO- | tar xz \
&& cd openssl-1.0.1j \
&& ./config --openssldir=/usr/local/openssl-1.0.1j no-shared \
&& (make ${MAKEFLAGS_PARALLEL} || make -j 1) \
&& make install_sw \
&& rm -rf /tmp/openssl*
ENV OPENSSL_LEGACY=/usr/local/openssl-1.0.1j/bin/openssl
# Build OPENSSL as 1.0.2g
RUN cd /tmp \
&& wget https://www.openssl.org/source/old/1.0.2/openssl-1.0.2g.tar.gz -qO- | tar xz \
&& cd openssl-1.0.2g \
&& ./config --openssldir=/usr/local/openssl-1.0.2g no-shared \
&& (make ${MAKEFLAGS_PARALLEL} || make -j 1) \
&& make install_sw \
&& rm -rf /tmp/openssl*
ENV OPENSSL=/usr/local/openssl-1.0.2g/bin/openssl
# Build a new openssl binary for ARIA/CHACHA20 support
# Based on https://gist.github.com/bmaupin/8caca3a1e8c3c5686141 (build-openssl.sh)
RUN cd /tmp \
&& wget https://www.openssl.org/source/openssl-1.1.1a.tar.gz -qO- | tar xz \
&& cd openssl-1.1.1a \
&& ./config --prefix=/usr/local/openssl-1.1.1a -Wl,--enable-new-dtags,-rpath,'${LIBRPATH}' no-shared \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install_sw \
&& rm -rf /tmp/openssl*
ENV OPENSSL_NEXT=/usr/local/openssl-1.1.1a/bin/openssl
# Build libnettle 2.7.1 (needed by legacy gnutls)
RUN cd /tmp \
&& wget https://ftp.gnu.org/gnu/nettle/nettle-2.7.1.tar.gz -qO- | tar xz \
&& cd nettle-2.7.1 \
&& ./configure --disable-documentation \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& /sbin/ldconfig \
&& rm -rf /tmp/nettle*
# Build legacy gnutls (3.3.8)
RUN cd /tmp \
&& wget https://www.gnupg.org/ftp/gcrypt/gnutls/v3.3/gnutls-3.3.8.tar.xz -qO- | tar xJ \
&& cd gnutls-3.3.8 \
&& ./configure --prefix=/usr/local/gnutls-3.3.8 --exec_prefix=/usr/local/gnutls-3.3.8 --disable-shared --disable-guile --disable-doc \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& rm -rf /tmp/gnutls*
ENV GNUTLS_LEGACY_CLI=/usr/local/gnutls-3.3.8/bin/gnutls-cli
ENV GNUTLS_LEGACY_SERV=/usr/local/gnutls-3.3.8/bin/gnutls-serv
# Build libnettle 3.1 (needed by gnutls)
RUN cd /tmp \
&& wget https://ftp.gnu.org/gnu/nettle/nettle-3.1.tar.gz -qO- | tar xz \
&& cd nettle-3.1 \
&& ./configure --disable-documentation \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& /sbin/ldconfig \
&& rm -rf /tmp/nettle*
# Build gnutls (3.4.10)
RUN cd /tmp \
&& wget https://www.gnupg.org/ftp/gcrypt/gnutls/v3.4/gnutls-3.4.10.tar.xz -qO- | tar xJ \
&& cd gnutls-3.4.10 \
&& ./configure --prefix=/usr/local/gnutls-3.4.10 --exec_prefix=/usr/local/gnutls-3.4.10 \
--with-included-libtasn1 --without-p11-kit \
--disable-shared --disable-guile --disable-doc \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& rm -rf /tmp/gnutls*
ENV GNUTLS_CLI=/usr/local/gnutls-3.4.10/bin/gnutls-cli
ENV GNUTLS_SERV=/usr/local/gnutls-3.4.10/bin/gnutls-serv
# Build libnettle 3.7.3 (needed by gnutls next)
RUN cd /tmp \
&& wget https://ftp.gnu.org/gnu/nettle/nettle-3.7.3.tar.gz -qO- | tar xz \
&& cd nettle-3.7.3 \
&& ./configure --disable-documentation \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& /sbin/ldconfig \
&& rm -rf /tmp/nettle*
# Build gnutls next (3.7.2)
RUN cd /tmp \
&& wget https://www.gnupg.org/ftp/gcrypt/gnutls/v3.7/gnutls-3.7.2.tar.xz -qO- | tar xJ \
&& cd gnutls-3.7.2 \
&& ./configure --prefix=/usr/local/gnutls-3.7.2 --exec_prefix=/usr/local/gnutls-3.7.2 \
--with-included-libtasn1 --with-included-unistring --without-p11-kit \
--disable-shared --disable-guile --disable-doc \
&& make ${MAKEFLAGS_PARALLEL} \
&& make install \
&& rm -rf /tmp/gnutls*
ENV GNUTLS_NEXT_CLI=/usr/local/gnutls-3.7.2/bin/gnutls-cli
ENV GNUTLS_NEXT_SERV=/usr/local/gnutls-3.7.2/bin/gnutls-serv
-16
View File
@@ -1,16 +0,0 @@
README for git hooks script
===========================
git has a way to run scripts, which are invoked by specific git commands.
The git hooks are located in `<Mbed TLS root>/.git/hooks`, and as such are not under version control
for more information, see the [git documentation](https://git-scm.com/docs/githooks).
The Mbed TLS git hooks are located in `<Mbed TLS root>/tests/git-scripts` directory, and one must create a soft link from `<Mbed TLS root>/.git/hooks` to `<Mbed TLS root>/tests/git-scripts`, in order to make the hook scripts successfully work.
Example:
Execute the following command to create a link on Linux from the Mbed TLS `.git/hooks` directory:
`ln -s ../../tests/git-scripts/pre-push.sh pre-push`
**Note: Currently the Mbed TLS git hooks work only on a GNU platform. If using a non-GNU platform, don't enable these hooks!**
These scripts can also be used independently.
-34
View File
@@ -1,34 +0,0 @@
#!/bin/sh
# pre-push.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# Purpose
#
# Called by "git push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
# This script can also be used independently, not using git.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
REMOTE="$1"
URL="$2"
echo "REMOTE is $REMOTE"
echo "URL is $URL"
set -eu
tests/scripts/all.sh -q -k 'check_*'
-16
View File
@@ -1,16 +0,0 @@
/* platform_alt.h with dummy types for MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef PLATFORM_ALT_H
#define PLATFORM_ALT_H
typedef struct mbedtls_platform_context {
int dummy;
}
mbedtls_platform_context;
#endif /* platform_alt.h */
-14
View File
@@ -1,14 +0,0 @@
/* threading_alt.h with dummy types for MBEDTLS_THREADING_ALT */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef THREADING_ALT_H
#define THREADING_ALT_H
typedef struct mbedtls_threading_mutex_t {
int dummy;
} mbedtls_threading_mutex_t;
#endif /* threading_alt.h */
-19
View File
@@ -1,19 +0,0 @@
/* timing_alt.h with dummy types for MBEDTLS_TIMING_ALT */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef TIMING_ALT_H
#define TIMING_ALT_H
struct mbedtls_timing_hr_time {
int dummy;
};
typedef struct mbedtls_timing_delay_context {
int dummy;
} mbedtls_timing_delay_context;
#endif /* timing_alt.h */
-234
View File
@@ -1,234 +0,0 @@
/**
* \file certs.h
*
* \brief Sample certificates and DHM parameters for testing
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef MBEDTLS_CERTS_H
#define MBEDTLS_CERTS_H
#include "mbedtls/build_info.h"
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* List of all PEM-encoded CA certificates, terminated by NULL;
* PEM encoded if MBEDTLS_PEM_PARSE_C is enabled, DER encoded
* otherwise. */
extern const char *mbedtls_test_cas[];
extern const size_t mbedtls_test_cas_len[];
/* List of all DER-encoded CA certificates, terminated by NULL */
extern const unsigned char *mbedtls_test_cas_der[];
extern const size_t mbedtls_test_cas_der_len[];
#if defined(MBEDTLS_PEM_PARSE_C)
/* Concatenation of all CA certificates in PEM format if available */
extern const char mbedtls_test_cas_pem[];
extern const size_t mbedtls_test_cas_pem_len;
#endif /* MBEDTLS_PEM_PARSE_C */
/*
* CA test certificates
*/
extern const char mbedtls_test_ca_crt_ec_pem[];
extern const char mbedtls_test_ca_key_ec_pem[];
extern const char mbedtls_test_ca_pwd_ec_pem[];
extern const char mbedtls_test_ca_key_rsa_pem[];
extern const char mbedtls_test_ca_pwd_rsa_pem[];
extern const char mbedtls_test_ca_crt_rsa_sha1_pem[];
extern const char mbedtls_test_ca_crt_rsa_sha256_pem[];
extern const unsigned char mbedtls_test_ca_crt_ec_der[];
extern const unsigned char mbedtls_test_ca_key_ec_der[];
extern const unsigned char mbedtls_test_ca_key_rsa_der[];
extern const unsigned char mbedtls_test_ca_crt_rsa_sha1_der[];
extern const unsigned char mbedtls_test_ca_crt_rsa_sha256_der[];
extern const size_t mbedtls_test_ca_crt_ec_pem_len;
extern const size_t mbedtls_test_ca_key_ec_pem_len;
extern const size_t mbedtls_test_ca_pwd_ec_pem_len;
extern const size_t mbedtls_test_ca_key_rsa_pem_len;
extern const size_t mbedtls_test_ca_pwd_rsa_pem_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha1_pem_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha256_pem_len;
extern const size_t mbedtls_test_ca_crt_ec_der_len;
extern const size_t mbedtls_test_ca_key_ec_der_len;
extern const size_t mbedtls_test_ca_pwd_ec_der_len;
extern const size_t mbedtls_test_ca_key_rsa_der_len;
extern const size_t mbedtls_test_ca_pwd_rsa_der_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha1_der_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha256_der_len;
/* Config-dependent dispatch between PEM and DER encoding
* (PEM if enabled, otherwise DER) */
extern const char mbedtls_test_ca_crt_ec[];
extern const char mbedtls_test_ca_key_ec[];
extern const char mbedtls_test_ca_pwd_ec[];
extern const char mbedtls_test_ca_key_rsa[];
extern const char mbedtls_test_ca_pwd_rsa[];
extern const char mbedtls_test_ca_crt_rsa_sha1[];
extern const char mbedtls_test_ca_crt_rsa_sha256[];
extern const size_t mbedtls_test_ca_crt_ec_len;
extern const size_t mbedtls_test_ca_key_ec_len;
extern const size_t mbedtls_test_ca_pwd_ec_len;
extern const size_t mbedtls_test_ca_key_rsa_len;
extern const size_t mbedtls_test_ca_pwd_rsa_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha1_len;
extern const size_t mbedtls_test_ca_crt_rsa_sha256_len;
/* Config-dependent dispatch between SHA-1 and SHA-256
* (SHA-256 if enabled, otherwise SHA-1) */
extern const char mbedtls_test_ca_crt_rsa[];
extern const size_t mbedtls_test_ca_crt_rsa_len;
/* Config-dependent dispatch between EC and RSA
* (RSA if enabled, otherwise EC) */
extern const char *mbedtls_test_ca_crt;
extern const char *mbedtls_test_ca_key;
extern const char *mbedtls_test_ca_pwd;
extern const size_t mbedtls_test_ca_crt_len;
extern const size_t mbedtls_test_ca_key_len;
extern const size_t mbedtls_test_ca_pwd_len;
/*
* Server test certificates
*/
extern const char mbedtls_test_srv_crt_ec_pem[];
extern const char mbedtls_test_srv_key_ec_pem[];
extern const char mbedtls_test_srv_pwd_ec_pem[];
extern const char mbedtls_test_srv_key_rsa_pem[];
extern const char mbedtls_test_srv_pwd_rsa_pem[];
extern const char mbedtls_test_srv_crt_rsa_sha1_pem[];
extern const char mbedtls_test_srv_crt_rsa_sha256_pem[];
extern const unsigned char mbedtls_test_srv_crt_ec_der[];
extern const unsigned char mbedtls_test_srv_key_ec_der[];
extern const unsigned char mbedtls_test_srv_key_rsa_der[];
extern const unsigned char mbedtls_test_srv_crt_rsa_sha1_der[];
extern const unsigned char mbedtls_test_srv_crt_rsa_sha256_der[];
extern const size_t mbedtls_test_srv_crt_ec_pem_len;
extern const size_t mbedtls_test_srv_key_ec_pem_len;
extern const size_t mbedtls_test_srv_pwd_ec_pem_len;
extern const size_t mbedtls_test_srv_key_rsa_pem_len;
extern const size_t mbedtls_test_srv_pwd_rsa_pem_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha1_pem_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha256_pem_len;
extern const size_t mbedtls_test_srv_crt_ec_der_len;
extern const size_t mbedtls_test_srv_key_ec_der_len;
extern const size_t mbedtls_test_srv_pwd_ec_der_len;
extern const size_t mbedtls_test_srv_key_rsa_der_len;
extern const size_t mbedtls_test_srv_pwd_rsa_der_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha1_der_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha256_der_len;
/* Config-dependent dispatch between PEM and DER encoding
* (PEM if enabled, otherwise DER) */
extern const char mbedtls_test_srv_crt_ec[];
extern const char mbedtls_test_srv_key_ec[];
extern const char mbedtls_test_srv_pwd_ec[];
extern const char mbedtls_test_srv_key_rsa[];
extern const char mbedtls_test_srv_pwd_rsa[];
extern const char mbedtls_test_srv_crt_rsa_sha1[];
extern const char mbedtls_test_srv_crt_rsa_sha256[];
extern const size_t mbedtls_test_srv_crt_ec_len;
extern const size_t mbedtls_test_srv_key_ec_len;
extern const size_t mbedtls_test_srv_pwd_ec_len;
extern const size_t mbedtls_test_srv_key_rsa_len;
extern const size_t mbedtls_test_srv_pwd_rsa_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha1_len;
extern const size_t mbedtls_test_srv_crt_rsa_sha256_len;
/* Config-dependent dispatch between SHA-1 and SHA-256
* (SHA-256 if enabled, otherwise SHA-1) */
extern const char mbedtls_test_srv_crt_rsa[];
extern const size_t mbedtls_test_srv_crt_rsa_len;
/* Config-dependent dispatch between EC and RSA
* (RSA if enabled, otherwise EC) */
extern const char *mbedtls_test_srv_crt;
extern const char *mbedtls_test_srv_key;
extern const char *mbedtls_test_srv_pwd;
extern const size_t mbedtls_test_srv_crt_len;
extern const size_t mbedtls_test_srv_key_len;
extern const size_t mbedtls_test_srv_pwd_len;
/*
* Client test certificates
*/
extern const char mbedtls_test_cli_crt_ec_pem[];
extern const char mbedtls_test_cli_key_ec_pem[];
extern const char mbedtls_test_cli_pwd_ec_pem[];
extern const char mbedtls_test_cli_key_rsa_pem[];
extern const char mbedtls_test_cli_pwd_rsa_pem[];
extern const char mbedtls_test_cli_crt_rsa_pem[];
extern const unsigned char mbedtls_test_cli_crt_ec_der[];
extern const unsigned char mbedtls_test_cli_key_ec_der[];
extern const unsigned char mbedtls_test_cli_key_rsa_der[];
extern const unsigned char mbedtls_test_cli_crt_rsa_der[];
extern const size_t mbedtls_test_cli_crt_ec_pem_len;
extern const size_t mbedtls_test_cli_key_ec_pem_len;
extern const size_t mbedtls_test_cli_pwd_ec_pem_len;
extern const size_t mbedtls_test_cli_key_rsa_pem_len;
extern const size_t mbedtls_test_cli_pwd_rsa_pem_len;
extern const size_t mbedtls_test_cli_crt_rsa_pem_len;
extern const size_t mbedtls_test_cli_crt_ec_der_len;
extern const size_t mbedtls_test_cli_key_ec_der_len;
extern const size_t mbedtls_test_cli_key_rsa_der_len;
extern const size_t mbedtls_test_cli_crt_rsa_der_len;
/* Config-dependent dispatch between PEM and DER encoding
* (PEM if enabled, otherwise DER) */
extern const char mbedtls_test_cli_crt_ec[];
extern const char mbedtls_test_cli_key_ec[];
extern const char mbedtls_test_cli_pwd_ec[];
extern const char mbedtls_test_cli_key_rsa[];
extern const char mbedtls_test_cli_pwd_rsa[];
extern const char mbedtls_test_cli_crt_rsa[];
extern const size_t mbedtls_test_cli_crt_ec_len;
extern const size_t mbedtls_test_cli_key_ec_len;
extern const size_t mbedtls_test_cli_pwd_ec_len;
extern const size_t mbedtls_test_cli_key_rsa_len;
extern const size_t mbedtls_test_cli_pwd_rsa_len;
extern const size_t mbedtls_test_cli_crt_rsa_len;
/* Config-dependent dispatch between EC and RSA
* (RSA if enabled, otherwise EC) */
extern const char *mbedtls_test_cli_crt;
extern const char *mbedtls_test_cli_key;
extern const char *mbedtls_test_cli_pwd;
extern const size_t mbedtls_test_cli_crt_len;
extern const size_t mbedtls_test_cli_key_len;
extern const size_t mbedtls_test_cli_pwd_len;
#ifdef __cplusplus
}
#endif
#endif /* certs.h */
-820
View File
@@ -1,820 +0,0 @@
/* Automatically generated by generate_psa_wrappers.py, do not edit! */
/* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef TEST_PSA_TEST_WRAPPERS_H
#define TEST_PSA_TEST_WRAPPERS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <mbedtls/build_info.h>
#if defined(MBEDTLS_PSA_CRYPTO_C) && defined(MBEDTLS_TEST_HOOKS) && \
!defined(RECORD_PSA_STATUS_COVERAGE_LOG)
#include <psa/crypto.h>
#include <test/memory.h>
#include <test/psa_crypto_helpers.h>
#include <test/psa_test_wrappers.h>
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
psa_status_t mbedtls_test_wrap_mbedtls_psa_inject_entropy(
const uint8_t *arg0_seed,
size_t arg1_seed_size);
#define mbedtls_psa_inject_entropy(arg0_seed, arg1_seed_size) \
mbedtls_test_wrap_mbedtls_psa_inject_entropy(arg0_seed, arg1_seed_size)
#endif /* defined(MBEDTLS_PSA_INJECT_ENTROPY) */
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
psa_status_t mbedtls_test_wrap_mbedtls_psa_platform_get_builtin_key(
mbedtls_svc_key_id_t arg0_key_id,
psa_key_lifetime_t *arg1_lifetime,
psa_drv_slot_number_t *arg2_slot_number);
#define mbedtls_psa_platform_get_builtin_key(arg0_key_id, arg1_lifetime, arg2_slot_number) \
mbedtls_test_wrap_mbedtls_psa_platform_get_builtin_key(arg0_key_id, arg1_lifetime, arg2_slot_number)
#endif /* defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS) */
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_status_t mbedtls_test_wrap_mbedtls_psa_register_se_key(
const psa_key_attributes_t *arg0_attributes);
#define mbedtls_psa_register_se_key(arg0_attributes) \
mbedtls_test_wrap_mbedtls_psa_register_se_key(arg0_attributes)
#endif /* defined(MBEDTLS_PSA_CRYPTO_SE_C) */
psa_status_t mbedtls_test_wrap_psa_aead_abort(
psa_aead_operation_t *arg0_operation);
#define psa_aead_abort(arg0_operation) \
mbedtls_test_wrap_psa_aead_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_aead_decrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_nonce,
size_t arg3_nonce_length,
const uint8_t *arg4_additional_data,
size_t arg5_additional_data_length,
const uint8_t *arg6_ciphertext,
size_t arg7_ciphertext_length,
uint8_t *arg8_plaintext,
size_t arg9_plaintext_size,
size_t *arg10_plaintext_length);
#define psa_aead_decrypt(arg0_key, arg1_alg, arg2_nonce, arg3_nonce_length, arg4_additional_data, arg5_additional_data_length, arg6_ciphertext, arg7_ciphertext_length, arg8_plaintext, arg9_plaintext_size, arg10_plaintext_length) \
mbedtls_test_wrap_psa_aead_decrypt(arg0_key, arg1_alg, arg2_nonce, arg3_nonce_length, arg4_additional_data, arg5_additional_data_length, arg6_ciphertext, arg7_ciphertext_length, arg8_plaintext, arg9_plaintext_size, arg10_plaintext_length)
psa_status_t mbedtls_test_wrap_psa_aead_decrypt_setup(
psa_aead_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_aead_decrypt_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_aead_decrypt_setup(arg0_operation, arg1_key, arg2_alg)
psa_status_t mbedtls_test_wrap_psa_aead_encrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_nonce,
size_t arg3_nonce_length,
const uint8_t *arg4_additional_data,
size_t arg5_additional_data_length,
const uint8_t *arg6_plaintext,
size_t arg7_plaintext_length,
uint8_t *arg8_ciphertext,
size_t arg9_ciphertext_size,
size_t *arg10_ciphertext_length);
#define psa_aead_encrypt(arg0_key, arg1_alg, arg2_nonce, arg3_nonce_length, arg4_additional_data, arg5_additional_data_length, arg6_plaintext, arg7_plaintext_length, arg8_ciphertext, arg9_ciphertext_size, arg10_ciphertext_length) \
mbedtls_test_wrap_psa_aead_encrypt(arg0_key, arg1_alg, arg2_nonce, arg3_nonce_length, arg4_additional_data, arg5_additional_data_length, arg6_plaintext, arg7_plaintext_length, arg8_ciphertext, arg9_ciphertext_size, arg10_ciphertext_length)
psa_status_t mbedtls_test_wrap_psa_aead_encrypt_setup(
psa_aead_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_aead_encrypt_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_aead_encrypt_setup(arg0_operation, arg1_key, arg2_alg)
psa_status_t mbedtls_test_wrap_psa_aead_finish(
psa_aead_operation_t *arg0_operation,
uint8_t *arg1_ciphertext,
size_t arg2_ciphertext_size,
size_t *arg3_ciphertext_length,
uint8_t *arg4_tag,
size_t arg5_tag_size,
size_t *arg6_tag_length);
#define psa_aead_finish(arg0_operation, arg1_ciphertext, arg2_ciphertext_size, arg3_ciphertext_length, arg4_tag, arg5_tag_size, arg6_tag_length) \
mbedtls_test_wrap_psa_aead_finish(arg0_operation, arg1_ciphertext, arg2_ciphertext_size, arg3_ciphertext_length, arg4_tag, arg5_tag_size, arg6_tag_length)
psa_status_t mbedtls_test_wrap_psa_aead_generate_nonce(
psa_aead_operation_t *arg0_operation,
uint8_t *arg1_nonce,
size_t arg2_nonce_size,
size_t *arg3_nonce_length);
#define psa_aead_generate_nonce(arg0_operation, arg1_nonce, arg2_nonce_size, arg3_nonce_length) \
mbedtls_test_wrap_psa_aead_generate_nonce(arg0_operation, arg1_nonce, arg2_nonce_size, arg3_nonce_length)
psa_status_t mbedtls_test_wrap_psa_aead_set_lengths(
psa_aead_operation_t *arg0_operation,
size_t arg1_ad_length,
size_t arg2_plaintext_length);
#define psa_aead_set_lengths(arg0_operation, arg1_ad_length, arg2_plaintext_length) \
mbedtls_test_wrap_psa_aead_set_lengths(arg0_operation, arg1_ad_length, arg2_plaintext_length)
psa_status_t mbedtls_test_wrap_psa_aead_set_nonce(
psa_aead_operation_t *arg0_operation,
const uint8_t *arg1_nonce,
size_t arg2_nonce_length);
#define psa_aead_set_nonce(arg0_operation, arg1_nonce, arg2_nonce_length) \
mbedtls_test_wrap_psa_aead_set_nonce(arg0_operation, arg1_nonce, arg2_nonce_length)
psa_status_t mbedtls_test_wrap_psa_aead_update(
psa_aead_operation_t *arg0_operation,
const uint8_t *arg1_input,
size_t arg2_input_length,
uint8_t *arg3_output,
size_t arg4_output_size,
size_t *arg5_output_length);
#define psa_aead_update(arg0_operation, arg1_input, arg2_input_length, arg3_output, arg4_output_size, arg5_output_length) \
mbedtls_test_wrap_psa_aead_update(arg0_operation, arg1_input, arg2_input_length, arg3_output, arg4_output_size, arg5_output_length)
psa_status_t mbedtls_test_wrap_psa_aead_update_ad(
psa_aead_operation_t *arg0_operation,
const uint8_t *arg1_input,
size_t arg2_input_length);
#define psa_aead_update_ad(arg0_operation, arg1_input, arg2_input_length) \
mbedtls_test_wrap_psa_aead_update_ad(arg0_operation, arg1_input, arg2_input_length)
psa_status_t mbedtls_test_wrap_psa_aead_verify(
psa_aead_operation_t *arg0_operation,
uint8_t *arg1_plaintext,
size_t arg2_plaintext_size,
size_t *arg3_plaintext_length,
const uint8_t *arg4_tag,
size_t arg5_tag_length);
#define psa_aead_verify(arg0_operation, arg1_plaintext, arg2_plaintext_size, arg3_plaintext_length, arg4_tag, arg5_tag_length) \
mbedtls_test_wrap_psa_aead_verify(arg0_operation, arg1_plaintext, arg2_plaintext_size, arg3_plaintext_length, arg4_tag, arg5_tag_length)
psa_status_t mbedtls_test_wrap_psa_asymmetric_decrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
const uint8_t *arg4_salt,
size_t arg5_salt_length,
uint8_t *arg6_output,
size_t arg7_output_size,
size_t *arg8_output_length);
#define psa_asymmetric_decrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_salt, arg5_salt_length, arg6_output, arg7_output_size, arg8_output_length) \
mbedtls_test_wrap_psa_asymmetric_decrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_salt, arg5_salt_length, arg6_output, arg7_output_size, arg8_output_length)
psa_status_t mbedtls_test_wrap_psa_asymmetric_encrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
const uint8_t *arg4_salt,
size_t arg5_salt_length,
uint8_t *arg6_output,
size_t arg7_output_size,
size_t *arg8_output_length);
#define psa_asymmetric_encrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_salt, arg5_salt_length, arg6_output, arg7_output_size, arg8_output_length) \
mbedtls_test_wrap_psa_asymmetric_encrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_salt, arg5_salt_length, arg6_output, arg7_output_size, arg8_output_length)
psa_status_t mbedtls_test_wrap_psa_cipher_abort(
psa_cipher_operation_t *arg0_operation);
#define psa_cipher_abort(arg0_operation) \
mbedtls_test_wrap_psa_cipher_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_cipher_decrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
uint8_t *arg4_output,
size_t arg5_output_size,
size_t *arg6_output_length);
#define psa_cipher_decrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_output, arg5_output_size, arg6_output_length) \
mbedtls_test_wrap_psa_cipher_decrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_output, arg5_output_size, arg6_output_length)
psa_status_t mbedtls_test_wrap_psa_cipher_decrypt_setup(
psa_cipher_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_cipher_decrypt_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_cipher_decrypt_setup(arg0_operation, arg1_key, arg2_alg)
psa_status_t mbedtls_test_wrap_psa_cipher_encrypt(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
uint8_t *arg4_output,
size_t arg5_output_size,
size_t *arg6_output_length);
#define psa_cipher_encrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_output, arg5_output_size, arg6_output_length) \
mbedtls_test_wrap_psa_cipher_encrypt(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_output, arg5_output_size, arg6_output_length)
psa_status_t mbedtls_test_wrap_psa_cipher_encrypt_setup(
psa_cipher_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_cipher_encrypt_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_cipher_encrypt_setup(arg0_operation, arg1_key, arg2_alg)
psa_status_t mbedtls_test_wrap_psa_cipher_finish(
psa_cipher_operation_t *arg0_operation,
uint8_t *arg1_output,
size_t arg2_output_size,
size_t *arg3_output_length);
#define psa_cipher_finish(arg0_operation, arg1_output, arg2_output_size, arg3_output_length) \
mbedtls_test_wrap_psa_cipher_finish(arg0_operation, arg1_output, arg2_output_size, arg3_output_length)
psa_status_t mbedtls_test_wrap_psa_cipher_generate_iv(
psa_cipher_operation_t *arg0_operation,
uint8_t *arg1_iv,
size_t arg2_iv_size,
size_t *arg3_iv_length);
#define psa_cipher_generate_iv(arg0_operation, arg1_iv, arg2_iv_size, arg3_iv_length) \
mbedtls_test_wrap_psa_cipher_generate_iv(arg0_operation, arg1_iv, arg2_iv_size, arg3_iv_length)
psa_status_t mbedtls_test_wrap_psa_cipher_set_iv(
psa_cipher_operation_t *arg0_operation,
const uint8_t *arg1_iv,
size_t arg2_iv_length);
#define psa_cipher_set_iv(arg0_operation, arg1_iv, arg2_iv_length) \
mbedtls_test_wrap_psa_cipher_set_iv(arg0_operation, arg1_iv, arg2_iv_length)
psa_status_t mbedtls_test_wrap_psa_cipher_update(
psa_cipher_operation_t *arg0_operation,
const uint8_t *arg1_input,
size_t arg2_input_length,
uint8_t *arg3_output,
size_t arg4_output_size,
size_t *arg5_output_length);
#define psa_cipher_update(arg0_operation, arg1_input, arg2_input_length, arg3_output, arg4_output_size, arg5_output_length) \
mbedtls_test_wrap_psa_cipher_update(arg0_operation, arg1_input, arg2_input_length, arg3_output, arg4_output_size, arg5_output_length)
psa_status_t mbedtls_test_wrap_psa_copy_key(
mbedtls_svc_key_id_t arg0_source_key,
const psa_key_attributes_t *arg1_attributes,
mbedtls_svc_key_id_t *arg2_target_key);
#define psa_copy_key(arg0_source_key, arg1_attributes, arg2_target_key) \
mbedtls_test_wrap_psa_copy_key(arg0_source_key, arg1_attributes, arg2_target_key)
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_cipher_suite(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
psa_pake_cipher_suite_t *arg1_cipher_suite);
#define psa_crypto_driver_pake_get_cipher_suite(arg0_inputs, arg1_cipher_suite) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_cipher_suite(arg0_inputs, arg1_cipher_suite)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_password(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
uint8_t *arg1_buffer,
size_t arg2_buffer_size,
size_t *arg3_buffer_length);
#define psa_crypto_driver_pake_get_password(arg0_inputs, arg1_buffer, arg2_buffer_size, arg3_buffer_length) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_password(arg0_inputs, arg1_buffer, arg2_buffer_size, arg3_buffer_length)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_password_len(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
size_t *arg1_password_len);
#define psa_crypto_driver_pake_get_password_len(arg0_inputs, arg1_password_len) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_password_len(arg0_inputs, arg1_password_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_peer(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
uint8_t *arg1_peer_id,
size_t arg2_peer_id_size,
size_t *arg3_peer_id_length);
#define psa_crypto_driver_pake_get_peer(arg0_inputs, arg1_peer_id, arg2_peer_id_size, arg3_peer_id_length) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_peer(arg0_inputs, arg1_peer_id, arg2_peer_id_size, arg3_peer_id_length)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_peer_len(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
size_t *arg1_peer_len);
#define psa_crypto_driver_pake_get_peer_len(arg0_inputs, arg1_peer_len) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_peer_len(arg0_inputs, arg1_peer_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_user(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
uint8_t *arg1_user_id,
size_t arg2_user_id_size,
size_t *arg3_user_id_len);
#define psa_crypto_driver_pake_get_user(arg0_inputs, arg1_user_id, arg2_user_id_size, arg3_user_id_len) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_user(arg0_inputs, arg1_user_id, arg2_user_id_size, arg3_user_id_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_crypto_driver_pake_get_user_len(
const psa_crypto_driver_pake_inputs_t *arg0_inputs,
size_t *arg1_user_len);
#define psa_crypto_driver_pake_get_user_len(arg0_inputs, arg1_user_len) \
mbedtls_test_wrap_psa_crypto_driver_pake_get_user_len(arg0_inputs, arg1_user_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
psa_status_t mbedtls_test_wrap_psa_crypto_init(void);
#define psa_crypto_init() \
mbedtls_test_wrap_psa_crypto_init()
psa_status_t mbedtls_test_wrap_psa_destroy_key(
mbedtls_svc_key_id_t arg0_key);
#define psa_destroy_key(arg0_key) \
mbedtls_test_wrap_psa_destroy_key(arg0_key)
psa_status_t mbedtls_test_wrap_psa_export_key(
mbedtls_svc_key_id_t arg0_key,
uint8_t *arg1_data,
size_t arg2_data_size,
size_t *arg3_data_length);
#define psa_export_key(arg0_key, arg1_data, arg2_data_size, arg3_data_length) \
mbedtls_test_wrap_psa_export_key(arg0_key, arg1_data, arg2_data_size, arg3_data_length)
psa_status_t mbedtls_test_wrap_psa_export_public_key(
mbedtls_svc_key_id_t arg0_key,
uint8_t *arg1_data,
size_t arg2_data_size,
size_t *arg3_data_length);
#define psa_export_public_key(arg0_key, arg1_data, arg2_data_size, arg3_data_length) \
mbedtls_test_wrap_psa_export_public_key(arg0_key, arg1_data, arg2_data_size, arg3_data_length)
psa_status_t mbedtls_test_wrap_psa_generate_key(
const psa_key_attributes_t *arg0_attributes,
mbedtls_svc_key_id_t *arg1_key);
#define psa_generate_key(arg0_attributes, arg1_key) \
mbedtls_test_wrap_psa_generate_key(arg0_attributes, arg1_key)
psa_status_t mbedtls_test_wrap_psa_generate_key_custom(
const psa_key_attributes_t *arg0_attributes,
const psa_custom_key_parameters_t *arg1_custom,
const uint8_t *arg2_custom_data,
size_t arg3_custom_data_length,
mbedtls_svc_key_id_t *arg4_key);
#define psa_generate_key_custom(arg0_attributes, arg1_custom, arg2_custom_data, arg3_custom_data_length, arg4_key) \
mbedtls_test_wrap_psa_generate_key_custom(arg0_attributes, arg1_custom, arg2_custom_data, arg3_custom_data_length, arg4_key)
psa_status_t mbedtls_test_wrap_psa_generate_key_iop_abort(
psa_generate_key_iop_t *arg0_operation);
#define psa_generate_key_iop_abort(arg0_operation) \
mbedtls_test_wrap_psa_generate_key_iop_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_generate_key_iop_complete(
psa_generate_key_iop_t *arg0_operation,
psa_key_id_t *arg1_key);
#define psa_generate_key_iop_complete(arg0_operation, arg1_key) \
mbedtls_test_wrap_psa_generate_key_iop_complete(arg0_operation, arg1_key)
psa_status_t mbedtls_test_wrap_psa_generate_key_iop_setup(
psa_generate_key_iop_t *arg0_operation,
const psa_key_attributes_t *arg1_attributes);
#define psa_generate_key_iop_setup(arg0_operation, arg1_attributes) \
mbedtls_test_wrap_psa_generate_key_iop_setup(arg0_operation, arg1_attributes)
psa_status_t mbedtls_test_wrap_psa_generate_random(
uint8_t *arg0_output,
size_t arg1_output_size);
#define psa_generate_random(arg0_output, arg1_output_size) \
mbedtls_test_wrap_psa_generate_random(arg0_output, arg1_output_size)
psa_status_t mbedtls_test_wrap_psa_get_key_attributes(
mbedtls_svc_key_id_t arg0_key,
psa_key_attributes_t *arg1_attributes);
#define psa_get_key_attributes(arg0_key, arg1_attributes) \
mbedtls_test_wrap_psa_get_key_attributes(arg0_key, arg1_attributes)
psa_status_t mbedtls_test_wrap_psa_hash_abort(
psa_hash_operation_t *arg0_operation);
#define psa_hash_abort(arg0_operation) \
mbedtls_test_wrap_psa_hash_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_hash_clone(
const psa_hash_operation_t *arg0_source_operation,
psa_hash_operation_t *arg1_target_operation);
#define psa_hash_clone(arg0_source_operation, arg1_target_operation) \
mbedtls_test_wrap_psa_hash_clone(arg0_source_operation, arg1_target_operation)
psa_status_t mbedtls_test_wrap_psa_hash_compare(
psa_algorithm_t arg0_alg,
const uint8_t *arg1_input,
size_t arg2_input_length,
const uint8_t *arg3_hash,
size_t arg4_hash_length);
#define psa_hash_compare(arg0_alg, arg1_input, arg2_input_length, arg3_hash, arg4_hash_length) \
mbedtls_test_wrap_psa_hash_compare(arg0_alg, arg1_input, arg2_input_length, arg3_hash, arg4_hash_length)
psa_status_t mbedtls_test_wrap_psa_hash_compute(
psa_algorithm_t arg0_alg,
const uint8_t *arg1_input,
size_t arg2_input_length,
uint8_t *arg3_hash,
size_t arg4_hash_size,
size_t *arg5_hash_length);
#define psa_hash_compute(arg0_alg, arg1_input, arg2_input_length, arg3_hash, arg4_hash_size, arg5_hash_length) \
mbedtls_test_wrap_psa_hash_compute(arg0_alg, arg1_input, arg2_input_length, arg3_hash, arg4_hash_size, arg5_hash_length)
psa_status_t mbedtls_test_wrap_psa_hash_finish(
psa_hash_operation_t *arg0_operation,
uint8_t *arg1_hash,
size_t arg2_hash_size,
size_t *arg3_hash_length);
#define psa_hash_finish(arg0_operation, arg1_hash, arg2_hash_size, arg3_hash_length) \
mbedtls_test_wrap_psa_hash_finish(arg0_operation, arg1_hash, arg2_hash_size, arg3_hash_length)
psa_status_t mbedtls_test_wrap_psa_hash_setup(
psa_hash_operation_t *arg0_operation,
psa_algorithm_t arg1_alg);
#define psa_hash_setup(arg0_operation, arg1_alg) \
mbedtls_test_wrap_psa_hash_setup(arg0_operation, arg1_alg)
psa_status_t mbedtls_test_wrap_psa_hash_update(
psa_hash_operation_t *arg0_operation,
const uint8_t *arg1_input,
size_t arg2_input_length);
#define psa_hash_update(arg0_operation, arg1_input, arg2_input_length) \
mbedtls_test_wrap_psa_hash_update(arg0_operation, arg1_input, arg2_input_length)
psa_status_t mbedtls_test_wrap_psa_hash_verify(
psa_hash_operation_t *arg0_operation,
const uint8_t *arg1_hash,
size_t arg2_hash_length);
#define psa_hash_verify(arg0_operation, arg1_hash, arg2_hash_length) \
mbedtls_test_wrap_psa_hash_verify(arg0_operation, arg1_hash, arg2_hash_length)
psa_status_t mbedtls_test_wrap_psa_import_key(
const psa_key_attributes_t *arg0_attributes,
const uint8_t *arg1_data,
size_t arg2_data_length,
mbedtls_svc_key_id_t *arg3_key);
#define psa_import_key(arg0_attributes, arg1_data, arg2_data_length, arg3_key) \
mbedtls_test_wrap_psa_import_key(arg0_attributes, arg1_data, arg2_data_length, arg3_key)
psa_status_t mbedtls_test_wrap_psa_key_agreement(
mbedtls_svc_key_id_t arg0_private_key,
const uint8_t *arg1_peer_key,
size_t arg2_peer_key_length,
psa_algorithm_t arg3_alg,
const psa_key_attributes_t *arg4_attributes,
mbedtls_svc_key_id_t *arg5_key);
#define psa_key_agreement(arg0_private_key, arg1_peer_key, arg2_peer_key_length, arg3_alg, arg4_attributes, arg5_key) \
mbedtls_test_wrap_psa_key_agreement(arg0_private_key, arg1_peer_key, arg2_peer_key_length, arg3_alg, arg4_attributes, arg5_key)
psa_status_t mbedtls_test_wrap_psa_key_agreement_iop_abort(
psa_key_agreement_iop_t *arg0_operation);
#define psa_key_agreement_iop_abort(arg0_operation) \
mbedtls_test_wrap_psa_key_agreement_iop_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_key_agreement_iop_complete(
psa_key_agreement_iop_t *arg0_operation,
mbedtls_svc_key_id_t *arg1_key);
#define psa_key_agreement_iop_complete(arg0_operation, arg1_key) \
mbedtls_test_wrap_psa_key_agreement_iop_complete(arg0_operation, arg1_key)
psa_status_t mbedtls_test_wrap_psa_key_agreement_iop_setup(
psa_key_agreement_iop_t *arg0_operation,
mbedtls_svc_key_id_t arg1_private_key,
const uint8_t *arg2_peer_key,
size_t arg3_peer_key_length,
psa_algorithm_t arg4_alg,
const psa_key_attributes_t *arg5_attributes);
#define psa_key_agreement_iop_setup(arg0_operation, arg1_private_key, arg2_peer_key, arg3_peer_key_length, arg4_alg, arg5_attributes) \
mbedtls_test_wrap_psa_key_agreement_iop_setup(arg0_operation, arg1_private_key, arg2_peer_key, arg3_peer_key_length, arg4_alg, arg5_attributes)
psa_status_t mbedtls_test_wrap_psa_key_derivation_abort(
psa_key_derivation_operation_t *arg0_operation);
#define psa_key_derivation_abort(arg0_operation) \
mbedtls_test_wrap_psa_key_derivation_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_key_derivation_get_capacity(
const psa_key_derivation_operation_t *arg0_operation,
size_t *arg1_capacity);
#define psa_key_derivation_get_capacity(arg0_operation, arg1_capacity) \
mbedtls_test_wrap_psa_key_derivation_get_capacity(arg0_operation, arg1_capacity)
psa_status_t mbedtls_test_wrap_psa_key_derivation_input_bytes(
psa_key_derivation_operation_t *arg0_operation,
psa_key_derivation_step_t arg1_step,
const uint8_t *arg2_data,
size_t arg3_data_length);
#define psa_key_derivation_input_bytes(arg0_operation, arg1_step, arg2_data, arg3_data_length) \
mbedtls_test_wrap_psa_key_derivation_input_bytes(arg0_operation, arg1_step, arg2_data, arg3_data_length)
psa_status_t mbedtls_test_wrap_psa_key_derivation_input_integer(
psa_key_derivation_operation_t *arg0_operation,
psa_key_derivation_step_t arg1_step,
uint64_t arg2_value);
#define psa_key_derivation_input_integer(arg0_operation, arg1_step, arg2_value) \
mbedtls_test_wrap_psa_key_derivation_input_integer(arg0_operation, arg1_step, arg2_value)
psa_status_t mbedtls_test_wrap_psa_key_derivation_input_key(
psa_key_derivation_operation_t *arg0_operation,
psa_key_derivation_step_t arg1_step,
mbedtls_svc_key_id_t arg2_key);
#define psa_key_derivation_input_key(arg0_operation, arg1_step, arg2_key) \
mbedtls_test_wrap_psa_key_derivation_input_key(arg0_operation, arg1_step, arg2_key)
psa_status_t mbedtls_test_wrap_psa_key_derivation_key_agreement(
psa_key_derivation_operation_t *arg0_operation,
psa_key_derivation_step_t arg1_step,
mbedtls_svc_key_id_t arg2_private_key,
const uint8_t *arg3_peer_key,
size_t arg4_peer_key_length);
#define psa_key_derivation_key_agreement(arg0_operation, arg1_step, arg2_private_key, arg3_peer_key, arg4_peer_key_length) \
mbedtls_test_wrap_psa_key_derivation_key_agreement(arg0_operation, arg1_step, arg2_private_key, arg3_peer_key, arg4_peer_key_length)
psa_status_t mbedtls_test_wrap_psa_key_derivation_output_bytes(
psa_key_derivation_operation_t *arg0_operation,
uint8_t *arg1_output,
size_t arg2_output_length);
#define psa_key_derivation_output_bytes(arg0_operation, arg1_output, arg2_output_length) \
mbedtls_test_wrap_psa_key_derivation_output_bytes(arg0_operation, arg1_output, arg2_output_length)
psa_status_t mbedtls_test_wrap_psa_key_derivation_output_key(
const psa_key_attributes_t *arg0_attributes,
psa_key_derivation_operation_t *arg1_operation,
mbedtls_svc_key_id_t *arg2_key);
#define psa_key_derivation_output_key(arg0_attributes, arg1_operation, arg2_key) \
mbedtls_test_wrap_psa_key_derivation_output_key(arg0_attributes, arg1_operation, arg2_key)
psa_status_t mbedtls_test_wrap_psa_key_derivation_output_key_custom(
const psa_key_attributes_t *arg0_attributes,
psa_key_derivation_operation_t *arg1_operation,
const psa_custom_key_parameters_t *arg2_custom,
const uint8_t *arg3_custom_data,
size_t arg4_custom_data_length,
mbedtls_svc_key_id_t *arg5_key);
#define psa_key_derivation_output_key_custom(arg0_attributes, arg1_operation, arg2_custom, arg3_custom_data, arg4_custom_data_length, arg5_key) \
mbedtls_test_wrap_psa_key_derivation_output_key_custom(arg0_attributes, arg1_operation, arg2_custom, arg3_custom_data, arg4_custom_data_length, arg5_key)
psa_status_t mbedtls_test_wrap_psa_key_derivation_set_capacity(
psa_key_derivation_operation_t *arg0_operation,
size_t arg1_capacity);
#define psa_key_derivation_set_capacity(arg0_operation, arg1_capacity) \
mbedtls_test_wrap_psa_key_derivation_set_capacity(arg0_operation, arg1_capacity)
psa_status_t mbedtls_test_wrap_psa_key_derivation_setup(
psa_key_derivation_operation_t *arg0_operation,
psa_algorithm_t arg1_alg);
#define psa_key_derivation_setup(arg0_operation, arg1_alg) \
mbedtls_test_wrap_psa_key_derivation_setup(arg0_operation, arg1_alg)
psa_status_t mbedtls_test_wrap_psa_mac_abort(
psa_mac_operation_t *arg0_operation);
#define psa_mac_abort(arg0_operation) \
mbedtls_test_wrap_psa_mac_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_mac_compute(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
uint8_t *arg4_mac,
size_t arg5_mac_size,
size_t *arg6_mac_length);
#define psa_mac_compute(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_mac, arg5_mac_size, arg6_mac_length) \
mbedtls_test_wrap_psa_mac_compute(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_mac, arg5_mac_size, arg6_mac_length)
psa_status_t mbedtls_test_wrap_psa_mac_sign_finish(
psa_mac_operation_t *arg0_operation,
uint8_t *arg1_mac,
size_t arg2_mac_size,
size_t *arg3_mac_length);
#define psa_mac_sign_finish(arg0_operation, arg1_mac, arg2_mac_size, arg3_mac_length) \
mbedtls_test_wrap_psa_mac_sign_finish(arg0_operation, arg1_mac, arg2_mac_size, arg3_mac_length)
psa_status_t mbedtls_test_wrap_psa_mac_sign_setup(
psa_mac_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_mac_sign_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_mac_sign_setup(arg0_operation, arg1_key, arg2_alg)
psa_status_t mbedtls_test_wrap_psa_mac_update(
psa_mac_operation_t *arg0_operation,
const uint8_t *arg1_input,
size_t arg2_input_length);
#define psa_mac_update(arg0_operation, arg1_input, arg2_input_length) \
mbedtls_test_wrap_psa_mac_update(arg0_operation, arg1_input, arg2_input_length)
psa_status_t mbedtls_test_wrap_psa_mac_verify(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
const uint8_t *arg4_mac,
size_t arg5_mac_length);
#define psa_mac_verify(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_mac, arg5_mac_length) \
mbedtls_test_wrap_psa_mac_verify(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_mac, arg5_mac_length)
psa_status_t mbedtls_test_wrap_psa_mac_verify_finish(
psa_mac_operation_t *arg0_operation,
const uint8_t *arg1_mac,
size_t arg2_mac_length);
#define psa_mac_verify_finish(arg0_operation, arg1_mac, arg2_mac_length) \
mbedtls_test_wrap_psa_mac_verify_finish(arg0_operation, arg1_mac, arg2_mac_length)
psa_status_t mbedtls_test_wrap_psa_mac_verify_setup(
psa_mac_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg);
#define psa_mac_verify_setup(arg0_operation, arg1_key, arg2_alg) \
mbedtls_test_wrap_psa_mac_verify_setup(arg0_operation, arg1_key, arg2_alg)
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_abort(
psa_pake_operation_t *arg0_operation);
#define psa_pake_abort(arg0_operation) \
mbedtls_test_wrap_psa_pake_abort(arg0_operation)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_get_implicit_key(
psa_pake_operation_t *arg0_operation,
psa_key_derivation_operation_t *arg1_output);
#define psa_pake_get_implicit_key(arg0_operation, arg1_output) \
mbedtls_test_wrap_psa_pake_get_implicit_key(arg0_operation, arg1_output)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_input(
psa_pake_operation_t *arg0_operation,
psa_pake_step_t arg1_step,
const uint8_t *arg2_input,
size_t arg3_input_length);
#define psa_pake_input(arg0_operation, arg1_step, arg2_input, arg3_input_length) \
mbedtls_test_wrap_psa_pake_input(arg0_operation, arg1_step, arg2_input, arg3_input_length)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_output(
psa_pake_operation_t *arg0_operation,
psa_pake_step_t arg1_step,
uint8_t *arg2_output,
size_t arg3_output_size,
size_t *arg4_output_length);
#define psa_pake_output(arg0_operation, arg1_step, arg2_output, arg3_output_size, arg4_output_length) \
mbedtls_test_wrap_psa_pake_output(arg0_operation, arg1_step, arg2_output, arg3_output_size, arg4_output_length)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_set_password_key(
psa_pake_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_password);
#define psa_pake_set_password_key(arg0_operation, arg1_password) \
mbedtls_test_wrap_psa_pake_set_password_key(arg0_operation, arg1_password)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_set_peer(
psa_pake_operation_t *arg0_operation,
const uint8_t *arg1_peer_id,
size_t arg2_peer_id_len);
#define psa_pake_set_peer(arg0_operation, arg1_peer_id, arg2_peer_id_len) \
mbedtls_test_wrap_psa_pake_set_peer(arg0_operation, arg1_peer_id, arg2_peer_id_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_set_role(
psa_pake_operation_t *arg0_operation,
psa_pake_role_t arg1_role);
#define psa_pake_set_role(arg0_operation, arg1_role) \
mbedtls_test_wrap_psa_pake_set_role(arg0_operation, arg1_role)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_set_user(
psa_pake_operation_t *arg0_operation,
const uint8_t *arg1_user_id,
size_t arg2_user_id_len);
#define psa_pake_set_user(arg0_operation, arg1_user_id, arg2_user_id_len) \
mbedtls_test_wrap_psa_pake_set_user(arg0_operation, arg1_user_id, arg2_user_id_len)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
#if defined(PSA_WANT_ALG_SOME_PAKE)
psa_status_t mbedtls_test_wrap_psa_pake_setup(
psa_pake_operation_t *arg0_operation,
const psa_pake_cipher_suite_t *arg1_cipher_suite);
#define psa_pake_setup(arg0_operation, arg1_cipher_suite) \
mbedtls_test_wrap_psa_pake_setup(arg0_operation, arg1_cipher_suite)
#endif /* defined(PSA_WANT_ALG_SOME_PAKE) */
psa_status_t mbedtls_test_wrap_psa_purge_key(
mbedtls_svc_key_id_t arg0_key);
#define psa_purge_key(arg0_key) \
mbedtls_test_wrap_psa_purge_key(arg0_key)
psa_status_t mbedtls_test_wrap_psa_raw_key_agreement(
psa_algorithm_t arg0_alg,
mbedtls_svc_key_id_t arg1_private_key,
const uint8_t *arg2_peer_key,
size_t arg3_peer_key_length,
uint8_t *arg4_output,
size_t arg5_output_size,
size_t *arg6_output_length);
#define psa_raw_key_agreement(arg0_alg, arg1_private_key, arg2_peer_key, arg3_peer_key_length, arg4_output, arg5_output_size, arg6_output_length) \
mbedtls_test_wrap_psa_raw_key_agreement(arg0_alg, arg1_private_key, arg2_peer_key, arg3_peer_key_length, arg4_output, arg5_output_size, arg6_output_length)
psa_status_t mbedtls_test_wrap_psa_sign_hash(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_hash,
size_t arg3_hash_length,
uint8_t *arg4_signature,
size_t arg5_signature_size,
size_t *arg6_signature_length);
#define psa_sign_hash(arg0_key, arg1_alg, arg2_hash, arg3_hash_length, arg4_signature, arg5_signature_size, arg6_signature_length) \
mbedtls_test_wrap_psa_sign_hash(arg0_key, arg1_alg, arg2_hash, arg3_hash_length, arg4_signature, arg5_signature_size, arg6_signature_length)
psa_status_t mbedtls_test_wrap_psa_sign_hash_abort(
psa_sign_hash_interruptible_operation_t *arg0_operation);
#define psa_sign_hash_abort(arg0_operation) \
mbedtls_test_wrap_psa_sign_hash_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_sign_hash_complete(
psa_sign_hash_interruptible_operation_t *arg0_operation,
uint8_t *arg1_signature,
size_t arg2_signature_size,
size_t *arg3_signature_length);
#define psa_sign_hash_complete(arg0_operation, arg1_signature, arg2_signature_size, arg3_signature_length) \
mbedtls_test_wrap_psa_sign_hash_complete(arg0_operation, arg1_signature, arg2_signature_size, arg3_signature_length)
psa_status_t mbedtls_test_wrap_psa_sign_hash_start(
psa_sign_hash_interruptible_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg,
const uint8_t *arg3_hash,
size_t arg4_hash_length);
#define psa_sign_hash_start(arg0_operation, arg1_key, arg2_alg, arg3_hash, arg4_hash_length) \
mbedtls_test_wrap_psa_sign_hash_start(arg0_operation, arg1_key, arg2_alg, arg3_hash, arg4_hash_length)
psa_status_t mbedtls_test_wrap_psa_sign_message(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
uint8_t *arg4_signature,
size_t arg5_signature_size,
size_t *arg6_signature_length);
#define psa_sign_message(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_signature, arg5_signature_size, arg6_signature_length) \
mbedtls_test_wrap_psa_sign_message(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_signature, arg5_signature_size, arg6_signature_length)
psa_status_t mbedtls_test_wrap_psa_verify_hash(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_hash,
size_t arg3_hash_length,
const uint8_t *arg4_signature,
size_t arg5_signature_length);
#define psa_verify_hash(arg0_key, arg1_alg, arg2_hash, arg3_hash_length, arg4_signature, arg5_signature_length) \
mbedtls_test_wrap_psa_verify_hash(arg0_key, arg1_alg, arg2_hash, arg3_hash_length, arg4_signature, arg5_signature_length)
psa_status_t mbedtls_test_wrap_psa_verify_hash_abort(
psa_verify_hash_interruptible_operation_t *arg0_operation);
#define psa_verify_hash_abort(arg0_operation) \
mbedtls_test_wrap_psa_verify_hash_abort(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_verify_hash_complete(
psa_verify_hash_interruptible_operation_t *arg0_operation);
#define psa_verify_hash_complete(arg0_operation) \
mbedtls_test_wrap_psa_verify_hash_complete(arg0_operation)
psa_status_t mbedtls_test_wrap_psa_verify_hash_start(
psa_verify_hash_interruptible_operation_t *arg0_operation,
mbedtls_svc_key_id_t arg1_key,
psa_algorithm_t arg2_alg,
const uint8_t *arg3_hash,
size_t arg4_hash_length,
const uint8_t *arg5_signature,
size_t arg6_signature_length);
#define psa_verify_hash_start(arg0_operation, arg1_key, arg2_alg, arg3_hash, arg4_hash_length, arg5_signature, arg6_signature_length) \
mbedtls_test_wrap_psa_verify_hash_start(arg0_operation, arg1_key, arg2_alg, arg3_hash, arg4_hash_length, arg5_signature, arg6_signature_length)
psa_status_t mbedtls_test_wrap_psa_verify_message(
mbedtls_svc_key_id_t arg0_key,
psa_algorithm_t arg1_alg,
const uint8_t *arg2_input,
size_t arg3_input_length,
const uint8_t *arg4_signature,
size_t arg5_signature_length);
#define psa_verify_message(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_signature, arg5_signature_length) \
mbedtls_test_wrap_psa_verify_message(arg0_key, arg1_alg, arg2_input, arg3_input_length, arg4_signature, arg5_signature_length)
#endif /* defined(MBEDTLS_PSA_CRYPTO_C) && defined(MBEDTLS_TEST_HOOKS) && \
!defined(RECORD_PSA_STATUS_COVERAGE_LOG) */
#ifdef __cplusplus
}
#endif
#endif /* TEST_PSA_TEST_WRAPPERS_H */
/* End of automatically generated file. */
-664
View File
@@ -1,664 +0,0 @@
/** \file ssl_helpers.h
*
* \brief This file contains helper functions to set up a TLS connection.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef SSL_HELPERS_H
#define SSL_HELPERS_H
#include "mbedtls/build_info.h"
#include <string.h>
#include <test/helpers.h>
#include <test/macros.h>
#include <test/random.h>
#include <test/psa_crypto_helpers.h>
#if defined(MBEDTLS_SSL_TLS_C)
#include <ssl_misc.h>
#include <mbedtls/timing.h>
#include <mbedtls/debug.h>
#include "test/certs.h"
#if defined(MBEDTLS_SSL_CACHE_C)
#include "mbedtls/ssl_cache.h"
#endif
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#define PSA_TO_MBEDTLS_ERR(status) PSA_TO_MBEDTLS_ERR_LIST(status, \
psa_to_ssl_errors, \
psa_generic_status_to_mbedtls)
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
#if defined(PSA_WANT_KEY_TYPE_AES)
#if defined(PSA_WANT_ALG_GCM)
#if defined(PSA_WANT_ALG_SHA_384)
#define MBEDTLS_TEST_HAS_TLS1_3_AES_256_GCM_SHA384
#endif
#if defined(PSA_WANT_ALG_SHA_256)
#define MBEDTLS_TEST_HAS_TLS1_3_AES_128_GCM_SHA256
#endif
#endif /* PSA_WANT_ALG_GCM */
#if defined(PSA_WANT_ALG_CCM) && defined(PSA_WANT_ALG_SHA_256)
#define MBEDTLS_TEST_HAS_TLS1_3_AES_128_CCM_SHA256
#define MBEDTLS_TEST_HAS_TLS1_3_AES_128_CCM_8_SHA256
#endif
#endif /* PSA_WANT_KEY_TYPE_AES */
#if defined(PSA_WANT_ALG_CHACHA20_POLY1305) && defined(PSA_WANT_ALG_SHA_256)
#define MBEDTLS_TEST_HAS_TLS1_3_CHACHA20_POLY1305_SHA256
#endif
#if defined(MBEDTLS_TEST_HAS_TLS1_3_AES_256_GCM_SHA384) || \
defined(MBEDTLS_TEST_HAS_TLS1_3_AES_128_GCM_SHA256) || \
defined(MBEDTLS_TEST_HAS_TLS1_3_AES_128_CCM_SHA256) || \
defined(MBEDTLS_TEST_HAS_TLS1_3_AES_128_CCM_8_SHA256) || \
defined(MBEDTLS_TEST_HAS_TLS1_3_CHACHA20_POLY1305_SHA256)
#define MBEDTLS_TEST_AT_LEAST_ONE_TLS1_3_CIPHERSUITE
#endif
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
#define MBEDTLS_CAN_HANDLE_RSA_TEST_KEY
#endif
enum {
#define MBEDTLS_SSL_TLS1_3_LABEL(name, string) \
tls13_label_ ## name,
MBEDTLS_SSL_TLS1_3_LABEL_LIST
#undef MBEDTLS_SSL_TLS1_3_LABEL
};
#if defined(MBEDTLS_SSL_ALPN)
#define MBEDTLS_TEST_MAX_ALPN_LIST_SIZE 10
#endif
typedef struct mbedtls_test_ssl_log_pattern {
const char *pattern;
size_t counter;
} mbedtls_test_ssl_log_pattern;
typedef struct mbedtls_test_handshake_test_options {
const char *cipher;
uint16_t *group_list;
mbedtls_ssl_protocol_version client_min_version;
mbedtls_ssl_protocol_version client_max_version;
mbedtls_ssl_protocol_version server_min_version;
mbedtls_ssl_protocol_version server_max_version;
mbedtls_ssl_protocol_version expected_negotiated_version;
int expected_handshake_result;
int expected_ciphersuite;
int pk_alg;
int opaque_alg;
int opaque_alg2;
int opaque_usage;
data_t *psk_str;
int dtls;
int srv_auth_mode;
int serialize;
int mfl;
int cli_msg_len;
int srv_msg_len;
int expected_cli_fragments;
int expected_srv_fragments;
int renegotiate;
int legacy_renegotiation;
void *srv_log_obj;
void *cli_log_obj;
void (*srv_log_fun)(void *, int, const char *, int, const char *);
void (*cli_log_fun)(void *, int, const char *, int, const char *);
int resize_buffers;
int early_data;
int max_early_data_size;
#if defined(MBEDTLS_SSL_CACHE_C)
mbedtls_ssl_cache_context *cache;
#endif
#if defined(MBEDTLS_SSL_ALPN)
const char *alpn_list[MBEDTLS_TEST_MAX_ALPN_LIST_SIZE];
#endif
} mbedtls_test_handshake_test_options;
/*
* Buffer structure for custom I/O callbacks.
*/
typedef struct mbedtls_test_ssl_buffer {
size_t start;
size_t content_length;
size_t capacity;
unsigned char *buffer;
} mbedtls_test_ssl_buffer;
/*
* Context for a message metadata queue (fifo) that is on top of the ring buffer.
*/
typedef struct mbedtls_test_ssl_message_queue {
size_t *messages;
int pos;
int num;
int capacity;
} mbedtls_test_ssl_message_queue;
/*
* Context for the I/O callbacks simulating network connection.
*/
#define MBEDTLS_MOCK_SOCKET_CONNECTED 1
typedef struct mbedtls_test_mock_socket {
int status;
mbedtls_test_ssl_buffer *input;
mbedtls_test_ssl_buffer *output;
struct mbedtls_test_mock_socket *peer;
} mbedtls_test_mock_socket;
/* Errors used in the message socket mocks */
#define MBEDTLS_TEST_ERROR_CONTEXT_ERROR -55
#define MBEDTLS_TEST_ERROR_SEND_FAILED -66
#define MBEDTLS_TEST_ERROR_RECV_FAILED -77
/*
* Structure used as an addon, or a wrapper, around the mocked sockets.
* Contains an input queue, to which the other socket pushes metadata,
* and an output queue, to which this one pushes metadata. This context is
* considered as an owner of the input queue only, which is initialized and
* freed in the respective setup and free calls.
*/
typedef struct mbedtls_test_message_socket_context {
mbedtls_test_ssl_message_queue *queue_input;
mbedtls_test_ssl_message_queue *queue_output;
mbedtls_test_mock_socket *socket;
} mbedtls_test_message_socket_context;
#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
/*
* Structure with endpoint's certificates for SSL communication tests.
*/
typedef struct mbedtls_test_ssl_endpoint_certificate {
mbedtls_x509_crt *ca_cert;
mbedtls_x509_crt *cert;
mbedtls_pk_context *pkey;
} mbedtls_test_ssl_endpoint_certificate;
/*
* Endpoint structure for SSL communication tests.
*/
typedef struct mbedtls_test_ssl_endpoint {
const char *name;
mbedtls_ssl_context ssl;
mbedtls_ssl_config conf;
mbedtls_test_mock_socket socket;
mbedtls_test_ssl_endpoint_certificate cert;
} mbedtls_test_ssl_endpoint;
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
/*
* Random number generator aimed for TLS unitary tests. Its main purpose is to
* simplify the set-up of a random number generator for TLS
* unitary tests: no need to set up a good entropy source for example.
*/
int mbedtls_test_random(void *p_rng, unsigned char *output, size_t output_len);
/*
* This function can be passed to mbedtls to receive output logs from it. In
* this case, it will count the instances of a mbedtls_test_ssl_log_pattern
* in the received logged messages.
*/
void mbedtls_test_ssl_log_analyzer(void *ctx, int level,
const char *file, int line,
const char *str);
void mbedtls_test_init_handshake_options(
mbedtls_test_handshake_test_options *opts);
void mbedtls_test_free_handshake_options(
mbedtls_test_handshake_test_options *opts);
/*
* Initialises \p buf. After calling this function it is safe to call
* `mbedtls_test_ssl_buffer_free()` on \p buf.
*/
void mbedtls_test_ssl_buffer_init(mbedtls_test_ssl_buffer *buf);
/*
* Sets up \p buf. After calling this function it is safe to call
* `mbedtls_test_ssl_buffer_put()` and `mbedtls_test_ssl_buffer_get()`
* on \p buf.
*/
int mbedtls_test_ssl_buffer_setup(mbedtls_test_ssl_buffer *buf,
size_t capacity);
void mbedtls_test_ssl_buffer_free(mbedtls_test_ssl_buffer *buf);
/*
* Puts \p input_len bytes from the \p input buffer into the ring buffer \p buf.
*
* \p buf must have been initialized and set up by calling
* `mbedtls_test_ssl_buffer_init()` and `mbedtls_test_ssl_buffer_setup()`.
*
* \retval \p input_len, if the data fits.
* \retval 0 <= value < \p input_len, if the data does not fit.
* \retval -1, if \p buf is NULL, it hasn't been set up or \p input_len is not
* zero and \p input is NULL.
*/
int mbedtls_test_ssl_buffer_put(mbedtls_test_ssl_buffer *buf,
const unsigned char *input, size_t input_len);
/*
* Gets \p output_len bytes from the ring buffer \p buf into the
* \p output buffer. The output buffer can be NULL, in this case a part of the
* ring buffer will be dropped, if the requested length is available.
*
* \p buf must have been initialized and set up by calling
* `mbedtls_test_ssl_buffer_init()` and `mbedtls_test_ssl_buffer_setup()`.
*
* \retval \p output_len, if the data is available.
* \retval 0 <= value < \p output_len, if the data is not available.
* \retval -1, if \buf is NULL or it hasn't been set up.
*/
int mbedtls_test_ssl_buffer_get(mbedtls_test_ssl_buffer *buf,
unsigned char *output, size_t output_len);
/*
* Errors used in the message transport mock tests
*/
#define MBEDTLS_TEST_ERROR_ARG_NULL -11
#define MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED -44
/*
* Setup and free functions for the message metadata queue.
*
* \p capacity describes the number of message metadata chunks that can be held
* within the queue.
*
* \retval 0, if a metadata queue of a given length can be allocated.
* \retval MBEDTLS_ERR_SSL_ALLOC_FAILED, if allocation failed.
*/
int mbedtls_test_ssl_message_queue_setup(
mbedtls_test_ssl_message_queue *queue, size_t capacity);
void mbedtls_test_ssl_message_queue_free(
mbedtls_test_ssl_message_queue *queue);
/*
* Push message length information onto the message metadata queue.
* This will become the last element to leave it (fifo).
*
* \retval MBEDTLS_TEST_ERROR_ARG_NULL, if the queue is null.
* \retval MBEDTLS_ERR_SSL_WANT_WRITE, if the queue is full.
* \retval \p len, if the push was successful.
*/
int mbedtls_test_ssl_message_queue_push_info(
mbedtls_test_ssl_message_queue *queue, size_t len);
/*
* Pop information about the next message length from the queue. This will be
* the oldest inserted message length(fifo). \p msg_len can be null, in which
* case the data will be popped from the queue but not copied anywhere.
*
* \retval MBEDTLS_TEST_ERROR_ARG_NULL, if the queue is null.
* \retval MBEDTLS_ERR_SSL_WANT_READ, if the queue is empty.
* \retval message length, if the pop was successful, up to the given
\p buf_len.
*/
int mbedtls_test_ssl_message_queue_pop_info(
mbedtls_test_ssl_message_queue *queue, size_t buf_len);
/*
* Setup and teardown functions for mock sockets.
*/
void mbedtls_test_mock_socket_init(mbedtls_test_mock_socket *socket);
/*
* Closes the socket \p socket.
*
* \p socket must have been previously initialized by calling
* mbedtls_test_mock_socket_init().
*
* This function frees all allocated resources and both sockets are aware of the
* new connection state.
*
* That is, this function does not simulate half-open TCP connections and the
* phenomenon that when closing a UDP connection the peer is not aware of the
* connection having been closed.
*/
void mbedtls_test_mock_socket_close(mbedtls_test_mock_socket *socket);
/*
* Establishes a connection between \p peer1 and \p peer2.
*
* \p peer1 and \p peer2 must have been previously initialized by calling
* mbedtls_test_mock_socket_init().
*
* The capacities of the internal buffers are set to \p bufsize. Setting this to
* the correct value allows for simulation of MTU, sanity testing the mock
* implementation and mocking TCP connections with lower memory cost.
*/
int mbedtls_test_mock_socket_connect(mbedtls_test_mock_socket *peer1,
mbedtls_test_mock_socket *peer2,
size_t bufsize);
/*
* Callbacks for simulating blocking I/O over connection-oriented transport.
*/
int mbedtls_test_mock_tcp_send_b(void *ctx,
const unsigned char *buf, size_t len);
int mbedtls_test_mock_tcp_recv_b(void *ctx, unsigned char *buf, size_t len);
/*
* Callbacks for simulating non-blocking I/O over connection-oriented transport.
*/
int mbedtls_test_mock_tcp_send_nb(void *ctx,
const unsigned char *buf, size_t len);
int mbedtls_test_mock_tcp_recv_nb(void *ctx, unsigned char *buf, size_t len);
void mbedtls_test_message_socket_init(
mbedtls_test_message_socket_context *ctx);
/*
* Setup a given message socket context including initialization of
* input/output queues to a chosen capacity of messages. Also set the
* corresponding mock socket.
*
* \retval 0, if everything succeeds.
* \retval MBEDTLS_ERR_SSL_ALLOC_FAILED, if allocation of a message
* queue failed.
*/
int mbedtls_test_message_socket_setup(
mbedtls_test_ssl_message_queue *queue_input,
mbedtls_test_ssl_message_queue *queue_output,
size_t queue_capacity,
mbedtls_test_mock_socket *socket,
mbedtls_test_message_socket_context *ctx);
/*
* Close a given message socket context, along with the socket itself. Free the
* memory allocated by the input queue.
*/
void mbedtls_test_message_socket_close(
mbedtls_test_message_socket_context *ctx);
/*
* Send one message through a given message socket context.
*
* \retval \p len, if everything succeeds.
* \retval MBEDTLS_TEST_ERROR_CONTEXT_ERROR, if any of the needed context
* elements or the context itself is null.
* \retval MBEDTLS_TEST_ERROR_SEND_FAILED if
* mbedtls_test_mock_tcp_send_b failed.
* \retval MBEDTLS_ERR_SSL_WANT_WRITE, if the output queue is full.
*
* This function will also return any error from
* mbedtls_test_ssl_message_queue_push_info.
*/
int mbedtls_test_mock_tcp_send_msg(void *ctx,
const unsigned char *buf, size_t len);
/*
* Receive one message from a given message socket context and return message
* length or an error.
*
* \retval message length, if everything succeeds.
* \retval MBEDTLS_TEST_ERROR_CONTEXT_ERROR, if any of the needed context
* elements or the context itself is null.
* \retval MBEDTLS_TEST_ERROR_RECV_FAILED if
* mbedtls_test_mock_tcp_recv_b failed.
*
* This function will also return any error other than
* MBEDTLS_TEST_ERROR_MESSAGE_TRUNCATED from test_ssl_message_queue_peek_info.
*/
int mbedtls_test_mock_tcp_recv_msg(void *ctx,
unsigned char *buf, size_t buf_len);
#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
/*
* Initializes \p ep_cert structure and assigns it to endpoint
* represented by \p ep.
*
* \retval 0 on success, otherwise error code.
*/
int mbedtls_test_ssl_endpoint_certificate_init(mbedtls_test_ssl_endpoint *ep,
int pk_alg,
int opaque_alg, int opaque_alg2,
int opaque_usage);
/*
* Initializes \p ep structure. It is important to call
* `mbedtls_test_ssl_endpoint_free()` after calling this function
* even if it fails.
*
* \p endpoint_type must be set as MBEDTLS_SSL_IS_SERVER or
* MBEDTLS_SSL_IS_CLIENT.
* \p pk_alg the algorithm to use, currently only MBEDTLS_PK_RSA and
* MBEDTLS_PK_ECDSA are supported.
* \p dtls_context - in case of DTLS - this is the context handling metadata.
* \p input_queue - used only in case of DTLS.
* \p output_queue - used only in case of DTLS.
*
* \retval 0 on success, otherwise error code.
*/
int mbedtls_test_ssl_endpoint_init(
mbedtls_test_ssl_endpoint *ep, int endpoint_type,
mbedtls_test_handshake_test_options *options,
mbedtls_test_message_socket_context *dtls_context,
mbedtls_test_ssl_message_queue *input_queue,
mbedtls_test_ssl_message_queue *output_queue);
/*
* Deinitializes endpoint represented by \p ep.
*/
void mbedtls_test_ssl_endpoint_free(
mbedtls_test_ssl_endpoint *ep,
mbedtls_test_message_socket_context *context);
/*
* This function moves ssl handshake from \p ssl to prescribed \p state.
* /p second_ssl is used as second endpoint and their sockets have to be
* connected before calling this function.
*
* \retval 0 on success, otherwise error code.
*/
int mbedtls_test_move_handshake_to_state(mbedtls_ssl_context *ssl,
mbedtls_ssl_context *second_ssl,
int state);
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
/*
* Helper function setting up inverse record transformations
* using given cipher, hash, EtM mode, authentication tag length,
* and version.
*/
#define CHK(x) \
do \
{ \
if (!(x)) \
{ \
ret = -1; \
goto cleanup; \
} \
} while (0)
#if MBEDTLS_SSL_CID_OUT_LEN_MAX > MBEDTLS_SSL_CID_IN_LEN_MAX
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_IN_LEN_MAX
#else
#define SSL_CID_LEN_MIN MBEDTLS_SSL_CID_OUT_LEN_MAX
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(PSA_WANT_ALG_CBC_NO_PADDING) && defined(PSA_WANT_KEY_TYPE_AES)
int mbedtls_test_psa_cipher_encrypt_helper(mbedtls_ssl_transform *transform,
const unsigned char *iv,
size_t iv_len,
const unsigned char *input,
size_t ilen,
unsigned char *output,
size_t *olen);
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && PSA_WANT_ALG_CBC_NO_PADDING &&
PSA_WANT_KEY_TYPE_AES */
int mbedtls_test_ssl_build_transforms(mbedtls_ssl_transform *t_in,
mbedtls_ssl_transform *t_out,
int cipher_type, int hash_id,
int etm, int tag_mode,
mbedtls_ssl_protocol_version tls_version,
size_t cid0_len,
size_t cid1_len);
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_MAC)
/**
* \param[in,out] record The record to prepare.
* It must contain the data to MAC at offset
* `record->data_offset`, of length
* `record->data_length`.
* On success, write the MAC immediately
* after the data and increment
* `record->data_length` accordingly.
* \param[in,out] transform_out The out transform, typically prepared by
* mbedtls_test_ssl_build_transforms().
* Its HMAC context may be used. Other than that
* it is treated as an input parameter.
*
* \return 0 on success, an `MBEDTLS_ERR_xxx` error code
* or -1 on error.
*/
int mbedtls_test_ssl_prepare_record_mac(mbedtls_record *record,
mbedtls_ssl_transform *transform_out);
#endif /* MBEDTLS_SSL_SOME_SUITES_USE_MAC */
/*
* Populate a session structure for serialization tests.
* Choose dummy values, mostly non-0 to distinguish from the init default.
*/
int mbedtls_test_ssl_tls12_populate_session(mbedtls_ssl_session *session,
int ticket_len,
int endpoint_type,
const char *crt_file);
#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
int mbedtls_test_ssl_tls13_populate_session(mbedtls_ssl_session *session,
int ticket_len,
int endpoint_type);
#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
/*
* Perform data exchanging between \p ssl_1 and \p ssl_2 and check if the
* message was sent in the correct number of fragments.
*
* /p ssl_1 and /p ssl_2 Endpoints represented by mbedtls_ssl_context. Both
* of them must be initialized and connected
* beforehand.
* /p msg_len_1 and /p msg_len_2 specify the size of the message to send.
* /p expected_fragments_1 and /p expected_fragments_2 determine in how many
* fragments the message should be sent.
* expected_fragments is 0: can be used for DTLS testing while the message
* size is larger than MFL. In that case the message
* cannot be fragmented and sent to the second
* endpoint.
* This value can be used for negative tests.
* expected_fragments is 1: can be used for TLS/DTLS testing while the
* message size is below MFL
* expected_fragments > 1: can be used for TLS testing while the message
* size is larger than MFL
*
* \retval 0 on success, otherwise error code.
*/
int mbedtls_test_ssl_exchange_data(
mbedtls_ssl_context *ssl_1,
int msg_len_1, const int expected_fragments_1,
mbedtls_ssl_context *ssl_2,
int msg_len_2, const int expected_fragments_2);
#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
void mbedtls_test_ssl_perform_handshake(
mbedtls_test_handshake_test_options *options);
#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
#if defined(MBEDTLS_TEST_HOOKS)
/*
* Tweak vector lengths in a TLS 1.3 Certificate message
*
* \param[in] buf Buffer containing the Certificate message to tweak
* \param[in]]out] end End of the buffer to parse
* \param tweak Tweak identifier (from 1 to the number of tweaks).
* \param[out] expected_result Error code expected from the parsing function
* \param[out] args Arguments of the MBEDTLS_SSL_CHK_BUF_READ_PTR call that
* is expected to fail. All zeroes if no
* MBEDTLS_SSL_CHK_BUF_READ_PTR failure is expected.
*/
int mbedtls_test_tweak_tls13_certificate_msg_vector_len(
unsigned char *buf, unsigned char **end, int tweak,
int *expected_result, mbedtls_ssl_chk_buf_ptr_args *args);
#endif /* MBEDTLS_TEST_HOOKS */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
int mbedtls_test_ticket_write(
void *p_ticket, const mbedtls_ssl_session *session,
unsigned char *start, const unsigned char *end,
size_t *tlen, uint32_t *ticket_lifetime);
int mbedtls_test_ticket_parse(void *p_ticket, mbedtls_ssl_session *session,
unsigned char *buf, size_t len);
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SRV_C) && \
defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS) && \
defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
int mbedtls_test_get_tls13_ticket(
mbedtls_test_handshake_test_options *client_options,
mbedtls_test_handshake_test_options *server_options,
mbedtls_ssl_session *session);
#endif
#define ECJPAKE_TEST_PWD "bla"
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#define ECJPAKE_TEST_SET_PASSWORD(exp_ret_val) \
ret = (use_opaque_arg) ? \
mbedtls_ssl_set_hs_ecjpake_password_opaque(&ssl, pwd_slot) : \
mbedtls_ssl_set_hs_ecjpake_password(&ssl, pwd_string, pwd_len); \
TEST_EQUAL(ret, exp_ret_val)
#else
#define ECJPAKE_TEST_SET_PASSWORD(exp_ret_val) \
ret = mbedtls_ssl_set_hs_ecjpake_password(&ssl, \
pwd_string, pwd_len); \
TEST_EQUAL(ret, exp_ret_val)
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#define TEST_AVAILABLE_ECC(tls_id_, group_id_, psa_family_, psa_bits_) \
TEST_EQUAL(mbedtls_ssl_get_ecp_group_id_from_tls_id(tls_id_), \
group_id_); \
TEST_EQUAL(mbedtls_ssl_get_tls_id_from_ecp_group_id(group_id_), \
tls_id_); \
TEST_EQUAL(mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id_, \
&psa_type, &psa_bits), PSA_SUCCESS); \
TEST_EQUAL(psa_family_, PSA_KEY_TYPE_ECC_GET_FAMILY(psa_type)); \
TEST_EQUAL(psa_bits_, psa_bits);
#define TEST_UNAVAILABLE_ECC(tls_id_, group_id_, psa_family_, psa_bits_) \
TEST_EQUAL(mbedtls_ssl_get_ecp_group_id_from_tls_id(tls_id_), \
MBEDTLS_ECP_DP_NONE); \
TEST_EQUAL(mbedtls_ssl_get_tls_id_from_ecp_group_id(group_id_), \
0); \
TEST_EQUAL(mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id_, \
&psa_type, &psa_bits), \
PSA_ERROR_NOT_SUPPORTED);
#endif /* MBEDTLS_SSL_TLS_C */
#endif /* SSL_HELPERS_H */
-21
View File
@@ -1,21 +0,0 @@
#!/bin/bash -eu
# make-in-docker.sh
#
# Purpose
# -------
# This runs make in a Docker container.
#
# See also:
# - scripts/docker_env.sh for general Docker prerequisites and other information.
#
# WARNING: the Dockerfile used by this script is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
source tests/scripts/docker_env.sh
run_in_docker make $@
-383
View File
@@ -1,383 +0,0 @@
# Test that SSL sample programs can interoperate with each other
# and with OpenSSL and GnuTLS.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
: ${PROGRAMS_DIR:=../programs/ssl}
# Disable session tickets for ssl_client1 when potentially using TLS 1.3
# until https://github.com/Mbed-TLS/mbedtls/issues/6640 is resolved
# and (if relevant) implemented in ssl_client1.
run_test "Sample: ssl_client1, ssl_server2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server2 tickets=0" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
requires_protocol_version tls12
run_test "Sample: ssl_client1, openssl server, TLS 1.2" \
-P 4433 \
"$O_SRV -tls1_2" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-c "Protocol.*TLSv1.2" \
-S "ERROR" \
-C "error"
requires_protocol_version tls12
run_test "Sample: ssl_client1, gnutls server, TLS 1.2" \
-P 4433 \
"$G_SRV --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "Version: TLS1.2" \
-c "<TD>Protocol version:</TD><TD>TLS1.2</TD>" \
-S "Error" \
-C "error"
# Disable session tickets for ssl_client1 when using TLS 1.3
# until https://github.com/Mbed-TLS/mbedtls/issues/6640 is resolved
# and (if relevant) implemented in ssl_client1.
requires_protocol_version tls13
requires_openssl_tls1_3
run_test "Sample: ssl_client1, openssl server, TLS 1.3" \
-P 4433 \
"$O_NEXT_SRV -tls1_3 -num_tickets 0" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-c "New, TLSv1.3, Cipher is" \
-S "ERROR" \
-C "error"
# Disable session tickets for ssl_client1 when using TLS 1.3
# until https://github.com/Mbed-TLS/mbedtls/issues/6640 is resolved
# and (if relevant) implemented in ssl_client1.
requires_protocol_version tls13
requires_gnutls_tls1_3
run_test "Sample: ssl_client1, gnutls server, TLS 1.3" \
-P 4433 \
"$G_NEXT_SRV --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.3 --noticket" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "Version: TLS1.3" \
-c "<TD>Protocol version:</TD><TD>TLS1.3</TD>" \
-S "Error" \
-C "error"
# The server complains of extra data after it closes the connection
# because the client keeps sending data, so the server receives
# more application data when it expects a new handshake. We consider
# the test a success if both sides have sent and received application
# data, no matter what happens afterwards.
run_test "Sample: dtls_client, ssl_server2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server2 dtls=1 server_addr=localhost" \
"$PROGRAMS_DIR/dtls_client" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-C "error"
# The dtls_client program connects to localhost. This test case fails on
# systems where the name "localhost" resolves to an IPv6 address, but
# the IPv6 connection is not possible. Possible reasons include:
# * OpenSSL is too old (IPv6 support was added in 1.1.0).
# * OpenSSL was built without IPv6 support.
# * A firewall blocks IPv6.
#
# To facilitate working with this test case, have it run with $OPENSSL_NEXT
# which is at least 1.1.1a. At the time it was introduced, this test case
# passed with OpenSSL 1.0.2g on an environment where IPv6 is disabled.
requires_protocol_version dtls12
run_test "Sample: dtls_client, openssl server, DTLS 1.2" \
-P 4433 \
"$O_NEXT_SRV -dtls1_2" \
"$PROGRAMS_DIR/dtls_client" \
0 \
-s "Echo this" \
-c "Echo this" \
-c "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-S "ERROR" \
-C "error"
requires_protocol_version dtls12
run_test "Sample: dtls_client, gnutls server, DTLS 1.2" \
-P 4433 \
"$G_SRV -u --echo --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2" \
"$PROGRAMS_DIR/dtls_client" \
0 \
-s "Server listening" \
-s "[1-9][0-9]* bytes command:" \
-c "Echo this" \
-c "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-S "Error" \
-C "error"
run_test "Sample: ssl_server, ssl_client2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$PROGRAMS_DIR/ssl_client2" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
run_test "Sample: ssl_client1 with ssl_server" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
requires_protocol_version tls12
run_test "Sample: ssl_server, openssl client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$O_CLI -tls1_2" \
0 \
-s "Successful connection using: TLS-" \
-c "Protocol.*TLSv1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls12
run_test "Sample: ssl_server, gnutls client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$G_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2 localhost" \
0 \
-s "Successful connection using: TLS-" \
-c "Description:.*TLS1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_openssl_tls1_3
run_test "Sample: ssl_server, openssl client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$O_NEXT_CLI -tls1_3" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "New, TLSv1.3, Cipher is" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_gnutls_tls1_3
run_test "Sample: ssl_server, gnutls client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_server" \
"$G_NEXT_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.3 localhost" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "Description:.*TLS1.3" \
-S "error" \
-C "ERROR"
run_test "Sample: ssl_fork_server, ssl_client2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$PROGRAMS_DIR/ssl_client2" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
run_test "Sample: ssl_client1 with ssl_fork_server" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
requires_protocol_version tls12
run_test "Sample: ssl_fork_server, openssl client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$O_CLI -tls1_2" \
0 \
-s "Successful connection using: TLS-" \
-c "Protocol.*TLSv1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls12
run_test "Sample: ssl_fork_server, gnutls client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$G_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2 localhost" \
0 \
-s "Successful connection using: TLS-" \
-c "Description:.*TLS1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_openssl_tls1_3
run_test "Sample: ssl_fork_server, openssl client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$O_NEXT_CLI -tls1_3" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "New, TLSv1.3, Cipher is" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_gnutls_tls1_3
run_test "Sample: ssl_fork_server, gnutls client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_fork_server" \
"$G_NEXT_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.3 localhost" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "Description:.*TLS1.3" \
-S "error" \
-C "ERROR"
run_test "Sample: ssl_pthread_server, ssl_client2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$PROGRAMS_DIR/ssl_client2" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
run_test "Sample: ssl_client1 with ssl_pthread_server" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$PROGRAMS_DIR/ssl_client1" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
requires_protocol_version tls12
run_test "Sample: ssl_pthread_server, openssl client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$O_CLI -tls1_2" \
0 \
-s "Successful connection using: TLS-" \
-c "Protocol.*TLSv1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls12
run_test "Sample: ssl_pthread_server, gnutls client, TLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$G_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2 localhost" \
0 \
-s "Successful connection using: TLS-" \
-c "Description:.*TLS1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_openssl_tls1_3
run_test "Sample: ssl_pthread_server, openssl client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$O_NEXT_CLI -tls1_3" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "New, TLSv1.3, Cipher is" \
-S "error" \
-C "ERROR"
requires_protocol_version tls13
requires_gnutls_tls1_3
run_test "Sample: ssl_pthread_server, gnutls client, TLS 1.3" \
-P 4433 \
"$PROGRAMS_DIR/ssl_pthread_server" \
"$G_NEXT_CLI --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.3 localhost" \
0 \
-s "Successful connection using: TLS1-3-" \
-c "Description:.*TLS1.3" \
-S "error" \
-C "ERROR"
run_test "Sample: dtls_client with dtls_server" \
-P 4433 \
"$PROGRAMS_DIR/dtls_server" \
"$PROGRAMS_DIR/dtls_client" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
run_test "Sample: ssl_client2, dtls_server" \
-P 4433 \
"$PROGRAMS_DIR/dtls_server" \
"$PROGRAMS_DIR/ssl_client2 dtls=1" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "[1-9][0-9]* bytes read" \
-c "[1-9][0-9]* bytes written" \
-S "error" \
-C "error"
requires_protocol_version dtls12
run_test "Sample: dtls_server, openssl client, DTLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/dtls_server" \
"$O_CLI -dtls1_2" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "Protocol.*TLSv1.2" \
-S "error" \
-C "ERROR"
requires_protocol_version dtls12
run_test "Sample: dtls_server, gnutls client, DTLS 1.2" \
-P 4433 \
"$PROGRAMS_DIR/dtls_server" \
"$G_CLI -u --priority=NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2 localhost" \
0 \
-s "[1-9][0-9]* bytes read" \
-s "[1-9][0-9]* bytes written" \
-c "Description:.*DTLS1.2" \
-S "error" \
-C "ERROR"
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-6
View File
@@ -1,6 +0,0 @@
### PSA Crypto Client-Server Testing
Everything in this directory should currently be considered experimental. We are adding features and extending CI support for it.
Once stable, of production quality, and being tested by the CI, it will eventually be migrated into
the [MbedTLS framework repository](https://github.com/Mbed-TLS/mbedtls-framework).
-12
View File
@@ -1,12 +0,0 @@
bin/*
*.o
*.so
test/psa_ff_bootstrap.c
test/psa_manifest/*
test/client
test/partition
cscope.out
*.orig
*.swp
*.DS_Store
*psa_ff_bootstrap_*
-81
View File
@@ -1,81 +0,0 @@
CFLAGS += -Wall -Werror -std=c99 -D_XOPEN_SOURCE=1 -D_POSIX_C_SOURCE=200809L
ifeq ($(DEBUG),1)
override CFLAGS += -DDEBUG -O0 -g
endif
CLIENT_LIBS := -Lclient_libs -lpsaclient -lmbedtls -lmbedx509 -lmbedcrypto
SERVER_LIBS := -Lserver_libs -lmbedcrypto
MBEDTLS_ROOT_PATH = ../../..
COMMON_INCLUDE := -I./include -I$(MBEDTLS_ROOT_PATH)/include \
-I$(MBEDTLS_ROOT_PATH)/tf-psa-crypto/include \
-I$(MBEDTLS_ROOT_PATH)/tf-psa-crypto/drivers/builtin/include
GENERATED_H_FILES = include/psa_manifest/manifest.h \
include/psa_manifest/pid.h \
include/psa_manifest/sid.h
LIBPSACLIENT_SRC = src/psa_ff_client.c \
src/psa_sim_crypto_client.c \
src/psa_sim_serialise.c
LIBPSACLIENT_OBJS=$(LIBPSACLIENT_SRC:.c=.o)
PSA_CLIENT_BASE_SRC = $(LIBPSACLIENT_SRC) src/client.c
PSA_CLIENT_FULL_SRC = $(LIBPSACLIENT_SRC) \
$(wildcard src/aut_*.c)
PARTITION_SERVER_BOOTSTRAP = src/psa_ff_bootstrap_TEST_PARTITION.c
PSA_SERVER_SRC = $(PARTITION_SERVER_BOOTSTRAP) \
src/psa_ff_server.c \
src/psa_sim_crypto_server.c \
src/psa_sim_serialise.c
.PHONY: all clean client_libs server_libs
all:
test/seedfile:
dd if=/dev/urandom of=./test/seedfile bs=64 count=1
src/%.o: src/%.c $(GENERATED_H_FILES)
$(CC) $(COMMON_INCLUDE) $(CFLAGS) -c $< $(LDFLAGS) -o $@
client_libs/libpsaclient: $(LIBPSACLIENT_OBJS)
mkdir -p client_libs
$(AR) -src client_libs/libpsaclient.a $(LIBPSACLIENT_OBJS)
test/psa_client_base: $(PSA_CLIENT_BASE_SRC) $(GENERATED_H_FILES) test/seedfile
$(CC) $(COMMON_INCLUDE) $(CFLAGS) $(PSA_CLIENT_BASE_SRC) $(CLIENT_LIBS) $(LDFLAGS) -o $@
test/psa_client_full: $(PSA_CLIENT_FULL_SRC) $(GENERATED_H_FILES) test/seedfile
$(CC) $(COMMON_INCLUDE) $(CFLAGS) $(PSA_CLIENT_FULL_SRC) $(CLIENT_LIBS) $(LDFLAGS) -o $@
test/psa_server: $(PSA_SERVER_SRC) $(GENERATED_H_FILES)
$(CC) $(COMMON_INCLUDE) $(CFLAGS) $(PSA_SERVER_SRC) $(SERVER_LIBS) $(LDFLAGS) -o $@
$(PARTITION_SERVER_BOOTSTRAP) $(GENERATED_H_FILES): src/manifest.json src/server.c
tools/psa_autogen.py src/manifest.json
# Build MbedTLS libraries (crypto, x509 and tls) and copy them locally to
# build client/server applications.
#
# Note: these rules assume that mbedtls_config.h is already configured by all.sh.
# If not using all.sh then the user must do it manually.
client_libs: client_libs/libpsaclient
client_libs server_libs:
$(MAKE) -C $(MBEDTLS_ROOT_PATH)/library CFLAGS="$(CFLAGS)" LDFLAGS="$(LDFLAGS)" libmbedcrypto.a libmbedx509.a libmbedtls.a
mkdir -p $@
cp $(MBEDTLS_ROOT_PATH)/library/libmbed*.a $@/
clean_server_intermediate_files:
rm -f $(PARTITION_SERVER_BOOTSTRAP)
rm -rf include/psa_manifest
clean: clean_server_intermediate_files
rm -f test/psa_client_base test/psa_client_full test/psa_server
rm -rf client_libs server_libs
rm -f test/psa_service_* test/psa_notify_* test/*.log
rm -f test/seedfile
-61
View File
@@ -1,61 +0,0 @@
# psasim
This tool simulates a PSA Firmware Framework implementation.
It allows you to develop secure partitions and their clients on a desktop computer.
It should be able to run on all systems that support POSIX and System V IPC:
e.g. macOS, Linux, FreeBSD, and perhaps Windows 10 WSL2.
Please note that the code in this directory is maintained by the Mbed TLS / PSA Crypto project solely for the purpose of testing the use of Mbed TLS with client/service separation. We do not recommend using this code for any other purpose. In particular:
* This simulator is not intended to pass or demonstrate compliance.
* This code is only intended for simulation and does not have any security goals. It does not isolate services from clients.
## Building
To build and run the test program make sure you have `make`, `python` and a
C compiler installed and then enter the following commands:
```sh
make run
```
Optionally the `DEBUG=1` command line option can be enabled to increase verbosity:
```sh
make DEBUG=1 run
```
Once done with the test, it is possible to clean all the generated files with:
```sh
make clean
```
## Features
The implemented API is intended to be compliant with PSA-FF 1.0.0 with the exception of a couple of things that are a work in progress:
* `psa_notify` support
* "strict" policy in manifest
The only supported "interrupts" are POSIX signals, which act
as a "virtual interrupt".
The standard PSA RoT APIs are not included (e.g. cryptography, attestation, lifecycle etc).
## Design
The code is designed to be readable rather than fast or secure.
In this implementation only one message is delivered to a
RoT service at a time.
The code is not thread-safe.
## Unsupported features
Because this is a simulator there are a few things that
can't be reasonably emulated:
* Manifest MMIO regions are unsupported
* Manifest priority field is ignored
* Partition IDs are in fact POSIX `pid_t`, which are only assigned at runtime,
making it infeasible to populate pid.h with correct values.
@@ -1,75 +0,0 @@
/* PSA Firmware Framework client header for psasim. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef __PSA_CLIENT_H__
#define __PSA_CLIENT_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include "psa/crypto.h"
#include "error_ext.h"
/*********************** PSA Client Macros and Types *************************/
#define PSA_FRAMEWORK_VERSION (0x0100)
#define PSA_VERSION_NONE (0)
/* PSA response types */
#define PSA_CONNECTION_REFUSED PSA_ERROR_CONNECTION_REFUSED
#define PSA_CONNECTION_BUSY PSA_ERROR_CONNECTION_BUSY
#define PSA_DROP_CONNECTION PSA_ERROR_PROGRAMMER_ERROR
/* PSA message handles */
#define PSA_NULL_HANDLE ((psa_handle_t) 0)
#define PSA_HANDLE_IS_VALID(handle) ((psa_handle_t) (handle) > 0)
#define PSA_HANDLE_TO_ERROR(handle) ((psa_status_t) (handle))
/**
* A read-only input memory region provided to an RoT Service.
*/
typedef struct psa_invec {
const void *base;
size_t len;
} psa_invec;
/**
* A writable output memory region provided to an RoT Service.
*/
typedef struct psa_outvec {
void *base;
size_t len;
} psa_outvec;
/*************************** PSA Client API **********************************/
uint32_t psa_framework_version(void);
uint32_t psa_version(uint32_t sid);
psa_handle_t psa_connect(uint32_t sid, uint32_t version);
psa_status_t psa_call(psa_handle_t handle,
int32_t type,
const psa_invec *in_vec,
size_t in_len,
psa_outvec *out_vec,
size_t out_len);
void psa_close(psa_handle_t handle);
#ifdef __cplusplus
}
#endif
#endif /* __PSA_CLIENT_H__ */
@@ -1,52 +0,0 @@
/* Common definitions used for clients and services */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef _COMMON_H_
#define _COMMON_H_
#include <stdint.h>
#include <stddef.h>
/* Increasing this might break on some platforms */
#define MAX_FRAGMENT_SIZE 200
#define CONNECT_REQUEST 1
#define CALL_REQUEST 2
#define CLOSE_REQUEST 3
#define VERSION_REQUEST 4
#define READ_REQUEST 5
#define READ_RESPONSE 6
#define WRITE_REQUEST 7
#define WRITE_RESPONSE 8
#define SKIP_REQUEST 9
#define PSA_REPLY 10
#define NON_SECURE (1 << 30)
typedef int32_t psa_handle_t;
#define PSA_MAX_IOVEC (4u)
#define PSA_IPC_CALL (0)
struct message_text {
int qid;
int32_t psa_type;
char buf[MAX_FRAGMENT_SIZE];
};
struct message {
long message_type;
struct message_text message_text;
};
typedef struct vector_sizes {
size_t invec_sizes[PSA_MAX_IOVEC];
size_t outvec_sizes[PSA_MAX_IOVEC];
} vector_sizes_t;
#endif /* _COMMON_H_ */
@@ -1,19 +0,0 @@
/* PSA status codes used by psasim. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef PSA_ERROR_H
#define PSA_ERROR_H
#include <stdint.h>
#include "common.h"
#define PSA_ERROR_PROGRAMMER_ERROR ((psa_status_t) -129)
#define PSA_ERROR_CONNECTION_REFUSED ((psa_status_t) -130)
#define PSA_ERROR_CONNECTION_BUSY ((psa_status_t) -131)
#endif
@@ -1,15 +0,0 @@
/* Declarations of internal functions. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <stdint.h>
#include <service.h>
void raise_signal(psa_signal_t signal);
void __init_psasim(const char **array,
int size,
const int allow_ns_clients_array[32],
const uint32_t versions[32],
const int strict_policy_array[32]);
@@ -1,17 +0,0 @@
/* PSA lifecycle states used by psasim. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#define PSA_LIFECYCLE_PSA_STATE_MASK (0xff00u)
#define PSA_LIFECYCLE_IMP_STATE_MASK (0x00ffu)
#define PSA_LIFECYCLE_UNKNOWN (0x0000u)
#define PSA_LIFECYCLE_ASSEMBLY_AND_TEST (0x1000u)
#define PSA_LIFECYCLE_PSA_ROT_PROVISIONING (0x2000u)
#define PSA_LIFECYCLE_SECURED (0x3000u)
#define PSA_LIFECYCLE_NON_PSA_ROT_DEBUG (0x4000u)
#define PSA_LIFECYCLE_RECOVERABLE_PSA_ROT_DEBUG (0x5000u)
#define PSA_LIFECYCLE_DECOMMISSIONED (0x6000u)
#define psa_rot_lifecycle_state(void) PSA_LIFECYCLE_UNKNOWN
@@ -1,253 +0,0 @@
/* PSA Firmware Framework service header for psasim. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef __PSA_SERVICE_H__
#define __PSA_SERVICE_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include "common.h"
#include "psa/crypto.h"
/********************** PSA Secure Partition Macros and Types ****************/
/* PSA wait timeouts */
#define PSA_POLL (0x00000000u)
#define PSA_BLOCK (0x80000000u)
/* A mask value that includes all Secure Partition signals */
#define PSA_WAIT_ANY (~0u)
/* Doorbell signal */
#define PSA_DOORBELL (0x00000008u)
/* PSA message types */
#define PSA_IPC_CONNECT (-1)
#define PSA_IPC_DISCONNECT (-2)
/* Return code from psa_get() */
#define PSA_ERR_NOMSG (INT32_MIN + 3)
/* Store a set of one or more Secure Partition signals */
typedef uint32_t psa_signal_t;
/**
* Describe a message received by an RoT Service after calling \ref psa_get().
*/
typedef struct psa_msg_t {
uint32_t type; /* One of the following values:
* \ref PSA_IPC_CONNECT
* \ref PSA_IPC_CALL
* \ref PSA_IPC_DISCONNECT
*/
psa_handle_t handle; /* A reference generated by the SPM to the
* message returned by psa_get().
*/
int32_t client_id; /* Partition ID of the sender of the message */
void *rhandle; /* Be useful for binding a connection to some
* application-specific data or function
* pointer within the RoT Service
* implementation.
*/
size_t in_size[PSA_MAX_IOVEC]; /* Provide the size of each client input
* vector in bytes.
*/
size_t out_size[PSA_MAX_IOVEC];/* Provide the size of each client output
* vector in bytes.
*/
} psa_msg_t;
/************************* PSA Secure Partition API **************************/
/**
* \brief Return the Secure Partition interrupt signals that have been asserted
* from a subset of signals provided by the caller.
*
* \param[in] signal_mask A set of signals to query. Signals that are not
* in this set will be ignored.
* \param[in] timeout Specify either blocking \ref PSA_BLOCK or
* polling \ref PSA_POLL operation.
*
* \retval >0 At least one signal is asserted.
* \retval 0 No signals are asserted. This is only seen when
* a polling timeout is used.
*/
psa_signal_t psa_wait(psa_signal_t signal_mask, uint32_t timeout);
/**
* \brief Retrieve the message which corresponds to a given RoT Service signal
* and remove the message from the RoT Service queue.
*
* \param[in] signal The signal value for an asserted RoT Service.
* \param[out] msg Pointer to \ref psa_msg_t object for receiving
* the message.
*
* \retval PSA_SUCCESS Success, *msg will contain the delivered
* message.
* \retval PSA_ERR_NOMSG Message could not be delivered.
* \retval "Does not return" The call is invalid because one or more of the
* following are true:
* \arg signal has more than a single bit set.
* \arg signal does not correspond to an RoT Service.
* \arg The RoT Service signal is not currently
* asserted.
* \arg The msg pointer provided is not a valid memory
* reference.
*/
psa_status_t psa_get(psa_signal_t signal, psa_msg_t *msg);
/**
* \brief Associate some RoT Service private data with a client connection.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] rhandle Reverse handle allocated by the RoT Service.
*
* \retval void Success, rhandle will be provided with all
* subsequent messages delivered on this
* connection.
* \retval "Does not return" msg_handle is invalid.
*/
void psa_set_rhandle(psa_handle_t msg_handle, void *rhandle);
/**
* \brief Read a message parameter or part of a message parameter from a client
* input vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] invec_idx Index of the input vector to read from. Must be
* less than \ref PSA_MAX_IOVEC.
* \param[out] buffer Buffer in the Secure Partition to copy the
* requested data to.
* \param[in] num_bytes Maximum number of bytes to be read from the
* client input vector.
*
* \retval >0 Number of bytes copied.
* \retval 0 There was no remaining data in this input
* vector.
* \retval "Does not return" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a
* \ref PSA_IPC_CALL message.
* \arg invec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
* \arg the memory reference for buffer is invalid or
* not writable.
*/
size_t psa_read(psa_handle_t msg_handle, uint32_t invec_idx,
void *buffer, size_t num_bytes);
/**
* \brief Skip over part of a client input vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] invec_idx Index of input vector to skip from. Must be
* less than \ref PSA_MAX_IOVEC.
* \param[in] num_bytes Maximum number of bytes to skip in the client
* input vector.
*
* \retval >0 Number of bytes skipped.
* \retval 0 There was no remaining data in this input
* vector.
* \retval "Does not return" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a
* \ref PSA_IPC_CALL message.
* \arg invec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
*/
size_t psa_skip(psa_handle_t msg_handle, uint32_t invec_idx, size_t num_bytes);
/**
* \brief Write a message response to a client output vector.
*
* \param[in] msg_handle Handle for the client's message.
* \param[out] outvec_idx Index of output vector in message to write to.
* Must be less than \ref PSA_MAX_IOVEC.
* \param[in] buffer Buffer with the data to write.
* \param[in] num_bytes Number of bytes to write to the client output
* vector.
*
* \retval void Success
* \retval "Does not return" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg msg_handle does not refer to a
* \ref PSA_IPC_CALL message.
* \arg outvec_idx is equal to or greater than
* \ref PSA_MAX_IOVEC.
* \arg The memory reference for buffer is invalid.
* \arg The call attempts to write data past the end
* of the client output vector.
*/
void psa_write(psa_handle_t msg_handle, uint32_t outvec_idx,
const void *buffer, size_t num_bytes);
/**
* \brief Complete handling of a specific message and unblock the client.
*
* \param[in] msg_handle Handle for the client's message.
* \param[in] status Message result value to be reported to the
* client.
*
* \retval void Success.
* \retval "Does not return" The call is invalid, one or more of the
* following are true:
* \arg msg_handle is invalid.
* \arg An invalid status code is specified for the
* type of message.
*/
void psa_reply(psa_handle_t msg_handle, psa_status_t status);
/**
* \brief Send a PSA_DOORBELL signal to a specific Secure Partition.
*
* \param[in] partition_id Secure Partition ID of the target partition.
*
* \retval void Success.
* \retval "Does not return" partition_id does not correspond to a Secure
* Partition.
*/
void psa_notify(int32_t partition_id);
/**
* \brief Clear the PSA_DOORBELL signal.
*
* \retval void Success.
* \retval "Does not return" The Secure Partition's doorbell signal is not
* currently asserted.
*/
void psa_clear(void);
/**
* \brief Inform the SPM that an interrupt has been handled (end of interrupt).
*
* \param[in] irq_signal The interrupt signal that has been processed.
*
* \retval void Success.
* \retval "Does not return" The call is invalid, one or more of the
* following are true:
* \arg irq_signal is not an interrupt signal.
* \arg irq_signal indicates more than one signal.
* \arg irq_signal is not currently asserted.
*/
void psa_eoi(psa_signal_t irq_signal);
#define psa_panic(X) abort();
#ifdef __cplusplus
}
#endif
#endif /* __PSA_SERVICE_H__ */
@@ -1,31 +0,0 @@
/* Common definitions used for clients and services */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "service.h"
#define PRINT(fmt, ...) \
fprintf(stdout, fmt "\n", ##__VA_ARGS__)
#if defined(DEBUG)
#define INFO(fmt, ...) \
fprintf(stdout, "Info (%s - %d): " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#else /* !DEBUG */
#define INFO(...)
#endif /* DEBUG*/
#define ERROR(fmt, ...) \
fprintf(stderr, "Error (%s - %d): " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__)
#define FATAL(fmt, ...) \
{ \
fprintf(stderr, "Fatal (%s - %d): " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__); \
abort(); \
}
#define PROJECT_ID 'M'
#define PATHNAMESIZE 256
#define TMP_FILE_BASE_PATH "./"
@@ -1,71 +0,0 @@
/**
* This is the base AUT that exectues all other AUTs meant to test PSA APIs
* through PSASIM.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/* First include Mbed TLS headers to get the Mbed TLS configuration and
* platform definitions that we'll use in this program. Also include
* standard C headers for functions we'll use here. */
#include "mbedtls/build_info.h"
#include "psa/crypto.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int psa_hash_compute_main(void);
int psa_hash_main(void);
int psa_aead_encrypt_main(char *cipher_name);
int psa_aead_encrypt_decrypt_main(void);
int psa_cipher_encrypt_decrypt_main(void);
int psa_asymmetric_encrypt_decrypt_main(void);
int psa_random_main(void);
int psa_mac_main(void);
int psa_key_agreement_main(void);
int psa_sign_verify_main(void);
int psa_hkdf_main(void);
#define TEST_MODULE(main_func) \
do { \
char title[128] = { 0 }; \
char separator[128] = { 0 }; \
int title_len = snprintf(title, sizeof(title), "=== Test: %s ===", #main_func); \
memset(separator, '=', title_len); \
printf("%s\n%s\n%s\n", separator, title, separator); \
ret = main_func; \
if (ret != 0) { \
goto exit; \
} \
} while (0)
int main()
{
int ret;
TEST_MODULE(psa_hash_compute_main());
TEST_MODULE(psa_hash_main());
TEST_MODULE(psa_aead_encrypt_main("aes128-gcm"));
TEST_MODULE(psa_aead_encrypt_main("aes256-gcm"));
TEST_MODULE(psa_aead_encrypt_main("aes128-gcm_8"));
TEST_MODULE(psa_aead_encrypt_main("chachapoly"));
TEST_MODULE(psa_aead_encrypt_decrypt_main());
TEST_MODULE(psa_cipher_encrypt_decrypt_main());
TEST_MODULE(psa_asymmetric_encrypt_decrypt_main());
TEST_MODULE(psa_random_main());
TEST_MODULE(psa_mac_main());
TEST_MODULE(psa_key_agreement_main());
TEST_MODULE(psa_sign_verify_main());
TEST_MODULE(psa_hkdf_main());
exit:
return (ret != 0) ? 1 : 0;
}
@@ -1,227 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "psa/crypto.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
const char usage[] =
"Usage: aead_demo [aes128-gcm|aes256-gcm|aes128-gcm_8|chachapoly]";
/* Dummy data for encryption: IV/nonce, additional data, 2-part message */
const unsigned char iv1[12] = { 0x00 };
const unsigned char add_data1[] = { 0x01, 0x02 };
const unsigned char msg1_part1[] = { 0x03, 0x04 };
const unsigned char msg1_part2[] = { 0x05, 0x06, 0x07 };
/* Dummy data (2nd message) */
const unsigned char iv2[12] = { 0x10 };
const unsigned char add_data2[] = { 0x11, 0x12 };
const unsigned char msg2_part1[] = { 0x13, 0x14 };
const unsigned char msg2_part2[] = { 0x15, 0x16, 0x17 };
/* Maximum total size of the messages */
#define MSG1_SIZE (sizeof(msg1_part1) + sizeof(msg1_part2))
#define MSG2_SIZE (sizeof(msg2_part1) + sizeof(msg2_part2))
#define MSG_MAX_SIZE (MSG1_SIZE > MSG2_SIZE ? MSG1_SIZE : MSG2_SIZE)
/* Dummy key material - never do this in production!
* 32-byte is enough to all the key size supported by this program. */
const unsigned char key_bytes[32] = { 0x2a };
/* Print the contents of a buffer in hex */
void print_buf(const char *title, uint8_t *buf, size_t len)
{
printf("%s:", title);
for (size_t i = 0; i < len; i++) {
printf(" %02x", buf[i]);
}
printf("\n");
}
/* Run a PSA function and bail out if it fails.
* The symbolic name of the error code can be recovered using:
* programs/psa/psa_constant_name status <value> */
#define PSA_CHECK(expr) \
do \
{ \
status = (expr); \
if (status != PSA_SUCCESS) \
{ \
printf("Error %d at line %d: %s\n", \
(int) status, \
__LINE__, \
#expr); \
goto exit; \
} \
} \
while (0)
/*
* Prepare encryption material:
* - interpret command-line argument
* - set up key
* - outputs: key and algorithm, which together hold all the information
*/
static psa_status_t aead_prepare(const char *info,
psa_key_id_t *key,
psa_algorithm_t *alg)
{
psa_status_t status;
/* Convert arg to alg + key_bits + key_type */
size_t key_bits;
psa_key_type_t key_type;
if (strcmp(info, "aes128-gcm") == 0) {
*alg = PSA_ALG_GCM;
key_bits = 128;
key_type = PSA_KEY_TYPE_AES;
} else if (strcmp(info, "aes256-gcm") == 0) {
*alg = PSA_ALG_GCM;
key_bits = 256;
key_type = PSA_KEY_TYPE_AES;
} else if (strcmp(info, "aes128-gcm_8") == 0) {
*alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG(PSA_ALG_GCM, 8);
key_bits = 128;
key_type = PSA_KEY_TYPE_AES;
} else if (strcmp(info, "chachapoly") == 0) {
*alg = PSA_ALG_CHACHA20_POLY1305;
key_bits = 256;
key_type = PSA_KEY_TYPE_CHACHA20;
} else {
puts(usage);
return PSA_ERROR_INVALID_ARGUMENT;
}
/* Prepare key attributes */
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
psa_set_key_algorithm(&attributes, *alg);
psa_set_key_type(&attributes, key_type);
psa_set_key_bits(&attributes, key_bits); // optional
/* Import key */
PSA_CHECK(psa_import_key(&attributes, key_bytes, key_bits / 8, key));
exit:
return status;
}
/*
* Print out some information.
*
* All of this information was present in the command line argument, but his
* function demonstrates how each piece can be recovered from (key, alg).
*/
static void aead_info(psa_key_id_t key, psa_algorithm_t alg)
{
psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT;
(void) psa_get_key_attributes(key, &attr);
psa_key_type_t key_type = psa_get_key_type(&attr);
size_t key_bits = psa_get_key_bits(&attr);
psa_algorithm_t base_alg = PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(alg);
size_t tag_len = PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg);
const char *type_str = key_type == PSA_KEY_TYPE_AES ? "AES"
: key_type == PSA_KEY_TYPE_CHACHA20 ? "Chacha"
: "???";
const char *base_str = base_alg == PSA_ALG_GCM ? "GCM"
: base_alg == PSA_ALG_CHACHA20_POLY1305 ? "ChachaPoly"
: "???";
printf("%s, %u, %s, %u\n",
type_str, (unsigned) key_bits, base_str, (unsigned) tag_len);
}
/*
* Encrypt a 2-part message.
*/
static int aead_encrypt(psa_key_id_t key, psa_algorithm_t alg,
const unsigned char *iv, size_t iv_len,
const unsigned char *ad, size_t ad_len,
const unsigned char *part1, size_t part1_len,
const unsigned char *part2, size_t part2_len)
{
psa_status_t status;
size_t olen, olen_tag;
unsigned char out[PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(MSG_MAX_SIZE)];
unsigned char *p = out, *end = out + sizeof(out);
unsigned char tag[PSA_AEAD_TAG_MAX_SIZE];
psa_aead_operation_t op = PSA_AEAD_OPERATION_INIT;
PSA_CHECK(psa_aead_encrypt_setup(&op, key, alg));
PSA_CHECK(psa_aead_set_nonce(&op, iv, iv_len));
PSA_CHECK(psa_aead_update_ad(&op, ad, ad_len));
PSA_CHECK(psa_aead_update(&op, part1, part1_len, p, end - p, &olen));
p += olen;
PSA_CHECK(psa_aead_update(&op, part2, part2_len, p, end - p, &olen));
p += olen;
PSA_CHECK(psa_aead_finish(&op, p, end - p, &olen,
tag, sizeof(tag), &olen_tag));
p += olen;
memcpy(p, tag, olen_tag);
p += olen_tag;
olen = p - out;
print_buf("out", out, olen);
exit:
psa_aead_abort(&op); // required on errors, harmless on success
return status;
}
/*
* AEAD demo: set up key/alg, print out info, encrypt messages.
*/
static psa_status_t aead_demo(const char *info)
{
psa_status_t status;
psa_key_id_t key;
psa_algorithm_t alg;
PSA_CHECK(aead_prepare(info, &key, &alg));
aead_info(key, alg);
PSA_CHECK(aead_encrypt(key, alg,
iv1, sizeof(iv1), add_data1, sizeof(add_data1),
msg1_part1, sizeof(msg1_part1),
msg1_part2, sizeof(msg1_part2)));
PSA_CHECK(aead_encrypt(key, alg,
iv2, sizeof(iv2), add_data2, sizeof(add_data2),
msg2_part1, sizeof(msg2_part1),
msg2_part2, sizeof(msg2_part2)));
exit:
psa_destroy_key(key);
return status;
}
/*
* Main function
*/
int psa_aead_encrypt_main(char *cipher_name)
{
psa_status_t status = PSA_SUCCESS;
/* Initialize the PSA crypto library. */
PSA_CHECK(psa_crypto_init());
/* Run the demo */
PSA_CHECK(aead_demo(cipher_name));
/* Deinitialize the PSA crypto library. */
mbedtls_psa_crypto_free();
exit:
return status == PSA_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
}
@@ -1,109 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 500
static void print_bytestr(const uint8_t *bytes, size_t len)
{
for (unsigned int idx = 0; idx < len; idx++) {
printf("%02X", bytes[idx]);
}
}
int psa_aead_encrypt_decrypt_main(void)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
uint8_t encrypt[BUFFER_SIZE] = { 0 };
uint8_t decrypt[BUFFER_SIZE] = { 0 };
const uint8_t plaintext[] = "Hello World!";
const uint8_t key_bytes[32] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
uint8_t nonce[PSA_AEAD_NONCE_LENGTH(PSA_KEY_TYPE_AES, PSA_ALG_CCM)];
size_t nonce_length = sizeof(nonce);
size_t ciphertext_length;
size_t plaintext_length;
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes,
PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_CCM);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 256);
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
status = psa_generate_random(nonce, nonce_length);
if (status != PSA_SUCCESS) {
printf("psa_generate_random failed\n");
return EXIT_FAILURE;
}
status = psa_aead_encrypt(key_id, // key
PSA_ALG_CCM, // algorithm
nonce, nonce_length, // nonce
NULL, 0, // additional data
plaintext, sizeof(plaintext), // plaintext
encrypt, sizeof(encrypt), // ciphertext
&ciphertext_length); // length of output
if (status != PSA_SUCCESS) {
printf("psa_aead_encrypt failed\n");
return EXIT_FAILURE;
}
printf("AES-CCM encryption:\n");
printf("- Plaintext: '%s':\n", plaintext);
printf("- Key: ");
print_bytestr(key_bytes, sizeof(key_bytes));
printf("\n- Nonce: ");
print_bytestr(nonce, nonce_length);
printf("\n- No additional data\n");
printf("- Ciphertext:\n");
for (size_t j = 0; j < ciphertext_length; j++) {
if (j % 8 == 0) {
printf("\n ");
}
printf("%02x ", encrypt[j]);
}
printf("\n");
status = psa_aead_decrypt(key_id, // key
PSA_ALG_CCM, // algorithm
nonce, nonce_length, // nonce
NULL, 0, // additional data
encrypt, ciphertext_length, // ciphertext
decrypt, sizeof(decrypt), // plaintext
&plaintext_length); // length of output
if (status != PSA_SUCCESS) {
printf("psa_aead_decrypt failed\n");
return EXIT_FAILURE;
}
if (memcmp(plaintext, decrypt, sizeof(plaintext)) != 0) {
printf("\nEncryption/Decryption failed!\n");
} else {
printf("\nEncryption/Decryption successful!\n");
}
psa_destroy_key(key_id);
mbedtls_psa_crypto_free();
return 0;
}
@@ -1,81 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define KEY_BITS 4096
#define BUFFER_SIZE PSA_BITS_TO_BYTES(KEY_BITS)
static void print_bytestr(const uint8_t *bytes, size_t len)
{
for (unsigned int idx = 0; idx < len; idx++) {
printf("%02X", bytes[idx]);
}
}
int psa_asymmetric_encrypt_decrypt_main(void)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
uint8_t original[BUFFER_SIZE/2] = { 0 };
uint8_t encrypt[BUFFER_SIZE] = { 0 };
uint8_t decrypt[BUFFER_SIZE] = { 0 };
size_t encrypted_length;
size_t decrypted_length;
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
status = psa_generate_random(original, sizeof(original));
if (status != PSA_SUCCESS) {
printf("psa_generate_random() failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes,
PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_RSA_PKCS1V15_CRYPT);
psa_set_key_type(&attributes, PSA_KEY_TYPE_RSA_KEY_PAIR);
psa_set_key_bits(&attributes, KEY_BITS);
status = psa_generate_key(&attributes, &key_id);
if (status != PSA_SUCCESS) {
printf("psa_generate_key failed (%d)\n", status);
return EXIT_FAILURE;
}
status = psa_asymmetric_encrypt(key_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
original, sizeof(original), NULL, 0,
encrypt, sizeof(encrypt), &encrypted_length);
if (status != PSA_SUCCESS) {
printf("psa_asymmetric_encrypt failed (%d)\n", status);
return EXIT_FAILURE;
}
status = psa_asymmetric_decrypt(key_id, PSA_ALG_RSA_PKCS1V15_CRYPT,
encrypt, encrypted_length, NULL, 0,
decrypt, sizeof(decrypt), &decrypted_length);
if (status != PSA_SUCCESS) {
printf("psa_cipher_decrypt failed (%d)\n", status);
return EXIT_FAILURE;
}
if (memcmp(original, decrypt, sizeof(original)) != 0) {
printf("\nEncryption/Decryption failed!\n");
} else {
printf("\nEncryption/Decryption successful!\n");
}
psa_destroy_key(key_id);
mbedtls_psa_crypto_free();
return 0;
}
@@ -1,81 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 4096
static void print_bytestr(const uint8_t *bytes, size_t len)
{
for (unsigned int idx = 0; idx < len; idx++) {
printf("%02X", bytes[idx]);
}
}
int psa_cipher_encrypt_decrypt_main(void)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
uint8_t original[BUFFER_SIZE] = { 0 };
uint8_t encrypt[BUFFER_SIZE] = { 0 };
uint8_t decrypt[BUFFER_SIZE] = { 0 };
const uint8_t key_bytes[32] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
size_t encrypted_length;
size_t decrypted_length;
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
status = psa_generate_random(original, sizeof(original));
if (status != PSA_SUCCESS) {
printf("psa_generate_random() failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes,
PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_ECB_NO_PADDING);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 256);
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
status = psa_cipher_encrypt(key_id, PSA_ALG_ECB_NO_PADDING,
original, sizeof(original),
encrypt, sizeof(encrypt), &encrypted_length);
if (status != PSA_SUCCESS) {
printf("psa_cipher_encrypt failed\n");
return EXIT_FAILURE;
}
status = psa_cipher_decrypt(key_id, PSA_ALG_ECB_NO_PADDING,
encrypt, encrypted_length,
decrypt, sizeof(decrypt), &decrypted_length);
if (status != PSA_SUCCESS) {
printf("psa_cipher_decrypt failed\n");
return EXIT_FAILURE;
}
if (memcmp(original, decrypt, sizeof(original)) != 0) {
printf("\nEncryption/Decryption failed!\n");
} else {
printf("\nEncryption/Decryption successful!\n");
}
psa_destroy_key(key_id);
mbedtls_psa_crypto_free();
return 0;
}
@@ -1,167 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#define HASH_ALG PSA_ALG_SHA_256
static const uint8_t sample_message[] = "Hello World!";
/* sample_message is terminated with a null byte which is not part of
* the message itself so we make sure to subtract it in order to get
* the message length. */
static const size_t sample_message_length = sizeof(sample_message) - 1;
#define EXPECTED_HASH_VALUE { \
0x7f, 0x83, 0xb1, 0x65, 0x7f, 0xf1, 0xfc, 0x53, 0xb9, 0x2d, 0xc1, 0x81, \
0x48, 0xa1, 0xd6, 0x5d, 0xfc, 0x2d, 0x4b, 0x1f, 0xa3, 0xd6, 0x77, 0x28, \
0x4a, 0xdd, 0xd2, 0x00, 0x12, 0x6d, 0x90, 0x69 \
}
static const uint8_t expected_hash[] = EXPECTED_HASH_VALUE;
static const size_t expected_hash_len = sizeof(expected_hash);
int psa_hash_main(void)
{
psa_status_t status;
uint8_t hash[PSA_HASH_LENGTH(HASH_ALG)];
size_t hash_length;
psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
psa_hash_operation_t cloned_hash_operation = PSA_HASH_OPERATION_INIT;
mbedtls_printf("PSA Crypto API: SHA-256 example\n\n");
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
/* Compute hash using multi-part operation */
status = psa_hash_setup(&hash_operation, HASH_ALG);
if (status == PSA_ERROR_NOT_SUPPORTED) {
mbedtls_printf("unknown hash algorithm supplied\n");
return EXIT_FAILURE;
} else if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_setup failed\n");
return EXIT_FAILURE;
}
status = psa_hash_update(&hash_operation, sample_message, sample_message_length);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_update failed\n");
goto cleanup;
}
status = psa_hash_clone(&hash_operation, &cloned_hash_operation);
if (status != PSA_SUCCESS) {
mbedtls_printf("PSA hash clone failed\n");
goto cleanup;
}
status = psa_hash_finish(&hash_operation, hash, sizeof(hash), &hash_length);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_finish failed\n");
goto cleanup;
}
/* Check the result of the operation against the sample */
if (hash_length != expected_hash_len ||
(memcmp(hash, expected_hash, expected_hash_len) != 0)) {
mbedtls_printf("Multi-part hash operation gave the wrong result!\n\n");
goto cleanup;
}
status =
psa_hash_verify(&cloned_hash_operation, expected_hash,
expected_hash_len);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_verify failed\n");
goto cleanup;
} else {
mbedtls_printf("Multi-part hash operation successful!\n");
}
/* A bit of white-box testing: ensure that we can abort an operation more
* times than there are operation slots on the simulator server.
*/
for (int i = 0; i < 200; i++) {
/* This should be a no-op */
status = psa_hash_abort(&hash_operation);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_abort failed\n");
goto cleanup;
}
}
/* Compute hash using multi-part operation using the same operation struct */
status = psa_hash_setup(&hash_operation, HASH_ALG);
if (status == PSA_ERROR_NOT_SUPPORTED) {
mbedtls_printf("unknown hash algorithm supplied\n");
goto cleanup;
} else if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_setup failed: %d\n", status);
goto cleanup;
}
status = psa_hash_update(&hash_operation, sample_message, sample_message_length);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_update failed\n");
goto cleanup;
}
/* Don't use psa_hash_finish() when going to check against an expected result */
status = psa_hash_verify(&hash_operation, expected_hash, expected_hash_len);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_verify failed: %d\n", status);
goto cleanup;
} else {
mbedtls_printf("Second multi-part hash operation successful!\n");
}
/* Clear local variables prior to one-shot hash demo */
memset(hash, 0, sizeof(hash));
hash_length = 0;
/* Compute hash using one-shot function call */
status = psa_hash_compute(HASH_ALG,
sample_message, sample_message_length,
hash, sizeof(hash),
&hash_length);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_compute failed\n");
goto cleanup;
}
if (hash_length != expected_hash_len ||
(memcmp(hash, expected_hash, expected_hash_len) != 0)) {
mbedtls_printf("One-shot hash operation gave the wrong result!\n\n");
goto cleanup;
}
mbedtls_printf("One-shot hash operation successful!\n\n");
/* Print out result */
mbedtls_printf("The SHA-256( '%s' ) is: ", sample_message);
for (size_t j = 0; j < expected_hash_len; j++) {
mbedtls_printf("%02x", hash[j]);
}
mbedtls_printf("\n");
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
cleanup:
psa_hash_abort(&hash_operation);
psa_hash_abort(&cloned_hash_operation);
return EXIT_FAILURE;
}
@@ -1,81 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#define HASH_ALG PSA_ALG_SHA_256
static const uint8_t sample_message[] = "Hello World!";
/* sample_message is terminated with a null byte which is not part of
* the message itself so we make sure to subtract it in order to get
* the message length. */
static const size_t sample_message_length = sizeof(sample_message) - 1;
#define EXPECTED_HASH_VALUE { \
0x7f, 0x83, 0xb1, 0x65, 0x7f, 0xf1, 0xfc, 0x53, 0xb9, 0x2d, 0xc1, 0x81, \
0x48, 0xa1, 0xd6, 0x5d, 0xfc, 0x2d, 0x4b, 0x1f, 0xa3, 0xd6, 0x77, 0x28, \
0x4a, 0xdd, 0xd2, 0x00, 0x12, 0x6d, 0x90, 0x69 \
}
static const uint8_t expected_hash[] = EXPECTED_HASH_VALUE;
static const size_t expected_hash_len = sizeof(expected_hash);
int psa_hash_compute_main(void)
{
psa_status_t status;
uint8_t hash[PSA_HASH_LENGTH(HASH_ALG)];
size_t hash_length;
mbedtls_printf("PSA Crypto API: SHA-256 example\n\n");
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
/* Clear local variables prior to one-shot hash demo */
memset(hash, 0, sizeof(hash));
hash_length = 0;
/* Compute hash using one-shot function call */
status = psa_hash_compute(HASH_ALG,
sample_message, sample_message_length,
hash, sizeof(hash),
&hash_length);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_hash_compute failed\n");
goto cleanup;
}
if (hash_length != expected_hash_len ||
(memcmp(hash, expected_hash, expected_hash_len) != 0)) {
mbedtls_printf("One-shot hash operation gave the wrong result!\n\n");
goto cleanup;
}
mbedtls_printf("One-shot hash operation successful!\n\n");
/* Print out result */
mbedtls_printf("The SHA-256( '%s' ) is: ", sample_message);
for (size_t j = 0; j < expected_hash_len; j++) {
mbedtls_printf("%02x", hash[j]);
}
mbedtls_printf("\n");
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
cleanup:
return EXIT_FAILURE;
}
@@ -1,121 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
int psa_hkdf_main(void)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
/* Example test vector from RFC 5869 */
/* Input keying material (IKM) */
unsigned char ikm[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
unsigned char salt[] =
{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c };
/* Context and application specific information, which can be of zero length */
unsigned char info[] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
/* Expected OKM based on the RFC 5869-provided test vector */
unsigned char expected_okm[] = { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43,
0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90,
0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4,
0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18,
0x58, 0x65 };
/* The output size of the HKDF function depends on the hash function used.
* In our case we use SHA-256, which produces a 32 byte fingerprint.
* Therefore, we allocate a buffer of 32 bytes to hold the output keying
* material (OKM).
*/
unsigned char output[32];
psa_algorithm_t alg = PSA_ALG_HKDF(PSA_ALG_SHA_256);
printf("PSA Crypto API: HKDF SHA-256 example\n\n");
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
psa_set_key_algorithm(&attributes, PSA_ALG_HKDF(PSA_ALG_SHA_256));
psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
status = psa_import_key(&attributes, ikm, sizeof(ikm), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
status = psa_key_derivation_setup(&operation, alg);
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_setup failed");
return EXIT_FAILURE;
}
status = psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_SALT,
salt, sizeof(salt));
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_input_bytes (salt) failed");
return EXIT_FAILURE;
}
status = psa_key_derivation_input_key(&operation, PSA_KEY_DERIVATION_INPUT_SECRET,
key_id);
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_input_key failed");
return EXIT_FAILURE;
}
status = psa_key_derivation_input_bytes(&operation, PSA_KEY_DERIVATION_INPUT_INFO,
info, sizeof(info));
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_input_bytes (info) failed");
return EXIT_FAILURE;
}
status = psa_key_derivation_output_bytes(&operation, output, sizeof(output));
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_output_bytes failed");
return EXIT_FAILURE;
}
status = psa_key_derivation_abort(&operation);
if (status != PSA_SUCCESS) {
printf("psa_key_derivation_abort failed");
return EXIT_FAILURE;
}
printf("OKM: \n");
for (size_t j = 0; j < sizeof(output); j++) {
if (output[j] != expected_okm[j]) {
printf("\n --- Unexpected outcome!\n");
return EXIT_FAILURE;
}
if (j % 8 == 0) {
printf("\n ");
}
printf("%02x ", output[j]);
}
printf("\n");
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
}
@@ -1,146 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
#include "mbedtls/debug.h"
#include "mbedtls/platform.h"
#define BUFFER_SIZE 500
#define SERVER_PK_VALUE { \
0x04, 0xde, 0xa5, 0xe4, 0x5d, 0x0e, 0xa3, 0x7f, 0xc5, \
0x66, 0x23, 0x2a, 0x50, 0x8f, 0x4a, 0xd2, 0x0e, 0xa1, \
0x3d, 0x47, 0xe4, 0xbf, 0x5f, 0xa4, 0xd5, 0x4a, 0x57, \
0xa0, 0xba, 0x01, 0x20, 0x42, 0x08, 0x70, 0x97, 0x49, \
0x6e, 0xfc, 0x58, 0x3f, 0xed, 0x8b, 0x24, 0xa5, 0xb9, \
0xbe, 0x9a, 0x51, 0xde, 0x06, 0x3f, 0x5a, 0x00, 0xa8, \
0xb6, 0x98, 0xa1, 0x6f, 0xd7, 0xf2, 0x9b, 0x54, 0x85, \
0xf3, 0x20 \
}
#define KEY_BITS 256
int psa_key_agreement_main(void)
{
psa_status_t status;
psa_key_attributes_t client_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_attributes_t server_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_attributes_t check_attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t client_key_id = 0;
psa_key_id_t server_key_id = 0;
uint8_t client_pk[BUFFER_SIZE] = { 0 };
size_t client_pk_len;
size_t key_bits;
psa_key_type_t key_type;
const uint8_t server_pk[] = SERVER_PK_VALUE;
uint8_t derived_key[BUFFER_SIZE] = { 0 };
size_t derived_key_len;
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&client_attributes, PSA_KEY_USAGE_DERIVE);
psa_set_key_algorithm(&client_attributes, PSA_ALG_ECDH);
psa_set_key_type(&client_attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&client_attributes, KEY_BITS);
/* Generate ephemeral key pair */
status = psa_generate_key(&client_attributes, &client_key_id);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_generate_key failed\n");
return EXIT_FAILURE;
}
status = psa_export_public_key(client_key_id,
client_pk, sizeof(client_pk),
&client_pk_len);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_export_public_key failed\n");
return EXIT_FAILURE;
}
mbedtls_printf("Client Public Key (%" MBEDTLS_PRINTF_SIZET " bytes):\n", client_pk_len);
for (size_t j = 0; j < client_pk_len; j++) {
if (j % 8 == 0) {
mbedtls_printf("\n ");
}
mbedtls_printf("%02x ", client_pk[j]);
}
mbedtls_printf("\n\n");
psa_set_key_usage_flags(&server_attributes, PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT);
psa_set_key_algorithm(&server_attributes, PSA_ALG_ECDSA_ANY);
psa_set_key_type(&server_attributes, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1));
/* Import server public key */
status = psa_import_key(&server_attributes, server_pk, sizeof(server_pk), &server_key_id);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
status = psa_get_key_attributes(server_key_id, &check_attributes);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_get_key_attributes failed\n");
return EXIT_FAILURE;
}
key_bits = psa_get_key_bits(&check_attributes);
if (key_bits != 256) {
mbedtls_printf("Incompatible key size!\n");
return EXIT_FAILURE;
}
key_type = psa_get_key_type(&check_attributes);
if (key_type != PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)) {
mbedtls_printf("Unsupported key type!\n");
return EXIT_FAILURE;
}
mbedtls_printf("Server Public Key (%" MBEDTLS_PRINTF_SIZET " bytes):\n", sizeof(server_pk));
for (size_t j = 0; j < sizeof(server_pk); j++) {
if (j % 8 == 0) {
mbedtls_printf("\n ");
}
mbedtls_printf("%02x ", server_pk[j]);
}
mbedtls_printf("\n\n");
/* Generate ECDHE derived key */
status = psa_raw_key_agreement(PSA_ALG_ECDH, // algorithm
client_key_id, // client secret key
server_pk, sizeof(server_pk), // server public key
derived_key, sizeof(derived_key), // buffer to store derived key
&derived_key_len);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_raw_key_agreement failed\n");
return EXIT_FAILURE;
}
mbedtls_printf("Derived Key (%" MBEDTLS_PRINTF_SIZET " bytes):\n", derived_key_len);
for (size_t j = 0; j < derived_key_len; j++) {
if (j % 8 == 0) {
mbedtls_printf("\n ");
}
mbedtls_printf("%02x ", derived_key[j]);
}
mbedtls_printf("\n");
psa_destroy_key(server_key_id);
psa_destroy_key(client_key_id);
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
}
@@ -1,162 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
/* constant-time buffer comparison */
static inline int safer_memcmp(const void *a, const void *b, size_t n)
{
size_t i;
volatile const unsigned char *A = (volatile const unsigned char *) a;
volatile const unsigned char *B = (volatile const unsigned char *) b;
volatile unsigned char diff = 0;
for (i = 0; i < n; i++) {
/* Read volatile data in order before computing diff.
* This avoids IAR compiler warning:
* 'the order of volatile accesses is undefined ..' */
unsigned char x = A[i], y = B[i];
diff |= x ^ y;
}
return diff;
}
int psa_mac_main(void)
{
uint8_t input[] = "Hello World!";
psa_status_t status;
size_t mac_size_real = 0;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key_id = 0;
uint8_t mac[PSA_MAC_MAX_SIZE];
psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
const uint8_t key_bytes[16] = "kkkkkkkkkkkkkkkk";
const uint8_t mbedtls_test_hmac_sha256[] = {
0xae, 0x72, 0x34, 0x5a, 0x10, 0x36, 0xfb, 0x71,
0x35, 0x3c, 0x7d, 0x6c, 0x81, 0x98, 0x52, 0x86,
0x00, 0x4a, 0x43, 0x7c, 0x2d, 0xb3, 0x1a, 0xd8,
0x67, 0xb1, 0xad, 0x11, 0x4d, 0x18, 0x49, 0x8b
};
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_MESSAGE |
PSA_KEY_USAGE_SIGN_HASH |
PSA_KEY_USAGE_SIGN_MESSAGE);
psa_set_key_algorithm(&attributes, PSA_ALG_HMAC(PSA_ALG_SHA_256));
psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
/* Single-part MAC operation with psa_mac_compute() */
status = psa_mac_compute(key_id,
PSA_ALG_HMAC(PSA_ALG_SHA_256),
input,
sizeof(input),
mac,
sizeof(mac),
&mac_size_real);
if (status != PSA_SUCCESS) {
printf("psa_mac_compute failed\n");
return EXIT_FAILURE;
}
printf("HMAC-SHA-256(%s) with psa_mac_compute():\n", input);
for (size_t j = 0; j < mac_size_real; j++) {
if (j % 8 == 0) {
printf("\n ");
}
printf("%02x ", mac[j]);
}
printf("\n");
if (safer_memcmp(mac,
mbedtls_test_hmac_sha256,
mac_size_real
) != 0) {
printf("\nMAC verified incorrectly!\n");
} else {
printf("\nMAC verified correctly!\n");
}
psa_destroy_key(key_id);
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
/* Single-part MAC operation with psa_mac_verify() */
status = psa_mac_verify(key_id,
PSA_ALG_HMAC(PSA_ALG_SHA_256),
input,
sizeof(input),
mbedtls_test_hmac_sha256,
sizeof(mbedtls_test_hmac_sha256));
if (status != PSA_SUCCESS) {
printf("psa_mac_verify failed\n");
return EXIT_FAILURE;
} else {
printf("psa_mac_verify passed successfully\n");
}
psa_destroy_key(key_id);
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
/* Multi-part MAC operation */
status = psa_mac_sign_setup(&operation, key_id, PSA_ALG_HMAC(PSA_ALG_SHA_256));
if (status != PSA_SUCCESS) {
printf("psa_mac_sign_setup failed\n");
return EXIT_FAILURE;
}
status = psa_mac_update(&operation, input, sizeof(input));
if (status != PSA_SUCCESS) {
printf("psa_mac_update failed\n");
return EXIT_FAILURE;
}
status = psa_mac_sign_finish(&operation, mac, sizeof(mac), &mac_size_real);
if (status != PSA_SUCCESS) {
printf("psa_mac_sign_finish failed\n");
return EXIT_FAILURE;
}
if (safer_memcmp(mac,
mbedtls_test_hmac_sha256,
mac_size_real
) != 0) {
printf("MAC, calculated with multi-part MAC operation, verified incorrectly!\n");
} else {
printf("MAC, calculated with multi-part MAC operation, verified correctly!\n");
}
psa_destroy_key(key_id);
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
}
@@ -1,47 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include <psa/crypto.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/entropy.h"
#define BUFFER_SIZE 100
int psa_random_main(void)
{
psa_status_t status;
uint8_t output[BUFFER_SIZE] = { 0 };
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
status = psa_generate_random(output, BUFFER_SIZE);
if (status != PSA_SUCCESS) {
printf("psa_generate_random failed\n");
return EXIT_FAILURE;
}
printf("Random bytes generated:\n");
for (size_t j = 0; j < BUFFER_SIZE; j++) {
if (j % 8 == 0) {
printf("\n ");
}
printf("%02x ", output[j]);
}
printf("\n");
mbedtls_psa_crypto_free();
return 0;
}
@@ -1,93 +0,0 @@
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "psa/crypto.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#define KEY_BYTES_VALUE { \
0x49, 0xc9, 0xa8, 0xc1, 0x8c, 0x4b, 0x88, 0x56, 0x38, 0xc4, 0x31, 0xcf, \
0x1d, 0xf1, 0xc9, 0x94, 0x13, 0x16, 0x09, 0xb5, 0x80, 0xd4, 0xfd, 0x43, \
0xa0, 0xca, 0xb1, 0x7d, 0xb2, 0xf1, 0x3e, 0xee \
}
#define PLAINTEXT_VALUE "Hello World!"
/* SHA-256(plaintext) */
#define HASH_VALUE { \
0x5a, 0x09, 0xe8, 0xfa, 0x9c, 0x77, 0x80, 0x7b, 0x24, 0xe9, 0x9c, 0x9c, \
0xf9, 0x99, 0xde, 0xbf, 0xad, 0x84, 0x41, 0xe2, 0x69, 0xeb, 0x96, 0x0e, \
0x20, 0x1f, 0x61, 0xfc, 0x3d, 0xe2, 0x0d, 0x5a \
}
int psa_sign_verify_main(void)
{
psa_status_t status;
psa_key_id_t key_id = 0;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
uint8_t signature[PSA_SIGNATURE_MAX_SIZE] = { 0 };
size_t signature_length;
const uint8_t key_bytes[] = KEY_BYTES_VALUE;
const uint8_t plaintext[] = PLAINTEXT_VALUE;
const uint8_t hash[] = HASH_VALUE;
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_crypto_init failed\n");
return EXIT_FAILURE;
}
psa_set_key_usage_flags(&attributes,
PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
psa_set_key_type(&attributes, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
status = psa_import_key(&attributes, key_bytes, sizeof(key_bytes), &key_id);
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_import_key failed\n");
return EXIT_FAILURE;
}
status = psa_sign_hash(key_id, // key handle
PSA_ALG_ECDSA(PSA_ALG_SHA_256), // signature algorithm
hash, sizeof(hash), // hash of the message
signature, sizeof(signature), // signature (as output)
&signature_length); // length of signature output
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_sign_hash failed\n");
return EXIT_FAILURE;
}
mbedtls_printf("ECDSA-SHA256 signature of SHA-256('%s'):\n", plaintext);
for (size_t j = 0; j < signature_length; j++) {
if (j % 8 == 0) {
mbedtls_printf("\n ");
}
mbedtls_printf("%02x ", signature[j]);
}
mbedtls_printf("\n");
status = psa_verify_hash(key_id, // key handle
PSA_ALG_ECDSA(PSA_ALG_SHA_256), // signature algorithm
hash, sizeof(hash), // hash of message
signature, signature_length); // signature
if (status != PSA_SUCCESS) {
mbedtls_printf("psa_verify_hash failed\n");
return EXIT_FAILURE;
} else {
mbedtls_printf("\nSignature verification successful!\n");
}
psa_destroy_key(key_id);
mbedtls_psa_crypto_free();
return EXIT_SUCCESS;
}
@@ -1,23 +0,0 @@
/* psasim test client */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/* Includes from mbedtls */
#include "psa/crypto.h"
#include "util.h"
int main()
{
/* psa_crypto_init() connects to the server */
psa_status_t status = psa_crypto_init();
if (status != PSA_SUCCESS) {
ERROR("psa_crypto_init returned %d", status);
return 1;
}
mbedtls_psa_crypto_free();
return 0;
}
@@ -1,29 +0,0 @@
{
"psa_framework_version":1.0,
"name":"TEST_PARTITION",
"type":"PSA-ROT",
"priority":"LOW",
"entry_point":"psa_server_main",
"stack_size":"0x400",
"heap_size":"0x100",
"services":[
{
"name":"PSA_SID_CRYPTO",
"sid":"0x0000F000",
"signal":"PSA_CRYPTO",
"non_secure_clients": "true",
"minor_version":1,
"minor_policy":"STRICT"
}
],
"irqs": [
{
"source": "SIGINT",
"signal": "SIGINT_SIG"
},
{
"source": "SIGTSTP",
"signal": "SIGSTP_SIG"
}
]
}
@@ -1,385 +0,0 @@
/* PSA firmware framework client API */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <inttypes.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "client.h"
#include "common.h"
#include "error_ext.h"
#include "util.h"
typedef struct internal_handle {
int server_qid;
int client_qid;
int internal_server_qid;
int valid;
} internal_handle_t;
typedef struct vectors {
const psa_invec *in_vec;
size_t in_len;
psa_outvec *out_vec;
size_t out_len;
} vectors_t;
/* Note that this implementation is functional and not secure */
int __psa_ff_client_security_state = NON_SECURE;
/* Access to this global is not thread safe */
#define MAX_HANDLES 32
static internal_handle_t handles[MAX_HANDLES] = { { 0 } };
static int get_next_free_handle()
{
/* Never return handle 0 as it's a special null handle */
for (int i = 1; i < MAX_HANDLES; i++) {
if (handles[i].valid == 0) {
return i;
}
}
return -1;
}
static int handle_is_valid(psa_handle_t handle)
{
if (handle > 0 && handle < MAX_HANDLES) {
if (handles[handle].valid == 1) {
return 1;
}
}
ERROR("ERROR: Invalid handle");
return 0;
}
static int get_queue_info(char *path, int *cqid, int *sqid)
{
key_t server_queue_key;
int rx_qid, server_qid;
INFO("Attempting to contact a RoT service queue");
if ((rx_qid = msgget(IPC_PRIVATE, 0660)) == -1) {
ERROR("msgget: rx_qid");
return -1;
}
if ((server_queue_key = ftok(path, PROJECT_ID)) == -1) {
ERROR("ftok");
return -2;
}
if ((server_qid = msgget(server_queue_key, 0)) == -1) {
ERROR("msgget: server_qid");
return -3;
}
*cqid = rx_qid;
*sqid = server_qid;
return 0;
}
static psa_status_t process_response(int rx_qid, vectors_t *vecs, int type,
int *internal_server_qid)
{
struct message response, request;
psa_status_t ret = PSA_ERROR_CONNECTION_REFUSED;
size_t invec_seek[4] = { 0 };
size_t data_size;
psa_status_t invec, outvec; /* TODO: Should these be size_t ? */
assert(internal_server_qid > 0);
while (1) {
data_size = 0;
invec = 0;
outvec = 0;
/* read response from server */
if (msgrcv(rx_qid, &response, sizeof(struct message_text), 0, 0) == -1) {
ERROR(" msgrcv failed");
return ret;
}
/* process return message from server */
switch (response.message_type) {
case PSA_REPLY:
memcpy(&ret, response.message_text.buf, sizeof(psa_status_t));
INFO(" Message received from server: %d", ret);
if (type == PSA_IPC_CONNECT && ret > 0) {
*internal_server_qid = ret;
INFO(" ASSSIGNED q ID %d", *internal_server_qid);
ret = PSA_SUCCESS;
}
return ret;
break;
case READ_REQUEST:
/* read data request */
request.message_type = READ_RESPONSE;
assert(vecs != 0);
memcpy(&invec, response.message_text.buf, sizeof(psa_status_t));
memcpy(&data_size, response.message_text.buf+sizeof(size_t), sizeof(size_t));
INFO(" Partition asked for %lu bytes from invec %d", data_size, invec);
/* need to add more checks here */
assert(invec >= 0 && invec < PSA_MAX_IOVEC);
if (data_size > MAX_FRAGMENT_SIZE) {
data_size = MAX_FRAGMENT_SIZE;
}
/* send response */
INFO(" invec_seek[invec] is %lu", invec_seek[invec]);
INFO(" Reading from offset %p", vecs->in_vec[invec].base + invec_seek[invec]);
memcpy(request.message_text.buf,
(vecs->in_vec[invec].base + invec_seek[invec]),
data_size);
/* update invec base TODO: check me */
invec_seek[invec] = invec_seek[invec] + data_size;
INFO(" Sending message of type %li", request.message_type);
INFO(" with content %s", request.message_text.buf);
if (msgsnd(*internal_server_qid, &request,
sizeof(int) + sizeof(uint32_t) + data_size, 0) == -1) {
ERROR("Internal error: failed to respond to read request");
}
break;
case WRITE_REQUEST:
assert(vecs != 0);
request.message_type = WRITE_RESPONSE;
memcpy(&outvec, response.message_text.buf, sizeof(psa_status_t));
memcpy(&data_size, response.message_text.buf + sizeof(size_t), sizeof(size_t));
INFO(" Partition wants to write %lu bytes to outvec %d", data_size, outvec);
assert(outvec >= 0 && outvec < PSA_MAX_IOVEC);
/* copy memory into message and send back amount written */
size_t sofar = vecs->out_vec[outvec].len;
memcpy(vecs->out_vec[outvec].base + sofar,
response.message_text.buf+(sizeof(size_t)*2), data_size);
INFO(" Data size is %lu", data_size);
vecs->out_vec[outvec].len += data_size;
INFO(" Sending message of type %li", request.message_type);
/* send response */
if (msgsnd(*internal_server_qid, &request, sizeof(int) + data_size, 0) == -1) {
ERROR("Internal error: failed to respond to write request");
}
break;
case SKIP_REQUEST:
memcpy(&invec, response.message_text.buf, sizeof(psa_status_t));
memcpy(&data_size, response.message_text.buf+sizeof(size_t), sizeof(size_t));
INFO(" Partition asked to skip %lu bytes in invec %d", data_size, invec);
assert(invec >= 0 && invec < PSA_MAX_IOVEC);
/* update invec base TODO: check me */
invec_seek[invec] = invec_seek[invec] + data_size;
break;
default:
FATAL(" ERROR: unknown internal message type: %ld",
response.message_type);
}
}
}
static psa_status_t send(int rx_qid, int server_qid, int *internal_server_qid,
int32_t type, uint32_t minor_version, vectors_t *vecs)
{
psa_status_t ret = PSA_ERROR_CONNECTION_REFUSED;
size_t request_msg_size = (sizeof(int) + sizeof(long)); /* msg type plus queue id */
struct message request;
request.message_type = 1; /* TODO: change this */
request.message_text.psa_type = type;
vector_sizes_t vec_sizes;
/* If the client is non-secure then set the NS bit */
if (__psa_ff_client_security_state != 0) {
request.message_type |= NON_SECURE;
}
assert(request.message_type >= 0);
INFO("SEND: Sending message of type %ld with psa_type %d", request.message_type, type);
INFO(" internal_server_qid = %i", *internal_server_qid);
request.message_text.qid = rx_qid;
if (type == PSA_IPC_CONNECT) {
memcpy(request.message_text.buf, &minor_version, sizeof(minor_version));
request_msg_size = request_msg_size + sizeof(minor_version);
INFO(" Request msg size is %lu", request_msg_size);
} else {
assert(internal_server_qid > 0);
}
if (vecs != NULL && type >= PSA_IPC_CALL) {
memset(&vec_sizes, 0, sizeof(vec_sizes));
/* Copy invec sizes */
for (size_t i = 0; i < (vecs->in_len); i++) {
vec_sizes.invec_sizes[i] = vecs->in_vec[i].len;
INFO(" Client sending vector %lu: %lu", i, vec_sizes.invec_sizes[i]);
}
/* Copy outvec sizes */
for (size_t i = 0; i < (vecs->out_len); i++) {
vec_sizes.outvec_sizes[i] = vecs->out_vec[i].len;
/* Reset to 0 since we need to eventually fill in with bytes written */
vecs->out_vec[i].len = 0;
}
memcpy(request.message_text.buf, &vec_sizes, sizeof(vec_sizes));
request_msg_size = request_msg_size + sizeof(vec_sizes);
}
INFO(" Sending and then waiting");
/* send message to server */
if (msgsnd(server_qid, &request, request_msg_size, 0) == -1) {
ERROR(" msgsnd failed");
return ret;
}
return process_response(rx_qid, vecs, type, internal_server_qid);
}
uint32_t psa_framework_version(void)
{
return PSA_FRAMEWORK_VERSION;
}
psa_handle_t psa_connect(uint32_t sid, uint32_t minor_version)
{
int idx;
psa_status_t ret;
char pathname[PATHNAMESIZE] = { 0 };
idx = get_next_free_handle();
/* if there's a free handle available */
if (idx >= 0) {
snprintf(pathname, PATHNAMESIZE - 1, TMP_FILE_BASE_PATH "psa_service_%u", sid);
INFO("Attempting to contact RoT service at %s", pathname);
/* if communication is possible */
if (get_queue_info(pathname, &handles[idx].client_qid, &handles[idx].server_qid) >= 0) {
ret = send(handles[idx].client_qid,
handles[idx].server_qid,
&handles[idx].internal_server_qid,
PSA_IPC_CONNECT,
minor_version,
NULL);
/* if connection accepted by RoT service */
if (ret >= 0) {
handles[idx].valid = 1;
return idx;
} else {
ERROR("Server didn't like you");
}
} else {
ERROR("Couldn't contact RoT service. Does it exist?");
if (__psa_ff_client_security_state == 0) {
ERROR("Invalid SID");
}
}
}
INFO("Couldn't obtain a free handle");
return PSA_ERROR_CONNECTION_REFUSED;
}
uint32_t psa_version(uint32_t sid)
{
int idx;
psa_status_t ret;
char pathname[PATHNAMESIZE] = { 0 };
idx = get_next_free_handle();
if (idx >= 0) {
snprintf(pathname, PATHNAMESIZE, TMP_FILE_BASE_PATH "psa_service_%u", sid);
if (get_queue_info(pathname, &handles[idx].client_qid, &handles[idx].server_qid) >= 0) {
ret = send(handles[idx].client_qid,
handles[idx].server_qid,
&handles[idx].internal_server_qid,
VERSION_REQUEST,
0,
NULL);
INFO("psa_version: Recieved from server %d", ret);
if (ret > 0) {
return ret;
}
}
}
ERROR("psa_version failed: does the service exist?");
return PSA_VERSION_NONE;
}
psa_status_t psa_call(psa_handle_t handle,
int32_t type,
const psa_invec *in_vec,
size_t in_len,
psa_outvec *out_vec,
size_t out_len)
{
handle_is_valid(handle);
if ((in_len + out_len) > PSA_MAX_IOVEC) {
ERROR("Too many iovecs: %lu + %lu", in_len, out_len);
}
vectors_t vecs = { 0 };
vecs.in_vec = in_vec;
vecs.in_len = in_len;
vecs.out_vec = out_vec;
vecs.out_len = out_len;
return send(handles[handle].client_qid,
handles[handle].server_qid,
&handles[handle].internal_server_qid,
type,
0,
&vecs);
}
void psa_close(psa_handle_t handle)
{
handle_is_valid(handle);
if (send(handles[handle].client_qid, handles[handle].server_qid,
&handles[handle].internal_server_qid, PSA_IPC_DISCONNECT, 0, NULL)) {
ERROR("ERROR: Couldn't send disconnect msg");
} else {
if (msgctl(handles[handle].client_qid, IPC_RMID, NULL) != 0) {
ERROR("ERROR: Failed to delete msg queue");
}
}
INFO("Closing handle %u", handle);
handles[handle].valid = 0;
}
@@ -1,655 +0,0 @@
/* PSA Firmware Framework service API */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <time.h>
#include <assert.h>
#include "service.h"
#include "init.h"
#include "error_ext.h"
#include "common.h"
#include "util.h"
#define MAX_CLIENTS 128
#define MAX_MESSAGES 32
struct connection {
uint32_t client;
void *rhandle;
int client_to_server_q;
};
/* Note that this implementation is functional and not secure. */
int __psa_ff_client_security_state = NON_SECURE;
static psa_msg_t messages[MAX_MESSAGES]; /* Message slots */
static uint8_t pending_message[MAX_MESSAGES] = { 0 }; /* Booleans indicating active message slots */
static uint32_t message_client[MAX_MESSAGES] = { 0 }; /* Each client's response queue */
static int nsacl[32];
static int strict_policy[32] = { 0 };
static uint32_t rot_svc_versions[32];
static int rot_svc_incoming_queue[32] = { -1 };
static struct connection connections[MAX_CLIENTS] = { { 0 } };
static uint32_t exposed_signals = 0;
void print_vectors(vector_sizes_t *sizes)
{
INFO("Printing iovec sizes");
for (int j = 0; j < PSA_MAX_IOVEC; j++) {
INFO("Invec %d: %lu", j, sizes->invec_sizes[j]);
}
for (int j = 0; j < PSA_MAX_IOVEC; j++) {
INFO("Outvec %d: %lu", j, sizes->outvec_sizes[j]);
}
}
int find_connection(uint32_t client)
{
for (int i = 1; i < MAX_CLIENTS; i++) {
if (client == connections[i].client) {
return i;
}
}
return -1;
}
void destroy_connection(uint32_t client)
{
int idx = find_connection(client);
if (idx >= 0) {
connections[idx].client = 0;
connections[idx].rhandle = 0;
INFO("Destroying connection");
} else {
ERROR("Couldn't destroy connection for %u", client);
}
}
int find_free_connection()
{
INFO("Allocating connection");
return find_connection(0);
}
static void reply(psa_handle_t msg_handle, psa_status_t status)
{
pending_message[msg_handle] = 1;
psa_reply(msg_handle, status);
pending_message[msg_handle] = 0;
}
psa_signal_t psa_wait(psa_signal_t signal_mask, uint32_t timeout)
{
psa_signal_t mask;
struct message msg;
vector_sizes_t sizes;
struct msqid_ds qinfo;
uint32_t requested_version;
ssize_t len;
int idx;
if (timeout == PSA_POLL) {
INFO("psa_wait: Called in polling mode");
}
do {
mask = signal_mask;
/* Check the status of each queue */
for (int i = 0; i < 32; i++) {
if (mask & 0x1) {
if (i < 3) {
// do nothing (reserved)
} else if (i == 3) {
// this must be psa doorbell
} else {
/* Check if this signal corresponds to a queue */
if (rot_svc_incoming_queue[i] >= 0 && (pending_message[i] == 0)) {
/* AFAIK there is no "peek" method in SysV, so try to get a message */
len = msgrcv(rot_svc_incoming_queue[i],
&msg,
sizeof(struct message_text),
0,
IPC_NOWAIT);
if (len > 0) {
INFO("Storing that QID in message_client[%d]", i);
INFO("The message handle will be %d", i);
msgctl(rot_svc_incoming_queue[i], IPC_STAT, &qinfo);
messages[i].client_id = qinfo.msg_lspid; /* PID of last msgsnd(2) call */
message_client[i] = msg.message_text.qid;
idx = find_connection(msg.message_text.qid);
if (msg.message_type & NON_SECURE) {
/* This is a non-secure message */
/* Check if NS client is allowed for this RoT service */
if (nsacl[i] <= 0) {
#if 0
INFO(
"Rejecting non-secure client due to manifest security policy");
reply(i, PSA_ERROR_CONNECTION_REFUSED);
continue; /* Skip to next signal */
#endif
}
msg.message_type &= ~(NON_SECURE); /* clear */
messages[i].client_id = messages[i].client_id * -1;
}
INFO("Got a message from client ID %d", messages[i].client_id);
INFO("Message type is %lu", msg.message_type);
INFO("PSA message type is %d", msg.message_text.psa_type);
messages[i].handle = i;
switch (msg.message_text.psa_type) {
case PSA_IPC_CONNECT:
if (len >= 16) {
memcpy(&requested_version, msg.message_text.buf,
sizeof(requested_version));
INFO("Requesting version %u", requested_version);
INFO("Implemented version %u", rot_svc_versions[i]);
/* TODO: need to check whether the policy is strict,
* and if so, then reject the client if the number doesn't match */
if (requested_version > rot_svc_versions[i]) {
INFO(
"Rejecting client because requested version that was too high");
reply(i, PSA_ERROR_CONNECTION_REFUSED);
continue; /* Skip to next signal */
}
if (strict_policy[i] == 1 &&
(requested_version != rot_svc_versions[i])) {
INFO(
"Rejecting client because enforcing a STRICT version policy");
reply(i, PSA_ERROR_CONNECTION_REFUSED);
continue; /* Skip to next signal */
} else {
INFO("Not rejecting client");
}
}
messages[i].type = PSA_IPC_CONNECT;
if (idx < 0) {
idx = find_free_connection();
}
if (idx >= 0) {
connections[idx].client = msg.message_text.qid;
} else {
/* We've run out of system wide connections */
reply(i, PSA_ERROR_CONNECTION_BUSY);
ERROR("Ran out of free connections");
continue;
}
break;
case PSA_IPC_DISCONNECT:
messages[i].type = PSA_IPC_DISCONNECT;
break;
case VERSION_REQUEST:
INFO("Got a version request");
reply(i, rot_svc_versions[i]);
continue; /* Skip to next signal */
break;
default:
/* PSA CALL */
if (msg.message_text.psa_type >= 0) {
messages[i].type = msg.message_text.psa_type;
memcpy(&sizes, msg.message_text.buf, sizeof(sizes));
print_vectors(&sizes);
memcpy(&messages[i].in_size, &sizes.invec_sizes,
(sizeof(size_t) * PSA_MAX_IOVEC));
memcpy(&messages[i].out_size, &sizes.outvec_sizes,
(sizeof(size_t) * PSA_MAX_IOVEC));
} else {
FATAL("UNKNOWN MESSAGE TYPE RECEIVED %li",
msg.message_type);
}
break;
}
messages[i].handle = i;
/* Check if the client has a connection */
if (idx >= 0) {
messages[i].rhandle = connections[idx].rhandle;
} else {
/* Client is begging for a programmer error */
reply(i, PSA_ERROR_PROGRAMMER_ERROR);
continue;
}
/* House keeping */
pending_message[i] = 1; /* set message as pending */
exposed_signals |= (0x1 << i); /* assert the signal */
}
}
}
mask = mask >> 1;
}
}
if ((timeout == PSA_BLOCK) && (exposed_signals > 0)) {
break;
} else {
/* There is no 'select' function in SysV to block on multiple queues, so busy-wait :( */
}
} while (timeout == PSA_BLOCK);
/* Assert signals */
return signal_mask & exposed_signals;
}
static int signal_to_index(psa_signal_t signal)
{
int i;
int count = 0;
int ret = -1;
for (i = 0; i < 32; i++) {
if (signal & 0x1) {
ret = i;
count++;
}
signal = signal >> 1;
}
if (count > 1) {
ERROR("ERROR: Too many signals");
return -1; /* Too many signals */
}
return ret;
}
static void clear_signal(psa_signal_t signal)
{
exposed_signals = exposed_signals & ~signal;
}
void raise_signal(psa_signal_t signal)
{
exposed_signals |= signal;
}
psa_status_t psa_get(psa_signal_t signal, psa_msg_t *msg)
{
int index = signal_to_index(signal);
if (index < 0) {
ERROR("Bad signal");
}
clear_signal(signal);
assert(messages[index].handle != 0);
if (pending_message[index] == 1) {
INFO("There is a pending message!");
memcpy(msg, &messages[index], sizeof(struct psa_msg_t));
assert(msg->handle != 0);
return PSA_SUCCESS;
} else {
INFO("no pending message");
}
return PSA_ERROR_DOES_NOT_EXIST;
}
static inline int is_valid_msg_handle(psa_handle_t h)
{
if (h > 0 && h < MAX_MESSAGES) {
return 1;
}
ERROR("Not a valid message handle");
return 0;
}
static inline int is_call_msg(psa_handle_t h)
{
assert(messages[h].type >= PSA_IPC_CALL);
return 1;
}
void psa_set_rhandle(psa_handle_t msg_handle, void *rhandle)
{
is_valid_msg_handle(msg_handle);
int idx = find_connection(message_client[msg_handle]);
INFO("Setting rhandle to %p", rhandle);
assert(idx >= 0);
connections[idx].rhandle = rhandle;
}
/* Sends a message from the server to the client. Does not wait for a response */
static void send_msg(psa_handle_t msg_handle,
int ctrl_msg,
psa_status_t status,
size_t amount,
const void *data,
size_t data_amount)
{
struct message response;
int flags = 0;
assert(ctrl_msg > 0); /* According to System V, it must be greater than 0 */
response.message_type = ctrl_msg;
if (ctrl_msg == PSA_REPLY) {
memcpy(response.message_text.buf, &status, sizeof(psa_status_t));
} else if (ctrl_msg == READ_REQUEST || ctrl_msg == WRITE_REQUEST || ctrl_msg == SKIP_REQUEST) {
memcpy(response.message_text.buf, &status, sizeof(psa_status_t));
memcpy(response.message_text.buf+sizeof(size_t), &amount, sizeof(size_t));
if (ctrl_msg == WRITE_REQUEST) {
/* TODO: Check if too big */
memcpy(response.message_text.buf + (sizeof(size_t) * 2), data, data_amount);
}
}
/* TODO: sizeof doesn't need to be so big here for small responses */
if (msgsnd(message_client[msg_handle], &response, sizeof(response.message_text), flags) == -1) {
ERROR("Failed to reply");
}
}
static size_t skip(psa_handle_t msg_handle, uint32_t invec_idx, size_t num_bytes)
{
if (num_bytes < (messages[msg_handle].in_size[invec_idx] - num_bytes)) {
messages[msg_handle].in_size[invec_idx] = messages[msg_handle].in_size[invec_idx] -
num_bytes;
return num_bytes;
} else {
if (num_bytes >= messages[msg_handle].in_size[invec_idx]) {
size_t ret = messages[msg_handle].in_size[invec_idx];
messages[msg_handle].in_size[invec_idx] = 0;
return ret;
} else {
return num_bytes;
}
}
}
size_t psa_read(psa_handle_t msg_handle, uint32_t invec_idx,
void *buffer, size_t num_bytes)
{
size_t sofar = 0;
struct message msg = { 0 };
int idx;
ssize_t len;
is_valid_msg_handle(msg_handle);
is_call_msg(msg_handle);
if (invec_idx >= PSA_MAX_IOVEC) {
ERROR("Invalid iovec number");
}
/* If user wants more data than what's available, truncate their request */
if (num_bytes > messages[msg_handle].in_size[invec_idx]) {
num_bytes = messages[msg_handle].in_size[invec_idx];
}
while (sofar < num_bytes) {
INFO("Server: requesting %lu bytes from client", (num_bytes - sofar));
send_msg(msg_handle, READ_REQUEST, invec_idx, (num_bytes - sofar), NULL, 0);
idx = find_connection(message_client[msg_handle]);
assert(idx >= 0);
len = msgrcv(connections[idx].client_to_server_q, &msg, sizeof(struct message_text), 0, 0);
len = (len - offsetof(struct message_text, buf));
if (len < 0) {
FATAL("Internal error: failed to dispatch read request to the client");
}
if (len > (num_bytes - sofar)) {
if ((num_bytes - sofar) > 0) {
memcpy(buffer+sofar, msg.message_text.buf, (num_bytes - sofar));
}
} else {
memcpy(buffer + sofar, msg.message_text.buf, len);
}
INFO("Printing what i got so far: %s", msg.message_text.buf);
sofar = sofar + len;
}
/* Update the seek count */
skip(msg_handle, invec_idx, num_bytes);
INFO("Finished psa_read");
return sofar;
}
void psa_write(psa_handle_t msg_handle, uint32_t outvec_idx,
const void *buffer, size_t num_bytes)
{
size_t sofar = 0;
struct message msg = { 0 };
int idx;
ssize_t len;
is_valid_msg_handle(msg_handle);
is_call_msg(msg_handle);
if (outvec_idx >= PSA_MAX_IOVEC) {
ERROR("Invalid iovec number");
}
if (num_bytes > messages[msg_handle].out_size[outvec_idx]) {
ERROR("Program tried to write too much data %lu/%lu", num_bytes,
messages[msg_handle].out_size[outvec_idx]);
}
while (sofar < num_bytes) {
size_t sending = (num_bytes - sofar);
if (sending > (MAX_FRAGMENT_SIZE - (sizeof(size_t) * 2))) {
sending = MAX_FRAGMENT_SIZE - (sizeof(size_t) * 2);
}
INFO("Server: sending %lu bytes to client, sofar = %lu", sending, (long) sofar);
send_msg(msg_handle, WRITE_REQUEST, outvec_idx, sending, buffer + sofar, sending);
idx = find_connection(message_client[msg_handle]);
assert(idx >= 0);
len = msgrcv(connections[idx].client_to_server_q, &msg, sizeof(struct message_text), 0, 0);
if (len < 1) {
FATAL("Client didn't give me a full response");
}
sofar = sofar + sending;
}
/* Update the seek count */
messages[msg_handle].out_size[outvec_idx] -= num_bytes;
}
size_t psa_skip(psa_handle_t msg_handle, uint32_t invec_idx, size_t num_bytes)
{
is_valid_msg_handle(msg_handle);
is_call_msg(msg_handle);
size_t ret = skip(msg_handle, invec_idx, num_bytes);
/* notify client to skip */
send_msg(msg_handle, SKIP_REQUEST, invec_idx, num_bytes, NULL, 0);
return ret;
}
static void destroy_temporary_queue(int myqid)
{
if (msgctl(myqid, IPC_RMID, NULL) != 0) {
INFO("ERROR: Failed to delete msg queue %d", myqid);
}
}
static int make_temporary_queue()
{
int myqid;
if ((myqid = msgget(IPC_PRIVATE, 0660)) == -1) {
INFO("msgget: myqid");
return -1;
}
return myqid;
}
/**
* Assumes msg_handle is the index into the message array
*/
void psa_reply(psa_handle_t msg_handle, psa_status_t status)
{
int idx, q;
is_valid_msg_handle(msg_handle);
if (pending_message[msg_handle] != 1) {
ERROR("Not a valid message handle");
}
if (messages[msg_handle].type == PSA_IPC_CONNECT) {
switch (status) {
case PSA_SUCCESS:
idx = find_connection(message_client[msg_handle]);
q = make_temporary_queue();
if (q > 0 && idx >= 0) {
connections[idx].client_to_server_q = q;
status = q;
} else {
FATAL("What happened?");
}
break;
case PSA_ERROR_CONNECTION_REFUSED:
destroy_connection(message_client[msg_handle]);
break;
case PSA_ERROR_CONNECTION_BUSY:
destroy_connection(message_client[msg_handle]);
break;
case PSA_ERROR_PROGRAMMER_ERROR:
destroy_connection(message_client[msg_handle]);
break;
default:
ERROR("Not a valid reply %d", status);
}
} else if (messages[msg_handle].type == PSA_IPC_DISCONNECT) {
idx = find_connection(message_client[msg_handle]);
if (idx >= 0) {
destroy_temporary_queue(connections[idx].client_to_server_q);
}
destroy_connection(message_client[msg_handle]);
}
send_msg(msg_handle, PSA_REPLY, status, 0, NULL, 0);
pending_message[msg_handle] = 0;
message_client[msg_handle] = 0;
}
/* TODO: make sure you only clear interrupt signals, and not others */
void psa_eoi(psa_signal_t signal)
{
int index = signal_to_index(signal);
if (index >= 0 && (rot_svc_incoming_queue[index] >= 0)) {
clear_signal(signal);
} else {
ERROR("Tried to EOI a signal that isn't an interrupt");
}
}
void psa_notify(int32_t partition_id)
{
char pathname[PATHNAMESIZE] = { 0 };
if (partition_id < 0) {
ERROR("Not a valid secure partition");
}
snprintf(pathname, PATHNAMESIZE, "/tmp/psa_notify_%u", partition_id);
INFO("psa_notify: notifying partition %u using %s",
partition_id, pathname);
INFO("psa_notify is unimplemented");
}
void psa_clear(void)
{
clear_signal(PSA_DOORBELL);
}
void __init_psasim(const char **array,
int size,
const int allow_ns_clients_array[32],
const uint32_t versions[32],
const int strict_policy_array[32])
{
static uint8_t library_initialised = 0;
key_t key;
int qid;
FILE *fp;
char doorbell_file[PATHNAMESIZE] = { 0 };
char queue_path[PATHNAMESIZE];
snprintf(doorbell_file, PATHNAMESIZE, "psa_notify_%u", getpid());
if (library_initialised > 0) {
return;
} else {
library_initialised = 1;
}
if (size != 32) {
FATAL("Unsupported value. Aborting.");
}
array[3] = doorbell_file;
for (int i = 0; i < 32; i++) {
if (strncmp(array[i], "", 1) != 0) {
INFO("Setting up %s", array[i]);
memset(queue_path, 0, sizeof(queue_path));
snprintf(queue_path, sizeof(queue_path), "%s%s", TMP_FILE_BASE_PATH, array[i]);
/* Create file if doesn't exist */
fp = fopen(queue_path, "ab+");
if (fp) {
fclose(fp);
}
if ((key = ftok(queue_path, PROJECT_ID)) == -1) {
FATAL("Error finding message queue during initialisation");
}
/* TODO: Investigate. Permissions are likely to be too relaxed */
if ((qid = msgget(key, IPC_CREAT | 0660)) == -1) {
FATAL("Error opening message queue during initialisation");
} else {
rot_svc_incoming_queue[i] = qid;
}
}
}
memcpy(nsacl, allow_ns_clients_array, sizeof(int) * 32);
memcpy(strict_policy, strict_policy_array, sizeof(int) * 32);
memcpy(rot_svc_versions, versions, sizeof(uint32_t) * 32);
memset(&connections, 0, sizeof(struct connection) * MAX_CLIENTS);
__psa_ff_client_security_state = 0; /* Set the client status to SECURE */
}
@@ -1,93 +0,0 @@
/* THIS FILE WAS AUTO-GENERATED BY psa_sim_generate.pl. DO NOT EDIT!! */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef _PSA_FUNCTIONS_CODES_H_
#define _PSA_FUNCTIONS_CODES_H_
enum {
/* Start here to avoid overlap with PSA_IPC_CONNECT, PSA_IPC_DISCONNECT
* and VERSION_REQUEST */
PSA_CRYPTO_INIT = 100,
PSA_AEAD_ABORT,
PSA_AEAD_DECRYPT,
PSA_AEAD_DECRYPT_SETUP,
PSA_AEAD_ENCRYPT,
PSA_AEAD_ENCRYPT_SETUP,
PSA_AEAD_FINISH,
PSA_AEAD_GENERATE_NONCE,
PSA_AEAD_SET_LENGTHS,
PSA_AEAD_SET_NONCE,
PSA_AEAD_UPDATE,
PSA_AEAD_UPDATE_AD,
PSA_AEAD_VERIFY,
PSA_ASYMMETRIC_DECRYPT,
PSA_ASYMMETRIC_ENCRYPT,
PSA_CIPHER_ABORT,
PSA_CIPHER_DECRYPT,
PSA_CIPHER_DECRYPT_SETUP,
PSA_CIPHER_ENCRYPT,
PSA_CIPHER_ENCRYPT_SETUP,
PSA_CIPHER_FINISH,
PSA_CIPHER_GENERATE_IV,
PSA_CIPHER_SET_IV,
PSA_CIPHER_UPDATE,
PSA_COPY_KEY,
PSA_DESTROY_KEY,
PSA_EXPORT_KEY,
PSA_EXPORT_PUBLIC_KEY,
PSA_GENERATE_KEY,
PSA_GENERATE_KEY_CUSTOM,
PSA_GENERATE_RANDOM,
PSA_GET_KEY_ATTRIBUTES,
PSA_HASH_ABORT,
PSA_HASH_CLONE,
PSA_HASH_COMPARE,
PSA_HASH_COMPUTE,
PSA_HASH_FINISH,
PSA_HASH_SETUP,
PSA_HASH_UPDATE,
PSA_HASH_VERIFY,
PSA_IMPORT_KEY,
PSA_INTERRUPTIBLE_GET_MAX_OPS,
PSA_INTERRUPTIBLE_SET_MAX_OPS,
PSA_KEY_DERIVATION_ABORT,
PSA_KEY_DERIVATION_GET_CAPACITY,
PSA_KEY_DERIVATION_INPUT_BYTES,
PSA_KEY_DERIVATION_INPUT_INTEGER,
PSA_KEY_DERIVATION_INPUT_KEY,
PSA_KEY_DERIVATION_KEY_AGREEMENT,
PSA_KEY_DERIVATION_OUTPUT_BYTES,
PSA_KEY_DERIVATION_OUTPUT_KEY,
PSA_KEY_DERIVATION_OUTPUT_KEY_CUSTOM,
PSA_KEY_DERIVATION_SET_CAPACITY,
PSA_KEY_DERIVATION_SETUP,
PSA_MAC_ABORT,
PSA_MAC_COMPUTE,
PSA_MAC_SIGN_FINISH,
PSA_MAC_SIGN_SETUP,
PSA_MAC_UPDATE,
PSA_MAC_VERIFY,
PSA_MAC_VERIFY_FINISH,
PSA_MAC_VERIFY_SETUP,
PSA_PURGE_KEY,
PSA_RAW_KEY_AGREEMENT,
PSA_RESET_KEY_ATTRIBUTES,
PSA_SIGN_HASH,
PSA_SIGN_HASH_ABORT,
PSA_SIGN_HASH_COMPLETE,
PSA_SIGN_HASH_GET_NUM_OPS,
PSA_SIGN_HASH_START,
PSA_SIGN_MESSAGE,
PSA_VERIFY_HASH,
PSA_VERIFY_HASH_ABORT,
PSA_VERIFY_HASH_COMPLETE,
PSA_VERIFY_HASH_GET_NUM_OPS,
PSA_VERIFY_HASH_START,
PSA_VERIFY_MESSAGE,
};
#endif /* _PSA_FUNCTIONS_CODES_H_ */
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
-118
View File
@@ -1,118 +0,0 @@
/* psasim test server */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <unistd.h>
#include <stdio.h>
/* Includes from psasim */
#include "service.h"
#include "error_ext.h"
#include "util.h"
#include "psa_manifest/manifest.h"
#include "psa_functions_codes.h"
/* Includes from mbedtls */
#include "mbedtls/version.h"
#include "psa/crypto.h"
#ifdef DEBUG
#define SERVER_PRINT(fmt, ...) \
PRINT("Server: " fmt, ##__VA_ARGS__)
#else
#define SERVER_PRINT(...)
#endif
#define BUF_SIZE 25
static int kill_on_disconnect = 0; /* Kill the server on client disconnection. */
void parse_input_args(int argc, char *argv[])
{
int opt;
while ((opt = getopt(argc, argv, "k")) != -1) {
switch (opt) {
case 'k':
kill_on_disconnect = 1;
break;
default:
fprintf(stderr, "Usage: %s [-k]\n", argv[0]);
exit(EXIT_FAILURE);
}
}
}
int psa_server_main(int argc, char *argv[])
{
psa_status_t ret = PSA_ERROR_PROGRAMMER_ERROR;
psa_msg_t msg = { -1 };
const int magic_num = 66;
int client_disconnected = 0;
extern psa_status_t psa_crypto_call(psa_msg_t msg);
extern psa_status_t psa_crypto_close(void);
#if defined(MBEDTLS_VERSION_C)
char mbedtls_version[18];
mbedtls_version_get_string_full(mbedtls_version);
SERVER_PRINT("%s", mbedtls_version);
#endif
parse_input_args(argc, argv);
SERVER_PRINT("Starting");
while (!(kill_on_disconnect && client_disconnected)) {
psa_signal_t signals = psa_wait(PSA_WAIT_ANY, PSA_BLOCK);
if (signals > 0) {
SERVER_PRINT("Signals: 0x%08x", signals);
}
if (signals & PSA_CRYPTO_SIGNAL) {
if (PSA_SUCCESS == psa_get(PSA_CRYPTO_SIGNAL, &msg)) {
SERVER_PRINT("handle: %d - rhandle: %p", msg.handle, (int *) msg.rhandle);
switch (msg.type) {
case PSA_IPC_CONNECT:
SERVER_PRINT("Got a connection message");
psa_set_rhandle(msg.handle, (void *) &magic_num);
ret = PSA_SUCCESS;
break;
case PSA_IPC_DISCONNECT:
SERVER_PRINT("Got a disconnection message");
ret = PSA_SUCCESS;
client_disconnected = 1;
psa_crypto_close();
break;
default:
SERVER_PRINT("Got an IPC call of type %d", msg.type);
ret = psa_crypto_call(msg);
SERVER_PRINT("Internal function call returned %d", ret);
if (msg.client_id > 0) {
psa_notify(msg.client_id);
} else {
SERVER_PRINT("Client is non-secure, so won't notify");
}
}
psa_reply(msg.handle, ret);
} else {
SERVER_PRINT("Failed to retrieve message");
}
} else if (SIGSTP_SIG & signals) {
SERVER_PRINT("Recieved SIGSTP signal. Gonna EOI it.");
psa_eoi(SIGSTP_SIG);
} else if (SIGINT_SIG & signals) {
SERVER_PRINT("Handling interrupt!");
SERVER_PRINT("Gracefully quitting");
psa_panic();
} else {
SERVER_PRINT("No signal asserted");
}
}
return 0;
}
@@ -1,17 +0,0 @@
#!/bin/bash
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -e
pkill psa_server || true
# Remove temporary files
rm -f psa_notify_*
# Remove all IPCs
# Not just ipcrm -all=msg as it is not supported on macOS.
# Filter out header and empty lines, choosing to select based on keys being
# output in hex.
ipcs -q | fgrep 0x | awk '{ printf " -q " $2 }' | xargs ipcrm > /dev/null 2>&1 || true
@@ -1,24 +0,0 @@
#!/bin/bash
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This is a simple bash script that tests psa_client/psa_server interaction.
# This script is automatically executed when "make run" is launched by the
# "psasim" root folder. The script can also be launched manually once
# binary files are built (i.e. after "make test" is executed from the "psasim"
# root folder).
set -e
cd "$(dirname "$0")"
CLIENT_BIN=$1
shift
./kill_servers.sh
./start_server.sh
./$CLIENT_BIN "$@"
./kill_servers.sh
@@ -1,17 +0,0 @@
#!/bin/bash
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -e
# The server creates some local files when it starts up so we can wait for this
# event as signal that the server is ready so that we can start client(s).
function wait_for_server_startup() {
while [ $(find . -name "psa_notify_*" | wc -l) -eq 0 ]; do
sleep 0.1
done
}
$(dirname "$0")/psa_server &
wait_for_server_startup
@@ -1,174 +0,0 @@
#!/usr/bin/env python3
"""This hacky script generates a partition from a manifest file"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import json
import os
import sys
from os import listdir
if len(sys.argv) != 2:
print("Usage: psa_autogen <manifest_file>")
sys.exit(1)
FILENAME = str(sys.argv[1])
SCRIPT_PATH = os.path.dirname(__file__)
GENERATED_H_PATH = os.path.join(SCRIPT_PATH, "..", "include", "psa_manifest")
GENERATED_C_PATH = os.path.join(SCRIPT_PATH, "..", "src")
MANIFEST_FILE = os.path.join(GENERATED_H_PATH, "manifest.h")
PID_FILE = os.path.join(GENERATED_H_PATH, "pid.h")
SID_FILE = os.path.join(GENERATED_H_PATH, "sid.h")
with open(str(FILENAME), "r") as read_file:
data = json.load(read_file)
FILENAME = os.path.basename(FILENAME)
FILENAME = FILENAME.split('.')[0]
print("Base filename is " + str(FILENAME))
if str(data['psa_framework_version'] == "1.0"):
entry_point = str(data['entry_point'])
partition_name = str(data['name'])
services = data['services']
try:
irqs = data['irqs']
except KeyError:
irqs = []
try:
os.mkdir(GENERATED_H_PATH)
print("Generating psa_manifest directory")
except OSError:
print("PSA manifest directory already exists")
manifest_content = []
pids_content = []
sids_content = []
if len(services) > 28:
print ("Unsupported number of services")
count = 4 # For creating SID array
nsacl = "const int ns_allowed[32] = { "
policy = "const int strict_policy[32] = { "
qcode = "const char *psa_queues[] = { "
versions = "const uint32_t versions[32] = { "
queue_path = "psa_service_"
start = False
for x in range(0, count):
qcode = qcode + "\"\", "
nsacl = nsacl + "0, "
policy = policy + "0, "
versions = versions + "0, "
# Go through all the services to make sid.h and pid.h
for svc in services:
manifest_content.append("#define {}_SIGNAL 0x{:08x}".format(svc['signal'], 2**count))
sids_content.append("#define {}_SID {}".format(svc['name'], svc['sid']))
qcode = qcode + "\"" + queue_path + str(int(svc['sid'], 16)) + "\","
ns_clients = svc['non_secure_clients']
print(str(svc))
if ns_clients == "true":
nsacl = nsacl + "1, "
else:
nsacl = nsacl + "0, "
try:
versions = versions + str(svc['minor_version']) + ", "
except KeyError:
versions = versions + "1, "
strict = 0
try:
if str(svc['minor_policy']).lower() == "strict":
strict = 1
policy = policy + "1, "
else:
policy = policy + "0, "
except KeyError:
strict = 0
policy = policy + "0, "
count = count+1
sigcode = ""
handlercode = "void __sig_handler(int signo) {\n"
irqcount = count
for irq in irqs:
manifest_content.append("#define {} 0x{:08x}".format(irq['signal'], 2**irqcount))
sigcode = sigcode + " signal({}, __sig_handler);\n".format(irq['source'])
handlercode = handlercode + \
" if (signo == {}) {{ raise_signal(0x{:08x}); }};\n".format(irq['source'], 2**irqcount)
irqcount = irqcount+1
handlercode = handlercode + "}\n"
while (count < 32):
qcode = qcode + "\"\", "
nsacl = nsacl + "0, "
versions = versions + "0, "
policy = policy + "0, "
count = count + 1
qcode = qcode + "};\n"
nsacl = nsacl + "};\n"
versions = versions + "};\n"
policy = policy + "};\n"
with open(MANIFEST_FILE, "wt") as output:
output.write("\n".join(manifest_content))
with open(SID_FILE, "wt") as output:
output.write("\n".join(sids_content))
with open(PID_FILE, "wt") as output:
output.write("\n".join(pids_content))
symbols = []
# Go through source files and look for the entrypoint
for root, directories, filenames in os.walk(GENERATED_C_PATH):
for filename in filenames:
if "psa_ff_bootstrap" in filename or filename == "psa_manifest":
continue
try:
fullpath = os.path.join(root,filename)
with open(fullpath, encoding='utf-8') as currentFile:
text = currentFile.read()
if str(entry_point + "(") in text:
symbols.append(filename)
except IOError:
print("Couldn't open " + filename)
except UnicodeDecodeError:
pass
print(str("Number of entrypoints detected: " + str(len(symbols))))
if len(symbols) < 1:
print("Couldn't find function " + entry_point)
sys.exit(1)
elif len(symbols) > 1:
print("Duplicate entrypoint symbol detected: " + str(symbols))
sys.exit(2)
else:
C_FILENAME = os.path.join(GENERATED_C_PATH, "psa_ff_bootstrap_" + partition_name + ".c")
c_content = []
c_content.append("#include <init.h>")
c_content.append("#include \"" + symbols[0] + "\"")
c_content.append("#include <signal.h>")
c_content.append(qcode)
c_content.append(nsacl)
c_content.append(policy)
c_content.append(versions)
c_content.append(handlercode)
c_content.append("int main(int argc, char *argv[]) {")
c_content.append(" (void) argc;")
c_content.append(sigcode)
c_content.append(" __init_psasim(psa_queues, 32, ns_allowed, versions,"
"strict_policy);")
c_content.append(" " + entry_point + "(argc, argv);")
c_content.append("}")
with open(C_FILENAME, "wt") as output:
output.write("\n".join(c_content))
print("Success")
-27
View File
@@ -1,27 +0,0 @@
#!/bin/bash -eu
# all-in-docker.sh
#
# Purpose
# -------
# This runs all.sh (except for armcc) in a Docker container.
#
# WARNING: the Dockerfile used by this script is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
#
# Notes for users
# ---------------
# See docker_env.sh for prerequisites and other information.
#
# See also all.sh for notes about invocation of that script.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
source tests/scripts/docker_env.sh
# Run tests that are possible with openly available compilers
run_in_docker tests/scripts/all.sh \
--no-armcc \
$@
-112
View File
@@ -1,112 +0,0 @@
#! /usr/bin/env bash
# all.sh (transitional wrapper)
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This is a transitional wrapper that's only meant for the CI.
# Developers should directly invoke on or two of:
# - tests/scripts/mbedtls-all.sh ...
# - (cd tf-psa-crypto && tests/scripts/all.sh ...)
#
# During the transition, it's illegal for a tf-psa-crypto component to have
# the same name as an mbedtls components; since this wrapper handles both
# sides at once, component names need to be globally unique. Once the
# transition period is over, unicity on each side will be enough.
#
# For context, here are the steps of the transition:
# 1. We have an all.sh in tf-psa-crypto but for now we don't invoke it directly
# on the CI, only through this transitional wrapper in mbedtls. (tf-psa-crypto
# doesn't have its own CI initially and runs Mbed TLS's instead.)
# 2. We move all relevant components to tf-psa-crypto so that it gets the level of
# coverage we want. We need to make sure the new names are unique.
# 3. We change the CI job on tf-psa-crypto to stop checking out mbedtls and running
# its all.sh - instead we do the normal thing of checking out tf-psa-crypto and
# running its all.sh. (In two steps: (a) add the new job, (b) remove the old
# one.)
# 4. We remove the transitional wrapper in mbedtls and we're now free to rename
# tf-psa-crypto components as we want. If we followed a consistent naming
# pattern, this can be as simple as s/_tf_psa_crypto// in components-*.sh.
# This script must be invoked from the project's root.
# There are exactly 4 ways this is invoked in the CI:
# 1. tests/scripts/all.sh --help
# 2. tests/scripts/all.sh --list-all-components
# 3. tests/scripts/all.sh --list-components
# 4. tests/scripts/all.sh --seed 4 --keep-going single_component_name
# This wrapper does not support other invocations.
set -eu
# Cases 1-3
if [ "$#" -eq 1 ]; then
if [ "$1" = '--help' ]; then
# It doesn't matter which one we use, they're the same
tests/scripts/mbedtls-all.sh "$1"
exit 0
fi
if [ "$1" = '--list-all-components' -o "$1" = '--list-components' ]; then
# Invoke both
tests/scripts/mbedtls-all.sh "$1"
(cd tf-psa-crypto && tests/scripts/all.sh "$1")
exit 0
fi
fi
if [ "$#" -ne 4 -o "${1:-unset}" != '--seed' -o "${3:-unset}" != '--keep-going' ]; then
echo "This invocation is not supported by the transitional wrapper." >&2
echo "See the comments at the top of $0." >&2
exit 1
fi
# Case 4: invoke the right all.sh for this component
comp_name=$4
# Get the list of components available on each side.
COMP_MBEDTLS=$(tests/scripts/mbedtls-all.sh --list-all-components | tr '\n' ' ')
COMP_CRYPTO=$(cd tf-psa-crypto && tests/scripts/all.sh --list-all-components | tr '\n' ' ')
# tell if $1 is in space-separated list $2
is_in() {
needle=$1
haystack=$2
case " $haystack " in
*" $needle "*) echo 1;;
*) echo 0;;
esac
}
is_crypto=$(is_in "$comp_name" "$COMP_CRYPTO")
is_mbedtls=$(is_in "$comp_name" "$COMP_MBEDTLS")
# Component should be on exactly one side (see comment near the top).
if [ "$is_crypto" -eq 1 -a "$is_mbedtls" -eq 1 ]; then
echo "Component '$comp_name' is both in crypto and Mbed TLS". >&2
echo "See the comments at the top of $0." >&2
exit 1
fi
if [ "$is_crypto" -eq 0 -a "$is_mbedtls" -eq 0 ]; then
echo "Component '$comp_name' is neither in crypto nor in Mbed TLS". >&2
echo "See the comments at the top of $0." >&2
exit 1
fi
# Invoke the real thing
if [ "$is_crypto" -eq 1 ]; then
# Make sure the path to the outcomes file is absolute. This is done by
# pre_prepare_outcome_file() however by the time it runs we've already
# changed the working directory, so do it now.
if [ -n "${MBEDTLS_TEST_OUTCOME_FILE+set}" ]; then
case "$MBEDTLS_TEST_OUTCOME_FILE" in
[!/]*) MBEDTLS_TEST_OUTCOME_FILE="$PWD/$MBEDTLS_TEST_OUTCOME_FILE";;
esac
export MBEDTLS_TEST_OUTCOME_FILE
fi
cd tf-psa-crypto
exec tests/scripts/all.sh "$@"
else
exec tests/scripts/mbedtls-all.sh "$@"
fi
-763
View File
@@ -1,763 +0,0 @@
#!/usr/bin/env python3
"""Analyze the test outcomes from a full CI run.
This script can also run on outcomes from a partial run, but the results are
less likely to be useful.
"""
import re
import typing
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import outcome_analysis
class CoverageTask(outcome_analysis.CoverageTask):
"""Justify test cases that are never executed."""
@staticmethod
def _has_word_re(words: typing.Iterable[str],
exclude: typing.Optional[str] = None) -> typing.Pattern:
"""Construct a regex that matches if any of the words appears.
The occurrence must start and end at a word boundary.
If exclude is specified, strings containing a match for that
regular expression will not match the returned pattern.
"""
exclude_clause = r''
if exclude:
exclude_clause = r'(?!.*' + exclude + ')'
return re.compile(exclude_clause +
r'.*\b(?:' + r'|'.join(words) + r')\b.*',
re.DOTALL)
# generate_psa_tests.py generates test cases involving cryptographic
# mechanisms (key types, families, algorithms) that are declared but
# not implemented. Until we improve the Python scripts, ignore those
# test cases in the analysis.
# https://github.com/Mbed-TLS/mbedtls/issues/9572
_PSA_MECHANISMS_NOT_IMPLEMENTED = [
r'CBC_MAC',
r'DETERMINISTIC_DSA',
r'DET_DSA',
r'DSA',
r'ECC_KEY_PAIR\(BRAINPOOL_P_R1\) (?:160|192|224|320)-bit',
r'ECC_KEY_PAIR\(SECP_K1\) 225-bit',
r'ECC_PAIR\(BP_R1\) (?:160|192|224|320)-bit',
r'ECC_PAIR\(SECP_K1\) 225-bit',
r'ECC_PUBLIC_KEY\(BRAINPOOL_P_R1\) (?:160|192|224|320)-bit',
r'ECC_PUBLIC_KEY\(SECP_K1\) 225-bit',
r'ECC_PUB\(BP_R1\) (?:160|192|224|320)-bit',
r'ECC_PUB\(SECP_K1\) 225-bit',
r'ED25519PH',
r'ED448PH',
r'PEPPER',
r'PURE_EDDSA',
r'SECP_R2',
r'SECT_K1',
r'SECT_R1',
r'SECT_R2',
r'SHAKE256_512',
r'SHA_512_224',
r'SHA_512_256',
r'TWISTED_EDWARDS',
r'XTS',
]
PSA_MECHANISM_NOT_IMPLEMENTED_SEARCH_RE = \
_has_word_re(_PSA_MECHANISMS_NOT_IMPLEMENTED)
IGNORED_TESTS = {
'ssl-opt': [
# We don't run ssl-opt.sh with Valgrind on the CI because
# it's extremely slow. We don't intend to change this.
'DTLS client reconnect from same port: reconnect, nbio, valgrind',
# We don't have IPv6 in our CI environment.
# https://github.com/Mbed-TLS/mbedtls-test/issues/176
'DTLS cookie: enabled, IPv6',
# Disabled due to OpenSSL bug.
# https://github.com/openssl/openssl/issues/18887
'DTLS fragmenting: 3d, openssl client, DTLS 1.2',
# We don't run ssl-opt.sh with Valgrind on the CI because
# it's extremely slow. We don't intend to change this.
'DTLS fragmenting: proxy MTU: auto-reduction (with valgrind)',
# TLS doesn't use restartable ECDH yet.
# https://github.com/Mbed-TLS/mbedtls/issues/7294
re.compile(r'EC restart:.*no USE_PSA.*'),
],
'test_suite_config.mbedtls_boolean': [
# https://github.com/Mbed-TLS/mbedtls/issues/9583
'Config: !MBEDTLS_ECP_NIST_OPTIM',
# We never test without the PSA client code. Should we?
# https://github.com/Mbed-TLS/TF-PSA-Crypto/issues/112
'Config: !MBEDTLS_PSA_CRYPTO_CLIENT',
# Missing coverage of test configurations.
# https://github.com/Mbed-TLS/mbedtls/issues/9585
'Config: !MBEDTLS_SSL_DTLS_ANTI_REPLAY',
# Missing coverage of test configurations.
# https://github.com/Mbed-TLS/mbedtls/issues/9585
'Config: !MBEDTLS_SSL_DTLS_HELLO_VERIFY',
# We don't run test_suite_config when we test this.
# https://github.com/Mbed-TLS/mbedtls/issues/9586
'Config: !MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED',
# We only test multithreading with pthreads.
# https://github.com/Mbed-TLS/mbedtls/issues/9584
'Config: !MBEDTLS_THREADING_PTHREAD',
# Built but not tested.
# https://github.com/Mbed-TLS/mbedtls/issues/9587
'Config: MBEDTLS_AES_USE_HARDWARE_ONLY',
# Untested platform-specific optimizations.
# https://github.com/Mbed-TLS/mbedtls/issues/9588
'Config: MBEDTLS_HAVE_SSE2',
# Obsolete configuration option, to be replaced by
# PSA entropy drivers.
# https://github.com/Mbed-TLS/mbedtls/issues/8150
'Config: MBEDTLS_NO_PLATFORM_ENTROPY',
# Untested aspect of the platform interface.
# https://github.com/Mbed-TLS/mbedtls/issues/9589
'Config: MBEDTLS_PLATFORM_NO_STD_FUNCTIONS',
# In a client-server build, test_suite_config runs in the
# client configuration, so it will never report
# MBEDTLS_PSA_CRYPTO_SPM as enabled. That's ok.
'Config: MBEDTLS_PSA_CRYPTO_SPM',
# We don't test on armv8 yet.
'Config: MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
'Config: MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY',
'Config: MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY',
'Config: MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY',
# We don't run test_suite_config when we test this.
# https://github.com/Mbed-TLS/mbedtls/issues/9586
'Config: MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND',
],
'test_suite_config.psa_boolean': [
# We don't test with HMAC disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9591
'Config: !PSA_WANT_ALG_HMAC',
# The DERIVE key type is always enabled.
'Config: !PSA_WANT_KEY_TYPE_DERIVE',
# More granularity of key pair type enablement macros
# than we care to test.
# https://github.com/Mbed-TLS/mbedtls/issues/9590
'Config: !PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT',
'Config: !PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE',
'Config: !PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT',
# More granularity of key pair type enablement macros
# than we care to test.
# https://github.com/Mbed-TLS/mbedtls/issues/9590
'Config: !PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT',
'Config: !PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT',
# We don't test with HMAC disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9591
'Config: !PSA_WANT_KEY_TYPE_HMAC',
# The PASSWORD key type is always enabled.
'Config: !PSA_WANT_KEY_TYPE_PASSWORD',
# The PASSWORD_HASH key type is always enabled.
'Config: !PSA_WANT_KEY_TYPE_PASSWORD_HASH',
# The RAW_DATA key type is always enabled.
'Config: !PSA_WANT_KEY_TYPE_RAW_DATA',
# More granularity of key pair type enablement macros
# than we care to test.
# https://github.com/Mbed-TLS/mbedtls/issues/9590
'Config: !PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT',
'Config: !PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT',
# Algorithm declared but not supported.
'Config: PSA_WANT_ALG_CBC_MAC',
# Algorithm declared but not supported.
'Config: PSA_WANT_ALG_XTS',
# Family declared but not supported.
'Config: PSA_WANT_ECC_SECP_K1_224',
# More granularity of key pair type enablement macros
# than we care to test.
# https://github.com/Mbed-TLS/mbedtls/issues/9590
'Config: PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE',
'Config: PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
'Config: PSA_WANT_KEY_TYPE_RSA_KEY_PAIR',
'Config: PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
],
'test_suite_config.psa_combinations': [
# We don't test this unusual, but sensible configuration.
# https://github.com/Mbed-TLS/mbedtls/issues/9592
'Config: PSA_WANT_ALG_DETERMINSTIC_ECDSA without PSA_WANT_ALG_ECDSA',
],
'test_suite_pkcs12': [
# We never test with CBC/PKCS5/PKCS12 enabled but
# PKCS7 padding disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9580
'PBE Decrypt, (Invalid padding & PKCS7 padding disabled)',
'PBE Encrypt, pad = 8 (PKCS7 padding disabled)',
],
'test_suite_pkcs5': [
# We never test with CBC/PKCS5/PKCS12 enabled but
# PKCS7 padding disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9580
'PBES2 Decrypt (Invalid padding & PKCS7 padding disabled)',
'PBES2 Encrypt, pad=6 (PKCS7 padding disabled)',
'PBES2 Encrypt, pad=8 (PKCS7 padding disabled)',
],
'test_suite_psa_crypto_generate_key.generated': [
# Ignore mechanisms that are not implemented, except
# for public keys for which we always test that
# psa_generate_key() returns PSA_ERROR_INVALID_ARGUMENT
# regardless of whether the specific key type is supported.
_has_word_re((mech
for mech in _PSA_MECHANISMS_NOT_IMPLEMENTED
if not mech.startswith('ECC_PUB')),
exclude=r'ECC_PUB'),
],
'test_suite_psa_crypto_metadata': [
# Algorithms declared but not supported.
# https://github.com/Mbed-TLS/mbedtls/issues/9579
'Asymmetric signature: Ed25519ph',
'Asymmetric signature: Ed448ph',
'Asymmetric signature: pure EdDSA',
'Cipher: XTS',
'MAC: CBC_MAC-3DES',
'MAC: CBC_MAC-AES-128',
'MAC: CBC_MAC-AES-192',
'MAC: CBC_MAC-AES-256',
],
'test_suite_psa_crypto_not_supported.generated': [
# It is a bug that not-supported test cases aren't getting
# run for never-implemented key types.
# https://github.com/Mbed-TLS/mbedtls/issues/7915
PSA_MECHANISM_NOT_IMPLEMENTED_SEARCH_RE,
# We never test with DH key support disabled but support
# for a DH group enabled. The dependencies of these test
# cases don't really make sense.
# https://github.com/Mbed-TLS/mbedtls/issues/9574
re.compile(r'PSA \w+ DH_.*type not supported'),
# We only test partial support for DH with the 2048-bit group
# enabled and the other groups disabled.
# https://github.com/Mbed-TLS/mbedtls/issues/9575
'PSA generate DH_KEY_PAIR(RFC7919) 2048-bit group not supported',
'PSA import DH_KEY_PAIR(RFC7919) 2048-bit group not supported',
'PSA import DH_PUBLIC_KEY(RFC7919) 2048-bit group not supported',
],
'test_suite_psa_crypto_op_fail.generated': [
# Ignore mechanisms that are not implemented, except
# for test cases that assume the mechanism is not supported.
_has_word_re(_PSA_MECHANISMS_NOT_IMPLEMENTED,
exclude=(r'.*: !(?:' +
r'|'.join(_PSA_MECHANISMS_NOT_IMPLEMENTED) +
r')\b')),
# Incorrect dependency generation. To be fixed as part of the
# resolution of https://github.com/Mbed-TLS/mbedtls/issues/9167
# by forward-porting the commit
# "PSA test case generation: dependency inference class: operation fail"
# from https://github.com/Mbed-TLS/mbedtls/pull/9025 .
re.compile(r'.* with (?:DH|ECC)_(?:KEY_PAIR|PUBLIC_KEY)\(.*'),
# We never test with the HMAC algorithm enabled but the HMAC
# key type disabled. Those dependencies don't really make sense.
# https://github.com/Mbed-TLS/mbedtls/issues/9573
re.compile(r'.* !HMAC with HMAC'),
],
'test_suite_psa_crypto_storage_format.current': [
PSA_MECHANISM_NOT_IMPLEMENTED_SEARCH_RE,
],
'test_suite_psa_crypto_storage_format.v0': [
PSA_MECHANISM_NOT_IMPLEMENTED_SEARCH_RE,
],
'tls13-misc': [
# Disabled due to OpenSSL bug.
# https://github.com/openssl/openssl/issues/10714
'TLS 1.3 O->m: resumption',
# Disabled due to OpenSSL command line limitation.
# https://github.com/Mbed-TLS/mbedtls/issues/9582
'TLS 1.3 m->O: resumption with early data',
],
}
# The names that we give to classes derived from DriverVSReference do not
# follow the usual naming convention, because it's more readable to use
# underscores and parts of the configuration names. Also, these classes
# are just there to specify some data, so they don't need repetitive
# documentation.
#pylint: disable=invalid-name,missing-class-docstring
class DriverVSReference_hash(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_hash_use_psa'
DRIVER = 'test_psa_crypto_config_accel_hash_use_psa'
IGNORED_SUITES = [
'shax', 'mdx', # the software implementations that are being excluded
'md.psa', # purposefully depends on whether drivers are present
'psa_crypto_low_hash.generated', # testing the builtins
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
}
class DriverVSReference_hmac(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_hmac'
DRIVER = 'test_psa_crypto_config_accel_hmac'
IGNORED_SUITES = [
# These suites require legacy hash support, which is disabled
# in the accelerated component.
'shax', 'mdx',
# This suite tests builtins directly, but these are missing
# in the accelerated case.
'psa_crypto_low_hash.generated',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
re.compile(r'.*\bMBEDTLS_MD_C\b')
],
'test_suite_md': [
# Builtin HMAC is not supported in the accelerate component.
re.compile('.*HMAC.*'),
# Following tests make use of functions which are not available
# when MD_C is disabled, as it happens in the accelerated
# test component.
re.compile('generic .* Hash file .*'),
'MD list',
],
'test_suite_md.psa': [
# "legacy only" tests require hash algorithms to be NOT
# accelerated, but this of course false for the accelerated
# test component.
re.compile('PSA dispatch .* legacy only'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
}
class DriverVSReference_cipher_aead_cmac(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_cipher_aead_cmac'
DRIVER = 'test_psa_crypto_config_accel_cipher_aead_cmac'
# Modules replaced by drivers.
IGNORED_SUITES = [
# low-level (block/stream) cipher modules
'aes', 'aria', 'camellia', 'des', 'chacha20',
# AEAD modes and CMAC
'ccm', 'chachapoly', 'cmac', 'gcm',
# The Cipher abstraction layer
'cipher',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA|CHACHA20|DES)_.*'),
re.compile(r'.*\bMBEDTLS_(CCM|CHACHAPOLY|CMAC|GCM)_.*'),
re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
re.compile(r'.*\bMBEDTLS_CIPHER_.*'),
],
# PEM decryption is not supported so far.
# The rest of PEM (write, unencrypted read) works though.
'test_suite_pem': [
re.compile(r'PEM read .*(AES|DES|\bencrypt).*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# Following tests depend on AES_C/DES_C but are not about
# them really, just need to know some error code is there.
'test_suite_error': [
'Low and high error',
'Single low error'
],
# Similar to test_suite_error above.
'test_suite_version': [
'Check for MBEDTLS_AES_C when already present',
],
# The en/decryption part of PKCS#12 is not supported so far.
# The rest of PKCS#12 (key derivation) works though.
'test_suite_pkcs12': [
re.compile(r'PBE Encrypt, .*'),
re.compile(r'PBE Decrypt, .*'),
],
# The en/decryption part of PKCS#5 is not supported so far.
# The rest of PKCS#5 (PBKDF2) works though.
'test_suite_pkcs5': [
re.compile(r'PBES2 Encrypt, .*'),
re.compile(r'PBES2 Decrypt .*'),
],
# Encrypted keys are not supported so far.
# pylint: disable=line-too-long
'test_suite_pkparse': [
'Key ASN1 (Encrypted key PKCS12, trailing garbage data)',
'Key ASN1 (Encrypted key PKCS5, trailing garbage data)',
re.compile(r'Parse (RSA|EC) Key .*\(.* ([Ee]ncrypted|password).*\)'),
],
# Encrypted keys are not supported so far.
'ssl-opt': [
'TLS: password protected server key',
'TLS: password protected client key',
'TLS: password protected server key, two certificates',
],
}
class DriverVSReference_ecp_light_only(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_ecc_ecp_light_only'
DRIVER = 'test_psa_crypto_config_accel_ecc_ecp_light_only'
IGNORED_SUITES = [
# Modules replaced by drivers
'ecdsa', 'ecdh', 'ecjpake',
# Unit tests for the built-in implementation
'psa_crypto_ecp',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# This test wants a legacy function that takes f_rng, p_rng
# arguments, and uses legacy ECDSA for that. The test is
# really about the wrapper around the PSA RNG, not ECDSA.
'test_suite_random': [
'PSA classic wrapper: ECDSA signature (SECP256R1)',
],
# In the accelerated test ECP_C is not set (only ECP_LIGHT is)
# so we must ignore disparities in the tests for which ECP_C
# is required.
'test_suite_ecp': [
re.compile(r'ECP check public-private .*'),
re.compile(r'ECP calculate public: .*'),
re.compile(r'ECP gen keypair .*'),
re.compile(r'ECP point muladd .*'),
re.compile(r'ECP point multiplication .*'),
re.compile(r'ECP test vectors .*'),
],
'test_suite_ssl': [
# This deprecated function is only present when ECP_C is On.
'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
],
}
class DriverVSReference_no_ecp_at_all(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_ecc_no_ecp_at_all'
DRIVER = 'test_psa_crypto_config_accel_ecc_no_ecp_at_all'
IGNORED_SUITES = [
# Modules replaced by drivers
'ecp', 'ecdsa', 'ecdh', 'ecjpake',
# Unit tests for the built-in implementation
'psa_crypto_ecp',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# See ecp_light_only
'test_suite_random': [
'PSA classic wrapper: ECDSA signature (SECP256R1)',
],
'test_suite_pkparse': [
# When PK_PARSE_C and ECP_C are defined then PK_PARSE_EC_COMPRESSED
# is automatically enabled in build_info.h (backward compatibility)
# even if it is disabled in config_psa_crypto_no_ecp_at_all(). As a
# consequence compressed points are supported in the reference
# component but not in the accelerated one, so they should be skipped
# while checking driver's coverage.
re.compile(r'Parse EC Key .*compressed\)'),
re.compile(r'Parse Public EC Key .*compressed\)'),
],
# See ecp_light_only
'test_suite_ssl': [
'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
],
}
class DriverVSReference_ecc_no_bignum(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_ecc_no_bignum'
DRIVER = 'test_psa_crypto_config_accel_ecc_no_bignum'
IGNORED_SUITES = [
# Modules replaced by drivers
'ecp', 'ecdsa', 'ecdh', 'ecjpake',
'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
'bignum.generated', 'bignum.misc',
# Unit tests for the built-in implementation
'psa_crypto_ecp',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# See ecp_light_only
'test_suite_random': [
'PSA classic wrapper: ECDSA signature (SECP256R1)',
],
# See no_ecp_at_all
'test_suite_pkparse': [
re.compile(r'Parse EC Key .*compressed\)'),
re.compile(r'Parse Public EC Key .*compressed\)'),
],
'test_suite_asn1parse': [
'INTEGER too large for mpi',
],
'test_suite_asn1write': [
re.compile(r'ASN.1 Write mpi.*'),
],
'test_suite_debug': [
re.compile(r'Debug print mbedtls_mpi.*'),
],
# See ecp_light_only
'test_suite_ssl': [
'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
],
}
class DriverVSReference_ecc_ffdh_no_bignum(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_ecc_ffdh_no_bignum'
DRIVER = 'test_psa_crypto_config_accel_ecc_ffdh_no_bignum'
IGNORED_SUITES = [
# Modules replaced by drivers
'ecp', 'ecdsa', 'ecdh', 'ecjpake', 'dhm',
'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
'bignum.generated', 'bignum.misc',
# Unit tests for the built-in implementation
'psa_crypto_ecp',
]
IGNORED_TESTS = {
'ssl-opt': [
# DHE support in TLS 1.2 requires built-in MBEDTLS_DHM_C
# (because it needs custom groups, which PSA does not
# provide), even with MBEDTLS_USE_PSA_CRYPTO.
re.compile(r'PSK callback:.*\bdhe-psk\b.*'),
],
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
re.compile(r'.*\bMBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\b.*'),
re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# See ecp_light_only
'test_suite_random': [
'PSA classic wrapper: ECDSA signature (SECP256R1)',
],
# See no_ecp_at_all
'test_suite_pkparse': [
re.compile(r'Parse EC Key .*compressed\)'),
re.compile(r'Parse Public EC Key .*compressed\)'),
],
'test_suite_asn1parse': [
'INTEGER too large for mpi',
],
'test_suite_asn1write': [
re.compile(r'ASN.1 Write mpi.*'),
],
'test_suite_debug': [
re.compile(r'Debug print mbedtls_mpi.*'),
],
# See ecp_light_only
'test_suite_ssl': [
'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
],
}
class DriverVSReference_ffdh_alg(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_ffdh'
DRIVER = 'test_psa_crypto_config_accel_ffdh'
IGNORED_SUITES = ['dhm']
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
}
class DriverVSReference_tfm_config(outcome_analysis.DriverVSReference):
REFERENCE = 'test_tfm_config_no_p256m'
DRIVER = 'test_tfm_config_p256m_driver_accel_ec'
IGNORED_SUITES = [
# Modules replaced by drivers
'asn1parse', 'asn1write',
'ecp', 'ecdsa', 'ecdh', 'ecjpake',
'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
'bignum.generated', 'bignum.misc',
# Unit tests for the built-in implementation
'psa_crypto_ecp',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
re.compile(r'.*\bMBEDTLS_(ASN1\w+)_C\b.*'),
re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECP)_.*'),
re.compile(r'.*\bMBEDTLS_PSA_P256M_DRIVER_ENABLED\b.*')
],
'test_suite_config.crypto_combinations': [
'Config: ECC: Weierstrass curves only',
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# See ecp_light_only
'test_suite_random': [
'PSA classic wrapper: ECDSA signature (SECP256R1)',
],
}
class DriverVSReference_rsa(outcome_analysis.DriverVSReference):
REFERENCE = 'test_psa_crypto_config_reference_rsa_crypto'
DRIVER = 'test_psa_crypto_config_accel_rsa_crypto'
IGNORED_SUITES = [
# Modules replaced by drivers.
'rsa', 'pkcs1_v15', 'pkcs1_v21',
# We temporarily don't care about PK stuff.
'pk', 'pkwrite', 'pkparse'
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(PKCS1|RSA)_.*'),
re.compile(r'.*\bMBEDTLS_GENPRIME\b.*')
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
# Following tests depend on RSA_C but are not about
# them really, just need to know some error code is there.
'test_suite_error': [
'Low and high error',
'Single high error'
],
# Constant time operations only used for PKCS1_V15
'test_suite_constant_time': [
re.compile(r'mbedtls_ct_zeroize_if .*'),
re.compile(r'mbedtls_ct_memmove_left .*')
],
'test_suite_psa_crypto': [
# We don't support generate_key_custom entry points
# in drivers yet.
re.compile(r'PSA generate key custom: RSA, e=.*'),
re.compile(r'PSA generate key ext: RSA, e=.*'),
],
}
class DriverVSReference_block_cipher_dispatch(outcome_analysis.DriverVSReference):
REFERENCE = 'test_full_block_cipher_legacy_dispatch'
DRIVER = 'test_full_block_cipher_psa_dispatch'
IGNORED_SUITES = [
# Skipped in the accelerated component
'aes', 'aria', 'camellia',
# These require AES_C, ARIA_C or CAMELLIA_C to be enabled in
# order for the cipher module (actually cipher_wrapper) to work
# properly. However these symbols are disabled in the accelerated
# component so we ignore them.
'cipher.ccm', 'cipher.gcm', 'cipher.aes', 'cipher.aria',
'cipher.camellia',
]
IGNORED_TESTS = {
'test_suite_config': [
re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA)_.*'),
re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
],
'test_suite_cmac': [
# Following tests require AES_C/ARIA_C/CAMELLIA_C to be enabled,
# but these are not available in the accelerated component.
'CMAC null arguments',
re.compile('CMAC.* (AES|ARIA|Camellia).*'),
],
'test_suite_cipher.padding': [
# Following tests require AES_C/CAMELLIA_C to be enabled,
# but these are not available in the accelerated component.
re.compile('Set( non-existent)? padding with (AES|CAMELLIA).*'),
],
'test_suite_pkcs5': [
# The AES part of PKCS#5 PBES2 is not yet supported.
# The rest of PKCS#5 (PBKDF2) works, though.
re.compile(r'PBES2 .* AES-.*')
],
'test_suite_pkparse': [
# PEM (called by pkparse) requires AES_C in order to decrypt
# the key, but this is not available in the accelerated
# component.
re.compile('Parse RSA Key.*(password|AES-).*'),
],
'test_suite_pem': [
# Following tests require AES_C, but this is diabled in the
# accelerated component.
re.compile('PEM read .*AES.*'),
'PEM read (unknown encryption algorithm)',
],
'test_suite_error': [
# Following tests depend on AES_C but are not about them
# really, just need to know some error code is there.
'Single low error',
'Low and high error',
],
'test_suite_version': [
# Similar to test_suite_error above.
'Check for MBEDTLS_AES_C when already present',
],
'test_suite_platform': [
# Incompatible with sanitizers (e.g. ASan). If the driver
# component uses a sanitizer but the reference component
# doesn't, we have a PASS vs SKIP mismatch.
'Check mbedtls_calloc overallocation',
],
}
#pylint: enable=invalid-name,missing-class-docstring
# List of tasks with a function that can handle this task and additional arguments if required
KNOWN_TASKS = {
'analyze_coverage': CoverageTask,
'analyze_driver_vs_reference_hash': DriverVSReference_hash,
'analyze_driver_vs_reference_hmac': DriverVSReference_hmac,
'analyze_driver_vs_reference_cipher_aead_cmac': DriverVSReference_cipher_aead_cmac,
'analyze_driver_vs_reference_ecp_light_only': DriverVSReference_ecp_light_only,
'analyze_driver_vs_reference_no_ecp_at_all': DriverVSReference_no_ecp_at_all,
'analyze_driver_vs_reference_ecc_no_bignum': DriverVSReference_ecc_no_bignum,
'analyze_driver_vs_reference_ecc_ffdh_no_bignum': DriverVSReference_ecc_ffdh_no_bignum,
'analyze_driver_vs_reference_ffdh_alg': DriverVSReference_ffdh_alg,
'analyze_driver_vs_reference_tfm_config': DriverVSReference_tfm_config,
'analyze_driver_vs_reference_rsa': DriverVSReference_rsa,
'analyze_block_cipher_dispatch': DriverVSReference_block_cipher_dispatch,
}
if __name__ == '__main__':
outcome_analysis.main(KNOWN_TASKS)
-469
View File
@@ -1,469 +0,0 @@
#!/usr/bin/env python3
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""Audit validity date of X509 crt/crl/csr.
This script is used to audit the validity date of crt/crl/csr used for testing.
It prints the information about X.509 objects excluding the objects that
are valid throughout the desired validity period. The data are collected
from framework/data_files/ and tests/suites/*.data files by default.
"""
import os
import re
import typing
import argparse
import datetime
import glob
import logging
import hashlib
from enum import Enum
# The script requires cryptography >= 35.0.0 which is only available
# for Python >= 3.6.
import cryptography
from cryptography import x509
from generate_test_code import FileWrapper
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
from mbedtls_framework import logging_util
def check_cryptography_version():
match = re.match(r'^[0-9]+', cryptography.__version__)
if match is None or int(match.group(0)) < 35:
raise Exception("audit-validity-dates requires cryptography >= 35.0.0"
+ "({} is too old)".format(cryptography.__version__))
class DataType(Enum):
CRT = 1 # Certificate
CRL = 2 # Certificate Revocation List
CSR = 3 # Certificate Signing Request
class DataFormat(Enum):
PEM = 1 # Privacy-Enhanced Mail
DER = 2 # Distinguished Encoding Rules
class AuditData:
"""Store data location, type and validity period of X.509 objects."""
#pylint: disable=too-few-public-methods
def __init__(self, data_type: DataType, x509_obj):
self.data_type = data_type
# the locations that the x509 object could be found
self.locations = [] # type: typing.List[str]
self.fill_validity_duration(x509_obj)
self._obj = x509_obj
encoding = cryptography.hazmat.primitives.serialization.Encoding.DER
self._identifier = hashlib.sha1(self._obj.public_bytes(encoding)).hexdigest()
@property
def identifier(self):
"""
Identifier of the underlying X.509 object, which is consistent across
different runs.
"""
return self._identifier
def fill_validity_duration(self, x509_obj):
"""Read validity period from an X.509 object."""
# Certificate expires after "not_valid_after"
# Certificate is invalid before "not_valid_before"
if self.data_type == DataType.CRT:
self.not_valid_after = x509_obj.not_valid_after
self.not_valid_before = x509_obj.not_valid_before
# CertificateRevocationList expires after "next_update"
# CertificateRevocationList is invalid before "last_update"
elif self.data_type == DataType.CRL:
self.not_valid_after = x509_obj.next_update
self.not_valid_before = x509_obj.last_update
# CertificateSigningRequest is always valid.
elif self.data_type == DataType.CSR:
self.not_valid_after = datetime.datetime.max
self.not_valid_before = datetime.datetime.min
else:
raise ValueError("Unsupported file_type: {}".format(self.data_type))
class X509Parser:
"""A parser class to parse crt/crl/csr file or data in PEM/DER format."""
PEM_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}(?P<data>.*?)-{5}END (?P=type)-{5}'
PEM_TAG_REGEX = br'-{5}BEGIN (?P<type>.*?)-{5}\n'
PEM_TAGS = {
DataType.CRT: 'CERTIFICATE',
DataType.CRL: 'X509 CRL',
DataType.CSR: 'CERTIFICATE REQUEST'
}
def __init__(self,
backends:
typing.Dict[DataType,
typing.Dict[DataFormat,
typing.Callable[[bytes], object]]]) \
-> None:
self.backends = backends
self.__generate_parsers()
def __generate_parser(self, data_type: DataType):
"""Parser generator for a specific DataType"""
tag = self.PEM_TAGS[data_type]
pem_loader = self.backends[data_type][DataFormat.PEM]
der_loader = self.backends[data_type][DataFormat.DER]
def wrapper(data: bytes):
pem_type = X509Parser.pem_data_type(data)
# It is in PEM format with target tag
if pem_type == tag:
return pem_loader(data)
# It is in PEM format without target tag
if pem_type:
return None
# It might be in DER format
try:
result = der_loader(data)
except ValueError:
result = None
return result
wrapper.__name__ = "{}.parser[{}]".format(type(self).__name__, tag)
return wrapper
def __generate_parsers(self):
"""Generate parsers for all support DataType"""
self.parsers = {}
for data_type, _ in self.PEM_TAGS.items():
self.parsers[data_type] = self.__generate_parser(data_type)
def __getitem__(self, item):
return self.parsers[item]
@staticmethod
def pem_data_type(data: bytes) -> typing.Optional[str]:
"""Get the tag from the data in PEM format
:param data: data to be checked in binary mode.
:return: PEM tag or "" when no tag detected.
"""
m = re.search(X509Parser.PEM_TAG_REGEX, data)
if m is not None:
return m.group('type').decode('UTF-8')
else:
return None
@staticmethod
def check_hex_string(hex_str: str) -> bool:
"""Check if the hex string is possibly DER data."""
hex_len = len(hex_str)
# At least 6 hex char for 3 bytes: Type + Length + Content
if hex_len < 6:
return False
# Check if Type (1 byte) is SEQUENCE.
if hex_str[0:2] != '30':
return False
# Check LENGTH (1 byte) value
content_len = int(hex_str[2:4], base=16)
consumed = 4
if content_len in (128, 255):
# Indefinite or Reserved
return False
elif content_len > 127:
# Definite, Long
length_len = (content_len - 128) * 2
content_len = int(hex_str[consumed:consumed+length_len], base=16)
consumed += length_len
# Check LENGTH
if hex_len != content_len * 2 + consumed:
return False
return True
class Auditor:
"""
A base class that uses X509Parser to parse files to a list of AuditData.
A subclass must implement the following methods:
- collect_default_files: Return a list of file names that are defaultly
used for parsing (auditing). The list will be stored in
Auditor.default_files.
- parse_file: Method that parses a single file to a list of AuditData.
A subclass may override the following methods:
- parse_bytes: Defaultly, it parses `bytes` that contains only one valid
X.509 data(DER/PEM format) to an X.509 object.
- walk_all: Defaultly, it iterates over all the files in the provided
file name list, calls `parse_file` for each file and stores the results
by extending the `results` passed to the function.
"""
def __init__(self, logger):
self.logger = logger
self.default_files = self.collect_default_files()
self.parser = X509Parser({
DataType.CRT: {
DataFormat.PEM: x509.load_pem_x509_certificate,
DataFormat.DER: x509.load_der_x509_certificate
},
DataType.CRL: {
DataFormat.PEM: x509.load_pem_x509_crl,
DataFormat.DER: x509.load_der_x509_crl
},
DataType.CSR: {
DataFormat.PEM: x509.load_pem_x509_csr,
DataFormat.DER: x509.load_der_x509_csr
},
})
def collect_default_files(self) -> typing.List[str]:
"""Collect the default files for parsing."""
raise NotImplementedError
def parse_file(self, filename: str) -> typing.List[AuditData]:
"""
Parse a list of AuditData from file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
raise NotImplementedError
def parse_bytes(self, data: bytes):
"""Parse AuditData from bytes."""
for data_type in list(DataType):
try:
result = self.parser[data_type](data)
except ValueError as val_error:
result = None
self.logger.warning(val_error)
if result is not None:
audit_data = AuditData(data_type, result)
return audit_data
return None
def walk_all(self,
results: typing.Dict[str, AuditData],
file_list: typing.Optional[typing.List[str]] = None) \
-> None:
"""
Iterate over all the files in the list and get audit data. The
results will be written to `results` passed to this function.
:param results: The dictionary used to store the parsed
AuditData. The keys of this dictionary should
be the identifier of the AuditData.
"""
if file_list is None:
file_list = self.default_files
for filename in file_list:
data_list = self.parse_file(filename)
for d in data_list:
if d.identifier in results:
results[d.identifier].locations.extend(d.locations)
else:
results[d.identifier] = d
@staticmethod
def find_test_dir():
"""Get the relative path for the Mbed TLS test directory."""
return os.path.relpath(build_tree.guess_mbedtls_root() + '/tests')
class TestDataAuditor(Auditor):
"""Class for auditing files in `framework/data_files/`"""
def collect_default_files(self):
"""Collect all files in `framework/data_files/`"""
test_data_glob = os.path.join(build_tree.guess_mbedtls_root(),
'framework', 'data_files/**')
data_files = [f for f in glob.glob(test_data_glob, recursive=True)
if os.path.isfile(f)]
return data_files
def parse_file(self, filename: str) -> typing.List[AuditData]:
"""
Parse a list of AuditData from data file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
with open(filename, 'rb') as f:
data = f.read()
results = []
# Try to parse all PEM blocks.
is_pem = False
for idx, m in enumerate(re.finditer(X509Parser.PEM_REGEX, data, flags=re.S), 1):
is_pem = True
result = self.parse_bytes(data[m.start():m.end()])
if result is not None:
result.locations.append("{}#{}".format(filename, idx))
results.append(result)
# Might be DER format.
if not is_pem:
result = self.parse_bytes(data)
if result is not None:
result.locations.append("{}".format(filename))
results.append(result)
return results
def parse_suite_data(data_f):
"""
Parses .data file for test arguments that possiblly have a
valid X.509 data. If you need a more precise parser, please
use generate_test_code.parse_test_data instead.
:param data_f: file object of the data file.
:return: Generator that yields test function argument list.
"""
for line in data_f:
line = line.strip()
# Skip comments
if line.startswith('#'):
continue
# Check parameters line
match = re.search(r'\A\w+(.*:)?\"', line)
if match:
# Read test vectors
parts = re.split(r'(?<!\\):', line)
parts = [x for x in parts if x]
args = parts[1:]
yield args
class SuiteDataAuditor(Auditor):
"""Class for auditing files in `tests/suites/*.data`"""
def collect_default_files(self):
"""Collect all files in `tests/suites/*.data`"""
test_dir = self.find_test_dir()
suites_data_folder = os.path.join(test_dir, 'suites')
data_files = glob.glob(os.path.join(suites_data_folder, '*.data'))
return data_files
def parse_file(self, filename: str):
"""
Parse a list of AuditData from test suite data file.
:param filename: name of the file to parse.
:return list of AuditData parsed from the file.
"""
audit_data_list = []
data_f = FileWrapper(filename)
for test_args in parse_suite_data(data_f):
for idx, test_arg in enumerate(test_args):
match = re.match(r'"(?P<data>[0-9a-fA-F]+)"', test_arg)
if not match:
continue
if not X509Parser.check_hex_string(match.group('data')):
continue
audit_data = self.parse_bytes(bytes.fromhex(match.group('data')))
if audit_data is None:
continue
audit_data.locations.append("{}:{}:#{}".format(filename,
data_f.line_no,
idx + 1))
audit_data_list.append(audit_data)
return audit_data_list
def list_all(audit_data: AuditData):
for loc in audit_data.locations:
print("{}\t{:20}\t{:20}\t{:3}\t{}".format(
audit_data.identifier,
audit_data.not_valid_before.isoformat(timespec='seconds'),
audit_data.not_valid_after.isoformat(timespec='seconds'),
audit_data.data_type.name,
loc))
def main():
"""
Perform argument parsing.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-a', '--all',
action='store_true',
help='list the information of all the files')
parser.add_argument('-v', '--verbose',
action='store_true', dest='verbose',
help='show logs')
parser.add_argument('--from', dest='start_date',
help=('Start of desired validity period (UTC, YYYY-MM-DD). '
'Default: today'),
metavar='DATE')
parser.add_argument('--to', dest='end_date',
help=('End of desired validity period (UTC, YYYY-MM-DD). '
'Default: --from'),
metavar='DATE')
parser.add_argument('--data-files', action='append', nargs='*',
help='data files to audit',
metavar='FILE')
parser.add_argument('--suite-data-files', action='append', nargs='*',
help='suite data files to audit',
metavar='FILE')
args = parser.parse_args()
# start main routine
# setup logger
logger = logging.getLogger()
logging_util.configure_logger(logger)
logger.setLevel(logging.DEBUG if args.verbose else logging.ERROR)
td_auditor = TestDataAuditor(logger)
sd_auditor = SuiteDataAuditor(logger)
data_files = []
suite_data_files = []
if args.data_files is None and args.suite_data_files is None:
data_files = td_auditor.default_files
suite_data_files = sd_auditor.default_files
else:
if args.data_files is not None:
data_files = [x for l in args.data_files for x in l]
if args.suite_data_files is not None:
suite_data_files = [x for l in args.suite_data_files for x in l]
# validity period start date
if args.start_date:
start_date = datetime.datetime.fromisoformat(args.start_date)
else:
start_date = datetime.datetime.today()
# validity period end date
if args.end_date:
end_date = datetime.datetime.fromisoformat(args.end_date)
else:
end_date = start_date
# go through all the files
audit_results = {}
td_auditor.walk_all(audit_results, data_files)
sd_auditor.walk_all(audit_results, suite_data_files)
logger.info("Total: {} objects found!".format(len(audit_results)))
# we filter out the files whose validity duration covers the provided
# duration.
filter_func = lambda d: (start_date < d.not_valid_before) or \
(d.not_valid_after < end_date)
sortby_end = lambda d: d.not_valid_after
if args.all:
filter_func = None
# filter and output the results
for d in sorted(filter(filter_func, audit_results.values()), key=sortby_end):
list_all(d)
logger.debug("Done!")
check_cryptography_version()
if __name__ == "__main__":
main()
-249
View File
@@ -1,249 +0,0 @@
#!/bin/sh
# basic-build-test.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# Purpose
#
# Executes the basic test suites, captures the results, and generates a simple
# test report and code coverage report.
#
# The tests include:
# * Unit tests - executed using tests/scripts/run-test-suite.pl
# * Self-tests - executed using the test suites above
# * System tests - executed using tests/ssl-opt.sh
# * Interoperability tests - executed using tests/compat.sh
#
# The tests focus on functionality and do not consider performance.
#
# Note the tests self-adapt due to configurations in include/mbedtls/mbedtls_config.h
# which can lead to some tests being skipped, and can cause the number of
# available tests to fluctuate.
#
# This script has been written to be generic and should work on any shell.
#
# Usage: basic-build-test.sh
#
# Abort on errors (and uninitiliased variables)
set -eu
if [ -d library -a -d include -a -d tests ]; then :; else
echo "Must be run from Mbed TLS root" >&2
exit 1
fi
: ${OPENSSL:="openssl"}
: ${GNUTLS_CLI:="gnutls-cli"}
: ${GNUTLS_SERV:="gnutls-serv"}
# Used to make ssl-opt.sh deterministic.
#
# See also RELEASE_SEED in all.sh. Debugging is easier if both values are kept
# in sync. If you change the value here because it breaks some tests, you'll
# definitely want to change it in all.sh as well.
: ${SEED:=1}
export SEED
# if MAKEFLAGS is not set add the -j option to speed up invocations of make
if [ -z "${MAKEFLAGS+set}" ]; then
export MAKEFLAGS="-j"
fi
# To avoid setting OpenSSL and GnuTLS for each call to compat.sh and ssl-opt.sh
# we just export the variables they require
export OPENSSL="$OPENSSL"
export GNUTLS_CLI="$GNUTLS_CLI"
export GNUTLS_SERV="$GNUTLS_SERV"
CONFIG_H='include/mbedtls/mbedtls_config.h'
CONFIG_BAK="$CONFIG_H.bak"
# Step 0 - print build environment info
OPENSSL="$OPENSSL" \
GNUTLS_CLI="$GNUTLS_CLI" \
GNUTLS_SERV="$GNUTLS_SERV" \
scripts/output_env.sh
echo
# Step 1 - Make and instrumented build for code coverage
export CFLAGS=' --coverage -g3 -O0 '
export LDFLAGS=' --coverage'
make clean
cp "$CONFIG_H" "$CONFIG_BAK"
scripts/config.py full
make
# Step 2 - Execute the tests
TEST_OUTPUT=out_${PPID}
cd tests
if [ ! -f "seedfile" ]; then
dd if=/dev/urandom of="seedfile" bs=64 count=1
fi
if [ ! -f "../tf-psa-crypto/tests/seedfile" ]; then
cp "seedfile" "../tf-psa-crypto/tests/seedfile"
fi
echo
# Step 2a - Unit Tests (keep going even if some tests fail)
echo '################ Unit tests ################'
perl scripts/run-test-suites.pl -v 2 |tee unit-test-$TEST_OUTPUT
echo '^^^^^^^^^^^^^^^^ Unit tests ^^^^^^^^^^^^^^^^'
echo
# Step 2b - System Tests (keep going even if some tests fail)
echo
echo '################ ssl-opt.sh ################'
echo "ssl-opt.sh will use SEED=$SEED for udp_proxy"
sh ssl-opt.sh |tee sys-test-$TEST_OUTPUT
echo '^^^^^^^^^^^^^^^^ ssl-opt.sh ^^^^^^^^^^^^^^^^'
echo
# Step 2c - Compatibility tests (keep going even if some tests fail)
echo '################ compat.sh ################'
{
echo '#### compat.sh: Default versions'
sh compat.sh -e 'ARIA\|CHACHA'
echo
echo '#### compat.sh: next (ARIA, ChaCha)'
OPENSSL="$OPENSSL_NEXT" sh compat.sh -e '^$' -f 'ARIA\|CHACHA'
echo
} | tee compat-test-$TEST_OUTPUT
echo '^^^^^^^^^^^^^^^^ compat.sh ^^^^^^^^^^^^^^^^'
echo
# Step 3 - Process the coverage report
cd ..
{
make lcov
echo SUCCESS
} | tee tests/cov-$TEST_OUTPUT
if [ "$(tail -n1 tests/cov-$TEST_OUTPUT)" != "SUCCESS" ]; then
echo >&2 "Fatal: 'make lcov' failed"
exit 2
fi
# Step 4 - Summarise the test report
echo
echo "========================================================================="
echo "Test Report Summary"
echo
# A failure of the left-hand side of a pipe is ignored (this is a limitation
# of sh). We'll use the presence of this file as a marker that the generation
# of the report succeeded.
rm -f "tests/basic-build-test-$$.ok"
{
cd tests
# Step 4a - Unit tests
echo "Unit tests - tests/scripts/run-test-suites.pl"
PASSED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/test cases passed :[\t]*\([0-9]*\)/\1/p'| tr -d ' ')
SKIPPED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/skipped :[ \t]*\([0-9]*\)/\1/p'| tr -d ' ')
TOTAL_SUITES=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/.* (\([0-9]*\) .*, [0-9]* tests run)/\1/p'| tr -d ' ')
FAILED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/failed :[\t]*\([0-9]*\)/\1/p' |tr -d ' ')
echo "No test suites : $TOTAL_SUITES"
echo "Passed : $PASSED_TESTS"
echo "Failed : $FAILED_TESTS"
echo "Skipped : $SKIPPED_TESTS"
echo "Total exec'd tests : $(($PASSED_TESTS + $FAILED_TESTS))"
echo "Total avail tests : $(($PASSED_TESTS + $FAILED_TESTS + $SKIPPED_TESTS))"
echo
TOTAL_PASS=$PASSED_TESTS
TOTAL_FAIL=$FAILED_TESTS
TOTAL_SKIP=$SKIPPED_TESTS
TOTAL_AVAIL=$(($PASSED_TESTS + $FAILED_TESTS + $SKIPPED_TESTS))
TOTAL_EXED=$(($PASSED_TESTS + $FAILED_TESTS))
# Step 4b - TLS Options tests
echo "TLS Options tests - tests/ssl-opt.sh"
PASSED_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* (\([0-9]*\) \/ [0-9]* tests ([0-9]* skipped))$/\1/p')
SKIPPED_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* ([0-9]* \/ [0-9]* tests (\([0-9]*\) skipped))$/\1/p')
TOTAL_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* ([0-9]* \/ \([0-9]*\) tests ([0-9]* skipped))$/\1/p')
FAILED_TESTS=$(($TOTAL_TESTS - $PASSED_TESTS))
echo "Passed : $PASSED_TESTS"
echo "Failed : $FAILED_TESTS"
echo "Skipped : $SKIPPED_TESTS"
echo "Total exec'd tests : $TOTAL_TESTS"
echo "Total avail tests : $(($TOTAL_TESTS + $SKIPPED_TESTS))"
echo
TOTAL_PASS=$(($TOTAL_PASS+$PASSED_TESTS))
TOTAL_FAIL=$(($TOTAL_FAIL+$FAILED_TESTS))
TOTAL_SKIP=$(($TOTAL_SKIP+$SKIPPED_TESTS))
TOTAL_AVAIL=$(($TOTAL_AVAIL + $TOTAL_TESTS + $SKIPPED_TESTS))
TOTAL_EXED=$(($TOTAL_EXED + $TOTAL_TESTS))
# Step 4c - System Compatibility tests
echo "System/Compatibility tests - tests/compat.sh"
PASSED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* (\([0-9]*\) \/ [0-9]* tests ([0-9]* skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }')
SKIPPED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* ([0-9]* \/ [0-9]* tests (\([0-9]*\) skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }')
EXED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* ([0-9]* \/ \([0-9]*\) tests ([0-9]* skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }')
FAILED_TESTS=$(($EXED_TESTS - $PASSED_TESTS))
echo "Passed : $PASSED_TESTS"
echo "Failed : $FAILED_TESTS"
echo "Skipped : $SKIPPED_TESTS"
echo "Total exec'd tests : $EXED_TESTS"
echo "Total avail tests : $(($EXED_TESTS + $SKIPPED_TESTS))"
echo
TOTAL_PASS=$(($TOTAL_PASS+$PASSED_TESTS))
TOTAL_FAIL=$(($TOTAL_FAIL+$FAILED_TESTS))
TOTAL_SKIP=$(($TOTAL_SKIP+$SKIPPED_TESTS))
TOTAL_AVAIL=$(($TOTAL_AVAIL + $EXED_TESTS + $SKIPPED_TESTS))
TOTAL_EXED=$(($TOTAL_EXED + $EXED_TESTS))
# Step 4d - Grand totals
echo "-------------------------------------------------------------------------"
echo "Total tests"
echo "Total Passed : $TOTAL_PASS"
echo "Total Failed : $TOTAL_FAIL"
echo "Total Skipped : $TOTAL_SKIP"
echo "Total exec'd tests : $TOTAL_EXED"
echo "Total avail tests : $TOTAL_AVAIL"
echo
# Step 4e - Coverage report
echo "Coverage statistics:"
sed -n '1,/^Overall coverage/d; /%/p' cov-$TEST_OUTPUT
echo
rm unit-test-$TEST_OUTPUT
rm sys-test-$TEST_OUTPUT
rm compat-test-$TEST_OUTPUT
rm cov-$TEST_OUTPUT
# Mark the report generation as having succeeded. This must be the
# last thing in the report generation.
touch "basic-build-test-$$.ok"
} | tee coverage-summary.txt
make clean
if [ -f "$CONFIG_BAK" ]; then
mv "$CONFIG_BAK" "$CONFIG_H"
fi
# The file must exist, otherwise it means something went wrong while generating
# the coverage report. If something did go wrong, rm will complain so this
# script will exit with a failure status.
rm "tests/basic-build-test-$$.ok"
-36
View File
@@ -1,36 +0,0 @@
#!/bin/bash -eu
# basic-in-docker.sh
#
# Purpose
# -------
# This runs sanity checks and library tests in a Docker container. The tests
# are run for both clang and gcc. The testing includes a full test run
# in the default configuration, partial test runs in the reference
# configurations, and some dependency tests.
#
# WARNING: the Dockerfile used by this script is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
#
# Notes for users
# ---------------
# See docker_env.sh for prerequisites and other information.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
source tests/scripts/docker_env.sh
run_in_docker tests/scripts/all.sh 'check_*'
for compiler in clang gcc; do
run_in_docker -e CC=${compiler} cmake -D CMAKE_BUILD_TYPE:String="Check" .
run_in_docker -e CC=${compiler} make
run_in_docker -e CC=${compiler} make test
run_in_docker programs/test/selftest
run_in_docker -e OSSL_NO_DTLS=1 tests/compat.sh
run_in_docker tests/ssl-opt.sh -e '\(DTLS\|SCSV\).*openssl'
run_in_docker tests/scripts/depends.py curves
run_in_docker tests/scripts/depends.py kex
done
-67
View File
@@ -1,67 +0,0 @@
#!/usr/bin/env perl
# Detect comment blocks that are likely meant to be doxygen blocks but aren't.
#
# More precisely, look for normal comment block containing '\'.
# Of course one could use doxygen warnings, eg with:
# sed -e '/EXTRACT/s/YES/NO/' doxygen/mbedtls.doxyfile | doxygen -
# but that would warn about any undocumented item, while our goal is to find
# items that are documented, but not marked as such by mistake.
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use warnings;
use strict;
use File::Basename;
# C/header files in the following directories will be checked
my @directories = qw(include/mbedtls library doxygen/input);
# very naive pattern to find directives:
# everything with a backslach except '\0' and backslash at EOL
my $doxy_re = qr/\\(?!0|\n)/;
# Return an error code to the environment if a potential error in the
# source code is found.
my $exit_code = 0;
sub check_file {
my ($fname) = @_;
open my $fh, '<', $fname or die "Failed to open '$fname': $!\n";
# first line of the last normal comment block,
# or 0 if not in a normal comment block
my $block_start = 0;
while (my $line = <$fh>) {
$block_start = $. if $line =~ m/\/\*(?![*!])/;
$block_start = 0 if $line =~ m/\*\//;
if ($block_start and $line =~ m/$doxy_re/) {
print "$fname:$block_start: directive on line $.\n";
$block_start = 0; # report only one directive per block
$exit_code = 1;
}
}
close $fh;
}
sub check_dir {
my ($dirname) = @_;
for my $file (<$dirname/*.[ch]>) {
check_file($file);
}
}
# Check that the script is being run from the project's root directory.
for my $dir (@directories) {
if (! -d $dir) {
die "This script must be run from the Mbed TLS root directory";
} else {
check_dir($dir)
}
}
exit $exit_code;
__END__
-188
View File
@@ -1,188 +0,0 @@
#! /usr/bin/env sh
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# Purpose
#
# Check if generated files are up-to-date.
set -eu
if [ $# -ne 0 ] && [ "$1" = "--help" ]; then
cat <<EOF
$0 [-l | -u]
This script checks that all generated file are up-to-date. If some aren't, by
default the scripts reports it and exits in error; with the -u option, it just
updates them instead.
-u Update the files rather than return an error for out-of-date files.
-l List generated files, but do not update them.
EOF
exit
fi
in_mbedtls_repo () {
test -d include -a -d library -a -d programs -a -d tests
}
in_tf_psa_crypto_repo () {
test -d include -a -d core -a -d drivers -a -d programs -a -d tests
}
if in_mbedtls_repo; then
if [ -d tf-psa-crypto ]; then
crypto_core_dir='tf-psa-crypto/core'
builtin_drivers_dir='tf-psa-crypto/drivers/builtin/src'
else
crypto_core_dir='library'
builtin_drivers_dir='library'
fi
elif in_tf_psa_crypto_repo; then
crypto_core_dir='core'
builtin_drivers_dir='drivers/builtin/src/'
else
echo "Must be run from Mbed TLS root or TF-PSA-Crypto root" >&2
exit 1
fi
UPDATE=
LIST=
while getopts lu OPTLET; do
case $OPTLET in
l) LIST=1;;
u) UPDATE=1;;
esac
done
# check SCRIPT FILENAME[...]
# check SCRIPT DIRECTORY
# Run SCRIPT and check that it does not modify any of the specified files.
# In the first form, there can be any number of FILENAMEs, which must be
# regular files.
# In the second form, there must be a single DIRECTORY, standing for the
# list of files in the directory. Running SCRIPT must not modify any file
# in the directory and must not add or remove files either.
# If $UPDATE is empty, abort with an error status if a file is modified.
check()
{
SCRIPT=$1
shift
if [ -n "$LIST" ]; then
printf '%s\n' "$@"
return
fi
directory=
if [ -d "$1" ]; then
directory="$1"
rm -f "$directory"/*.bak
set -- "$1"/*
fi
for FILE in "$@"; do
if [ -e "$FILE" ]; then
cp -p "$FILE" "$FILE.bak"
else
rm -f "$FILE.bak"
fi
done
# In the case of the config tests, generate only the files to be checked
# by the caller as they are divided into Mbed TLS and TF-PSA-Crypto
# specific ones.
if [ "${SCRIPT##*/}" = "generate_config_tests.py" ]; then
"$SCRIPT" "$@"
else
"$SCRIPT"
fi
# Compare the script output to the old files and remove backups
for FILE in "$@"; do
if diff "$FILE" "$FILE.bak" >/dev/null 2>&1; then
# Move the original file back so that $FILE's timestamp doesn't
# change (avoids spurious rebuilds with make).
mv "$FILE.bak" "$FILE"
else
echo "'$FILE' was either modified or deleted by '$SCRIPT'"
if [ -z "$UPDATE" ]; then
exit 1
else
rm -f "$FILE.bak"
fi
fi
done
if [ -n "$directory" ]; then
old_list="$*"
set -- "$directory"/*
new_list="$*"
# Check if there are any new files
if [ "$old_list" != "$new_list" ]; then
echo "Files were deleted or created by '$SCRIPT'"
echo "Before: $old_list"
echo "After: $new_list"
if [ -z "$UPDATE" ]; then
exit 1
fi
fi
fi
}
# Note: if the format of calls to the "check" function changes, update
# scripts/code_style.py accordingly. For generated C source files (*.h or *.c),
# the format must be "check SCRIPT FILENAME...". For other source files,
# any shell syntax is permitted (including e.g. command substitution).
# Note: Instructions to generate those files are replicated in:
# - **/Makefile (to (re)build them with make)
# - **/CMakeLists.txt (to (re)build them with cmake)
# - scripts/make_generated_files.bat (to generate them under Windows)
# These checks are common to Mbed TLS and TF-PSA-Crypto
# The first case is temporary for the hybrid situation with a tf-psa-crypto
# directory in Mbed TLS that is not just a TF-PSA-Crypto submodule.
if [ -d tf-psa-crypto ]; then
cd tf-psa-crypto
check ../framework/scripts/generate_bignum_tests.py $(../framework/scripts/generate_bignum_tests.py --list)
check ../framework/scripts/generate_config_tests.py tests/suites/test_suite_config.psa_boolean.data
check ../framework/scripts/generate_ecp_tests.py $(../framework/scripts/generate_ecp_tests.py --list)
check ../framework/scripts/generate_psa_tests.py $(../framework/scripts/generate_psa_tests.py --list)
cd ..
check framework/scripts/generate_config_tests.py tests/suites/test_suite_config.mbedtls_boolean.data
else
check framework/scripts/generate_bignum_tests.py $(framework/scripts/generate_bignum_tests.py --list)
if in_tf_psa_crypto_repo; then
check framework/scripts/generate_config_tests.py tests/suites/test_suite_config.psa_boolean.data
else
check framework/scripts/generate_config_tests.py tests/suites/test_suite_config.mbedtls_boolean.data
fi
check framework/scripts/generate_ecp_tests.py $(framework/scripts/generate_ecp_tests.py --list)
check framework/scripts/generate_psa_tests.py $(framework/scripts/generate_psa_tests.py --list)
fi
check scripts/generate_psa_constants.py programs/psa/psa_constant_names_generated.c
check framework/scripts/generate_test_keys.py tests/src/test_keys.h
check scripts/generate_driver_wrappers.py ${crypto_core_dir}/psa_crypto_driver_wrappers.h \
${crypto_core_dir}/psa_crypto_driver_wrappers_no_static.c
# Additional checks for Mbed TLS only
if in_mbedtls_repo; then
check scripts/generate_errors.pl library/error.c
check scripts/generate_query_config.pl programs/test/query_config.c
check scripts/generate_features.pl library/version_features.c
check framework/scripts/generate_ssl_debug_helpers.py library/ssl_debug_helpers_generated.c
check framework/scripts/generate_tls13_compat_tests.py tests/opt-testcases/tls13-compat.sh
check framework/scripts/generate_test_cert_macros.py tests/src/test_certs.h
# generate_visualc_files enumerates source files (library/*.c). It doesn't
# care about their content, but the files must exist. So it must run after
# the step that creates or updates these files.
check scripts/generate_visualc_files.pl visualc/VS2017
fi
# Generated files that are present in the repository even in the development
# branch. (This is intended to be temporary, until the generator scripts are
# fully reviewed and the build scripts support a generated header file.)
check framework/scripts/generate_psa_wrappers.py tests/include/test/psa_test_wrappers.h tests/src/psa_test_wrappers.c
-68
View File
@@ -1,68 +0,0 @@
#! /usr/bin/env sh
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# Purpose: check Python files for potential programming errors or maintenance
# hurdles. Run pylint to detect some potential mistakes and enforce PEP8
# coding standards. Run mypy to perform static type checking.
# We'll keep going on errors and report the status at the end.
ret=0
if type python3 >/dev/null 2>/dev/null; then
PYTHON=python3
else
PYTHON=python
fi
check_version () {
$PYTHON - "$2" <<EOF
import packaging.version
import sys
import $1 as package
actual = package.__version__
wanted = sys.argv[1]
if packaging.version.parse(actual) < packaging.version.parse(wanted):
sys.stderr.write("$1: version %s is too old (want %s)\n" % (actual, wanted))
exit(1)
EOF
}
can_pylint () {
# Pylint 1.5.2 from Ubuntu 16.04 is too old:
# E: 34, 0: Unable to import 'mbedtls_framework' (import-error)
# Pylint 1.8.3 from Ubuntu 18.04 passed on the first commit containing this line.
check_version pylint 1.8.3
}
can_mypy () {
# mypy 0.770 is too old:
# tests/scripts/test_psa_constant_names.py:34: error: Cannot find implementation or library stub for module named 'mbedtls_framework'
# mypy 0.780 from pip passed on the first commit containing this line.
check_version mypy.version 0.780
}
# With just a --can-xxx option, check whether the tool for xxx is available
# with an acceptable version, and exit without running any checks. The exit
# status is true if the tool is available and acceptable and false otherwise.
if [ "$1" = "--can-pylint" ]; then
can_pylint
exit
elif [ "$1" = "--can-mypy" ]; then
can_mypy
exit
fi
echo 'Running pylint ...'
$PYTHON -m pylint framework/scripts/*.py framework/scripts/mbedtls_framework/*.py scripts/*.py tests/scripts/*.py || {
echo >&2 "pylint reported errors"
ret=1
}
echo
echo 'Running mypy ...'
$PYTHON -m mypy framework/scripts/*.py framework/scripts/mbedtls_framework/*.py scripts/*.py tests/scripts/*.py ||
ret=1
exit $ret
-565
View File
@@ -1,565 +0,0 @@
#!/usr/bin/env python3
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""
This script checks the current state of the source code for minor issues,
including incorrect file permissions, presence of tabs, non-Unix line endings,
trailing whitespace, and presence of UTF-8 BOM.
Note: requires python 3, must be run from Mbed TLS root.
"""
import argparse
import codecs
import inspect
import logging
import os
import re
import subprocess
import sys
try:
from typing import FrozenSet, Optional, Pattern # pylint: disable=unused-import
except ImportError:
pass
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
class FileIssueTracker:
"""Base class for file-wide issue tracking.
To implement a checker that processes a file as a whole, inherit from
this class and implement `check_file_for_issue` and define ``heading``.
``suffix_exemptions``: files whose name ends with a string in this set
will not be checked.
``path_exemptions``: files whose path (relative to the root of the source
tree) matches this regular expression will not be checked. This can be
``None`` to match no path. Paths are normalized and converted to ``/``
separators before matching.
``heading``: human-readable description of the issue
"""
suffix_exemptions = frozenset() #type: FrozenSet[str]
path_exemptions = None #type: Optional[Pattern[str]]
# heading must be defined in derived classes.
# pylint: disable=no-member
def __init__(self):
self.files_with_issues = {}
@staticmethod
def normalize_path(filepath):
"""Normalize ``filepath`` with / as the directory separator."""
filepath = os.path.normpath(filepath)
# On Windows, we may have backslashes to separate directories.
# We need slashes to match exemption lists.
seps = os.path.sep
if os.path.altsep is not None:
seps += os.path.altsep
return '/'.join(filepath.split(seps))
def should_check_file(self, filepath):
"""Whether the given file name should be checked.
Files whose name ends with a string listed in ``self.suffix_exemptions``
or whose path matches ``self.path_exemptions`` will not be checked.
"""
for files_exemption in self.suffix_exemptions:
if filepath.endswith(files_exemption):
return False
if self.path_exemptions and \
re.match(self.path_exemptions, self.normalize_path(filepath)):
return False
return True
def check_file_for_issue(self, filepath):
"""Check the specified file for the issue that this class is for.
Subclasses must implement this method.
"""
raise NotImplementedError
def record_issue(self, filepath, line_number):
"""Record that an issue was found at the specified location."""
if filepath not in self.files_with_issues.keys():
self.files_with_issues[filepath] = []
self.files_with_issues[filepath].append(line_number)
def output_file_issues(self, logger):
"""Log all the locations where the issue was found."""
if self.files_with_issues.values():
logger.info(self.heading)
for filename, lines in sorted(self.files_with_issues.items()):
if lines:
logger.info("{}: {}".format(
filename, ", ".join(str(x) for x in lines)
))
else:
logger.info(filename)
logger.info("")
BINARY_FILE_PATH_RE_LIST = [
r'docs/.*\.pdf\Z',
r'docs/.*\.png\Z',
r'programs/fuzz/corpuses/[^.]+\Z',
r'framework/data_files/[^.]+\Z',
r'framework/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
r'framework/data_files/.*\.req\.[^/]+\Z',
r'framework/data_files/.*malformed[^/]+\Z',
r'framework/data_files/format_pkcs12\.fmt\Z',
r'framework/data_files/.*\.bin\Z',
]
BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
class LineIssueTracker(FileIssueTracker):
"""Base class for line-by-line issue tracking.
To implement a checker that processes files line by line, inherit from
this class and implement `line_with_issue`.
"""
# Exclude binary files.
path_exemptions = BINARY_FILE_PATH_RE
def issue_with_line(self, line, filepath, line_number):
"""Check the specified line for the issue that this class is for.
Subclasses must implement this method.
"""
raise NotImplementedError
def check_file_line(self, filepath, line, line_number):
if self.issue_with_line(line, filepath, line_number):
self.record_issue(filepath, line_number)
def check_file_for_issue(self, filepath):
"""Check the lines of the specified file.
Subclasses must implement the ``issue_with_line`` method.
"""
with open(filepath, "rb") as f:
for i, line in enumerate(iter(f.readline, b"")):
self.check_file_line(filepath, line, i + 1)
def is_windows_file(filepath):
_root, ext = os.path.splitext(filepath)
return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
class ShebangIssueTracker(FileIssueTracker):
"""Track files with a bad, missing or extraneous shebang line.
Executable scripts must start with a valid shebang (#!) line.
"""
heading = "Invalid shebang line:"
# Allow either /bin/sh, /bin/bash, or /usr/bin/env.
# Allow at most one argument (this is a Linux limitation).
# For sh and bash, the argument if present must be options.
# For env, the argument must be the base name of the interpreter.
_shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
rb'|/usr/bin/env ([^\n /]+))$')
_extensions = {
b'bash': 'sh',
b'perl': 'pl',
b'python3': 'py',
b'sh': 'sh',
}
path_exemptions = re.compile(r'tests/scripts/quiet/.*')
def is_valid_shebang(self, first_line, filepath):
m = re.match(self._shebang_re, first_line)
if not m:
return False
interpreter = m.group(1) or m.group(2)
if interpreter not in self._extensions:
return False
if not filepath.endswith('.' + self._extensions[interpreter]):
return False
return True
def check_file_for_issue(self, filepath):
is_executable = os.access(filepath, os.X_OK)
with open(filepath, "rb") as f:
first_line = f.readline()
if first_line.startswith(b'#!'):
if not is_executable:
# Shebang on a non-executable file
self.files_with_issues[filepath] = None
elif not self.is_valid_shebang(first_line, filepath):
self.files_with_issues[filepath] = [1]
elif is_executable:
# Executable without a shebang
self.files_with_issues[filepath] = None
class EndOfFileNewlineIssueTracker(FileIssueTracker):
"""Track files that end with an incomplete line
(no newline character at the end of the last line)."""
heading = "Missing newline at end of file:"
path_exemptions = BINARY_FILE_PATH_RE
def check_file_for_issue(self, filepath):
with open(filepath, "rb") as f:
try:
f.seek(-1, 2)
except OSError:
# This script only works on regular files. If we can't seek
# 1 before the end, it means that this position is before
# the beginning of the file, i.e. that the file is empty.
return
if f.read(1) != b"\n":
self.files_with_issues[filepath] = None
class Utf8BomIssueTracker(FileIssueTracker):
"""Track files that start with a UTF-8 BOM.
Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
heading = "UTF-8 BOM present:"
suffix_exemptions = frozenset([".vcxproj", ".sln"])
path_exemptions = BINARY_FILE_PATH_RE
def check_file_for_issue(self, filepath):
with open(filepath, "rb") as f:
if f.read().startswith(codecs.BOM_UTF8):
self.files_with_issues[filepath] = None
class UnicodeIssueTracker(LineIssueTracker):
"""Track lines with invalid characters or invalid text encoding."""
heading = "Invalid UTF-8 or forbidden character:"
# Only allow valid UTF-8, and only other explicitly allowed characters.
# We deliberately exclude all characters that aren't a simple non-blank,
# non-zero-width glyph, apart from a very small set (tab, ordinary space,
# line breaks, "basic" no-break space and soft hyphen). In particular,
# non-ASCII control characters, combinig characters, and Unicode state
# changes (e.g. right-to-left text) are forbidden.
# Note that we do allow some characters with a risk of visual confusion,
# for example '-' (U+002D HYPHEN-MINUS) vs '­' (U+00AD SOFT HYPHEN) vs
# '' (U+2010 HYPHEN), or 'A' (U+0041 LATIN CAPITAL LETTER A) vs
# 'Α' (U+0391 GREEK CAPITAL LETTER ALPHA).
GOOD_CHARACTERS = ''.join([
'\t\n\r -~', # ASCII (tabs and line endings are checked separately)
'\u00A0-\u00FF', # Latin-1 Supplement (for NO-BREAK SPACE and punctuation)
'\u2010-\u2027\u2030-\u205E', # General Punctuation (printable)
'\u2070\u2071\u2074-\u208E\u2090-\u209C', # Superscripts and Subscripts
'\u2190-\u21FF', # Arrows
'\u2200-\u22FF', # Mathematical Symbols
'\u2500-\u257F' # Box Drawings characters used in markdown trees
])
# Allow any of the characters and ranges above, and anything classified
# as a word constituent.
GOOD_CHARACTERS_RE = re.compile(r'[\w{}]+\Z'.format(GOOD_CHARACTERS))
def issue_with_line(self, line, _filepath, line_number):
try:
text = line.decode('utf-8')
except UnicodeDecodeError:
return True
if line_number == 1 and text.startswith('\uFEFF'):
# Strip BOM (U+FEFF ZERO WIDTH NO-BREAK SPACE) at the beginning.
# Which files are allowed to have a BOM is handled in
# Utf8BomIssueTracker.
text = text[1:]
return not self.GOOD_CHARACTERS_RE.match(text)
class UnixLineEndingIssueTracker(LineIssueTracker):
"""Track files with non-Unix line endings (i.e. files with CR)."""
heading = "Non-Unix line endings:"
def should_check_file(self, filepath):
if not super().should_check_file(filepath):
return False
return not is_windows_file(filepath)
def issue_with_line(self, line, _filepath, _line_number):
return b"\r" in line
class WindowsLineEndingIssueTracker(LineIssueTracker):
"""Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
heading = "Non-Windows line endings:"
def should_check_file(self, filepath):
if not super().should_check_file(filepath):
return False
return is_windows_file(filepath)
def issue_with_line(self, line, _filepath, _line_number):
return not line.endswith(b"\r\n") or b"\r" in line[:-2]
class TrailingWhitespaceIssueTracker(LineIssueTracker):
"""Track lines with trailing whitespace."""
heading = "Trailing whitespace:"
suffix_exemptions = frozenset([".dsp", ".md"])
def issue_with_line(self, line, _filepath, _line_number):
return line.rstrip(b"\r\n") != line.rstrip()
class TabIssueTracker(LineIssueTracker):
"""Track lines with tabs."""
heading = "Tabs present:"
suffix_exemptions = frozenset([
".make",
".pem", # some openssl dumps have tabs
".sln",
"/.gitmodules",
"/Makefile",
"/Makefile.inc",
"/generate_visualc_files.pl",
])
def issue_with_line(self, line, _filepath, _line_number):
return b"\t" in line
class MergeArtifactIssueTracker(LineIssueTracker):
"""Track lines with merge artifacts.
These are leftovers from a ``git merge`` that wasn't fully edited."""
heading = "Merge artifact:"
def issue_with_line(self, line, _filepath, _line_number):
# Detect leftover git conflict markers.
if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
return True
if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
return True
if line.rstrip(b'\r\n') == b'=======' and \
not _filepath.endswith('.md'):
return True
return False
def this_location():
frame = inspect.currentframe()
assert frame is not None
info = inspect.getframeinfo(frame)
return os.path.basename(info.filename), info.lineno
THIS_FILE_BASE_NAME, LINE_NUMBER_BEFORE_LICENSE_ISSUE_TRACKER = this_location()
class LicenseIssueTracker(LineIssueTracker):
"""Check copyright statements and license indications.
This class only checks that statements are correct if present. It does
not enforce the presence of statements in each file.
"""
heading = "License issue:"
LICENSE_EXEMPTION_RE_LIST = [
# Exempt third-party drivers which may be under a different license
r'tf-psa-crypto/drivers/(?=(everest)/.*)',
# Documentation explaining the license may have accidental
# false positives.
r'(ChangeLog|LICENSE|framework\/LICENSE|[-0-9A-Z_a-z]+\.md)\Z',
# Files imported from TF-M, and not used except in test builds,
# may be under a different license.
r'configs/ext/crypto_config_profile_medium\.h\Z',
r'configs/ext/tfm_mbedcrypto_config_profile_medium\.h\Z',
r'configs/ext/README\.md\Z',
# Third-party file.
r'dco\.txt\Z',
r'framework\/dco\.txt\Z',
]
path_exemptions = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST +
LICENSE_EXEMPTION_RE_LIST))
COPYRIGHT_HOLDER = rb'The Mbed TLS Contributors'
# Catch "Copyright foo", "Copyright (C) foo", "Copyright © foo", etc.
COPYRIGHT_RE = re.compile(rb'.*\bcopyright\s+((?:\w|\s|[()]|[^ -~])*\w)', re.I)
SPDX_HEADER_KEY = b'SPDX-License-Identifier'
LICENSE_IDENTIFIER = b'Apache-2.0 OR GPL-2.0-or-later'
SPDX_RE = re.compile(br'.*?(' +
re.escape(SPDX_HEADER_KEY) +
br')(:\s*(.*?)\W*\Z|.*)', re.I)
LICENSE_MENTION_RE = re.compile(rb'.*(?:' + rb'|'.join([
rb'Apache License',
rb'General Public License',
]) + rb')', re.I)
def __init__(self):
super().__init__()
# Record what problem was caused. We can't easily report it due to
# the structure of the script. To be fixed after
# https://github.com/Mbed-TLS/mbedtls/pull/2506
self.problem = None
def issue_with_line(self, line, filepath, line_number):
#pylint: disable=too-many-return-statements
# Use endswith() rather than the more correct os.path.basename()
# because experimentally, it makes a significant difference to
# the running time.
if filepath.endswith(THIS_FILE_BASE_NAME) and \
line_number > LINE_NUMBER_BEFORE_LICENSE_ISSUE_TRACKER:
# Avoid false positives from the code in this class.
# Also skip the rest of this file, which is highly unlikely to
# contain any problematic statements since we put those near the
# top of files.
return False
m = self.COPYRIGHT_RE.match(line)
if m and m.group(1) != self.COPYRIGHT_HOLDER:
self.problem = 'Invalid copyright line'
return True
m = self.SPDX_RE.match(line)
if m:
if m.group(1) != self.SPDX_HEADER_KEY:
self.problem = 'Misspelled ' + self.SPDX_HEADER_KEY.decode()
return True
if not m.group(3):
self.problem = 'Improperly formatted SPDX license identifier'
return True
if m.group(3) != self.LICENSE_IDENTIFIER:
self.problem = 'Wrong SPDX license identifier'
return True
m = self.LICENSE_MENTION_RE.match(line)
if m:
self.problem = 'Suspicious license mention'
return True
return False
class ErrorAddIssueTracker(LineIssueTracker):
"""Signal direct additions of error codes.
Adding a low-level error code with a high-level error code is deprecated
and should use MBEDTLS_ERROR_ADD.
"""
heading = "Direct addition of error codes"
_ERR_PLUS_RE = re.compile(br'MBEDTLS_ERR_\w+ *\+|'
br'\+ *MBEDTLS_ERR_')
_EXCLUDE_RE = re.compile(br' *case ')
def issue_with_line(self, line, filepath, line_number):
if self._ERR_PLUS_RE.search(line) and not self._EXCLUDE_RE.match(line):
return True
return False
class IntegrityChecker:
"""Sanity-check files under the current directory."""
def __init__(self, log_file):
"""Instantiate the sanity checker.
Check files under the current directory.
Write a report of issues to log_file."""
build_tree.check_repo_path()
self.logger = None
self.setup_logger(log_file)
self.issues_to_check = [
ShebangIssueTracker(),
EndOfFileNewlineIssueTracker(),
Utf8BomIssueTracker(),
UnicodeIssueTracker(),
UnixLineEndingIssueTracker(),
WindowsLineEndingIssueTracker(),
TrailingWhitespaceIssueTracker(),
TabIssueTracker(),
MergeArtifactIssueTracker(),
LicenseIssueTracker(),
ErrorAddIssueTracker(),
]
def setup_logger(self, log_file, level=logging.INFO):
"""Log to log_file if provided, or to stderr if None."""
self.logger = logging.getLogger()
self.logger.setLevel(level)
if log_file:
handler = logging.FileHandler(log_file)
self.logger.addHandler(handler)
else:
console = logging.StreamHandler()
self.logger.addHandler(console)
@staticmethod
def collect_files():
"""Return the list of files to check.
These are the regular files commited into Git.
"""
bytes_output = subprocess.check_output(['git', '-C', 'framework',
'ls-files', '-z'])
bytes_framework_filepaths = bytes_output.split(b'\0')[:-1]
bytes_framework_filepaths = ["framework/".encode() + filepath
for filepath in bytes_framework_filepaths]
bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
bytes_filepaths = bytes_output.split(b'\0')[:-1] + \
bytes_framework_filepaths
ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
# Filter out directories. Normally Git doesn't list directories
# (it only knows about the files inside them), but there is
# at least one case where 'git ls-files' includes a directory:
# submodules. Just skip submodules (and any other directories).
ascii_filepaths = [fp for fp in ascii_filepaths
if os.path.isfile(fp)]
# Prepend './' to files in the top-level directory so that
# something like `'/Makefile' in fp` matches in the top-level
# directory as well as in subdirectories.
return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
for fp in ascii_filepaths]
def check_files(self):
"""Check all files for all issues."""
for issue_to_check in self.issues_to_check:
for filepath in self.collect_files():
if issue_to_check.should_check_file(filepath):
issue_to_check.check_file_for_issue(filepath)
def output_issues(self):
"""Log the issues found and their locations.
Return 1 if there were issues, 0 otherwise.
"""
integrity_return_code = 0
for issue_to_check in self.issues_to_check:
if issue_to_check.files_with_issues:
integrity_return_code = 1
issue_to_check.output_file_issues(self.logger)
return integrity_return_code
def run_main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-l", "--log_file", type=str, help="path to optional output log",
)
check_args = parser.parse_args()
integrity_check = IntegrityChecker(check_args.log_file)
integrity_check.check_files()
return_code = integrity_check.output_issues()
sys.exit(return_code)
if __name__ == "__main__":
run_main()
-987
View File
@@ -1,987 +0,0 @@
#!/usr/bin/env python3
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""
This script confirms that the naming of all symbols and identifiers in Mbed TLS
are consistent with the house style and are also self-consistent. It only runs
on Linux and macOS since it depends on nm.
It contains two major Python classes, CodeParser and NameChecker. They both have
a comprehensive "run-all" function (comprehensive_parse() and perform_checks())
but the individual functions can also be used for specific needs.
CodeParser makes heavy use of regular expressions to parse the code, and is
dependent on the current code formatting. Many Python C parser libraries require
preprocessed C code, which means no macro parsing. Compiler tools are also not
very helpful when we want the exact location in the original source (which
becomes impossible when e.g. comments are stripped).
NameChecker performs the following checks:
- All exported and available symbols in the library object files, are explicitly
declared in the header files. This uses the nm command.
- All macros, constants, and identifiers (function names, struct names, etc)
follow the required regex pattern.
- Typo checking: All words that begin with MBED|PSA exist as macros or constants.
The script returns 0 on success, 1 on test failure, and 2 if there is a script
error. It must be run from Mbed TLS root.
"""
import abc
import argparse
import fnmatch
import glob
import textwrap
import os
import sys
import traceback
import re
import enum
import shutil
import subprocess
import logging
import scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
# Naming patterns to check against. These are defined outside the NameCheck
# class for ease of modification.
PUBLIC_MACRO_PATTERN = r"^(MBEDTLS|PSA)_[0-9A-Z_]*[0-9A-Z]$"
INTERNAL_MACRO_PATTERN = r"^[0-9A-Za-z_]*[0-9A-Z]$"
CONSTANTS_PATTERN = PUBLIC_MACRO_PATTERN
IDENTIFIER_PATTERN = r"^(mbedtls|psa)_[0-9a-z_]*[0-9a-z]$"
class Match(): # pylint: disable=too-few-public-methods
"""
A class representing a match, together with its found position.
Fields:
* filename: the file that the match was in.
* line: the full line containing the match.
* line_no: the line number.
* pos: a tuple of (start, end) positions on the line where the match is.
* name: the match itself.
"""
def __init__(self, filename, line, line_no, pos, name):
# pylint: disable=too-many-arguments
self.filename = filename
self.line = line
self.line_no = line_no
self.pos = pos
self.name = name
def __str__(self):
"""
Return a formatted code listing representation of the erroneous line.
"""
gutter = format(self.line_no, "4d")
underline = self.pos[0] * " " + (self.pos[1] - self.pos[0]) * "^"
return (
" {0} |\n".format(" " * len(gutter)) +
" {0} | {1}".format(gutter, self.line) +
" {0} | {1}\n".format(" " * len(gutter), underline)
)
class Problem(abc.ABC): # pylint: disable=too-few-public-methods
"""
An abstract parent class representing a form of static analysis error.
It extends an Abstract Base Class, which means it is not instantiable, and
it also mandates certain abstract methods to be implemented in subclasses.
"""
# Class variable to control the quietness of all problems
quiet = False
def __init__(self):
self.textwrapper = textwrap.TextWrapper()
self.textwrapper.width = 80
self.textwrapper.initial_indent = " > "
self.textwrapper.subsequent_indent = " "
def __str__(self):
"""
Unified string representation method for all Problems.
"""
if self.__class__.quiet:
return self.quiet_output()
return self.verbose_output()
@abc.abstractmethod
def quiet_output(self):
"""
The output when --quiet is enabled.
"""
pass
@abc.abstractmethod
def verbose_output(self):
"""
The default output with explanation and code snippet if appropriate.
"""
pass
class SymbolNotInHeader(Problem): # pylint: disable=too-few-public-methods
"""
A problem that occurs when an exported/available symbol in the object file
is not explicitly declared in header files. Created with
NameCheck.check_symbols_declared_in_header()
Fields:
* symbol_name: the name of the symbol.
"""
def __init__(self, symbol_name):
self.symbol_name = symbol_name
Problem.__init__(self)
def quiet_output(self):
return "{0}".format(self.symbol_name)
def verbose_output(self):
return self.textwrapper.fill(
"'{0}' was found as an available symbol in the output of nm, "
"however it was not declared in any header files."
.format(self.symbol_name))
class PatternMismatch(Problem): # pylint: disable=too-few-public-methods
"""
A problem that occurs when something doesn't match the expected pattern.
Created with NameCheck.check_match_pattern()
Fields:
* pattern: the expected regex pattern
* match: the Match object in question
"""
def __init__(self, pattern, match):
self.pattern = pattern
self.match = match
Problem.__init__(self)
def quiet_output(self):
return (
"{0}:{1}:{2}"
.format(self.match.filename, self.match.line_no, self.match.name)
)
def verbose_output(self):
return self.textwrapper.fill(
"{0}:{1}: '{2}' does not match the required pattern '{3}'."
.format(
self.match.filename,
self.match.line_no,
self.match.name,
self.pattern
)
) + "\n" + str(self.match)
class Typo(Problem): # pylint: disable=too-few-public-methods
"""
A problem that occurs when a word using MBED or PSA doesn't
appear to be defined as constants nor enum values. Created with
NameCheck.check_for_typos()
Fields:
* match: the Match object of the MBED|PSA name in question.
"""
def __init__(self, match):
self.match = match
Problem.__init__(self)
def quiet_output(self):
return (
"{0}:{1}:{2}"
.format(self.match.filename, self.match.line_no, self.match.name)
)
def verbose_output(self):
return self.textwrapper.fill(
"{0}:{1}: '{2}' looks like a typo. It was not found in any "
"macros or any enums. If this is not a typo, put "
"//no-check-names after it."
.format(self.match.filename, self.match.line_no, self.match.name)
) + "\n" + str(self.match)
class CodeParser():
"""
Class for retrieving files and parsing the code. This can be used
independently of the checks that NameChecker performs, for example for
list_internal_identifiers.py.
"""
def __init__(self, log):
self.log = log
build_tree.check_repo_path()
# Memo for storing "glob expression": set(filepaths)
self.files = {}
# Globally excluded filenames.
# Note that "*" can match directory separators in exclude lists.
self.excluded_files = ["*/bn_mul", "*/compat-2.x.h"]
def comprehensive_parse(self):
"""
Comprehensive ("default") function to call each parsing function and
retrieve various elements of the code, together with the source location.
Returns a dict of parsed item key to the corresponding List of Matches.
"""
self.log.info("Parsing source code...")
self.log.debug(
"The following files are excluded from the search: {}"
.format(str(self.excluded_files))
)
all_macros = {"public": [], "internal": [], "private":[]}
all_macros["public"] = self.parse_macros([
"include/mbedtls/*.h",
"include/psa/*.h",
"tf-psa-crypto/include/psa/*.h",
"tf-psa-crypto/drivers/builtin/include/mbedtls/*.h",
"tf-psa-crypto/drivers/everest/include/everest/everest.h",
"tf-psa-crypto/drivers/everest/include/everest/x25519.h"
])
all_macros["internal"] = self.parse_macros([
"library/*.h",
"tf-psa-crypto/core/*.h",
"tf-psa-crypto/drivers/builtin/src/*.h",
"tests/include/test/drivers/*.h",
])
all_macros["private"] = self.parse_macros([
"library/*.c",
"tf-psa-crypto/core/*.c",
"tf-psa-crypto/drivers/builtin/src/*.c",
])
enum_consts = self.parse_enum_consts([
"include/mbedtls/*.h",
"include/psa/*.h",
"tf-psa-crypto/include/psa/*.h",
"tf-psa-crypto/drivers/builtin/include/mbedtls/*.h",
"library/*.h",
"tf-psa-crypto/core/*.h",
"tf-psa-crypto/drivers/builtin/src/*.h",
"library/*.c",
"tf-psa-crypto/core/*.c",
"tf-psa-crypto/drivers/builtin/src/*.c",
"tf-psa-crypto/drivers/everest/include/everest/everest.h",
"tf-psa-crypto/drivers/everest/include/everest/x25519.h"
])
identifiers, excluded_identifiers = self.parse_identifiers([
"include/mbedtls/*.h",
"include/psa/*.h",
"tf-psa-crypto/include/psa/*.h",
"tf-psa-crypto/drivers/builtin/include/mbedtls/*.h",
"library/*.h",
"tf-psa-crypto/core/*.h",
"tf-psa-crypto/drivers/builtin/src/*.h",
"tf-psa-crypto/drivers/everest/include/everest/everest.h",
"tf-psa-crypto/drivers/everest/include/everest/x25519.h"
], ["tf-psa-crypto/drivers/p256-m/p256-m/p256-m.h"])
mbed_psa_words = self.parse_mbed_psa_words([
"include/mbedtls/*.h",
"include/psa/*.h",
"tf-psa-crypto/include/psa/*.h",
"tf-psa-crypto/drivers/builtin/include/mbedtls/*.h",
"library/*.h",
"tf-psa-crypto/core/*.h",
"tf-psa-crypto/drivers/builtin/src/*.h",
"tf-psa-crypto/drivers/everest/include/everest/everest.h",
"tf-psa-crypto/drivers/everest/include/everest/x25519.h",
"library/*.c",
"tf-psa-crypto/core/*.c",
"tf-psa-crypto/drivers/builtin/src/*.c",
"tf-psa-crypto/drivers/everest/library/everest.c",
"tf-psa-crypto/drivers/everest/library/x25519.c"
], ["tf-psa-crypto/core/psa_crypto_driver_wrappers.h"])
symbols = self.parse_symbols()
# Remove identifier macros like mbedtls_printf or mbedtls_calloc
identifiers_justname = [x.name for x in identifiers]
actual_macros = {"public": [], "internal": []}
for scope in actual_macros:
for macro in all_macros[scope]:
if macro.name not in identifiers_justname:
actual_macros[scope].append(macro)
self.log.debug("Found:")
# Aligns the counts on the assumption that none exceeds 4 digits
for scope in actual_macros:
self.log.debug(" {:4} Total {} Macros"
.format(len(all_macros[scope]), scope))
self.log.debug(" {:4} {} Non-identifier Macros"
.format(len(actual_macros[scope]), scope))
self.log.debug(" {:4} Enum Constants".format(len(enum_consts)))
self.log.debug(" {:4} Identifiers".format(len(identifiers)))
self.log.debug(" {:4} Exported Symbols".format(len(symbols)))
return {
"public_macros": actual_macros["public"],
"internal_macros": actual_macros["internal"],
"private_macros": all_macros["private"],
"enum_consts": enum_consts,
"identifiers": identifiers,
"excluded_identifiers": excluded_identifiers,
"symbols": symbols,
"mbed_psa_words": mbed_psa_words
}
def is_file_excluded(self, path, exclude_wildcards):
"""Whether the given file path is excluded."""
# exclude_wildcards may be None. Also, consider the global exclusions.
exclude_wildcards = (exclude_wildcards or []) + self.excluded_files
for pattern in exclude_wildcards:
if fnmatch.fnmatch(path, pattern):
return True
return False
def get_all_files(self, include_wildcards, exclude_wildcards):
"""
Get all files that match any of the included UNIX-style wildcards
and filter them into included and excluded lists.
While the check_names script is designed only for use on UNIX/macOS
(due to nm), this function alone will work fine on Windows even with
forward slashes in the wildcard.
Args:
* include_wildcards: a List of shell-style wildcards to match filepaths.
* exclude_wildcards: a List of shell-style wildcards to exclude.
Returns:
* inc_files: A List of relative filepaths for included files.
* exc_files: A List of relative filepaths for excluded files.
"""
accumulator = set()
all_wildcards = include_wildcards + (exclude_wildcards or [])
for wildcard in all_wildcards:
accumulator = accumulator.union(glob.iglob(wildcard))
inc_files = []
exc_files = []
for path in accumulator:
if self.is_file_excluded(path, exclude_wildcards):
exc_files.append(path)
else:
inc_files.append(path)
return (inc_files, exc_files)
def get_included_files(self, include_wildcards, exclude_wildcards):
"""
Get all files that match any of the included UNIX-style wildcards.
While the check_names script is designed only for use on UNIX/macOS
(due to nm), this function alone will work fine on Windows even with
forward slashes in the wildcard.
Args:
* include_wildcards: a List of shell-style wildcards to match filepaths.
* exclude_wildcards: a List of shell-style wildcards to exclude.
Returns a List of relative filepaths.
"""
accumulator = set()
for include_wildcard in include_wildcards:
accumulator = accumulator.union(glob.iglob(include_wildcard))
return list(path for path in accumulator
if not self.is_file_excluded(path, exclude_wildcards))
def parse_macros(self, include, exclude=None):
"""
Parse all macros defined by #define preprocessor directives.
Args:
* include: A List of glob expressions to look for files through.
* exclude: A List of glob expressions for excluding files.
Returns a List of Match objects for the found macros.
"""
macro_regex = re.compile(r"# *define +(?P<macro>\w+)")
exclusions = (
"asm", "inline", "EMIT", "_CRT_SECURE_NO_DEPRECATE", "MULADDC_"
)
files = self.get_included_files(include, exclude)
self.log.debug("Looking for macros in {} files".format(len(files)))
macros = []
for header_file in files:
with open(header_file, "r", encoding="utf-8") as header:
for line_no, line in enumerate(header):
for macro in macro_regex.finditer(line):
if macro.group("macro").startswith(exclusions):
continue
macros.append(Match(
header_file,
line,
line_no,
macro.span("macro"),
macro.group("macro")))
return macros
def parse_mbed_psa_words(self, include, exclude=None):
"""
Parse all words in the file that begin with MBED|PSA, in and out of
macros, comments, anything.
Args:
* include: A List of glob expressions to look for files through.
* exclude: A List of glob expressions for excluding files.
Returns a List of Match objects for words beginning with MBED|PSA.
"""
# Typos of TLS are common, hence the broader check below than MBEDTLS.
mbed_regex = re.compile(r"\b(MBED.+?|PSA)_[A-Z0-9_]*")
exclusions = re.compile(r"// *no-check-names|#error")
files = self.get_included_files(include, exclude)
self.log.debug(
"Looking for MBED|PSA words in {} files"
.format(len(files))
)
mbed_psa_words = []
for filename in files:
with open(filename, "r", encoding="utf-8") as fp:
for line_no, line in enumerate(fp):
if exclusions.search(line):
continue
for name in mbed_regex.finditer(line):
mbed_psa_words.append(Match(
filename,
line,
line_no,
name.span(0),
name.group(0)))
return mbed_psa_words
def parse_enum_consts(self, include, exclude=None):
"""
Parse all enum value constants that are declared.
Args:
* include: A List of glob expressions to look for files through.
* exclude: A List of glob expressions for excluding files.
Returns a List of Match objects for the findings.
"""
files = self.get_included_files(include, exclude)
self.log.debug("Looking for enum consts in {} files".format(len(files)))
# Emulate a finite state machine to parse enum declarations.
# OUTSIDE_KEYWORD = outside the enum keyword
# IN_BRACES = inside enum opening braces
# IN_BETWEEN = between enum keyword and opening braces
states = enum.Enum("FSM", ["OUTSIDE_KEYWORD", "IN_BRACES", "IN_BETWEEN"])
enum_consts = []
for header_file in files:
state = states.OUTSIDE_KEYWORD
with open(header_file, "r", encoding="utf-8") as header:
for line_no, line in enumerate(header):
# Match typedefs and brackets only when they are at the
# beginning of the line -- if they are indented, they might
# be sub-structures within structs, etc.
optional_c_identifier = r"([_a-zA-Z][_a-zA-Z0-9]*)?"
if (state == states.OUTSIDE_KEYWORD and
re.search(r"^(typedef +)?enum " + \
optional_c_identifier + \
r" *{", line)):
state = states.IN_BRACES
elif (state == states.OUTSIDE_KEYWORD and
re.search(r"^(typedef +)?enum", line)):
state = states.IN_BETWEEN
elif (state == states.IN_BETWEEN and
re.search(r"^{", line)):
state = states.IN_BRACES
elif (state == states.IN_BRACES and
re.search(r"^}", line)):
state = states.OUTSIDE_KEYWORD
elif (state == states.IN_BRACES and
not re.search(r"^ *#", line)):
enum_const = re.search(r"^ *(?P<enum_const>\w+)", line)
if not enum_const:
continue
enum_consts.append(Match(
header_file,
line,
line_no,
enum_const.span("enum_const"),
enum_const.group("enum_const")))
return enum_consts
IGNORED_CHUNK_REGEX = re.compile('|'.join([
r'/\*.*?\*/', # block comment entirely on one line
r'//.*', # line comment
r'(?P<string>")(?:[^\\\"]|\\.)*"', # string literal
]))
def strip_comments_and_literals(self, line, in_block_comment):
"""Strip comments and string literals from line.
Continuation lines are not supported.
If in_block_comment is true, assume that the line starts inside a
block comment.
Return updated values of (line, in_block_comment) where:
* Comments in line have been replaced by a space (or nothing at the
start or end of the line).
* String contents have been removed.
* in_block_comment indicates whether the line ends inside a block
comment that continues on the next line.
"""
# Terminate current multiline comment?
if in_block_comment:
m = re.search(r"\*/", line)
if m:
in_block_comment = False
line = line[m.end(0):]
else:
return '', True
# Remove full comments and string literals.
# Do it all together to handle cases like "/*" correctly.
# Note that continuation lines are not supported.
line = re.sub(self.IGNORED_CHUNK_REGEX,
lambda s: '""' if s.group('string') else ' ',
line)
# Start an unfinished comment?
# (If `/*` was part of a complete comment, it's already been removed.)
m = re.search(r"/\*", line)
if m:
in_block_comment = True
line = line[:m.start(0)]
return line, in_block_comment
IDENTIFIER_REGEX = re.compile('|'.join([
# Match " something(a" or " *something(a". Functions.
# Assumptions:
# - function definition from return type to one of its arguments is
# all on one line
# - function definition line only contains alphanumeric, asterisk,
# underscore, and open bracket
r".* \**(\w+) *\( *\w",
# Match "(*something)(".
r".*\( *\* *(\w+) *\) *\(",
# Match names of named data structures.
r"(?:typedef +)?(?:struct|union|enum) +(\w+)(?: *{)?$",
# Match names of typedef instances, after closing bracket.
r"}? *(\w+)[;[].*",
]))
# The regex below is indented for clarity.
EXCLUSION_LINES = re.compile("|".join([
r"extern +\"C\"",
r"(typedef +)?(struct|union|enum)( *{)?$",
r"} *;?$",
r"$",
r"//",
r"#",
]))
def parse_identifiers_in_file(self, header_file, identifiers):
"""
Parse all lines of a header where a function/enum/struct/union/typedef
identifier is declared, based on some regex and heuristics. Highly
dependent on formatting style.
Append found matches to the list ``identifiers``.
"""
with open(header_file, "r", encoding="utf-8") as header:
in_block_comment = False
# The previous line variable is used for concatenating lines
# when identifiers are formatted and spread across multiple
# lines.
previous_line = ""
for line_no, line in enumerate(header):
line, in_block_comment = \
self.strip_comments_and_literals(line, in_block_comment)
if self.EXCLUSION_LINES.match(line):
previous_line = ""
continue
# If the line contains only space-separated alphanumeric
# characters (or underscore, asterisk, or open parenthesis),
# and nothing else, high chance it's a declaration that
# continues on the next line
if re.search(r"^([\w\*\(]+\s+)+$", line):
previous_line += line
continue
# If previous line seemed to start an unfinished declaration
# (as above), concat and treat them as one.
if previous_line:
line = previous_line.strip() + " " + line.strip() + "\n"
previous_line = ""
# Skip parsing if line has a space in front = heuristic to
# skip function argument lines (highly subject to formatting
# changes)
if line[0] == " ":
continue
identifier = self.IDENTIFIER_REGEX.search(line)
if not identifier:
continue
# Find the group that matched, and append it
for group in identifier.groups():
if not group:
continue
identifiers.append(Match(
header_file,
line,
line_no,
identifier.span(),
group))
def parse_identifiers(self, include, exclude=None):
"""
Parse all lines of a header where a function/enum/struct/union/typedef
identifier is declared, based on some regex and heuristics. Highly
dependent on formatting style. Identifiers in excluded files are still
parsed
Args:
* include: A List of glob expressions to look for files through.
* exclude: A List of glob expressions for excluding files.
Returns: a Tuple of two Lists of Match objects with identifiers.
* included_identifiers: A List of Match objects with identifiers from
included files.
* excluded_identifiers: A List of Match objects with identifiers from
excluded files.
"""
included_files, excluded_files = \
self.get_all_files(include, exclude)
self.log.debug("Looking for included identifiers in {} files".format \
(len(included_files)))
included_identifiers = []
excluded_identifiers = []
for header_file in included_files:
self.parse_identifiers_in_file(header_file, included_identifiers)
for header_file in excluded_files:
self.parse_identifiers_in_file(header_file, excluded_identifiers)
return (included_identifiers, excluded_identifiers)
def parse_symbols(self):
"""
Compile the Mbed TLS libraries, and parse the TLS, Crypto, and x509
object files using nm to retrieve the list of referenced symbols.
Exceptions thrown here are rethrown because they would be critical
errors that void several tests, and thus needs to halt the program. This
is explicitly done for clarity.
Returns a List of unique symbols defined and used in the libraries.
"""
self.log.info("Compiling...")
symbols = []
# Back up the config and atomically compile with the full configuration.
shutil.copy(
"include/mbedtls/mbedtls_config.h",
"include/mbedtls/mbedtls_config.h.bak"
)
try:
# Use check=True in all subprocess calls so that failures are raised
# as exceptions and logged.
subprocess.run(
["python3", "scripts/config.py", "full"],
universal_newlines=True,
check=True
)
my_environment = os.environ.copy()
my_environment["CFLAGS"] = "-fno-asynchronous-unwind-tables"
# Run make clean separately to lib to prevent unwanted behavior when
# make is invoked with parallelism.
subprocess.run(
["make", "clean"],
universal_newlines=True,
check=True
)
subprocess.run(
["make", "lib"],
env=my_environment,
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=True
)
# Perform object file analysis using nm
symbols = self.parse_symbols_from_nm([
"library/libmbedcrypto.a",
"library/libmbedtls.a",
"library/libmbedx509.a"
])
subprocess.run(
["make", "clean"],
universal_newlines=True,
check=True
)
except subprocess.CalledProcessError as error:
self.log.debug(error.output)
raise error
finally:
# Put back the original config regardless of there being errors.
# Works also for keyboard interrupts.
shutil.move(
"include/mbedtls/mbedtls_config.h.bak",
"include/mbedtls/mbedtls_config.h"
)
return symbols
def parse_symbols_from_nm(self, object_files):
"""
Run nm to retrieve the list of referenced symbols in each object file.
Does not return the position data since it is of no use.
Args:
* object_files: a List of compiled object filepaths to search through.
Returns a List of unique symbols defined and used in any of the object
files.
"""
nm_undefined_regex = re.compile(r"^\S+: +U |^$|^\S+:$")
nm_valid_regex = re.compile(r"^\S+( [0-9A-Fa-f]+)* . _*(?P<symbol>\w+)")
exclusions = ("FStar", "Hacl")
symbols = []
# Gather all outputs of nm
nm_output = ""
for lib in object_files:
nm_output += subprocess.run(
["nm", "-og", lib],
universal_newlines=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
check=True
).stdout
for line in nm_output.splitlines():
if not nm_undefined_regex.search(line):
symbol = nm_valid_regex.search(line)
if (symbol and not symbol.group("symbol").startswith(exclusions)):
symbols.append(symbol.group("symbol"))
else:
self.log.error(line)
return symbols
class NameChecker():
"""
Representation of the core name checking operation performed by this script.
"""
def __init__(self, parse_result, log):
self.parse_result = parse_result
self.log = log
def perform_checks(self, quiet=False):
"""
A comprehensive checker that performs each check in order, and outputs
a final verdict.
Args:
* quiet: whether to hide detailed problem explanation.
"""
self.log.info("=============")
Problem.quiet = quiet
problems = 0
problems += self.check_symbols_declared_in_header()
pattern_checks = [
("public_macros", PUBLIC_MACRO_PATTERN),
("internal_macros", INTERNAL_MACRO_PATTERN),
("enum_consts", CONSTANTS_PATTERN),
("identifiers", IDENTIFIER_PATTERN)
]
for group, check_pattern in pattern_checks:
problems += self.check_match_pattern(group, check_pattern)
problems += self.check_for_typos()
self.log.info("=============")
if problems > 0:
self.log.info("FAIL: {0} problem(s) to fix".format(str(problems)))
if quiet:
self.log.info("Remove --quiet to see explanations.")
else:
self.log.info("Use --quiet for minimal output.")
return 1
else:
self.log.info("PASS")
return 0
def check_symbols_declared_in_header(self):
"""
Perform a check that all detected symbols in the library object files
are properly declared in headers.
Assumes parse_names_in_source() was called before this.
Returns the number of problems that need fixing.
"""
problems = []
all_identifiers = self.parse_result["identifiers"] + \
self.parse_result["excluded_identifiers"]
for symbol in self.parse_result["symbols"]:
found_symbol_declared = False
for identifier_match in all_identifiers:
if symbol == identifier_match.name:
found_symbol_declared = True
break
if not found_symbol_declared:
problems.append(SymbolNotInHeader(symbol))
self.output_check_result("All symbols in header", problems)
return len(problems)
def check_match_pattern(self, group_to_check, check_pattern):
"""
Perform a check that all items of a group conform to a regex pattern.
Assumes parse_names_in_source() was called before this.
Args:
* group_to_check: string key to index into self.parse_result.
* check_pattern: the regex to check against.
Returns the number of problems that need fixing.
"""
problems = []
for item_match in self.parse_result[group_to_check]:
if not re.search(check_pattern, item_match.name):
problems.append(PatternMismatch(check_pattern, item_match))
# Double underscore should not be used for names
if re.search(r".*__.*", item_match.name):
problems.append(
PatternMismatch("no double underscore allowed", item_match))
self.output_check_result(
"Naming patterns of {}".format(group_to_check),
problems)
return len(problems)
def check_for_typos(self):
"""
Perform a check that all words in the source code beginning with MBED are
either defined as macros, or as enum constants.
Assumes parse_names_in_source() was called before this.
Returns the number of problems that need fixing.
"""
problems = []
# Set comprehension, equivalent to a list comprehension wrapped by set()
all_caps_names = {
match.name
for match
in self.parse_result["public_macros"] +
self.parse_result["internal_macros"] +
self.parse_result["private_macros"] +
self.parse_result["enum_consts"]
}
typo_exclusion = re.compile(r"XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$|"
r"MBEDTLS_TEST_LIBTESTDRIVER*|"
r"PSA_CRYPTO_DRIVER_TEST")
for name_match in self.parse_result["mbed_psa_words"]:
found = name_match.name in all_caps_names
# Since MBEDTLS_PSA_ACCEL_XXX defines are defined by the
# PSA driver, they will not exist as macros. However, they
# should still be checked for typos using the equivalent
# BUILTINs that exist.
if "MBEDTLS_PSA_ACCEL_" in name_match.name:
found = name_match.name.replace(
"MBEDTLS_PSA_ACCEL_",
"MBEDTLS_PSA_BUILTIN_") in all_caps_names
if not found and not typo_exclusion.search(name_match.name):
problems.append(Typo(name_match))
self.output_check_result("Likely typos", problems)
return len(problems)
def output_check_result(self, name, problems):
"""
Write out the PASS/FAIL status of a performed check depending on whether
there were problems.
Args:
* name: the name of the test
* problems: a List of encountered Problems
"""
if problems:
self.log.info("{}: FAIL\n".format(name))
for problem in problems:
self.log.warning(str(problem))
else:
self.log.info("{}: PASS".format(name))
def main():
"""
Perform argument parsing, and create an instance of CodeParser and
NameChecker to begin the core operation.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=(
"This script confirms that the naming of all symbols and identifiers "
"in Mbed TLS are consistent with the house style and are also "
"self-consistent.\n\n"
"Expected to be run from the Mbed TLS root directory.")
)
parser.add_argument(
"-v", "--verbose",
action="store_true",
help="show parse results"
)
parser.add_argument(
"-q", "--quiet",
action="store_true",
help="hide unnecessary text, explanations, and highlights"
)
args = parser.parse_args()
# Configure the global logger, which is then passed to the classes below
log = logging.getLogger()
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
log.addHandler(logging.StreamHandler())
try:
code_parser = CodeParser(log)
parse_result = code_parser.comprehensive_parse()
except Exception: # pylint: disable=broad-except
traceback.print_exc()
sys.exit(2)
name_checker = NameChecker(parse_result, log)
return_code = name_checker.perform_checks(quiet=args.quiet)
sys.exit(return_code)
if __name__ == "__main__":
main()
-167
View File
@@ -1,167 +0,0 @@
# components-basic-checks.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Basic checks
################################################################
component_check_recursion () {
msg "Check: recursion.pl" # < 1s
tests/scripts/recursion.pl library/*.c
tests/scripts/recursion.pl ${PSA_CORE_PATH}/*.c
tests/scripts/recursion.pl ${BUILTIN_SRC_PATH}/*.c
}
component_check_generated_files () {
msg "Check: check-generated-files, files generated with make" # 2s
make generated_files
tests/scripts/check-generated-files.sh
msg "Check: check-generated-files -u, files present" # 2s
tests/scripts/check-generated-files.sh -u
# Check that the generated files are considered up to date.
tests/scripts/check-generated-files.sh
msg "Check: check-generated-files -u, files absent" # 2s
command make neat
tests/scripts/check-generated-files.sh -u
# Check that the generated files are considered up to date.
tests/scripts/check-generated-files.sh
# This component ends with the generated files present in the source tree.
# This is necessary for subsequent components!
}
component_check_doxy_blocks () {
msg "Check: doxygen markup outside doxygen blocks" # < 1s
tests/scripts/check-doxy-blocks.pl
}
component_check_files () {
msg "Check: file sanity checks (permissions, encodings)" # < 1s
tests/scripts/check_files.py
}
component_check_changelog () {
msg "Check: changelog entries" # < 1s
rm -f ChangeLog.new
scripts/assemble_changelog.py -o ChangeLog.new
if [ -e ChangeLog.new ]; then
# Show the diff for information. It isn't an error if the diff is
# non-empty.
diff -u ChangeLog ChangeLog.new || true
rm ChangeLog.new
fi
}
component_check_names () {
msg "Check: declared and exported names (builds the library)" # < 3s
tests/scripts/check_names.py -v
}
component_check_test_cases () {
msg "Check: test case descriptions" # < 1s
if [ $QUIET -eq 1 ]; then
opt='--quiet'
else
opt=''
fi
framework/scripts/check_test_cases.py -q $opt
unset opt
}
component_check_test_dependencies () {
msg "Check: test case dependencies: legacy vs PSA" # < 1s
# The purpose of this component is to catch unjustified dependencies on
# legacy feature macros (MBEDTLS_xxx) in PSA tests. Generally speaking,
# PSA test should use PSA feature macros (PSA_WANT_xxx, more rarely
# MBEDTLS_PSA_xxx).
#
# Most of the time, use of legacy MBEDTLS_xxx macros are mistakes, which
# this component is meant to catch. However a few of them are justified,
# mostly by the absence of a PSA equivalent, so this component includes a
# list of expected exceptions.
found="check-test-deps-found-$$"
expected="check-test-deps-expected-$$"
# Find legacy dependencies in PSA tests
grep 'depends_on' \
tf-psa-crypto/tests/suites/test_suite_psa*.data \
tf-psa-crypto/tests/suites/test_suite_psa*.function |
grep -Eo '!?MBEDTLS_[^: ]*' |
grep -v -e MBEDTLS_PSA_ -e MBEDTLS_TEST_ |
sort -u > $found
# Expected ones with justification - keep in sorted order by ASCII table!
rm -f $expected
# No PSA equivalent - WANT_KEY_TYPE_AES means all sizes
echo "!MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH" >> $expected
# No PSA equivalent - used to skip decryption tests in PSA-ECB, CBC/XTS/NIST_KW/DES
echo "!MBEDTLS_BLOCK_CIPHER_NO_DECRYPT" >> $expected
# MBEDTLS_ASN1_WRITE_C is used by import_rsa_made_up() in test_suite_psa_crypto
# in order to build a fake RSA key of the wanted size based on
# PSA_VENDOR_RSA_MAX_KEY_BITS. The legacy module is only used by
# the test code and that's probably the most convenient way of achieving
# the test's goal.
echo "MBEDTLS_ASN1_WRITE_C" >> $expected
# No PSA equivalent - used in test_suite_psa_crypto to get some "known" size
# for raw key generation.
echo "MBEDTLS_CTR_DRBG_MAX_REQUEST" >> $expected
# No PSA equivalent - we should probably have one in the future.
echo "MBEDTLS_ECP_RESTARTABLE" >> $expected
# No PSA equivalent - needed by some init tests
echo "MBEDTLS_ENTROPY_NV_SEED" >> $expected
# No PSA equivalent - required to run threaded tests.
echo "MBEDTLS_THREADING_PTHREAD" >> $expected
# Compare reality with expectation.
# We want an exact match, to ensure the above list remains up-to-date.
#
# The output should be empty. When it's not:
# - Each '+' line is a macro that was found but not expected. You want to
# find where that macro occurs, and either replace it with PSA macros, or
# add it to the exceptions list above with a justification.
# - Each '-' line is a macro that was expected but not found; it means the
# exceptions list above should be updated by removing that macro.
diff -U0 $expected $found
rm $found $expected
}
component_check_doxygen_warnings () {
msg "Check: doxygen warnings (builds the documentation)" # ~ 3s
tests/scripts/doxygen.sh
}
component_check_code_style () {
msg "Check C code style"
./scripts/code_style.py
}
support_check_code_style () {
case $(uncrustify --version) in
*0.75.1*) true;;
*) false;;
esac
}
component_check_python_files () {
msg "Lint: Python scripts"
tests/scripts/check-python-files.sh
}
component_check_test_helpers () {
msg "unit test: generate_test_code.py"
# unittest writes out mundane stuff like number or tests run on stderr.
# Our convention is to reserve stderr for actual errors, and write
# harmless info on stdout so it can be suppress with --quiet.
./framework/scripts/test_generate_test_code.py 2>&1
msg "unit test: translate_ciphers.py"
python3 -m unittest framework/scripts/translate_ciphers.py 2>&1
}
-238
View File
@@ -1,238 +0,0 @@
# components-build-system.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Build System Testing
################################################################
component_test_make_shared () {
msg "build/test: make shared" # ~ 40s
make SHARED=1 TEST_CPP=1 all check
ldd programs/util/strerror | grep libmbedcrypto
programs/test/dlopen_demo.sh
}
component_test_cmake_shared () {
msg "build/test: cmake shared" # ~ 2min
cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On .
make
ldd programs/util/strerror | grep libmbedcrypto
make test
programs/test/dlopen_demo.sh
}
support_test_cmake_out_of_source () {
distrib_id=""
distrib_ver=""
distrib_ver_minor=""
distrib_ver_major=""
# Attempt to parse lsb-release to find out distribution and version. If not
# found this should fail safe (test is supported).
if [[ -f /etc/lsb-release ]]; then
while read -r lsb_line; do
case "$lsb_line" in
"DISTRIB_ID"*) distrib_id=${lsb_line/#DISTRIB_ID=};;
"DISTRIB_RELEASE"*) distrib_ver=${lsb_line/#DISTRIB_RELEASE=};;
esac
done < /etc/lsb-release
distrib_ver_major="${distrib_ver%%.*}"
distrib_ver="${distrib_ver#*.}"
distrib_ver_minor="${distrib_ver%%.*}"
fi
# Running the out of source CMake test on Ubuntu 16.04 using more than one
# processor (as the CI does) can create a race condition whereby the build
# fails to see a generated file, despite that file actually having been
# generated. This problem appears to go away with 18.04 or newer, so make
# the out of source tests unsupported on Ubuntu 16.04.
[ "$distrib_id" != "Ubuntu" ] || [ "$distrib_ver_major" -gt 16 ]
}
component_test_cmake_out_of_source () {
# Remove existing generated files so that we use the ones cmake
# generates
make neat
msg "build: cmake 'out-of-source' build"
MBEDTLS_ROOT_DIR="$PWD"
mkdir "$OUT_OF_SOURCE_DIR"
cd "$OUT_OF_SOURCE_DIR"
# Note: Explicitly generate files as these are turned off in releases
cmake -D CMAKE_BUILD_TYPE:String=Check -D GEN_FILES=ON -D TEST_CPP=1 "$MBEDTLS_ROOT_DIR"
make
msg "test: cmake 'out-of-source' build"
make test
# Check that ssl-opt.sh can find the test programs.
# Also ensure that there are no error messages such as
# "No such file or directory", which would indicate that some required
# file is missing (ssl-opt.sh tolerates the absence of some files so
# may exit with status 0 but emit errors).
./tests/ssl-opt.sh -f 'Default' >ssl-opt.out 2>ssl-opt.err
grep PASS ssl-opt.out
cat ssl-opt.err >&2
# If ssl-opt.err is non-empty, record an error and keep going.
[ ! -s ssl-opt.err ]
rm ssl-opt.out ssl-opt.err
cd "$MBEDTLS_ROOT_DIR"
rm -rf "$OUT_OF_SOURCE_DIR"
}
component_test_cmake_as_subdirectory () {
# Remove existing generated files so that we use the ones CMake
# generates
make neat
msg "build: cmake 'as-subdirectory' build"
cd programs/test/cmake_subproject
# Note: Explicitly generate files as these are turned off in releases
cmake -D GEN_FILES=ON .
make
./cmake_subproject
}
support_test_cmake_as_subdirectory () {
support_test_cmake_out_of_source
}
component_test_cmake_as_package () {
# Remove existing generated files so that we use the ones CMake
# generates
make neat
msg "build: cmake 'as-package' build"
root_dir="$(pwd)"
cd programs/test/cmake_package
build_variant_dir="$(pwd)"
cmake .
make
./cmake_package
if [[ "$OSTYPE" == linux* ]]; then
PKG_CONFIG_PATH="${build_variant_dir}/mbedtls/pkgconfig" \
${root_dir}/tests/scripts/pkgconfig.sh \
mbedtls mbedx509 mbedcrypto
# These are the EXPECTED package names. Renaming these could break
# consumers of pkg-config, consider carefully.
fi
}
component_test_tf_psa_crypto_cmake_as_package () {
# Remove existing generated files so that we use the ones CMake
# generates
make neat
msg "build: cmake 'as-package' build"
root_dir="$(pwd)"
cd tf-psa-crypto/programs/test/cmake_package
build_variant_dir="$(pwd)"
cmake .
make
./cmake_package
if [[ "$OSTYPE" == linux* ]]; then
PKG_CONFIG_PATH="${build_variant_dir}/tf-psa-crypto/pkgconfig" \
${root_dir}/tests/scripts/pkgconfig.sh \
tfpsacrypto
# This is the EXPECTED package name. Renaming it could break consumers
# of pkg-config, consider carefully.
fi
}
support_test_cmake_as_package () {
support_test_cmake_out_of_source
}
component_test_cmake_as_package_install () {
# Remove existing generated files so that we use the ones CMake
# generates
make neat
msg "build: cmake 'as-installed-package' build"
cd programs/test/cmake_package_install
cmake .
make
./cmake_package_install
}
support_test_cmake_as_package_install () {
support_test_cmake_out_of_source
}
component_build_cmake_custom_config_file () {
# Make a copy of config file to use for the in-tree test
cp "$CONFIG_H" include/mbedtls_config_in_tree_copy.h
MBEDTLS_ROOT_DIR="$PWD"
mkdir "$OUT_OF_SOURCE_DIR"
cd "$OUT_OF_SOURCE_DIR"
# Build once to get the generated files (which need an intact config file)
cmake "$MBEDTLS_ROOT_DIR"
make
msg "build: cmake with -DMBEDTLS_CONFIG_FILE"
scripts/config.py -w full_config.h full
echo '#error "cmake -DMBEDTLS_CONFIG_FILE is not working."' > "$MBEDTLS_ROOT_DIR/$CONFIG_H"
cmake -DGEN_FILES=OFF -DMBEDTLS_CONFIG_FILE=full_config.h "$MBEDTLS_ROOT_DIR"
make
msg "build: cmake with -DMBEDTLS_CONFIG_FILE + -DMBEDTLS_USER_CONFIG_FILE"
# In the user config, disable one feature (for simplicity, pick a feature
# that nothing else depends on).
echo '#undef MBEDTLS_NIST_KW_C' >user_config.h
cmake -DGEN_FILES=OFF -DMBEDTLS_CONFIG_FILE=full_config.h -DMBEDTLS_USER_CONFIG_FILE=user_config.h "$MBEDTLS_ROOT_DIR"
make
not programs/test/query_compile_time_config MBEDTLS_NIST_KW_C
rm -f user_config.h full_config.h
cd "$MBEDTLS_ROOT_DIR"
rm -rf "$OUT_OF_SOURCE_DIR"
# Now repeat the test for an in-tree build:
# Restore config for the in-tree test
mv include/mbedtls_config_in_tree_copy.h "$CONFIG_H"
# Build once to get the generated files (which need an intact config)
cmake .
make
msg "build: cmake (in-tree) with -DMBEDTLS_CONFIG_FILE"
scripts/config.py -w full_config.h full
echo '#error "cmake -DMBEDTLS_CONFIG_FILE is not working."' > "$MBEDTLS_ROOT_DIR/$CONFIG_H"
cmake -DGEN_FILES=OFF -DMBEDTLS_CONFIG_FILE=full_config.h .
make
msg "build: cmake (in-tree) with -DMBEDTLS_CONFIG_FILE + -DMBEDTLS_USER_CONFIG_FILE"
# In the user config, disable one feature (for simplicity, pick a feature
# that nothing else depends on).
echo '#undef MBEDTLS_NIST_KW_C' >user_config.h
cmake -DGEN_FILES=OFF -DMBEDTLS_CONFIG_FILE=full_config.h -DMBEDTLS_USER_CONFIG_FILE=user_config.h .
make
not programs/test/query_compile_time_config MBEDTLS_NIST_KW_C
rm -f user_config.h full_config.h
}
support_build_cmake_custom_config_file () {
support_test_cmake_out_of_source
}
component_build_cmake_programs_no_testing () {
# Verify that the type of builds performed by oss-fuzz don't get accidentally broken
msg "build: cmake with -DENABLE_PROGRAMS=ON and -DENABLE_TESTING=OFF"
cmake -DENABLE_PROGRAMS=ON -DENABLE_TESTING=OFF .
make
}
support_build_cmake_programs_no_testing () {
support_test_cmake_out_of_source
}
-145
View File
@@ -1,145 +0,0 @@
# components-compiler.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Compiler Testing
################################################################
support_build_tfm_armcc () {
support_build_armcc
}
component_build_tfm_armcc () {
# test the TF-M configuration can build cleanly with various warning flags enabled
cp configs/config-tfm.h "$CONFIG_H"
msg "build: TF-M config, armclang armv7-m thumb2"
helper_armc6_build_test "--target=arm-arm-none-eabi -march=armv7-m -mthumb -Os -std=c99 -Werror -Wall -Wextra -Wwrite-strings -Wpointer-arith -Wimplicit-fallthrough -Wshadow -Wvla -Wformat=2 -Wno-format-nonliteral -Wshadow -Wasm-operand-widths -Wunused -I../tests/include/spe"
}
test_build_opt () {
info=$1 cc=$2; shift 2
$cc --version
for opt in "$@"; do
msg "build/test: $cc $opt, $info" # ~ 30s
make CC="$cc" CFLAGS="$opt -std=c99 -pedantic -Wall -Wextra -Werror"
# We're confident enough in compilers to not run _all_ the tests,
# but at least run the unit tests. In particular, runs with
# optimizations use inline assembly whereas runs with -O0
# skip inline assembly.
make test # ~30s
make clean
done
}
# For FreeBSD we invoke the function by name so this condition is added
# to disable the existing test_clang_opt function for linux.
if [[ $(uname) != "Linux" ]]; then
component_test_clang_opt () {
scripts/config.py full
test_build_opt 'full config' clang -O0 -Os -O2
}
fi
component_test_clang_latest_opt () {
scripts/config.py full
test_build_opt 'full config' "$CLANG_LATEST" -O0 -Os -O2
}
support_test_clang_latest_opt () {
type "$CLANG_LATEST" >/dev/null 2>/dev/null
}
component_test_clang_earliest_opt () {
scripts/config.py full
test_build_opt 'full config' "$CLANG_EARLIEST" -O2
}
support_test_clang_earliest_opt () {
type "$CLANG_EARLIEST" >/dev/null 2>/dev/null
}
component_test_gcc_latest_opt () {
scripts/config.py full
test_build_opt 'full config' "$GCC_LATEST" -O0 -Os -O2
}
support_test_gcc_latest_opt () {
type "$GCC_LATEST" >/dev/null 2>/dev/null
}
component_test_gcc_earliest_opt () {
scripts/config.py full
test_build_opt 'full config' "$GCC_EARLIEST" -O2
}
support_test_gcc_earliest_opt () {
type "$GCC_EARLIEST" >/dev/null 2>/dev/null
}
component_build_mingw () {
msg "build: Windows cross build - mingw64, make (Link Library)" # ~ 30s
make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS='-Werror -Wall -Wextra -maes -msse2 -mpclmul' WINDOWS_BUILD=1 lib programs
# note Make tests only builds the tests, but doesn't run them
make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS='-Werror -maes -msse2 -mpclmul' WINDOWS_BUILD=1 tests
make WINDOWS_BUILD=1 clean
msg "build: Windows cross build - mingw64, make (DLL)" # ~ 30s
make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS='-Werror -Wall -Wextra -maes -msse2 -mpclmul' WINDOWS_BUILD=1 SHARED=1 lib programs
make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS='-Werror -Wall -Wextra -maes -msse2 -mpclmul' WINDOWS_BUILD=1 SHARED=1 tests
make WINDOWS_BUILD=1 clean
msg "build: Windows cross build - mingw64, make (Library only, default config without MBEDTLS_AESNI_C)" # ~ 30s
./scripts/config.py unset MBEDTLS_AESNI_C #
make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar CFLAGS='-Werror -Wall -Wextra' WINDOWS_BUILD=1 lib
make WINDOWS_BUILD=1 clean
}
support_build_mingw () {
case $(i686-w64-mingw32-gcc -dumpversion 2>/dev/null) in
[0-5]*|"") false;;
*) true;;
esac
}
component_build_zeroize_checks () {
msg "build: check for obviously wrong calls to mbedtls_platform_zeroize()"
scripts/config.py full
# Only compile - we're looking for sizeof-pointer-memaccess warnings
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/user-config-zeroize-memset.h\"' -DMBEDTLS_TEST_DEFINES_ZEROIZE -Werror -Wsizeof-pointer-memaccess"
}
component_test_zeroize () {
# Test that the function mbedtls_platform_zeroize() is not optimized away by
# different combinations of compilers and optimization flags by using an
# auxiliary GDB script. Unfortunately, GDB does not return error values to the
# system in all cases that the script fails, so we must manually search the
# output to check whether the pass string is present and no failure strings
# were printed.
# Don't try to disable ASLR. We don't care about ASLR here. We do care
# about a spurious message if Gdb tries and fails, so suppress that.
gdb_disable_aslr=
if [ -z "$(gdb -batch -nw -ex 'set disable-randomization off' 2>&1)" ]; then
gdb_disable_aslr='set disable-randomization off'
fi
for optimization_flag in -O2 -O3 -Ofast -Os; do
for compiler in clang gcc; do
msg "test: $compiler $optimization_flag, mbedtls_platform_zeroize()"
make programs CC="$compiler" DEBUG=1 CFLAGS="$optimization_flag"
gdb -ex "$gdb_disable_aslr" -x tests/scripts/test_zeroize.gdb -nw -batch -nx 2>&1 | tee test_zeroize.log
grep "The buffer was correctly zeroized" test_zeroize.log
not grep -i "error" test_zeroize.log
rm -f test_zeroize.log
make clean
done
done
}
-32
View File
@@ -1,32 +0,0 @@
# components-compliance.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Compliance Testing
################################################################
component_test_psa_compliance () {
# The arch tests build with gcc, so require use of gcc here to link properly
msg "build: make, default config (out-of-box), libmbedcrypto.a only"
CC=gcc make -C library libmbedcrypto.a
msg "unit test: test_psa_compliance.py"
CC=gcc ./tests/scripts/test_psa_compliance.py --build-dir="."
}
support_test_psa_compliance () {
# psa-compliance-tests only supports CMake >= 3.10.0
ver="$(cmake --version)"
ver="${ver#cmake version }"
ver_major="${ver%%.*}"
ver="${ver#*.}"
ver_minor="${ver%%.*}"
[ "$ver_major" -eq 3 ] && [ "$ver_minor" -ge 10 ]
}
File diff suppressed because it is too large Load Diff
@@ -1,111 +0,0 @@
# components-configuration-platform.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Configuration Testing - Platform
################################################################
component_build_no_std_function () {
# catch compile bugs in _uninit functions
msg "build: full config with NO_STD_FUNCTION, make, gcc" # ~ 30s
scripts/config.py full
scripts/config.py set MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED
scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Check .
make
}
component_build_no_sockets () {
# Note, C99 compliance can also be tested with the sockets support disabled,
# as that requires a POSIX platform (which isn't the same as C99).
msg "build: full config except net_sockets.c, make, gcc -std=c99 -pedantic" # ~ 30s
scripts/config.py full
scripts/config.py unset MBEDTLS_NET_C # getaddrinfo() undeclared, etc.
scripts/config.py set MBEDTLS_NO_PLATFORM_ENTROPY # uses syscall() on GNU/Linux
make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1 -std=c99 -pedantic' lib
}
component_test_no_date_time () {
msg "build: default config without MBEDTLS_HAVE_TIME_DATE"
scripts/config.py unset MBEDTLS_HAVE_TIME_DATE
cmake -D CMAKE_BUILD_TYPE:String=Check .
make
msg "test: !MBEDTLS_HAVE_TIME_DATE - main suites"
make test
}
component_test_platform_calloc_macro () {
msg "build: MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO enabled (ASan build)"
scripts/config.py set MBEDTLS_PLATFORM_MEMORY
scripts/config.py set MBEDTLS_PLATFORM_CALLOC_MACRO calloc
scripts/config.py set MBEDTLS_PLATFORM_FREE_MACRO free
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO enabled (ASan build)"
make test
}
component_test_have_int32 () {
msg "build: gcc, force 32-bit bignum limbs"
scripts/config.py unset MBEDTLS_HAVE_ASM
scripts/config.py unset MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AESCE_C
make CC=gcc CFLAGS='-O2 -Werror -Wall -Wextra -DMBEDTLS_HAVE_INT32'
msg "test: gcc, force 32-bit bignum limbs"
make test
}
component_test_have_int64 () {
msg "build: gcc, force 64-bit bignum limbs"
scripts/config.py unset MBEDTLS_HAVE_ASM
scripts/config.py unset MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AESCE_C
make CC=gcc CFLAGS='-O2 -Werror -Wall -Wextra -DMBEDTLS_HAVE_INT64'
msg "test: gcc, force 64-bit bignum limbs"
make test
}
component_test_have_int32_cmake_new_bignum () {
msg "build: gcc, force 32-bit bignum limbs, new bignum interface, test hooks (ASan build)"
scripts/config.py unset MBEDTLS_HAVE_ASM
scripts/config.py unset MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AESCE_C
scripts/config.py set MBEDTLS_TEST_HOOKS
scripts/config.py set MBEDTLS_ECP_WITH_MPI_UINT
make CC=gcc CFLAGS="$ASAN_CFLAGS -Werror -Wall -Wextra -DMBEDTLS_HAVE_INT32" LDFLAGS="$ASAN_CFLAGS"
msg "test: gcc, force 32-bit bignum limbs, new bignum interface, test hooks (ASan build)"
make test
}
component_test_no_udbl_division () {
msg "build: MBEDTLS_NO_UDBL_DIVISION native" # ~ 10s
scripts/config.py full
scripts/config.py set MBEDTLS_NO_UDBL_DIVISION
make CFLAGS='-Werror -O1'
msg "test: MBEDTLS_NO_UDBL_DIVISION native" # ~ 10s
make test
}
component_test_no_64bit_multiplication () {
msg "build: MBEDTLS_NO_64BIT_MULTIPLICATION native" # ~ 10s
scripts/config.py full
scripts/config.py set MBEDTLS_NO_64BIT_MULTIPLICATION
make CFLAGS='-Werror -O1'
msg "test: MBEDTLS_NO_64BIT_MULTIPLICATION native" # ~ 10s
make test
}
@@ -1,691 +0,0 @@
# components-configuration-tls.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Configuration Testing - TLS
################################################################
component_test_config_suite_b () {
msg "build: configs/config-suite-b.h"
cp configs/config-suite-b.h "$CONFIG_H"
# test-ref-configs works by overwriting mbedtls_config.h; this makes cmake
# want to re-generate generated files that depend on it, quite correctly.
# However this doesn't work as the generation script expects a specific
# format for mbedtls_config.h, which the other files don't follow. Also,
# cmake can't know this, but re-generation is actually not necessary as
# the generated files only depend on the list of available options, not
# whether they're on or off. So, disable cmake's (over-sensitive here)
# dependency resolution for generated files and just rely on them being
# present (thanks to pre_generate_files) by turning GEN_FILES off.
CC=$ASAN_CC cmake -D GEN_FILES=Off -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: configs/config-suite-b.h - unit tests"
make test
msg "test: configs/config-suite-b.h - compat.sh"
tests/compat.sh -m tls12 -f 'ECDHE_ECDSA.*AES.*GCM' -p mbedTLS
msg "build: configs/config-suite-b.h + DEBUG"
MBEDTLS_TEST_CONFIGURATION="$MBEDTLS_TEST_CONFIGURATION+DEBUG"
make clean
scripts/config.py set MBEDTLS_DEBUG_C
scripts/config.py set MBEDTLS_ERROR_C
make ssl-opt
msg "test: configs/config-suite-b.h + DEBUG - ssl-opt.sh"
tests/ssl-opt.sh
}
component_test_no_renegotiation () {
msg "build: Default + !MBEDTLS_SSL_RENEGOTIATION (ASan build)" # ~ 6 min
scripts/config.py unset MBEDTLS_SSL_RENEGOTIATION
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: !MBEDTLS_SSL_RENEGOTIATION - main suites (inc. selftests) (ASan build)" # ~ 50s
make test
msg "test: !MBEDTLS_SSL_RENEGOTIATION - ssl-opt.sh (ASan build)" # ~ 6 min
tests/ssl-opt.sh
}
component_test_tls1_2_default_stream_cipher_only () {
msg "build: default with only stream cipher use psa"
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
# Disable AEAD (controlled by the presence of one of GCM_C, CCM_C, CHACHAPOLY_C)
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM_STAR_NO_TAG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_GCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CHACHA20_POLY1305
# Note: The three unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_GCM_C
scripts/config.py unset MBEDTLS_CCM_C
scripts/config.py unset MBEDTLS_CHACHAPOLY_C
#Disable TLS 1.3 (as no AEAD)
scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3
# Disable CBC. Note: When implemented, PSA_WANT_ALG_CBC_MAC will also need to be unset here to fully disable CBC
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CBC_NO_PADDING
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CBC_PKCS7
# Disable CBC-legacy (controlled by MBEDTLS_CIPHER_MODE_CBC plus at least one block cipher (AES, ARIA, Camellia, DES))
# Note: The unset below is to be removed for 4.0
scripts/config.py unset MBEDTLS_CIPHER_MODE_CBC
# Disable CBC-EtM (controlled by the same as CBC-legacy plus MBEDTLS_SSL_ENCRYPT_THEN_MAC)
scripts/config.py unset MBEDTLS_SSL_ENCRYPT_THEN_MAC
# Enable stream (currently that's just the NULL pseudo-cipher (controlled by MBEDTLS_CIPHER_NULL_CIPHER))
scripts/config.py set MBEDTLS_CIPHER_NULL_CIPHER
# Modules that depend on AEAD
scripts/config.py unset MBEDTLS_SSL_CONTEXT_SERIALIZATION
scripts/config.py unset MBEDTLS_SSL_TICKET_C
make
msg "test: default with only stream cipher use psa"
make test
# Not running ssl-opt.sh because most tests require a non-NULL ciphersuite.
}
component_test_tls1_2_default_cbc_legacy_cipher_only () {
msg "build: default with only CBC-legacy cipher use psa"
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
# Disable AEAD (controlled by the presence of one of GCM_C, CCM_C, CHACHAPOLY_C)
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM_STAR_NO_TAG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_GCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CHACHA20_POLY1305
# Note: The three unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_GCM_C
scripts/config.py unset MBEDTLS_CCM_C
scripts/config.py unset MBEDTLS_CHACHAPOLY_C
#Disable TLS 1.3 (as no AEAD)
scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3
# Enable CBC-legacy (controlled by MBEDTLS_CIPHER_MODE_CBC plus at least one block cipher (AES, ARIA, Camellia, DES))
scripts/config.py -f $CRYPTO_CONFIG_H set PSA_WANT_ALG_CBC_NO_PADDING
# Disable CBC-EtM (controlled by the same as CBC-legacy plus MBEDTLS_SSL_ENCRYPT_THEN_MAC)
scripts/config.py unset MBEDTLS_SSL_ENCRYPT_THEN_MAC
# Disable stream (currently that's just the NULL pseudo-cipher (controlled by MBEDTLS_CIPHER_NULL_CIPHER))
scripts/config.py unset MBEDTLS_CIPHER_NULL_CIPHER
# Modules that depend on AEAD
scripts/config.py unset MBEDTLS_SSL_CONTEXT_SERIALIZATION
scripts/config.py unset MBEDTLS_SSL_TICKET_C
make
msg "test: default with only CBC-legacy cipher use psa"
make test
msg "test: default with only CBC-legacy cipher use psa - ssl-opt.sh (subset)"
tests/ssl-opt.sh -f "TLS 1.2"
}
component_test_tls1_2_default_cbc_legacy_cbc_etm_cipher_only () {
msg "build: default with only CBC-legacy and CBC-EtM ciphers use psa"
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
# Disable AEAD (controlled by the presence of one of GCM_C, CCM_C, CHACHAPOLY_C)
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CCM_STAR_NO_TAG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_GCM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_CHACHA20_POLY1305
# Note: The three unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_GCM_C
scripts/config.py unset MBEDTLS_CCM_C
scripts/config.py unset MBEDTLS_CHACHAPOLY_C
#Disable TLS 1.3 (as no AEAD)
scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3
# Enable CBC-legacy (controlled by MBEDTLS_CIPHER_MODE_CBC plus at least one block cipher (AES, ARIA, Camellia, DES))
scripts/config.py -f $CRYPTO_CONFIG_H set PSA_WANT_ALG_CBC_NO_PADDING
# Enable CBC-EtM (controlled by the same as CBC-legacy plus MBEDTLS_SSL_ENCRYPT_THEN_MAC)
scripts/config.py set MBEDTLS_SSL_ENCRYPT_THEN_MAC
# Disable stream (currently that's just the NULL pseudo-cipher (controlled by MBEDTLS_CIPHER_NULL_CIPHER))
scripts/config.py unset MBEDTLS_CIPHER_NULL_CIPHER
# Modules that depend on AEAD
scripts/config.py unset MBEDTLS_SSL_CONTEXT_SERIALIZATION
scripts/config.py unset MBEDTLS_SSL_TICKET_C
make
msg "test: default with only CBC-legacy and CBC-EtM ciphers use psa"
make test
msg "test: default with only CBC-legacy and CBC-EtM ciphers use psa - ssl-opt.sh (subset)"
tests/ssl-opt.sh -f "TLS 1.2"
}
component_test_config_thread () {
msg "build: configs/config-thread.h"
cp configs/config-thread.h "$CONFIG_H"
# test-ref-configs works by overwriting mbedtls_config.h; this makes cmake
# want to re-generate generated files that depend on it, quite correctly.
# However this doesn't work as the generation script expects a specific
# format for mbedtls_config.h, which the other files don't follow. Also,
# cmake can't know this, but re-generation is actually not necessary as
# the generated files only depend on the list of available options, not
# whether they're on or off. So, disable cmake's (over-sensitive here)
# dependency resolution for generated files and just rely on them being
# present (thanks to pre_generate_files) by turning GEN_FILES off.
CC=$ASAN_CC cmake -D GEN_FILES=Off -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: configs/config-thread.h - unit tests"
make test
msg "test: configs/config-thread.h - ssl-opt.sh"
tests/ssl-opt.sh -f 'ECJPAKE.*nolog'
}
component_test_tls1_2_ccm_psk () {
msg "build: configs/config-ccm-psk-tls1_2.h"
cp configs/config-ccm-psk-tls1_2.h "$CONFIG_H"
# test-ref-configs works by overwriting mbedtls_config.h; this makes cmake
# want to re-generate generated files that depend on it, quite correctly.
# However this doesn't work as the generation script expects a specific
# format for mbedtls_config.h, which the other files don't follow. Also,
# cmake can't know this, but re-generation is actually not necessary as
# the generated files only depend on the list of available options, not
# whether they're on or off. So, disable cmake's (over-sensitive here)
# dependency resolution for generated files and just rely on them being
# present (thanks to pre_generate_files) by turning GEN_FILES off.
CC=$ASAN_CC cmake -D GEN_FILES=Off -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: configs/config-ccm-psk-tls1_2.h - unit tests"
make test
msg "test: configs/config-ccm-psk-tls1_2.h - compat.sh"
tests/compat.sh -m tls12 -f '^TLS_PSK_WITH_AES_..._CCM_8'
}
component_test_tls1_2_ccm_psk_dtls () {
msg "build: configs/config-ccm-psk-dtls1_2.h"
cp configs/config-ccm-psk-dtls1_2.h "$CONFIG_H"
# test-ref-configs works by overwriting mbedtls_config.h; this makes cmake
# want to re-generate generated files that depend on it, quite correctly.
# However this doesn't work as the generation script expects a specific
# format for mbedtls_config.h, which the other files don't follow. Also,
# cmake can't know this, but re-generation is actually not necessary as
# the generated files only depend on the list of available options, not
# whether they're on or off. So, disable cmake's (over-sensitive here)
# dependency resolution for generated files and just rely on them being
# present (thanks to pre_generate_files) by turning GEN_FILES off.
CC=$ASAN_CC cmake -D GEN_FILES=Off -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: configs/config-ccm-psk-dtls1_2.h - unit tests"
make test
msg "test: configs/config-ccm-psk-dtls1_2.h - compat.sh"
tests/compat.sh -m dtls12 -f '^TLS_PSK_WITH_AES_..._CCM_8'
msg "build: configs/config-ccm-psk-dtls1_2.h + DEBUG"
MBEDTLS_TEST_CONFIGURATION="$MBEDTLS_TEST_CONFIGURATION+DEBUG"
make clean
scripts/config.py set MBEDTLS_DEBUG_C
scripts/config.py set MBEDTLS_ERROR_C
make ssl-opt
msg "test: configs/config-ccm-psk-dtls1_2.h + DEBUG - ssl-opt.sh"
tests/ssl-opt.sh
}
component_test_small_ssl_out_content_len () {
msg "build: small SSL_OUT_CONTENT_LEN (ASan build)"
scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 16384
scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 4096
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: small SSL_OUT_CONTENT_LEN - ssl-opt.sh MFL and large packet tests"
tests/ssl-opt.sh -f "Max fragment\|Large packet"
}
component_test_small_ssl_in_content_len () {
msg "build: small SSL_IN_CONTENT_LEN (ASan build)"
scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 4096
scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 16384
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: small SSL_IN_CONTENT_LEN - ssl-opt.sh MFL tests"
tests/ssl-opt.sh -f "Max fragment"
}
component_test_small_ssl_dtls_max_buffering () {
msg "build: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #0"
scripts/config.py set MBEDTLS_SSL_DTLS_MAX_BUFFERING 1000
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #0 - ssl-opt.sh specific reordering test"
tests/ssl-opt.sh -f "DTLS reordering: Buffer out-of-order hs msg before reassembling next, free buffered msg"
}
component_test_small_mbedtls_ssl_dtls_max_buffering () {
msg "build: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #1"
scripts/config.py set MBEDTLS_SSL_DTLS_MAX_BUFFERING 190
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #1 - ssl-opt.sh specific reordering test"
tests/ssl-opt.sh -f "DTLS reordering: Buffer encrypted Finished message, drop for fragmented NewSessionTicket"
}
# Common helper for component_full_without_ecdhe_ecdsa() and
# component_full_without_ecdhe_ecdsa_and_tls13() which:
# - starts from the "full" configuration minus the list of symbols passed in
# as 1st parameter
# - build
# - test only TLS (i.e. test_suite_tls and ssl-opt)
build_full_minus_something_and_test_tls () {
symbols_to_disable="$1"
msg "build: full minus something, test TLS"
scripts/config.py full
for sym in $symbols_to_disable; do
echo "Disabling $sym"
scripts/config.py unset $sym
done
make
msg "test: full minus something, test TLS"
( cd tests; ./test_suite_ssl )
msg "ssl-opt: full minus something, test TLS"
tests/ssl-opt.sh
}
component_full_without_ecdhe_ecdsa () {
build_full_minus_something_and_test_tls "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED"
}
component_full_without_ecdhe_ecdsa_and_tls13 () {
build_full_minus_something_and_test_tls "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
MBEDTLS_SSL_PROTO_TLS1_3"
}
component_build_no_ssl_srv () {
msg "build: full config except SSL server, make, gcc" # ~ 30s
scripts/config.py full
scripts/config.py unset MBEDTLS_SSL_SRV_C
make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1 -Wmissing-prototypes'
}
component_build_no_ssl_cli () {
msg "build: full config except SSL client, make, gcc" # ~ 30s
scripts/config.py full
scripts/config.py unset MBEDTLS_SSL_CLI_C
make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1 -Wmissing-prototypes'
}
component_test_no_max_fragment_length () {
# Run max fragment length tests with MFL disabled
msg "build: default config except MFL extension (ASan build)" # ~ 30s
scripts/config.py unset MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: ssl-opt.sh, MFL-related tests"
tests/ssl-opt.sh -f "Max fragment length"
}
component_test_asan_remove_peer_certificate () {
msg "build: default config with MBEDTLS_SSL_KEEP_PEER_CERTIFICATE disabled (ASan build)"
scripts/config.py unset MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE"
make test
msg "test: ssl-opt.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE"
tests/ssl-opt.sh
msg "test: compat.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE"
tests/compat.sh
msg "test: context-info.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE"
tests/context-info.sh
}
component_test_no_max_fragment_length_small_ssl_out_content_len () {
msg "build: no MFL extension, small SSL_OUT_CONTENT_LEN (ASan build)"
scripts/config.py unset MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 16384
scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 4096
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: MFL tests (disabled MFL extension case) & large packet tests"
tests/ssl-opt.sh -f "Max fragment length\|Large buffer"
msg "test: context-info.sh (disabled MFL extension case)"
tests/context-info.sh
}
component_test_variable_ssl_in_out_buffer_len () {
msg "build: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled (ASan build)"
scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled"
make test
msg "test: ssl-opt.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled"
tests/ssl-opt.sh
msg "test: compat.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled"
tests/compat.sh
}
component_test_dtls_cid_legacy () {
msg "build: MBEDTLS_SSL_DTLS_CONNECTION_ID (legacy) enabled (ASan build)"
scripts/config.py set MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT 1
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: MBEDTLS_SSL_DTLS_CONNECTION_ID (legacy)"
make test
msg "test: ssl-opt.sh, MBEDTLS_SSL_DTLS_CONNECTION_ID (legacy) enabled"
tests/ssl-opt.sh
msg "test: compat.sh, MBEDTLS_SSL_DTLS_CONNECTION_ID (legacy) enabled"
tests/compat.sh
}
component_test_ssl_alloc_buffer_and_mfl () {
msg "build: default config with memory buffer allocator and MFL extension"
scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C
scripts/config.py set MBEDTLS_PLATFORM_MEMORY
scripts/config.py set MBEDTLS_MEMORY_DEBUG
scripts/config.py set MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
cmake -DCMAKE_BUILD_TYPE:String=Release .
make
msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH, MBEDTLS_MEMORY_BUFFER_ALLOC_C, MBEDTLS_MEMORY_DEBUG and MBEDTLS_SSL_MAX_FRAGMENT_LENGTH"
make test
msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH, MBEDTLS_MEMORY_BUFFER_ALLOC_C, MBEDTLS_MEMORY_DEBUG and MBEDTLS_SSL_MAX_FRAGMENT_LENGTH"
tests/ssl-opt.sh -f "Handshake memory usage"
}
component_test_when_no_ciphersuites_have_mac () {
msg "build: when no ciphersuites have MAC"
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f "$CRYPTO_CONFIG_H" unset PSA_WANT_ALG_CBC_NO_PADDING
scripts/config.py -f "$CRYPTO_CONFIG_H" unset PSA_WANT_ALG_CBC_PKCS7
scripts/config.py -f "$CRYPTO_CONFIG_H" unset PSA_WANT_ALG_CMAC
scripts/config.py -f "$CRYPTO_CONFIG_H" unset PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128
scripts/config.py unset MBEDTLS_CIPHER_NULL_CIPHER
scripts/config.py unset MBEDTLS_CIPHER_MODE_CBC
scripts/config.py unset MBEDTLS_CMAC_C
make
msg "test: !MBEDTLS_SSL_SOME_SUITES_USE_MAC"
make test
msg "test ssl-opt.sh: !MBEDTLS_SSL_SOME_SUITES_USE_MAC"
tests/ssl-opt.sh -f 'Default\|EtM' -e 'without EtM'
}
component_test_tls12_only () {
msg "build: default config without MBEDTLS_SSL_PROTO_TLS1_3, cmake, gcc, ASan"
scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: main suites (inc. selftests) (ASan build)"
make test
msg "test: ssl-opt.sh (ASan build)"
tests/ssl-opt.sh
msg "test: compat.sh (ASan build)"
tests/compat.sh
}
component_test_tls13_only () {
msg "build: default config without MBEDTLS_SSL_PROTO_TLS1_2"
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_SSL_RECORD_SIZE_LIMIT
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test: TLS 1.3 only, all key exchange modes enabled"
make test
msg "ssl-opt.sh: TLS 1.3 only, all key exchange modes enabled"
tests/ssl-opt.sh
}
component_test_tls13_only_psk () {
msg "build: TLS 1.3 only from default, only PSK key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_X509_CRT_PARSE_C
scripts/config.py unset MBEDTLS_X509_RSASSA_PSS_SUPPORT
scripts/config.py unset MBEDTLS_SSL_SERVER_NAME_INDICATION
scripts/config.py unset MBEDTLS_PKCS7_C
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDH
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_DETERMINISTIC_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_OAEP
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_PSS
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_FFDH
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_DH_RFC7919_2048
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_DH_RFC7919_3072
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_DH_RFC7919_4096
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_DH_RFC7919_6144
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_DH_RFC7919_8192
# Note: The four unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_ECDH_C
scripts/config.py unset MBEDTLS_ECDSA_C
scripts/config.py unset MBEDTLS_PKCS1_V21
scripts/config.py unset MBEDTLS_DHM_C
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, only PSK key exchange mode enabled"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, only PSK key exchange mode enabled"
tests/ssl-opt.sh
}
component_test_tls13_only_ephemeral () {
msg "build: TLS 1.3 only from default, only ephemeral key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_SSL_EARLY_DATA
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, only ephemeral key exchange mode"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, only ephemeral key exchange mode"
tests/ssl-opt.sh
}
component_test_tls13_only_ephemeral_ffdh () {
msg "build: TLS 1.3 only from default, only ephemeral ffdh key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDH
# Note: The unset below is to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_ECDH_C
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, only ephemeral ffdh key exchange mode"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, only ephemeral ffdh key exchange mode"
tests/ssl-opt.sh
}
component_test_tls13_only_psk_ephemeral () {
msg "build: TLS 1.3 only from default, only PSK ephemeral key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_X509_CRT_PARSE_C
scripts/config.py unset MBEDTLS_X509_RSASSA_PSS_SUPPORT
scripts/config.py unset MBEDTLS_SSL_SERVER_NAME_INDICATION
scripts/config.py unset MBEDTLS_PKCS7_C
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_DETERMINISTIC_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_OAEP
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_PSS
# Note: The two unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_ECDSA_C
scripts/config.py unset MBEDTLS_PKCS1_V21
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, only PSK ephemeral key exchange mode"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, only PSK ephemeral key exchange mode"
tests/ssl-opt.sh
}
component_test_tls13_only_psk_ephemeral_ffdh () {
msg "build: TLS 1.3 only from default, only PSK ephemeral ffdh key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_X509_CRT_PARSE_C
scripts/config.py unset MBEDTLS_X509_RSASSA_PSS_SUPPORT
scripts/config.py unset MBEDTLS_SSL_SERVER_NAME_INDICATION
scripts/config.py unset MBEDTLS_PKCS7_C
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDH
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_DETERMINISTIC_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_OAEP
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_PSS
# Note: The three unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_ECDH_C
scripts/config.py unset MBEDTLS_ECDSA_C
scripts/config.py unset MBEDTLS_PKCS1_V21
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, only PSK ephemeral ffdh key exchange mode"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, only PSK ephemeral ffdh key exchange mode"
tests/ssl-opt.sh
}
component_test_tls13_only_psk_all () {
msg "build: TLS 1.3 only from default, without ephemeral key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
scripts/config.py unset MBEDTLS_X509_CRT_PARSE_C
scripts/config.py unset MBEDTLS_X509_RSASSA_PSS_SUPPORT
scripts/config.py unset MBEDTLS_SSL_SERVER_NAME_INDICATION
scripts/config.py unset MBEDTLS_PKCS7_C
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_DETERMINISTIC_ECDSA
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_OAEP
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_RSA_PSS
# Note: The two unsets below are to be removed for Mbed TLS 4.0
scripts/config.py unset MBEDTLS_ECDSA_C
scripts/config.py unset MBEDTLS_PKCS1_V21
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, PSK and PSK ephemeral key exchange modes"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, PSK and PSK ephemeral key exchange modes"
tests/ssl-opt.sh
}
component_test_tls13_only_ephemeral_all () {
msg "build: TLS 1.3 only from default, without PSK key exchange mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
make CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"../tests/configs/tls13-only.h\"'"
msg "test_suite_ssl: TLS 1.3 only, ephemeral and PSK ephemeral key exchange modes"
cd tests; ./test_suite_ssl; cd ..
msg "ssl-opt.sh: TLS 1.3 only, ephemeral and PSK ephemeral key exchange modes"
tests/ssl-opt.sh
}
component_test_tls13_no_padding () {
msg "build: default config plus early data minus padding"
scripts/config.py set MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 1
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: default config plus early data minus padding"
make test
msg "ssl-opt.sh (TLS 1.3 no padding)"
tests/ssl-opt.sh
}
component_test_tls13_no_compatibility_mode () {
msg "build: default config plus early data minus middlebox compatibility mode"
scripts/config.py unset MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
scripts/config.py set MBEDTLS_SSL_EARLY_DATA
CC=$ASAN_CC cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: default config plus early data minus middlebox compatibility mode"
make test
msg "ssl-opt.sh (TLS 1.3 no compatibility mode)"
tests/ssl-opt.sh
}
component_test_full_minus_session_tickets () {
msg "build: full config without session tickets"
scripts/config.py full
scripts/config.py unset MBEDTLS_SSL_SESSION_TICKETS
scripts/config.py unset MBEDTLS_SSL_EARLY_DATA
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: full config without session tickets"
make test
msg "ssl-opt.sh (full config without session tickets)"
tests/ssl-opt.sh
}
component_test_depends_py_kex () {
msg "test/build: depends.py kex (gcc)"
tests/scripts/depends.py kex
}
@@ -1,35 +0,0 @@
# components-configuration-x509.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Configuration Testing - X509
################################################################
component_test_no_x509_info () {
msg "build: full + MBEDTLS_X509_REMOVE_INFO" # ~ 10s
scripts/config.pl full
scripts/config.pl unset MBEDTLS_MEMORY_BACKTRACE # too slow for tests
scripts/config.pl set MBEDTLS_X509_REMOVE_INFO
make CFLAGS='-Werror -O2'
msg "test: full + MBEDTLS_X509_REMOVE_INFO" # ~ 10s
make test
msg "test: ssl-opt.sh, full + MBEDTLS_X509_REMOVE_INFO" # ~ 1 min
tests/ssl-opt.sh
}
component_test_sw_inet_pton () {
msg "build: default plus MBEDTLS_TEST_SW_INET_PTON"
# MBEDTLS_TEST_HOOKS required for x509_crt_parse_cn_inet_pton
scripts/config.py set MBEDTLS_TEST_HOOKS
make CFLAGS="-DMBEDTLS_TEST_SW_INET_PTON"
msg "test: default plus MBEDTLS_TEST_SW_INET_PTON"
make test
}
-348
View File
@@ -1,348 +0,0 @@
# components-configuration.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Configuration Testing
################################################################
component_test_default_out_of_box () {
msg "build: make, default config (out-of-box)" # ~1min
make
# Disable fancy stuff
unset MBEDTLS_TEST_OUTCOME_FILE
msg "test: main suites make, default config (out-of-box)" # ~10s
make test
msg "selftest: make, default config (out-of-box)" # ~10s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~10s
tests/scripts/run_demos.py
}
component_test_default_cmake_gcc_asan () {
msg "build: cmake, gcc, ASan" # ~ 1 min 50s
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: main suites (inc. selftests) (ASan build)" # ~ 50s
make test
msg "program demos (ASan build)" # ~10s
tests/scripts/run_demos.py
msg "test: selftest (ASan build)" # ~ 10s
programs/test/selftest
msg "test: metatests (GCC, ASan build)"
tests/scripts/run-metatests.sh any asan poison
msg "test: ssl-opt.sh (ASan build)" # ~ 1 min
tests/ssl-opt.sh
msg "test: compat.sh (ASan build)" # ~ 6 min
tests/compat.sh
msg "test: context-info.sh (ASan build)" # ~ 15 sec
tests/context-info.sh
}
component_test_default_cmake_gcc_asan_new_bignum () {
msg "build: cmake, gcc, ASan" # ~ 1 min 50s
scripts/config.py set MBEDTLS_ECP_WITH_MPI_UINT
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: main suites (inc. selftests) (ASan build)" # ~ 50s
make test
msg "test: selftest (ASan build)" # ~ 10s
programs/test/selftest
msg "test: ssl-opt.sh (ASan build)" # ~ 1 min
tests/ssl-opt.sh
msg "test: compat.sh (ASan build)" # ~ 6 min
tests/compat.sh
msg "test: context-info.sh (ASan build)" # ~ 15 sec
tests/context-info.sh
}
component_test_full_cmake_gcc_asan () {
msg "build: full config, cmake, gcc, ASan"
scripts/config.py full
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: main suites (inc. selftests) (full config, ASan build)"
make test
msg "test: selftest (full config, ASan build)" # ~ 10s
programs/test/selftest
msg "test: ssl-opt.sh (full config, ASan build)"
tests/ssl-opt.sh
# Note: the next two invocations cover all compat.sh test cases.
# We should use the same here and in basic-build-test.sh.
msg "test: compat.sh: default version (full config, ASan build)"
tests/compat.sh -e 'ARIA\|CHACHA'
msg "test: compat.sh: next: ARIA, Chacha (full config, ASan build)"
env OPENSSL="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
msg "test: context-info.sh (full config, ASan build)" # ~ 15 sec
tests/context-info.sh
}
component_test_full_cmake_gcc_asan_new_bignum () {
msg "build: full config, cmake, gcc, ASan"
scripts/config.py full
scripts/config.py set MBEDTLS_ECP_WITH_MPI_UINT
CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan .
make
msg "test: main suites (inc. selftests) (full config, new bignum, ASan)"
make test
msg "test: selftest (full config, new bignum, ASan)" # ~ 10s
programs/test/selftest
msg "test: ssl-opt.sh (full config, new bignum, ASan)"
tests/ssl-opt.sh
# Note: the next two invocations cover all compat.sh test cases.
# We should use the same here and in basic-build-test.sh.
msg "test: compat.sh: default version (full config, new bignum, ASan)"
tests/compat.sh -e 'ARIA\|CHACHA'
msg "test: compat.sh: next: ARIA, Chacha (full config, new bignum, ASan)"
env OPENSSL="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA'
msg "test: context-info.sh (full config, new bignum, ASan)" # ~ 15 sec
tests/context-info.sh
}
component_test_full_cmake_clang () {
msg "build: cmake, full config, clang" # ~ 50s
scripts/config.py full
CC=clang CXX=clang cmake -D CMAKE_BUILD_TYPE:String=Release -D ENABLE_TESTING=On -D TEST_CPP=1 .
make
msg "test: main suites (full config, clang)" # ~ 5s
make test
msg "test: cpp_dummy_build (full config, clang)" # ~ 1s
programs/test/cpp_dummy_build
msg "test: metatests (clang)"
tests/scripts/run-metatests.sh any pthread
msg "program demos (full config, clang)" # ~10s
tests/scripts/run_demos.py
msg "test: psa_constant_names (full config, clang)" # ~ 1s
tests/scripts/test_psa_constant_names.py
msg "test: ssl-opt.sh default, ECJPAKE, SSL async (full config)" # ~ 1s
tests/ssl-opt.sh -f 'Default\|ECJPAKE\|SSL async private'
}
component_test_default_no_deprecated () {
# Test that removing the deprecated features from the default
# configuration leaves something consistent.
msg "build: make, default + MBEDTLS_DEPRECATED_REMOVED" # ~ 30s
scripts/config.py set MBEDTLS_DEPRECATED_REMOVED
make CFLAGS='-O -Werror -Wall -Wextra'
msg "test: make, default + MBEDTLS_DEPRECATED_REMOVED" # ~ 5s
make test
}
component_test_full_no_deprecated () {
msg "build: make, full_no_deprecated config" # ~ 30s
scripts/config.py full_no_deprecated
make CFLAGS='-O -Werror -Wall -Wextra'
msg "test: make, full_no_deprecated config" # ~ 5s
make test
msg "test: ensure that X509 has no direct dependency on BIGNUM_C"
not grep mbedtls_mpi library/libmbedx509.a
}
component_test_full_no_deprecated_deprecated_warning () {
# Test that there is nothing deprecated in "full_no_deprecated".
# A deprecated feature would trigger a warning (made fatal) from
# MBEDTLS_DEPRECATED_WARNING.
msg "build: make, full_no_deprecated config, MBEDTLS_DEPRECATED_WARNING" # ~ 30s
scripts/config.py full_no_deprecated
scripts/config.py unset MBEDTLS_DEPRECATED_REMOVED
scripts/config.py set MBEDTLS_DEPRECATED_WARNING
make CFLAGS='-O -Werror -Wall -Wextra'
msg "test: make, full_no_deprecated config, MBEDTLS_DEPRECATED_WARNING" # ~ 5s
make test
}
component_test_full_deprecated_warning () {
# Test that when MBEDTLS_DEPRECATED_WARNING is enabled, the build passes
# with only certain whitelisted types of warnings.
msg "build: make, full config + MBEDTLS_DEPRECATED_WARNING, expect warnings" # ~ 30s
scripts/config.py full
scripts/config.py set MBEDTLS_DEPRECATED_WARNING
# Expect warnings from '#warning' directives in check_config.h.
# Note that gcc is required to allow the use of -Wno-error=cpp, which allows us to
# display #warning messages without them being treated as errors.
make CC=gcc CFLAGS='-O -Werror -Wall -Wextra -Wno-error=cpp' lib programs
msg "build: make tests, full config + MBEDTLS_DEPRECATED_WARNING, expect warnings" # ~ 30s
# Set MBEDTLS_TEST_DEPRECATED to enable tests for deprecated features.
# By default those are disabled when MBEDTLS_DEPRECATED_WARNING is set.
# Expect warnings from '#warning' directives in check_config.h and
# from the use of deprecated functions in test suites.
make CC=gcc CFLAGS='-O -Werror -Wall -Wextra -Wno-error=deprecated-declarations -Wno-error=cpp -DMBEDTLS_TEST_DEPRECATED' tests
msg "test: full config + MBEDTLS_TEST_DEPRECATED" # ~ 30s
make test
msg "program demos: full config + MBEDTLS_TEST_DEPRECATED" # ~10s
tests/scripts/run_demos.py
}
component_build_baremetal () {
msg "build: make, baremetal config"
scripts/config.py baremetal
make CFLAGS="-O1 -Werror -I$PWD/tests/include/baremetal-override/"
}
support_build_baremetal () {
# Older Glibc versions include time.h from other headers such as stdlib.h,
# which makes the no-time.h-in-baremetal check fail. Ubuntu 16.04 has this
# problem, Ubuntu 18.04 is ok.
! grep -q -F time.h /usr/include/x86_64-linux-gnu/sys/types.h
}
component_build_tfm () {
# Check that the TF-M configuration can build cleanly with various
# warning flags enabled. We don't build or run tests, since the
# TF-M configuration needs a TF-M platform. A tweaked version of
# the configuration that works on mainstream platforms is in
# configs/config-tfm.h, tested via test-ref-configs.pl.
cp configs/config-tfm.h "$CONFIG_H"
msg "build: TF-M config, clang, armv7-m thumb2"
make lib CC="clang" CFLAGS="--target=arm-linux-gnueabihf -march=armv7-m -mthumb -Os -std=c99 -Werror -Wall -Wextra -Wwrite-strings -Wpointer-arith -Wimplicit-fallthrough -Wshadow -Wvla -Wformat=2 -Wno-format-nonliteral -Wshadow -Wasm-operand-widths -Wunused -I../tests/include/spe"
msg "build: TF-M config, gcc native build"
make clean
make lib CC="gcc" CFLAGS="-Os -std=c99 -Werror -Wall -Wextra -Wwrite-strings -Wpointer-arith -Wshadow -Wvla -Wformat=2 -Wno-format-nonliteral -Wshadow -Wformat-signedness -Wlogical-op -I../tests/include/spe"
}
component_test_malloc_0_null () {
msg "build: malloc(0) returns NULL (ASan+UBSan build)"
scripts/config.py full
make CC=$ASAN_CC CFLAGS="'-DMBEDTLS_USER_CONFIG_FILE=\"$PWD/tests/configs/user-config-malloc-0-null.h\"' $ASAN_CFLAGS" LDFLAGS="$ASAN_CFLAGS"
msg "test: malloc(0) returns NULL (ASan+UBSan build)"
make test
msg "selftest: malloc(0) returns NULL (ASan+UBSan build)"
# Just the calloc selftest. "make test" ran the others as part of the
# test suites.
programs/test/selftest calloc
msg "test ssl-opt.sh: malloc(0) returns NULL (ASan+UBSan build)"
# Run a subset of the tests. The choice is a balance between coverage
# and time (including time indirectly wasted due to flaky tests).
# The current choice is to skip tests whose description includes
# "proxy", which is an approximation of skipping tests that use the
# UDP proxy, which tend to be slower and flakier.
tests/ssl-opt.sh -e 'proxy'
}
component_test_no_platform () {
# Full configuration build, without platform support, file IO and net sockets.
# This should catch missing mbedtls_printf definitions, and by disabling file
# IO, it should catch missing '#include <stdio.h>'
msg "build: full config except platform/fsio/net, make, gcc, C99" # ~ 30s
scripts/config.py full_no_platform
scripts/config.py unset MBEDTLS_PLATFORM_C
scripts/config.py unset MBEDTLS_NET_C
scripts/config.py unset MBEDTLS_FS_IO
scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C
scripts/config.py unset MBEDTLS_PSA_ITS_FILE_C
scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED
# Note, _DEFAULT_SOURCE needs to be defined for platforms using glibc version >2.19,
# to re-enable platform integration features otherwise disabled in C99 builds
make CC=gcc CFLAGS='-Werror -Wall -Wextra -std=c99 -pedantic -Os -D_DEFAULT_SOURCE' lib programs
make CC=gcc CFLAGS='-Werror -Wall -Wextra -Os' test
}
component_build_mbedtls_config_file () {
msg "build: make with MBEDTLS_CONFIG_FILE" # ~40s
scripts/config.py -w full_config.h full
echo '#error "MBEDTLS_CONFIG_FILE is not working"' >"$CONFIG_H"
make CFLAGS="-I '$PWD' -DMBEDTLS_CONFIG_FILE='\"full_config.h\"'"
# Make sure this feature is enabled. We'll disable it in the next phase.
programs/test/query_compile_time_config MBEDTLS_NIST_KW_C
make clean
msg "build: make with MBEDTLS_CONFIG_FILE + MBEDTLS_USER_CONFIG_FILE"
# In the user config, disable one feature (for simplicity, pick a feature
# that nothing else depends on).
echo '#undef MBEDTLS_NIST_KW_C' >user_config.h
make CFLAGS="-I '$PWD' -DMBEDTLS_CONFIG_FILE='\"full_config.h\"' -DMBEDTLS_USER_CONFIG_FILE='\"user_config.h\"'"
not programs/test/query_compile_time_config MBEDTLS_NIST_KW_C
rm -f user_config.h full_config.h
}
component_test_no_strings () {
msg "build: no strings" # ~10s
scripts/config.py full
# Disable options that activate a large amount of string constants.
scripts/config.py unset MBEDTLS_DEBUG_C
scripts/config.py unset MBEDTLS_ERROR_C
scripts/config.py set MBEDTLS_ERROR_STRERROR_DUMMY
scripts/config.py unset MBEDTLS_VERSION_FEATURES
make CFLAGS='-Werror -Os'
msg "test: no strings" # ~ 10s
make test
}
component_test_memory_buffer_allocator_backtrace () {
msg "build: default config with memory buffer allocator and backtrace enabled"
scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C
scripts/config.py set MBEDTLS_PLATFORM_MEMORY
scripts/config.py set MBEDTLS_MEMORY_BACKTRACE
scripts/config.py set MBEDTLS_MEMORY_DEBUG
cmake -DCMAKE_BUILD_TYPE:String=Release .
make
msg "test: MBEDTLS_MEMORY_BUFFER_ALLOC_C and MBEDTLS_MEMORY_BACKTRACE"
make test
}
component_test_memory_buffer_allocator () {
msg "build: default config with memory buffer allocator"
scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C
scripts/config.py set MBEDTLS_PLATFORM_MEMORY
cmake -DCMAKE_BUILD_TYPE:String=Release .
make
msg "test: MBEDTLS_MEMORY_BUFFER_ALLOC_C"
make test
msg "test: ssl-opt.sh, MBEDTLS_MEMORY_BUFFER_ALLOC_C"
# MBEDTLS_MEMORY_BUFFER_ALLOC is slow. Skip tests that tend to time out.
tests/ssl-opt.sh -e '^DTLS proxy'
}
-604
View File
@@ -1,604 +0,0 @@
# components-platform.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Platform Testing
################################################################
component_test_m32_no_asm () {
# Build without assembly, so as to use portable C code (in a 32-bit
# build) and not the i386-specific inline assembly.
#
# Note that we require gcc, because clang Asan builds fail to link for
# this target (cannot find libclang_rt.lsan-i386.a - this is a known clang issue).
msg "build: i386, make, gcc, no asm (ASan build)" # ~ 30s
scripts/config.py full
scripts/config.py unset MBEDTLS_HAVE_ASM
scripts/config.py unset MBEDTLS_AESNI_C # AESNI for 32-bit is tested in test_aesni_m32
make CC=gcc CFLAGS="$ASAN_CFLAGS -m32" LDFLAGS="-m32 $ASAN_CFLAGS"
msg "test: i386, make, gcc, no asm (ASan build)"
make test
}
support_test_m32_no_asm () {
case $(uname -m) in
amd64|x86_64) true;;
*) false;;
esac
}
component_test_m32_o2 () {
# Build with optimization, to use the i386 specific inline assembly
# and go faster for tests.
msg "build: i386, make, gcc -O2 (ASan build)" # ~ 30s
scripts/config.py full
scripts/config.py unset MBEDTLS_AESNI_C # AESNI for 32-bit is tested in test_aesni_m32
make CC=gcc CFLAGS="$ASAN_CFLAGS -m32" LDFLAGS="-m32 $ASAN_CFLAGS"
msg "test: i386, make, gcc -O2 (ASan build)"
make test
msg "test ssl-opt.sh, i386, make, gcc-O2"
tests/ssl-opt.sh
}
support_test_m32_o2 () {
support_test_m32_no_asm "$@"
}
component_test_m32_everest () {
msg "build: i386, Everest ECDH context (ASan build)" # ~ 6 min
scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
scripts/config.py unset MBEDTLS_AESNI_C # AESNI for 32-bit is tested in test_aesni_m32
make CC=gcc CFLAGS="$ASAN_CFLAGS -m32" LDFLAGS="-m32 $ASAN_CFLAGS"
msg "test: i386, Everest ECDH context - main suites (inc. selftests) (ASan build)" # ~ 50s
make test
msg "test: i386, Everest ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s
tests/ssl-opt.sh -f ECDH
msg "test: i386, Everest ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min
# Exclude some symmetric ciphers that are redundant here to gain time.
tests/compat.sh -f ECDH -V NO -e 'ARIA\|CAMELLIA\|CHACHA'
}
support_test_m32_everest () {
support_test_m32_no_asm "$@"
}
component_test_mx32 () {
msg "build: 64-bit ILP32, make, gcc" # ~ 30s
scripts/config.py full
make CC=gcc CFLAGS='-O2 -Werror -Wall -Wextra -mx32' LDFLAGS='-mx32'
msg "test: 64-bit ILP32, make, gcc"
make test
}
support_test_mx32 () {
case $(uname -m) in
amd64|x86_64) true;;
*) false;;
esac
}
support_test_aesni () {
# Check that gcc targets x86_64 (we can build AESNI), and check for
# AESNI support on the host (we can run AESNI).
#
# The name of this function is possibly slightly misleading, but needs to align
# with the name of the corresponding test, component_test_aesni.
#
# In principle 32-bit x86 can support AESNI, but our implementation does not
# support 32-bit x86, so we check for x86-64.
# We can only grep /proc/cpuinfo on Linux, so this also checks for Linux
(gcc -v 2>&1 | grep Target | grep -q x86_64) &&
[[ "$HOSTTYPE" == "x86_64" && "$OSTYPE" == "linux-gnu" ]] &&
(lscpu | grep -qw aes)
}
component_test_aesni () { # ~ 60s
# This tests the two AESNI implementations (intrinsics and assembly), and also the plain C
# fallback. It also tests the logic that is used to select which implementation(s) to build.
#
# This test does not require the host to have support for AESNI (if it doesn't, the run-time
# AESNI detection will fallback to the plain C implementation, so the tests will instead
# exercise the plain C impl).
msg "build: default config with different AES implementations"
scripts/config.py set MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AES_USE_HARDWARE_ONLY
scripts/config.py set MBEDTLS_HAVE_ASM
# test the intrinsics implementation
msg "AES tests, test intrinsics"
make clean
make CC=gcc CFLAGS='-Werror -Wall -Wextra -mpclmul -msse2 -maes'
# check that we built intrinsics - this should be used by default when supported by the compiler
./programs/test/selftest aes | grep "AESNI code" | grep -q "intrinsics"
# test the asm implementation
msg "AES tests, test assembly"
make clean
make CC=gcc CFLAGS='-Werror -Wall -Wextra -mno-pclmul -mno-sse2 -mno-aes'
# check that we built assembly - this should be built if the compiler does not support intrinsics
./programs/test/selftest aes | grep "AESNI code" | grep -q "assembly"
# test the plain C implementation
scripts/config.py unset MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AES_USE_HARDWARE_ONLY
msg "AES tests, plain C"
make clean
make CC=gcc CFLAGS='-O2 -Werror'
# check that there is no AESNI code present
./programs/test/selftest aes | not grep -q "AESNI code"
not grep -q "AES note: using AESNI" ./programs/test/selftest
grep -q "AES note: built-in implementation." ./programs/test/selftest
# test the intrinsics implementation
scripts/config.py set MBEDTLS_AESNI_C
scripts/config.py set MBEDTLS_AES_USE_HARDWARE_ONLY
msg "AES tests, test AESNI only"
make clean
make CC=gcc CFLAGS='-Werror -Wall -Wextra -mpclmul -msse2 -maes'
./programs/test/selftest aes | grep -q "AES note: using AESNI"
./programs/test/selftest aes | not grep -q "AES note: built-in implementation."
grep -q "AES note: using AESNI" ./programs/test/selftest
not grep -q "AES note: built-in implementation." ./programs/test/selftest
}
support_test_aesni_m32 () {
support_test_m32_no_asm && (lscpu | grep -qw aes)
}
component_test_aesni_m32 () { # ~ 60s
# This tests are duplicated from component_test_aesni for i386 target
#
# AESNI intrinsic code supports i386 and assembly code does not support it.
msg "build: default config with different AES implementations"
scripts/config.py set MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AES_USE_HARDWARE_ONLY
scripts/config.py set MBEDTLS_HAVE_ASM
# test the intrinsics implementation with gcc
msg "AES tests, test intrinsics (gcc)"
make clean
make CC=gcc CFLAGS='-m32 -Werror -Wall -Wextra' LDFLAGS='-m32'
# check that we built intrinsics - this should be used by default when supported by the compiler
./programs/test/selftest aes | grep "AESNI code" | grep -q "intrinsics"
grep -q "AES note: using AESNI" ./programs/test/selftest
grep -q "AES note: built-in implementation." ./programs/test/selftest
grep -q mbedtls_aesni_has_support ./programs/test/selftest
scripts/config.py set MBEDTLS_AESNI_C
scripts/config.py set MBEDTLS_AES_USE_HARDWARE_ONLY
msg "AES tests, test AESNI only"
make clean
make CC=gcc CFLAGS='-m32 -Werror -Wall -Wextra -mpclmul -msse2 -maes' LDFLAGS='-m32'
./programs/test/selftest aes | grep -q "AES note: using AESNI"
./programs/test/selftest aes | not grep -q "AES note: built-in implementation."
grep -q "AES note: using AESNI" ./programs/test/selftest
not grep -q "AES note: built-in implementation." ./programs/test/selftest
not grep -q mbedtls_aesni_has_support ./programs/test/selftest
}
support_test_aesni_m32_clang () {
# clang >= 4 is required to build with target attributes
support_test_aesni_m32 && [[ $(clang_version) -ge 4 ]]
}
component_test_aesni_m32_clang () {
scripts/config.py set MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_AES_USE_HARDWARE_ONLY
scripts/config.py set MBEDTLS_HAVE_ASM
# test the intrinsics implementation with clang
msg "AES tests, test intrinsics (clang)"
make clean
make CC=clang CFLAGS='-m32 -Werror -Wall -Wextra' LDFLAGS='-m32'
# check that we built intrinsics - this should be used by default when supported by the compiler
./programs/test/selftest aes | grep "AESNI code" | grep -q "intrinsics"
grep -q "AES note: using AESNI" ./programs/test/selftest
grep -q "AES note: built-in implementation." ./programs/test/selftest
grep -q mbedtls_aesni_has_support ./programs/test/selftest
}
support_build_aes_armce () {
# clang >= 11 is required to build with AES extensions
[[ $(clang_version) -ge 11 ]]
}
component_build_aes_armce () {
# Test variations of AES with Armv8 crypto extensions
scripts/config.py set MBEDTLS_AESCE_C
scripts/config.py set MBEDTLS_AES_USE_HARDWARE_ONLY
msg "MBEDTLS_AES_USE_HARDWARE_ONLY, clang, aarch64"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a+crypto"
msg "clang, test aarch64 crypto instructions built"
grep -E 'aes[a-z]+\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "MBEDTLS_AES_USE_HARDWARE_ONLY, clang, arm"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72+crypto -marm"
msg "clang, test A32 crypto instructions built"
grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "MBEDTLS_AES_USE_HARDWARE_ONLY, clang, thumb"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32+crypto -mthumb"
msg "clang, test T32 crypto instructions built"
grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
scripts/config.py unset MBEDTLS_AES_USE_HARDWARE_ONLY
msg "MBEDTLS_AES_USE_both, clang, aarch64"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a+crypto"
msg "clang, test aarch64 crypto instructions built"
grep -E 'aes[a-z]+\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "MBEDTLS_AES_USE_both, clang, arm"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72+crypto -marm"
msg "clang, test A32 crypto instructions built"
grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "MBEDTLS_AES_USE_both, clang, thumb"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32+crypto -mthumb"
msg "clang, test T32 crypto instructions built"
grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
scripts/config.py unset MBEDTLS_AESCE_C
msg "no MBEDTLS_AESCE_C, clang, aarch64"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a"
msg "clang, test aarch64 crypto instructions not built"
not grep -E 'aes[a-z]+\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "no MBEDTLS_AESCE_C, clang, arm"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72 -marm"
msg "clang, test A32 crypto instructions not built"
not grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
msg "no MBEDTLS_AESCE_C, clang, thumb"
make -B library/../${BUILTIN_SRC_PATH}/aesce.o library/../${BUILTIN_SRC_PATH}/aesce.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32 -mthumb"
msg "clang, test T32 crypto instructions not built"
not grep -E 'aes[0-9a-z]+.[0-9]\s*[qv]' ${BUILTIN_SRC_PATH}/aesce.s
}
support_build_sha_armce () {
# clang >= 4 is required to build with SHA extensions
[[ $(clang_version) -ge 4 ]]
}
component_build_sha_armce () {
scripts/config.py unset MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT
# Test variations of SHA256 Armv8 crypto extensions
scripts/config.py set MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY clang, aarch64"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a+crypto"
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY clang, test aarch64 crypto instructions built"
grep -E 'sha256[a-z0-9]+\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY clang, arm"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72+crypto -marm"
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY clang, test A32 crypto instructions built"
grep -E 'sha256[a-z0-9]+.32\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
scripts/config.py unset MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY
# test the deprecated form of the config option
scripts/config.py set MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY
msg "MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY clang, thumb"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32+crypto -mthumb"
msg "MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY clang, test T32 crypto instructions built"
grep -E 'sha256[a-z0-9]+.32\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
scripts/config.py unset MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY
scripts/config.py set MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT clang, aarch64"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a+crypto"
msg "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT clang, test aarch64 crypto instructions built"
grep -E 'sha256[a-z0-9]+\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
scripts/config.py unset MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT
# test the deprecated form of the config option
scripts/config.py set MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT
msg "MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT clang, arm"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72+crypto -marm -std=c99"
msg "MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT clang, thumb"
make -B library/../${BUILTIN_SRC_PATH}/sha256.o library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32+crypto -mthumb"
msg "MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT clang, test T32 crypto instructions built"
grep -E 'sha256[a-z0-9]+.32\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
scripts/config.py unset MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT
# examine the disassembly for absence of SHA instructions
msg "clang, test A32 crypto instructions not built"
make -B library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a72 -marm"
not grep -E 'sha256[a-z0-9]+.32\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
msg "clang, test T32 crypto instructions not built"
make -B library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=arm-linux-gnueabihf -mcpu=cortex-a32 -mthumb"
not grep -E 'sha256[a-z0-9]+.32\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
msg "clang, test aarch64 crypto instructions not built"
make -B library/../${BUILTIN_SRC_PATH}/sha256.s CC=clang CFLAGS="--target=aarch64-linux-gnu -march=armv8-a"
not grep -E 'sha256[a-z0-9]+\s+[qv]' ${BUILTIN_SRC_PATH}/sha256.s
}
component_test_arm_linux_gnueabi_gcc_arm5vte () {
# Mimic Debian armel port
msg "test: ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc -march=arm5vte, default config" # ~4m
make CC="${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc" AR="${ARM_LINUX_GNUEABI_GCC_PREFIX}ar" CFLAGS='-Werror -Wall -Wextra -march=armv5te -O1'
msg "test: main suites make, default config (out-of-box)" # ~7m 40s
make test
msg "selftest: make, default config (out-of-box)" # ~0s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_arm5vte () {
can_run_arm_linux_gnueabi
}
# The hard float ABI is not implemented for Thumb 1, so use gnueabi
# Some Thumb 1 asm is sensitive to optimisation level, so test both -O0 and -Os
component_test_arm_linux_gnueabi_gcc_thumb_1_opt_0 () {
msg "test: ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc -O0, thumb 1, default config" # ~2m 10s
make CC="${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc" CFLAGS='-std=c99 -Werror -Wextra -O0 -mcpu=arm1136j-s -mthumb'
msg "test: main suites make, default config (out-of-box)" # ~36m
make test
msg "selftest: make, default config (out-of-box)" # ~10s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_thumb_1_opt_0 () {
can_run_arm_linux_gnueabi
}
component_test_arm_linux_gnueabi_gcc_thumb_1_opt_s () {
msg "test: ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc -Os, thumb 1, default config" # ~3m 10s
make CC="${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc" CFLAGS='-std=c99 -Werror -Wextra -Os -mcpu=arm1136j-s -mthumb'
msg "test: main suites make, default config (out-of-box)" # ~21m 10s
make test
msg "selftest: make, default config (out-of-box)" # ~2s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabi_gcc_thumb_1_opt_s () {
can_run_arm_linux_gnueabi
}
component_test_arm_linux_gnueabihf_gcc_armv7 () {
msg "test: ${ARM_LINUX_GNUEABIHF_GCC_PREFIX}gcc -O2, A32, default config" # ~4m 30s
make CC="${ARM_LINUX_GNUEABIHF_GCC_PREFIX}gcc" CFLAGS='-std=c99 -Werror -Wextra -O2 -march=armv7-a -marm'
msg "test: main suites make, default config (out-of-box)" # ~3m 30s
make test
msg "selftest: make, default config (out-of-box)" # ~0s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabihf_gcc_armv7 () {
can_run_arm_linux_gnueabihf
}
component_test_arm_linux_gnueabihf_gcc_thumb_2 () {
msg "test: ${ARM_LINUX_GNUEABIHF_GCC_PREFIX}gcc -Os, thumb 2, default config" # ~4m
make CC="${ARM_LINUX_GNUEABIHF_GCC_PREFIX}gcc" CFLAGS='-std=c99 -Werror -Wextra -Os -march=armv7-a -mthumb'
msg "test: main suites make, default config (out-of-box)" # ~3m 40s
make test
msg "selftest: make, default config (out-of-box)" # ~0s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_arm_linux_gnueabihf_gcc_thumb_2 () {
can_run_arm_linux_gnueabihf
}
component_test_aarch64_linux_gnu_gcc () {
msg "test: ${AARCH64_LINUX_GNU_GCC_PREFIX}gcc -O2, default config" # ~3m 50s
make CC="${AARCH64_LINUX_GNU_GCC_PREFIX}gcc" CFLAGS='-std=c99 -Werror -Wextra -O2'
msg "test: main suites make, default config (out-of-box)" # ~1m 50s
make test
msg "selftest: make, default config (out-of-box)" # ~0s
programs/test/selftest
msg "program demos: make, default config (out-of-box)" # ~0s
tests/scripts/run_demos.py
}
support_test_aarch64_linux_gnu_gcc () {
# Minimum version of GCC for MBEDTLS_AESCE_C is 6.0
[ "$(gcc_version "${AARCH64_LINUX_GNU_GCC_PREFIX}gcc")" -ge 6 ] && can_run_aarch64_linux_gnu
}
component_build_arm_none_eabi_gcc () {
msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -O1, baremetal+debug" # ~ 10s
scripts/config.py baremetal
make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra -O1' lib
msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -O1, baremetal+debug"
${ARM_NONE_EABI_GCC_PREFIX}size -t library/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${PSA_CORE_PATH}/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${BUILTIN_SRC_PATH}/*.o
}
component_build_arm_linux_gnueabi_gcc_arm5vte () {
msg "build: ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc -march=arm5vte, baremetal+debug" # ~ 10s
scripts/config.py baremetal
# Build for a target platform that's close to what Debian uses
# for its "armel" distribution (https://wiki.debian.org/ArmEabiPort).
# See https://github.com/Mbed-TLS/mbedtls/pull/2169 and comments.
# Build everything including programs, see for example
# https://github.com/Mbed-TLS/mbedtls/pull/3449#issuecomment-675313720
make CC="${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc" AR="${ARM_LINUX_GNUEABI_GCC_PREFIX}ar" CFLAGS='-Werror -Wall -Wextra -march=armv5te -O1' LDFLAGS='-march=armv5te'
msg "size: ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc -march=armv5te -O1, baremetal+debug"
${ARM_LINUX_GNUEABI_GCC_PREFIX}size -t library/*.o
${ARM_LINUX_GNUEABI_GCC_PREFIX}size -t ${PSA_CORE_PATH}/*.o
${ARM_LINUX_GNUEABI_GCC_PREFIX}size -t ${BUILTIN_SRC_PATH}/*.o
}
support_build_arm_linux_gnueabi_gcc_arm5vte () {
type ${ARM_LINUX_GNUEABI_GCC_PREFIX}gcc >/dev/null 2>&1
}
component_build_arm_none_eabi_gcc_arm5vte () {
msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -march=arm5vte, baremetal+debug" # ~ 10s
scripts/config.py baremetal
# This is an imperfect substitute for
# component_build_arm_linux_gnueabi_gcc_arm5vte
# in case the gcc-arm-linux-gnueabi toolchain is not available
make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" CFLAGS='-std=c99 -Werror -Wall -Wextra -march=armv5te -O1' LDFLAGS='-march=armv5te' SHELL='sh -x' lib
msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -march=armv5te -O1, baremetal+debug"
${ARM_NONE_EABI_GCC_PREFIX}size -t library/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${PSA_CORE_PATH}/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${BUILTIN_SRC_PATH}/*.o
}
component_build_arm_none_eabi_gcc_m0plus () {
msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -mthumb -mcpu=cortex-m0plus, baremetal_size" # ~ 10s
scripts/config.py baremetal_size
make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra -mthumb -mcpu=cortex-m0plus -Os' lib
msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -mthumb -mcpu=cortex-m0plus -Os, baremetal_size"
${ARM_NONE_EABI_GCC_PREFIX}size -t library/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${PSA_CORE_PATH}/*.o
${ARM_NONE_EABI_GCC_PREFIX}size -t ${BUILTIN_SRC_PATH}/*.o
for lib in library/*.a; do
echo "$lib:"
${ARM_NONE_EABI_GCC_PREFIX}size -t $lib | grep TOTALS
done
}
component_build_arm_none_eabi_gcc_no_udbl_division () {
msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -DMBEDTLS_NO_UDBL_DIVISION, make" # ~ 10s
scripts/config.py baremetal
scripts/config.py set MBEDTLS_NO_UDBL_DIVISION
make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra' lib
echo "Checking that software 64-bit division is not required"
not grep __aeabi_uldiv library/*.o
not grep __aeabi_uldiv ${PSA_CORE_PATH}/*.o
not grep __aeabi_uldiv ${BUILTIN_SRC_PATH}/*.o
}
component_build_arm_none_eabi_gcc_no_64bit_multiplication () {
msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc MBEDTLS_NO_64BIT_MULTIPLICATION, make" # ~ 10s
scripts/config.py baremetal
scripts/config.py set MBEDTLS_NO_64BIT_MULTIPLICATION
make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -O1 -march=armv6-m -mthumb' lib
echo "Checking that software 64-bit multiplication is not required"
not grep __aeabi_lmul library/*.o
not grep __aeabi_lmul ${PSA_CORE_PATH}/*.o
not grep __aeabi_lmul ${BUILTIN_SRC_PATH}/*.o
}
component_build_arm_clang_thumb () {
# ~ 30s
scripts/config.py baremetal
msg "build: clang thumb 2, make"
make clean
make CC="clang" CFLAGS='-std=c99 -Werror -Os --target=arm-linux-gnueabihf -march=armv7-m -mthumb' lib
# Some Thumb 1 asm is sensitive to optimisation level, so test both -O0 and -Os
msg "build: clang thumb 1 -O0, make"
make clean
make CC="clang" CFLAGS='-std=c99 -Werror -O0 --target=arm-linux-gnueabihf -mcpu=arm1136j-s -mthumb' lib
msg "build: clang thumb 1 -Os, make"
make clean
make CC="clang" CFLAGS='-std=c99 -Werror -Os --target=arm-linux-gnueabihf -mcpu=arm1136j-s -mthumb' lib
}
component_build_armcc () {
# Common configuration for all the builds below
scripts/config.py baremetal
# armc[56] don't support SHA-512 intrinsics
scripts/config.py unset MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
# older versions of armcc/armclang don't support AESCE_C on 32-bit Arm
scripts/config.py unset MBEDTLS_AESCE_C
# Stop armclang warning about feature detection for A64_CRYPTO.
# With this enabled, the library does build correctly under armclang,
# but in baremetal builds (as tested here), feature detection is
# unavailable, and the user is notified via a #warning. So enabling
# this feature would prevent us from building with -Werror on
# armclang. Tracked in #7198.
scripts/config.py unset MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT
scripts/config.py set MBEDTLS_HAVE_ASM
# Compile mostly with -O1 since some Arm inline assembly is disabled for -O0.
# ARM Compiler 6 - Target ARMv7-A
helper_armc6_build_test "-O1 --target=arm-arm-none-eabi -march=armv7-a"
# ARM Compiler 6 - Target ARMv7-M
helper_armc6_build_test "-O1 --target=arm-arm-none-eabi -march=armv7-m"
# ARM Compiler 6 - Target ARMv7-M+DSP
helper_armc6_build_test "-O1 --target=arm-arm-none-eabi -march=armv7-m+dsp"
# ARM Compiler 6 - Target ARMv8-A - AArch32
helper_armc6_build_test "-O1 --target=arm-arm-none-eabi -march=armv8.2-a"
# ARM Compiler 6 - Target ARMv8-M
helper_armc6_build_test "-O1 --target=arm-arm-none-eabi -march=armv8-m.main"
# ARM Compiler 6 - Target Cortex-M0 - no optimisation
helper_armc6_build_test "-O0 --target=arm-arm-none-eabi -mcpu=cortex-m0"
# ARM Compiler 6 - Target Cortex-M0
helper_armc6_build_test "-Os --target=arm-arm-none-eabi -mcpu=cortex-m0"
# ARM Compiler 6 - Target ARMv8.2-A - AArch64
#
# Re-enable MBEDTLS_AESCE_C as this should be supported by the version of armclang
# that we have in our CI
scripts/config.py set MBEDTLS_AESCE_C
helper_armc6_build_test "-O1 --target=aarch64-arm-none-eabi -march=armv8.2-a+crypto"
}
support_build_armcc () {
armc6_cc="$ARMC6_BIN_DIR/armclang"
(check_tools "$armc6_cc" > /dev/null 2>&1)
}
-99
View File
@@ -1,99 +0,0 @@
# components-psasim.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Remote Procedure Call PSA Testing
################################################################
# Helper function for controlling (start & stop) the psasim server.
helper_psasim_server() {
OPERATION=$1
if [ "$OPERATION" == "start" ]; then
msg "start server in tests"
(
cd tests
../$PSASIM_PATH/test/start_server.sh
)
msg "start server in tf-psa-crypto/tests"
(
cd tf-psa-crypto/tests
../../$PSASIM_PATH/test/start_server.sh
)
else
msg "terminate server in tests"
(
# This will kill both servers and clean up all the message queues,
# and clear temporary files in tests
cd tests
../$PSASIM_PATH/test/kill_servers.sh
)
msg "terminate server in tf-psa-crypto/tests"
(
# This just clears temporary files in tf-psa-crypto/tests
cd tf-psa-crypto/tests
../../$PSASIM_PATH/test/kill_servers.sh
)
fi
}
component_test_psasim() {
msg "build server library and application"
scripts/config.py crypto
helper_psasim_config server
helper_psasim_build server
helper_psasim_cleanup_before_client
msg "build library for client"
helper_psasim_config client
helper_psasim_build client
msg "build basic psasim client"
make -C $PSASIM_PATH CFLAGS="$ASAN_CFLAGS" LDFLAGS="$ASAN_CFLAGS" test/psa_client_base
msg "test basic psasim client"
$PSASIM_PATH/test/run_test.sh psa_client_base
msg "build full psasim client"
make -C $PSASIM_PATH CFLAGS="$ASAN_CFLAGS" LDFLAGS="$ASAN_CFLAGS" test/psa_client_full
msg "test full psasim client"
$PSASIM_PATH/test/run_test.sh psa_client_full
helper_psasim_server kill
make -C $PSASIM_PATH clean
}
component_test_suite_with_psasim()
{
msg "build server library and application"
helper_psasim_config server
# Modify server's library configuration here (if needed)
helper_psasim_build server
helper_psasim_cleanup_before_client
msg "build client library"
helper_psasim_config client
# PAKE functions are still unsupported from PSASIM
scripts/config.py -f $CRYPTO_CONFIG_H unset PSA_WANT_ALG_JPAKE
scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
helper_psasim_build client
msg "build test suites"
make PSASIM=1 CFLAGS="$ASAN_CFLAGS" LDFLAGS="$ASAN_CFLAGS" tests
helper_psasim_server start
# psasim takes an extremely long execution time on some test suites so we
# exclude them from the list.
SKIP_TEST_SUITES="constant_time_hmac,lmots,lms"
export SKIP_TEST_SUITES
msg "run test suites"
make PSASIM=1 test
helper_psasim_server kill
}
-190
View File
@@ -1,190 +0,0 @@
# components-sanitizers.sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file contains test components that are executed by all.sh
################################################################
#### Sanitizer Testing
################################################################
skip_suites_without_constant_flow () {
# Skip the test suites that don't have any constant-flow annotations.
# This will need to be adjusted if we ever start declaring things as
# secret from macros or functions inside tests/include or tests/src.
SKIP_TEST_SUITES=$(
git -C tests/suites grep -L TEST_CF_ 'test_suite_*.function' |
sed 's/test_suite_//; s/\.function$//' |
tr '\n' ,),$(
git -C tf-psa-crypto/tests/suites grep -L TEST_CF_ 'test_suite_*.function' |
sed 's/test_suite_//; s/\.function$//' |
tr '\n' ,)
export SKIP_TEST_SUITES
}
skip_all_except_given_suite () {
# Skip all but the given test suite
SKIP_TEST_SUITES=$(
ls -1 tests/suites/test_suite_*.function |
grep -v $1.function |
sed 's/tests.suites.test_suite_//; s/\.function$//' |
tr '\n' ,),$(
ls -1 tf-psa-crypto/tests/suites/test_suite_*.function |
grep -v $1.function |
sed 's/tf-psa-crypto.tests.suites.test_suite_//; s/\.function$//' |
tr '\n' ,)
export SKIP_TEST_SUITES
}
component_test_memsan_constant_flow_psa () {
# This tests both (1) accesses to undefined memory, and (2) branches or
# memory access depending on secret values. To distinguish between those:
# - unset MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN - does the failure persist?
# - or alternatively, change the build type to MemSanDbg, which enables
# origin tracking and nicer stack traces (which are useful for debugging
# anyway), and check if the origin was TEST_CF_SECRET() or something else.
msg "build: cmake MSan (clang), full config with constant flow testing"
scripts/config.py full
scripts/config.py set MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN
scripts/config.py unset MBEDTLS_AESNI_C # memsan doesn't grok asm
scripts/config.py unset MBEDTLS_HAVE_ASM
CC=clang cmake -D CMAKE_BUILD_TYPE:String=MemSan .
make
msg "test: main suites (Msan + constant flow)"
make test
}
component_release_test_valgrind_constant_flow_no_asm () {
# This tests both (1) everything that valgrind's memcheck usually checks
# (heap buffer overflows, use of uninitialized memory, use-after-free,
# etc.) and (2) branches or memory access depending on secret values,
# which will be reported as uninitialized memory. To distinguish between
# secret and actually uninitialized:
# - unset MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND - does the failure persist?
# - or alternatively, build with debug info and manually run the offending
# test suite with valgrind --track-origins=yes, then check if the origin
# was TEST_CF_SECRET() or something else.
msg "build: cmake release GCC, full config minus MBEDTLS_USE_PSA_CRYPTO, minus MBEDTLS_HAVE_ASM with constant flow testing"
scripts/config.py full
scripts/config.py set MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND
scripts/config.py unset MBEDTLS_AESNI_C
scripts/config.py unset MBEDTLS_HAVE_ASM
skip_suites_without_constant_flow
cmake -D CMAKE_BUILD_TYPE:String=Release .
make
# this only shows a summary of the results (how many of each type)
# details are left in Testing/<date>/DynamicAnalysis.xml
msg "test: some suites (full minus MBEDTLS_USE_PSA_CRYPTO, minus MBEDTLS_HAVE_ASM, valgrind + constant flow)"
make memcheck
}
component_release_test_valgrind_constant_flow_psa () {
# This tests both (1) everything that valgrind's memcheck usually checks
# (heap buffer overflows, use of uninitialized memory, use-after-free,
# etc.) and (2) branches or memory access depending on secret values,
# which will be reported as uninitialized memory. To distinguish between
# secret and actually uninitialized:
# - unset MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND - does the failure persist?
# - or alternatively, build with debug info and manually run the offending
# test suite with valgrind --track-origins=yes, then check if the origin
# was TEST_CF_SECRET() or something else.
msg "build: cmake release GCC, full config with constant flow testing"
scripts/config.py full
scripts/config.py set MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND
skip_suites_without_constant_flow
cmake -D CMAKE_BUILD_TYPE:String=Release .
make
# this only shows a summary of the results (how many of each type)
# details are left in Testing/<date>/DynamicAnalysis.xml
msg "test: some suites (valgrind + constant flow)"
make memcheck
}
component_test_tsan () {
msg "build: TSan (clang)"
scripts/config.py full
scripts/config.py set MBEDTLS_THREADING_C
scripts/config.py set MBEDTLS_THREADING_PTHREAD
# Self-tests do not currently use multiple threads.
scripts/config.py unset MBEDTLS_SELF_TEST
# The deprecated MBEDTLS_PSA_CRYPTO_SE_C interface is not thread safe.
scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C
CC=clang cmake -D CMAKE_BUILD_TYPE:String=TSan .
make
msg "test: main suites (TSan)"
make test
}
component_test_memsan () {
msg "build: MSan (clang)" # ~ 1 min 20s
scripts/config.py unset MBEDTLS_AESNI_C # memsan doesn't grok asm
scripts/config.py unset MBEDTLS_HAVE_ASM
CC=clang cmake -D CMAKE_BUILD_TYPE:String=MemSan .
make
msg "test: main suites (MSan)" # ~ 10s
make test
msg "test: metatests (MSan)"
tests/scripts/run-metatests.sh any msan
msg "program demos (MSan)" # ~20s
tests/scripts/run_demos.py
msg "test: ssl-opt.sh (MSan)" # ~ 1 min
tests/ssl-opt.sh
# Optional part(s)
if [ "$MEMORY" -gt 0 ]; then
msg "test: compat.sh (MSan)" # ~ 6 min 20s
tests/compat.sh
fi
}
component_release_test_valgrind () {
msg "build: Release (clang)"
# default config, in particular without MBEDTLS_USE_PSA_CRYPTO
CC=clang cmake -D CMAKE_BUILD_TYPE:String=Release .
make
msg "test: main suites, Valgrind (default config)"
make memcheck
# Optional parts (slow; currently broken on OS X because programs don't
# seem to receive signals under valgrind on OS X).
# These optional parts don't run on the CI.
if [ "$MEMORY" -gt 0 ]; then
msg "test: ssl-opt.sh --memcheck (default config)"
tests/ssl-opt.sh --memcheck
fi
if [ "$MEMORY" -gt 1 ]; then
msg "test: compat.sh --memcheck (default config)"
tests/compat.sh --memcheck
fi
if [ "$MEMORY" -gt 0 ]; then
msg "test: context-info.sh --memcheck (default config)"
tests/context-info.sh --memcheck
fi
}
component_release_test_valgrind_psa () {
msg "build: Release, full (clang)"
# full config, in particular with MBEDTLS_USE_PSA_CRYPTO
scripts/config.py full
CC=clang cmake -D CMAKE_BUILD_TYPE:String=Release .
make
msg "test: main suites, Valgrind (full config)"
make memcheck
}
-662
View File
@@ -1,662 +0,0 @@
#!/usr/bin/env python3
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""
Test Mbed TLS with a subset of algorithms.
This script can be divided into several steps:
First, include/mbedtls/mbedtls_config.h or a different config file passed
in the arguments is parsed to extract any configuration options (using config.py).
Then, test domains (groups of jobs, tests) are built based on predefined data
collected in the DomainData class. Here, each domain has five major traits:
- domain name, can be used to run only specific tests via command-line;
- configuration building method, described in detail below;
- list of symbols passed to the configuration building method;
- commands to be run on each job (only build, build and test, or any other custom);
- optional list of symbols to be excluded from testing.
The configuration building method can be one of the three following:
- ComplementaryDomain - build a job for each passed symbol by disabling a single
symbol and its reverse dependencies (defined in REVERSE_DEPENDENCIES);
- ExclusiveDomain - build a job where, for each passed symbol, only this particular
one is defined and other symbols from the list are unset. For each job look for
any non-standard symbols to set/unset in EXCLUSIVE_GROUPS. These are usually not
direct dependencies, but rather non-trivial results of other configs missing. Then
look for any unset symbols and handle their reverse dependencies.
Examples of EXCLUSIVE_GROUPS usage:
- MBEDTLS_SHA512_C job turns off all hashes except SHA512. MBEDTLS_SSL_COOKIE_C
requires either SHA256 or SHA384 to work, so it also has to be disabled.
This is not a dependency on SHA512_C, but a result of an exclusive domain
config building method. Relevant field:
'MBEDTLS_SHA512_C': ['-MBEDTLS_SSL_COOKIE_C'],
- DualDomain - combination of the two above - both complementary and exclusive domain
job generation code will be run. Currently only used for hashes.
Lastly, the collected jobs are executed and (optionally) tested, with
error reporting and coloring as configured in options. Each test starts with
a full config without a couple of slowing down or unnecessary options
(see set_reference_config), then the specific job config is derived.
"""
import argparse
import os
import re
import subprocess
import sys
import traceback
from typing import Union
# Add the Mbed TLS Python library directory to the module search path
import scripts_path # pylint: disable=unused-import
import config
from mbedtls_framework import c_build_helper
from mbedtls_framework import crypto_knowledge
from mbedtls_framework import psa_information
class Colors: # pylint: disable=too-few-public-methods
"""Minimalistic support for colored output.
Each field of an object of this class is either None if colored output
is not possible or not desired, or a pair of strings (start, stop) such
that outputting start switches the text color to the desired color and
stop switches the text color back to the default."""
red = None
green = None
cyan = None
bold_red = None
bold_green = None
def __init__(self, options=None):
"""Initialize color profile according to passed options."""
if not options or options.color in ['no', 'never']:
want_color = False
elif options.color in ['yes', 'always']:
want_color = True
else:
want_color = sys.stderr.isatty()
if want_color:
# Assume ANSI compatible terminal
normal = '\033[0m'
self.red = ('\033[31m', normal)
self.green = ('\033[32m', normal)
self.cyan = ('\033[36m', normal)
self.bold_red = ('\033[1;31m', normal)
self.bold_green = ('\033[1;32m', normal)
NO_COLORS = Colors(None)
def log_line(text, prefix='depends.py:', suffix='', color=None):
"""Print a status message."""
if color is not None:
prefix = color[0] + prefix
suffix = suffix + color[1]
sys.stderr.write(prefix + ' ' + text + suffix + '\n')
sys.stderr.flush()
def log_command(cmd):
"""Print a trace of the specified command.
cmd is a list of strings: a command name and its arguments."""
log_line(' '.join(cmd), prefix='+')
def option_exists(conf, option):
return option in conf.settings
def set_config_option_value(conf, option, colors, value: Union[bool, str]):
"""Set/unset a configuration option, optionally specifying a value.
value can be either True/False (set/unset config option), or a string,
which will make a symbol defined with a certain value."""
if not option_exists(conf, option):
log_line('Symbol {} was not found in {}'.format(option, conf.filename), color=colors.red)
return False
if value is False:
log_command(['config.py', 'unset', option])
conf.unset(option)
elif value is True:
log_command(['config.py', 'set', option])
conf.set(option)
else:
log_command(['config.py', 'set', option, value])
conf.set(option, value)
return True
def set_reference_config(conf, colors):
"""Change the library configuration file (mbedtls_config.h) to the reference state.
The reference state is the one from which the tested configurations are
derived."""
# Turn off options that are not relevant to the tests and slow them down.
log_command(['config.py', 'full'])
conf.adapt(config.full_adapter)
set_config_option_value(conf, 'MBEDTLS_TEST_HOOKS', colors, False)
class Job:
"""A job builds the library in a specific configuration and runs some tests."""
def __init__(self, name, config_settings, commands):
"""Build a job object.
The job uses the configuration described by config_settings. This is a
dictionary where the keys are preprocessor symbols and the values are
booleans or strings. A boolean indicates whether or not to #define the
symbol. With a string, the symbol is #define'd to that value.
After setting the configuration, the job runs the programs specified by
commands. This is a list of lists of strings; each list of string is a
command name and its arguments and is passed to subprocess.call with
shell=False."""
self.name = name
self.config_settings = config_settings
self.commands = commands
def announce(self, colors, what):
'''Announce the start or completion of a job.
If what is None, announce the start of the job.
If what is True, announce that the job has passed.
If what is False, announce that the job has failed.'''
if what is True:
log_line(self.name + ' PASSED', color=colors.green)
elif what is False:
log_line(self.name + ' FAILED', color=colors.red)
else:
log_line('starting ' + self.name, color=colors.cyan)
def configure(self, conf, colors):
'''Set library configuration options as required for the job.'''
set_reference_config(conf, colors)
for key, value in sorted(self.config_settings.items()):
ret = set_config_option_value(conf, key, colors, value)
if ret is False:
return False
return True
def _consistency_check(self):
'''Check if the testable option is consistent with the goal.
The purpose of this function to ensure that every option is set or unset according to
the settings.
'''
log_command(['consistency check'])
c_name = None
exe_name = None
header = '#include "mbedtls/build_info.h"\n'
# Generate a C error directive for each setting to test if it is active
for option, value in sorted(self.config_settings.items()):
header += '#if '
if value:
header += '!'
header += f'defined({option})\n'
header += f'#error "{option}"\n'
header += '#endif\n'
include_path = ['include', 'tf-psa-crypto/include',
'tf-psa-crypto/drivers/builtin/include']
try:
# Generate a C file, build and run it
c_file, c_name, exe_name = c_build_helper.create_c_file(self.name)
c_build_helper.generate_c_file(c_file, 'depends.py', header, lambda x: '')
c_file.close()
c_build_helper.compile_c_file(c_name, exe_name, include_path)
return True
except c_build_helper.CompileError as e:
# Read the command line output to find out which setting has been failed
failed = {m.group(1) for m in re.finditer('.*#error "(.*)"', e.message) if m}
log_line('Inconsistent config option(s):')
for option in sorted(failed):
log_line(' ' + option)
return False
finally:
c_build_helper.remove_file_if_exists(c_name)
c_build_helper.remove_file_if_exists(exe_name)
def test(self, options):
'''Run the job's build and test commands.
Return True if all the commands succeed and False otherwise.
If options.keep_going is false, stop as soon as one command fails. Otherwise
run all the commands, except that if the first command fails, none of the
other commands are run (typically, the first command is a build command
and subsequent commands are tests that cannot run if the build failed).'''
if not self._consistency_check():
return False
built = False
success = True
for command in self.commands:
log_command(command)
env = os.environ.copy()
if 'MBEDTLS_TEST_CONFIGURATION' in env:
env['MBEDTLS_TEST_CONFIGURATION'] += '-' + self.name
ret = subprocess.call(command, env=env)
if ret != 0:
if command[0] not in ['make', options.make_command]:
log_line('*** [{}] Error {}'.format(' '.join(command), ret))
if not options.keep_going or not built:
return False
success = False
built = True
return success
# If the configuration option A requires B, make sure that
# B in REVERSE_DEPENDENCIES[A].
# All the information here should be contained in check_config.h or check_crypto_config.h.
# This file includes a copy because it changes rarely and it would be a pain
# to extract automatically.
REVERSE_DEPENDENCIES = {
'PSA_WANT_KEY_TYPE_AES': ['PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128',
'MBEDTLS_CTR_DRBG_C',
'MBEDTLS_NIST_KW_C',
'MBEDTLS_AES_C'],
'PSA_WANT_KEY_TYPE_ARIA': ['MBEDTLS_ARIA_C'],
'PSA_WANT_KEY_TYPE_CAMELLIA': ['MBEDTLS_CAMELLIA_C'],
'PSA_WANT_KEY_TYPE_CHACHA20': ['PSA_WANT_ALG_CHACHA20_POLY1305',
'PSA_WANT_ALG_STREAM_CIPHER',
'MBEDTLS_CHACHA20_C',
'MBEDTLS_CHACHAPOLY_C'],
'PSA_WANT_KEY_TYPE_DES': ['MBEDTLS_DES_C'],
'PSA_WANT_ALG_CCM': ['PSA_WANT_ALG_CCM_STAR_NO_TAG',
'MBEDTLS_CCM_C'],
'PSA_WANT_ALG_CMAC': ['PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128',
'MBEDTLS_CMAC_C'],
'PSA_WANT_ALG_GCM': ['MBEDTLS_GCM_C'],
'MBEDTLS_CIPHER_MODE_CBC': ['PSA_WANT_ALG_CBC_PKCS7',
'PSA_WANT_ALG_CBC_NO_PADDING'],
'MBEDTLS_CIPHER_MODE_CFB': ['PSA_WANT_ALG_CFB'],
'MBEDTLS_CIPHER_MODE_CTR': ['PSA_WANT_ALG_CTR'],
'MBEDTLS_CIPHER_MODE_OFB': ['PSA_WANT_ALG_OFB'],
'MBEDTLS_CIPHER_PADDING_PKCS7': ['MBEDTLS_PKCS5_C',
'MBEDTLS_PKCS12_C',
'PSA_WANT_ALG_CBC_PKCS7'],
'MBEDTLS_ECP_DP_BP256R1_ENABLED': ['PSA_WANT_ECC_BRAINPOOL_P_R1_256'],
'MBEDTLS_ECP_DP_BP384R1_ENABLED': ['PSA_WANT_ECC_BRAINPOOL_P_R1_384'],
'MBEDTLS_ECP_DP_BP512R1_ENABLED': ['PSA_WANT_ECC_BRAINPOOL_P_R1_512'],
'MBEDTLS_ECP_DP_CURVE25519_ENABLED': ['PSA_WANT_ECC_MONTGOMERY_255'],
'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['PSA_WANT_ECC_MONTGOMERY_448'],
'MBEDTLS_ECP_DP_SECP192R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_192'],
'MBEDTLS_ECP_DP_SECP224R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_224'],
'MBEDTLS_ECP_DP_SECP256R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_256',
'PSA_WANT_ALG_JPAKE',
'MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
'MBEDTLS_ECP_DP_SECP384R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_384'],
'MBEDTLS_ECP_DP_SECP512R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_512'],
'MBEDTLS_ECP_DP_SECP521R1_ENABLED': ['PSA_WANT_ECC_SECP_R1_521'],
'MBEDTLS_ECP_DP_SECP192K1_ENABLED': ['PSA_WANT_ECC_SECP_K1_192'],
'MBEDTLS_ECP_DP_SECP256K1_ENABLED': ['PSA_WANT_ECC_SECP_K1_256'],
'MBEDTLS_ECDSA_C': ['MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
'PSA_WANT_ALG_ECDSA',
'PSA_WANT_ALG_DETERMINISTIC_ECDSA'],
'MBEDTLS_ECP_C': ['MBEDTLS_ECDSA_C',
'MBEDTLS_ECDH_C', 'PSA_WANT_ALG_ECDH',
'MBEDTLS_ECJPAKE_C',
'MBEDTLS_ECP_RESTARTABLE',
'MBEDTLS_PK_PARSE_EC_EXTENDED',
'MBEDTLS_PK_PARSE_EC_COMPRESSED',
'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED',
'MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED',
'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
'MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED',
'MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED',
'PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY',
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC',
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT',
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT',
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE',
'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE'],
'MBEDTLS_ECJPAKE_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
'PSA_WANT_ALG_JPAKE'],
'MBEDTLS_PKCS1_V21': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT',
'PSA_WANT_ALG_RSA_OAEP',
'PSA_WANT_ALG_RSA_PSS'],
'MBEDTLS_PKCS1_V15': ['MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED',
'PSA_WANT_ALG_RSA_PKCS1V15_CRYPT',
'PSA_WANT_ALG_RSA_PKCS1V15_SIGN'],
'MBEDTLS_RSA_C': ['MBEDTLS_PKCS1_V15',
'MBEDTLS_PKCS1_V21',
'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED',
'PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY',
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC',
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT',
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT',
'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE'],
'MBEDTLS_MD5_C' : ['PSA_WANT_ALG_MD5'],
'MBEDTLS_RIPEMD160_C' : ['PSA_WANT_ALG_RIPEMD160'],
'MBEDTLS_SHA1_C' : ['PSA_WANT_ALG_SHA_1'],
'MBEDTLS_SHA224_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
'MBEDTLS_ENTROPY_FORCE_SHA256',
'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT',
'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY',
'PSA_WANT_ALG_SHA_224'],
'MBEDTLS_SHA256_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
'MBEDTLS_ENTROPY_FORCE_SHA256',
'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT',
'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY',
'MBEDTLS_LMS_C',
'MBEDTLS_LMS_PRIVATE',
'PSA_WANT_ALG_SHA_256',
'PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS'],
'MBEDTLS_SHA384_C' : ['PSA_WANT_ALG_SHA_384'],
'MBEDTLS_SHA512_C': ['MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT',
'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY',
'PSA_WANT_ALG_SHA_512'],
'MBEDTLS_SHA3_C' : ['PSA_WANT_ALG_SHA3_224',
'PSA_WANT_ALG_SHA3_256',
'PSA_WANT_ALG_SHA3_384',
'PSA_WANT_ALG_SHA3_512'],
}
# If an option is tested in an exclusive test, alter the following defines.
# These are not necessarily dependencies, but just minimal required changes
# if a given define is the only one enabled from an exclusive group.
EXCLUSIVE_GROUPS = {
'MBEDTLS_SHA512_C': ['-MBEDTLS_SSL_COOKIE_C',
'-MBEDTLS_SSL_TLS_C'],
'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['-MBEDTLS_ECDSA_C',
'-MBEDTLS_ECDSA_DETERMINISTIC',
'-MBEDTLS_ECJPAKE_C',],
'MBEDTLS_ECP_DP_CURVE25519_ENABLED': ['-MBEDTLS_ECDSA_C',
'-MBEDTLS_ECDSA_DETERMINISTIC',
'-MBEDTLS_ECJPAKE_C'],
'PSA_WANT_KEY_TYPE_ARIA': ['-PSA_WANT_ALG_CMAC',
'-PSA_WANT_ALG_CCM',
'-PSA_WANT_ALG_GCM',
'-MBEDTLS_SSL_TICKET_C',
'-MBEDTLS_SSL_CONTEXT_SERIALIZATION'],
'PSA_WANT_KEY_TYPE_CAMELLIA': ['-PSA_WANT_ALG_CMAC'],
'PSA_WANT_KEY_TYPE_CHACHA20': ['-PSA_WANT_ALG_CMAC',
'-PSA_WANT_ALG_CCM',
'-PSA_WANT_ALG_GCM',
'-PSA_WANT_ALG_ECB_NO_PADDING'],
'PSA_WANT_KEY_TYPE_DES': ['-PSA_WANT_ALG_CCM',
'-PSA_WANT_ALG_GCM',
'-MBEDTLS_SSL_TICKET_C',
'-MBEDTLS_SSL_CONTEXT_SERIALIZATION'],
}
def handle_exclusive_groups(config_settings, symbol):
"""For every symbol tested in an exclusive group check if there are other
defines to be altered. """
for dep in EXCLUSIVE_GROUPS.get(symbol, []):
unset = dep.startswith('-')
dep = dep[1:]
config_settings[dep] = not unset
def turn_off_dependencies(config_settings):
"""For every option turned off config_settings, also turn off what depends on it.
An option O is turned off if config_settings[O] is False.
Handle the dependencies recursively.
"""
for key, value in sorted(config_settings.items()):
if value is not False:
continue
# Save the processed settings to handle cross referencies
revdep = set(REVERSE_DEPENDENCIES.get(key, []))
history = set()
while revdep:
dep = revdep.pop()
history.add(dep)
config_settings[dep] = False
# Do not add symbols which are already processed
revdep.update(set(REVERSE_DEPENDENCIES.get(dep, [])) - history)
class BaseDomain: # pylint: disable=too-few-public-methods, unused-argument
"""A base class for all domains."""
def __init__(self, symbols, commands, exclude):
"""Initialize the jobs container"""
self.jobs = []
class ExclusiveDomain(BaseDomain): # pylint: disable=too-few-public-methods
"""A domain consisting of a set of conceptually-equivalent settings.
Establish a list of configuration symbols. For each symbol, run a test job
with this symbol set and the others unset."""
def __init__(self, symbols, commands, exclude=None):
"""Build a domain for the specified list of configuration symbols.
The domain contains a set of jobs that enable one of the elements
of symbols and disable the others.
Each job runs the specified commands.
If exclude is a regular expression, skip generated jobs whose description
would match this regular expression."""
super().__init__(symbols, commands, exclude)
base_config_settings = {}
for symbol in symbols:
base_config_settings[symbol] = False
for symbol in symbols:
description = symbol
if exclude and re.match(exclude, description):
continue
config_settings = base_config_settings.copy()
config_settings[symbol] = True
handle_exclusive_groups(config_settings, symbol)
turn_off_dependencies(config_settings)
job = Job(description, config_settings, commands)
self.jobs.append(job)
class ComplementaryDomain(BaseDomain): # pylint: disable=too-few-public-methods
"""A domain consisting of a set of loosely-related settings.
Establish a list of configuration symbols. For each symbol, run a test job
with this symbol unset.
If exclude is a regular expression, skip generated jobs whose description
would match this regular expression."""
def __init__(self, symbols, commands, exclude=None):
"""Build a domain for the specified list of configuration symbols.
Each job in the domain disables one of the specified symbols.
Each job runs the specified commands."""
super().__init__(symbols, commands, exclude)
for symbol in symbols:
description = '!' + symbol
if exclude and re.match(exclude, description):
continue
config_settings = {symbol: False}
turn_off_dependencies(config_settings)
job = Job(description, config_settings, commands)
self.jobs.append(job)
class DualDomain(ExclusiveDomain, ComplementaryDomain): # pylint: disable=too-few-public-methods
"""A domain that contains both the ExclusiveDomain and BaseDomain tests.
Both parent class __init__ calls are performed in any order and
each call adds respective jobs. The job array initialization is done once in
BaseDomain, before the parent __init__ calls."""
class DomainData:
"""A container for domains and jobs, used to structurize testing."""
def config_symbols_matching(self, regexp):
"""List the mbedtls_config.h settings matching regexp."""
return [symbol for symbol in self.all_config_symbols
if re.match(regexp, symbol)]
# pylint: disable=too-many-locals
def __init__(self, options, conf):
"""Gather data about the library and establish a list of domains to test."""
build_command = [options.make_command, 'CFLAGS=-Werror -O2']
build_and_test = [build_command, [options.make_command, 'test']]
self.all_config_symbols = set(conf.settings.keys())
psa_info = psa_information.Information().constructors
algs = {crypto_knowledge.Algorithm(alg): symbol
for alg, symbol in ((alg, psa_information.psa_want_symbol(alg))
for alg in psa_info.algorithms)
if symbol in self.all_config_symbols}
cipher_algs = {alg
for alg in algs
if alg.can_do(crypto_knowledge.AlgorithmCategory.CIPHER)}
key_types = {crypto_knowledge.KeyType(expr): symbol
for key_type in psa_info.key_types
for expr, symbol in ((expr, psa_information.psa_want_symbol(key_type))
for expr in psa_info.generate_expressions([key_type]))
if symbol in self.all_config_symbols}
# Find hash modules by name.
hash_symbols = self.config_symbols_matching(r'MBEDTLS_(MD|RIPEMD|SHA)[0-9]+_C\Z')
# Find elliptic curve enabling macros by name.
curve_symbols = self.config_symbols_matching(r'MBEDTLS_ECP_DP_\w+_ENABLED\Z')
# Find key exchange enabling macros by name.
key_exchange_symbols = self.config_symbols_matching(r'MBEDTLS_KEY_EXCHANGE_\w+_ENABLED\Z')
# Find cipher key types
cipher_key_types = {symbol
for key_type, symbol in key_types.items()
for alg in cipher_algs
if key_type.can_do(alg)}
# Find block cipher chaining and padding mode enabling macros by name.
cipher_chaining_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_MODE_\w+\Z')
cipher_padding_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_PADDING_\w+\Z')
self.domains = {
# Cipher key types
'cipher_id': ExclusiveDomain(cipher_key_types, build_and_test),
'cipher_chaining': ExclusiveDomain(cipher_chaining_symbols,
build_and_test),
'cipher_padding': ExclusiveDomain(cipher_padding_symbols,
build_and_test),
# Elliptic curves. Run the test suites.
'curves': ExclusiveDomain(curve_symbols, build_and_test),
# Hash algorithms. Excluding exclusive domains of MD, RIPEMD, SHA1,
# SHA224 and SHA384 because MBEDTLS_ENTROPY_C is extensively used
# across various modules, but it depends on either SHA256 or SHA512.
# As a consequence an "exclusive" test of anything other than SHA256
# or SHA512 with MBEDTLS_ENTROPY_C enabled is not possible.
'hashes': DualDomain(hash_symbols, build_and_test,
exclude=r'MBEDTLS_(MD|RIPEMD|SHA1_)' \
'|MBEDTLS_SHA224_' \
'|MBEDTLS_SHA384_' \
'|MBEDTLS_SHA3_'),
# Key exchange types.
'kex': ExclusiveDomain(key_exchange_symbols, build_and_test),
'pkalgs': ComplementaryDomain(['MBEDTLS_ECDSA_C',
'MBEDTLS_ECP_C',
'MBEDTLS_PKCS1_V21',
'MBEDTLS_PKCS1_V15',
'MBEDTLS_RSA_C',
'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
build_and_test),
}
self.jobs = {}
for domain in self.domains.values():
for job in domain.jobs:
self.jobs[job.name] = job
def get_jobs(self, name):
"""Return the list of jobs identified by the given name.
A name can either be the name of a domain or the name of one specific job."""
if name in self.domains:
return sorted(self.domains[name].jobs, key=lambda job: job.name)
else:
return [self.jobs[name]]
def run(options, job, conf, colors=NO_COLORS):
"""Run the specified job (a Job instance)."""
subprocess.check_call([options.make_command, 'clean'])
job.announce(colors, None)
if not job.configure(conf, colors):
job.announce(colors, False)
return False
conf.write()
success = job.test(options)
job.announce(colors, success)
return success
def run_tests(options, domain_data, conf):
"""Run the desired jobs.
domain_data should be a DomainData instance that describes the available
domains and jobs.
Run the jobs listed in options.tasks."""
colors = Colors(options)
jobs = []
failures = []
successes = []
for name in options.tasks:
jobs += domain_data.get_jobs(name)
conf.backup()
try:
for job in jobs:
success = run(options, job, conf, colors=colors)
if not success:
if options.keep_going:
failures.append(job.name)
else:
return False
else:
successes.append(job.name)
conf.restore()
except:
# Restore the configuration, except in stop-on-error mode if there
# was an error, where we leave the failing configuration up for
# developer convenience.
if options.keep_going:
conf.restore()
raise
if successes:
log_line('{} passed'.format(' '.join(successes)), color=colors.bold_green)
if failures:
log_line('{} FAILED'.format(' '.join(failures)), color=colors.bold_red)
return False
else:
return True
def main():
try:
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=
"Test Mbed TLS with a subset of algorithms.\n\n"
"Example usage:\n"
r"./tests/scripts/depends.py \!MBEDTLS_SHA1_C MBEDTLS_SHA256_C""\n"
"./tests/scripts/depends.py MBEDTLS_AES_C hashes\n"
"./tests/scripts/depends.py cipher_id cipher_chaining\n")
parser.add_argument('--color', metavar='WHEN',
help='Colorize the output (always/auto/never)',
choices=['always', 'auto', 'never'], default='auto')
parser.add_argument('-c', '--config', metavar='FILE',
help='Configuration file to modify',
default=config.MbedTLSConfigFile.default_path[0])
parser.add_argument('-r', '--crypto-config', metavar='FILE',
help='Crypto configuration file to modify',
default=config.CryptoConfigFile.default_path[0])
parser.add_argument('-C', '--directory', metavar='DIR',
help='Change to this directory before anything else',
default='.')
parser.add_argument('-k', '--keep-going',
help='Try all configurations even if some fail (default)',
action='store_true', dest='keep_going', default=True)
parser.add_argument('-e', '--no-keep-going',
help='Stop as soon as a configuration fails',
action='store_false', dest='keep_going')
parser.add_argument('--list-jobs',
help='List supported jobs and exit',
action='append_const', dest='list', const='jobs')
parser.add_argument('--list-domains',
help='List supported domains and exit',
action='append_const', dest='list', const='domains')
parser.add_argument('--make-command', metavar='CMD',
help='Command to run instead of make (e.g. gmake)',
action='store', default='make')
parser.add_argument('tasks', metavar='TASKS', nargs='*',
help='The domain(s) or job(s) to test (default: all).',
default=True)
options = parser.parse_args()
os.chdir(options.directory)
conf = config.CombinedConfig(config.MbedTLSConfigFile(options.config),
config.CryptoConfigFile(options.crypto_config))
domain_data = DomainData(options, conf)
if options.tasks is True:
options.tasks = sorted(domain_data.domains.keys())
if options.list:
for arg in options.list:
for domain_name in sorted(getattr(domain_data, arg).keys()):
print(domain_name)
sys.exit(0)
else:
sys.exit(0 if run_tests(options, domain_data, conf) else 1)
except Exception: # pylint: disable=broad-except
traceback.print_exc()
sys.exit(3)
if __name__ == '__main__':
main()
-90
View File
@@ -1,90 +0,0 @@
#!/bin/bash -eu
# docker_env.sh
#
# Purpose
# -------
#
# This is a helper script to enable running tests under a Docker container,
# thus making it easier to get set up as well as isolating test dependencies
# (which include legacy/insecure configurations of openssl and gnutls).
#
# WARNING: the Dockerfile used by this script is no longer maintained! See
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
# for the set of Docker images we use on the CI.
#
# Notes for users
# ---------------
# This script expects a Linux x86_64 system with a recent version of Docker
# installed and available for use, as well as http/https access. If a proxy
# server must be used, invoke this script with the usual environment variables
# (http_proxy and https_proxy) set appropriately. If an alternate Docker
# registry is needed, specify MBEDTLS_DOCKER_REGISTRY to point at the
# host name.
#
#
# Running this script directly will check for Docker availability and set up
# the Docker image.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# default values, can be overridden by the environment
: ${MBEDTLS_DOCKER_GUEST:=bionic}
DOCKER_IMAGE_TAG="armmbed/mbedtls-test:${MBEDTLS_DOCKER_GUEST}"
# Make sure docker is available
if ! which docker > /dev/null; then
echo "Docker is required but doesn't seem to be installed. See https://www.docker.com/ to get started"
exit 1
fi
# Figure out if we need to 'sudo docker'
if groups | grep docker > /dev/null; then
DOCKER="docker"
else
echo "Using sudo to invoke docker since you're not a member of the docker group..."
DOCKER="sudo docker"
fi
# Figure out the number of processors available
if [ "$(uname)" == "Darwin" ]; then
NUM_PROC="$(sysctl -n hw.logicalcpu)"
else
NUM_PROC="$(nproc)"
fi
# Build the Docker image
echo "Getting docker image up to date (this may take a few minutes)..."
${DOCKER} image build \
-t ${DOCKER_IMAGE_TAG} \
--cache-from=${DOCKER_IMAGE_TAG} \
--build-arg MAKEFLAGS_PARALLEL="-j ${NUM_PROC}" \
--network host \
${http_proxy+--build-arg http_proxy=${http_proxy}} \
${https_proxy+--build-arg https_proxy=${https_proxy}} \
${MBEDTLS_DOCKER_REGISTRY+--build-arg MY_REGISTRY="${MBEDTLS_DOCKER_REGISTRY}/"} \
tests/docker/${MBEDTLS_DOCKER_GUEST}
run_in_docker()
{
ENV_ARGS=""
while [ "$1" == "-e" ]; do
ENV_ARGS="${ENV_ARGS} $1 $2"
shift 2
done
${DOCKER} container run -it --rm \
--cap-add SYS_PTRACE \
--user "$(id -u):$(id -g)" \
--volume $PWD:$PWD \
--workdir $PWD \
-e MAKEFLAGS \
-e PYLINTHOME=/tmp/.pylintd \
${ENV_ARGS} \
${DOCKER_IMAGE_TAG} \
$@
}
-32
View File
@@ -1,32 +0,0 @@
#!/bin/sh
# Make sure the doxygen documentation builds without warnings
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# Abort on errors (and uninitialised variables)
set -eu
if [ -d library -a -d include -a -d tests ]; then :; else
echo "Must be run from Mbed TLS root" >&2
exit 1
fi
if scripts/apidoc_full.sh > doc.out 2>doc.err; then :; else
cat doc.err
echo "FAIL" >&2
exit 1;
fi
cat doc.out doc.err | \
grep -v "warning: ignoring unsupported tag" \
> doc.filtered
if grep -E "(warning|error):" doc.filtered; then
echo "FAIL" >&2
exit 1;
fi
make apidoc_clean
rm -f doc.out doc.err doc.filtered
-96
View File
@@ -1,96 +0,0 @@
#!/usr/bin/env perl
#
# Based on NIST CTR_DRBG.rsp validation file
# Only uses AES-256-CTR cases that use a Derivation function
# and concats nonce and personalization for initialization.
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
my $line = <TEST_DATA>;
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
next if ($line !~ /^\[AES-256 use df/);
my $PredictionResistanceStr = get_suite_val("PredictionResistance");
my $PredictionResistance = 0;
$PredictionResistance = 1 if ($PredictionResistanceStr eq 'True');
my $EntropyInputLen = get_suite_val("EntropyInputLen");
my $NonceLen = get_suite_val("NonceLen");
my $PersonalizationStringLen = get_suite_val("PersonalizationStringLen");
my $AdditionalInputLen = get_suite_val("AdditionalInputLen");
for ($cnt = 0; $cnt < 15; $cnt++)
{
my $Count = get_val("COUNT");
my $EntropyInput = get_val("EntropyInput");
my $Nonce = get_val("Nonce");
my $PersonalizationString = get_val("PersonalizationString");
my $AdditionalInput1 = get_val("AdditionalInput");
my $EntropyInputPR1 = get_val("EntropyInputPR") if ($PredictionResistance == 1);
my $EntropyInputReseed = get_val("EntropyInputReseed") if ($PredictionResistance == 0);
my $AdditionalInputReseed = get_val("AdditionalInputReseed") if ($PredictionResistance == 0);
my $AdditionalInput2 = get_val("AdditionalInput");
my $EntropyInputPR2 = get_val("EntropyInputPR") if ($PredictionResistance == 1);
my $ReturnedBits = get_val("ReturnedBits");
if ($PredictionResistance == 1)
{
print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n");
print("ctr_drbg_validate_pr");
print(":\"$Nonce$PersonalizationString\"");
print(":\"$EntropyInput$EntropyInputPR1$EntropyInputPR2\"");
print(":\"$AdditionalInput1\"");
print(":\"$AdditionalInput2\"");
print(":\"$ReturnedBits\"");
print("\n\n");
}
else
{
print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n");
print("ctr_drbg_validate_nopr");
print(":\"$Nonce$PersonalizationString\"");
print(":\"$EntropyInput$EntropyInputReseed\"");
print(":\"$AdditionalInput1\"");
print(":\"$AdditionalInputReseed\"");
print(":\"$AdditionalInput2\"");
print(":\"$ReturnedBits\"");
print("\n\n");
}
}
}
close(TEST_DATA);
-101
View File
@@ -1,101 +0,0 @@
#!/usr/bin/env perl
#
# Based on NIST gcmDecryptxxx.rsp validation files
# Only first 3 of every set used for compile time saving
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if ($line !~ /^\[/);
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
last;
}
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
sub get_val_or_fail($)
{
my $name = shift;
my $val = "FAIL";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/ && $line !~ /FAIL/);
last;
}
($val) = ($line =~ /^$name = (\w+)/) if ($line =~ /=/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
my $key_len = get_suite_val("Keylen");
next if ($key_len !~ /\d+/);
my $iv_len = get_suite_val("IVlen");
my $pt_len = get_suite_val("PTlen");
my $add_len = get_suite_val("AADlen");
my $tag_len = get_suite_val("Taglen");
for ($cnt = 0; $cnt < 3; $cnt++)
{
my $Count = get_val("Count");
my $key = get_val("Key");
my $iv = get_val("IV");
my $ct = get_val("CT");
my $add = get_val("AAD");
my $tag = get_val("Tag");
my $pt = get_val_or_fail("PT");
print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n");
print("gcm_decrypt_and_verify");
print(":\"$key\"");
print(":\"$ct\"");
print(":\"$iv\"");
print(":\"$add\"");
print(":$tag_len");
print(":\"$tag\"");
print(":\"$pt\"");
print(":0");
print("\n\n");
}
}
print("GCM Selftest\n");
print("gcm_selftest:\n\n");
close(TEST_DATA);
-84
View File
@@ -1,84 +0,0 @@
#!/usr/bin/env perl
#
# Based on NIST gcmEncryptIntIVxxx.rsp validation files
# Only first 3 of every set used for compile time saving
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_suite_val($)
{
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if ($line !~ /^\[/);
($val) = ($line =~ /\[$name\s\=\s(\w+)\]/);
last;
}
return $val;
}
sub get_val($)
{
my $name = shift;
my $val = "";
my $line;
while($line = <TEST_DATA>)
{
next if($line !~ /=/);
last;
}
($val) = ($line =~ /^$name = (\w+)/);
return $val;
}
my $cnt = 1;;
while (my $line = <TEST_DATA>)
{
my $key_len = get_suite_val("Keylen");
next if ($key_len !~ /\d+/);
my $iv_len = get_suite_val("IVlen");
my $pt_len = get_suite_val("PTlen");
my $add_len = get_suite_val("AADlen");
my $tag_len = get_suite_val("Taglen");
for ($cnt = 0; $cnt < 3; $cnt++)
{
my $Count = get_val("Count");
my $key = get_val("Key");
my $pt = get_val("PT");
my $add = get_val("AAD");
my $iv = get_val("IV");
my $ct = get_val("CT");
my $tag = get_val("Tag");
print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n");
print("gcm_encrypt_and_tag");
print(":\"$key\"");
print(":\"$pt\"");
print(":\"$iv\"");
print(":\"$add\"");
print(":\"$ct\"");
print(":$tag_len");
print(":\"$tag\"");
print(":0");
print("\n\n");
}
}
print("GCM Selftest\n");
print("gcm_selftest:\n\n");
close(TEST_DATA);
@@ -1,74 +0,0 @@
#!/usr/bin/env perl
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
use strict;
my $file = shift;
open(TEST_DATA, "$file") or die "Opening test cases '$file': $!";
sub get_val($$)
{
my $str = shift;
my $name = shift;
my $val = "";
while(my $line = <TEST_DATA>)
{
next if($line !~ /^# $str/);
last;
}
while(my $line = <TEST_DATA>)
{
last if($line eq "\r\n");
$val .= $line;
}
$val =~ s/[ \r\n]//g;
return $val;
}
my $state = 0;
my $val_n = "";
my $val_e = "";
my $val_p = "";
my $val_q = "";
my $mod = 0;
my $cnt = 1;
while (my $line = <TEST_DATA>)
{
next if ($line !~ /^# Example/);
( $mod ) = ($line =~ /A (\d+)/);
$val_n = get_val("RSA modulus n", "N");
$val_e = get_val("RSA public exponent e", "E");
$val_p = get_val("Prime p", "P");
$val_q = get_val("Prime q", "Q");
for(my $i = 1; $i <= 6; $i++)
{
my $val_m = get_val("Message to be", "M");
my $val_salt = get_val("Salt", "Salt");
my $val_sig = get_val("Signature", "Sig");
print("RSASSA-PSS Signature Example ${cnt}_${i}\n");
print("pkcs1_rsassa_pss_sign:$mod:16:\"$val_p\":16:\"$val_q\":16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1");
print(":\"$val_m\"");
print(":\"$val_salt\"");
print(":\"$val_sig\":0");
print("\n\n");
print("RSASSA-PSS Signature Example ${cnt}_${i} (verify)\n");
print("pkcs1_rsassa_pss_verify:$mod:16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1");
print(":\"$val_m\"");
print(":\"$val_salt\"");
print(":\"$val_sig\":0");
print("\n\n");
}
$cnt++;
}
close(TEST_DATA);
-71
View File
@@ -1,71 +0,0 @@
#!/bin/sh
# This script splits the data test files containing the test cases into
# individual files (one test case per file) suitable for use with afl
# (American Fuzzy Lop). http://lcamtuf.coredump.cx/afl/
#
# Usage: generate-afl-tests.sh <test data file path>
# <test data file path> - should be the path to one of the test suite files
# such as 'test_suite_rsa.data'
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# Abort on errors
set -e
if [ -z $1 ]
then
echo " [!] No test file specified" >&2
echo "Usage: $0 <test data file>" >&2
exit 1
fi
SRC_FILEPATH=$(dirname $1)/$(basename $1)
TESTSUITE=$(basename $1 .data)
THIS_DIR=$(basename $PWD)
if [ -d ../library -a -d ../include -a -d ../tests -a $THIS_DIR == "tests" ];
then :;
else
echo " [!] Must be run from Mbed TLS tests directory" >&2
exit 1
fi
DEST_TESTCASE_DIR=$TESTSUITE-afl-tests
DEST_OUTPUT_DIR=$TESTSUITE-afl-out
echo " [+] Creating output directories" >&2
if [ -e $DEST_OUTPUT_DIR/* ];
then :
echo " [!] Test output files already exist." >&2
exit 1
else
mkdir -p $DEST_OUTPUT_DIR
fi
if [ -e $DEST_TESTCASE_DIR/* ];
then :
echo " [!] Test output files already exist." >&2
else
mkdir -p $DEST_TESTCASE_DIR
fi
echo " [+] Creating test cases" >&2
cd $DEST_TESTCASE_DIR
split -p '^\s*$' ../$SRC_FILEPATH
for f in *;
do
# Strip out any blank lines (no trim on OS X)
sed '/^\s*$/d' $f >testcase_$f
rm $f
done
cd ..
echo " [+] Test cases in $DEST_TESTCASE_DIR" >&2
@@ -1,87 +0,0 @@
#!/usr/bin/env python3
"""Generate server9-bad-saltlen.crt
Generate a certificate signed with RSA-PSS, with an incorrect salt length.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import subprocess
import argparse
from asn1crypto import pem, x509, core #type: ignore #pylint: disable=import-error
OPENSSL_RSA_PSS_CERT_COMMAND = r'''
openssl x509 -req -CA {ca_name}.crt -CAkey {ca_name}.key -set_serial 24 {ca_password} \
{openssl_extfile} -days 3650 -outform DER -in {csr} \
-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{anounce_saltlen} \
-sigopt rsa_mgf1_md:sha256
'''
SIG_OPT = \
r'-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{saltlen} -sigopt rsa_mgf1_md:sha256'
OPENSSL_RSA_PSS_DGST_COMMAND = r'''openssl dgst -sign {ca_name}.key {ca_password} \
-sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:{actual_saltlen} \
-sigopt rsa_mgf1_md:sha256'''
def auto_int(x):
return int(x, 0)
def build_argparser(parser):
"""Build argument parser"""
parser.description = __doc__
parser.add_argument('--ca-name', type=str, required=True,
help='Basename of CA files')
parser.add_argument('--ca-password', type=str,
required=True, help='CA key file password')
parser.add_argument('--csr', type=str, required=True,
help='CSR file for generating certificate')
parser.add_argument('--openssl-extfile', type=str,
required=True, help='X905 v3 extension config file')
parser.add_argument('--anounce_saltlen', type=auto_int,
required=True, help='Announced salt length')
parser.add_argument('--actual_saltlen', type=auto_int,
required=True, help='Actual salt length')
parser.add_argument('--output', type=str, required=True)
def main():
parser = argparse.ArgumentParser()
build_argparser(parser)
args = parser.parse_args()
return generate(**vars(args))
def generate(**kwargs):
"""Generate different salt length certificate file."""
ca_password = kwargs.get('ca_password', '')
if ca_password:
kwargs['ca_password'] = r'-passin "pass:{ca_password}"'.format(
**kwargs)
else:
kwargs['ca_password'] = ''
extfile = kwargs.get('openssl_extfile', '')
if extfile:
kwargs['openssl_extfile'] = '-extfile {openssl_extfile}'.format(
**kwargs)
else:
kwargs['openssl_extfile'] = ''
cmd = OPENSSL_RSA_PSS_CERT_COMMAND.format(**kwargs)
der_bytes = subprocess.check_output(cmd, shell=True)
target_certificate = x509.Certificate.load(der_bytes)
cmd = OPENSSL_RSA_PSS_DGST_COMMAND.format(**kwargs)
#pylint: disable=unexpected-keyword-arg
der_bytes = subprocess.check_output(cmd,
input=target_certificate['tbs_certificate'].dump(),
shell=True)
with open(kwargs.get('output'), 'wb') as f:
target_certificate['signature_value'] = core.OctetBitString(der_bytes)
f.write(pem.armor('CERTIFICATE', target_certificate.dump()))
if __name__ == '__main__':
main()
-54
View File
@@ -1,54 +0,0 @@
#!/bin/bash
#
# Create a file named identifiers containing identifiers from internal header
# files, based on the --internal flag.
# Outputs the line count of the file to stdout.
# A very thin wrapper around list_internal_identifiers.py for backwards
# compatibility.
# Must be run from Mbed TLS root.
#
# Usage: list-identifiers.sh [ -i | --internal ]
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -eu
if [ -d include/mbedtls ]; then :; else
echo "$0: Must be run from Mbed TLS root" >&2
exit 1
fi
INTERNAL=""
until [ -z "${1-}" ]
do
case "$1" in
-i|--internal)
INTERNAL="1"
;;
*)
# print error
echo "Unknown argument: '$1'"
exit 1
;;
esac
shift
done
if [ $INTERNAL ]
then
tests/scripts/list_internal_identifiers.py
wc -l identifiers
else
cat <<EOF
Sorry, this script has to be called with --internal.
This script exists solely for backwards compatibility with the previous
iteration of list-identifiers.sh, of which only the --internal option remains in
use. It is a thin wrapper around list_internal_identifiers.py.
check-names.sh, which used to depend on this script, has been replaced with
check_names.py and is now self-complete.
EOF
fi
@@ -1,47 +0,0 @@
#!/usr/bin/env python3
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
"""
This script generates a file called identifiers that contains all Mbed TLS
identifiers found on internal headers. This is the equivalent of what was
previously `list-identifiers.sh --internal`, and is useful for generating an
exclusion file list for ABI/API checking, since we do not promise compatibility
for them.
It uses the CodeParser class from check_names.py to perform the parsing.
The script returns 0 on success, 1 if there is a script error.
Must be run from Mbed TLS root.
"""
import argparse
import logging
from check_names import CodeParser
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=(
"This script writes a list of parsed identifiers in internal "
"headers to \"identifiers\". This is useful for generating a list "
"of names to exclude from API/ABI compatibility checking. "))
parser.parse_args()
name_check = CodeParser(logging.getLogger())
result = name_check.parse_identifiers([
"include/mbedtls/*_internal.h",
"library/*.h",
"tf-psa-crypto/core/*.h",
"tf-psa-crypto/drivers/builtin/src/*.h"
])[0]
result.sort(key=lambda x: x.name)
identifiers = ["{}\n".format(match.name) for match in result]
with open("identifiers", "w", encoding="utf-8") as f:
f.writelines(identifiers)
if __name__ == "__main__":
main()
-15
View File
@@ -1,15 +0,0 @@
#! /usr/bin/env bash
# all.sh (mbedtls part)
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
# This file is executable; it is the entry point for users and the CI.
# See "Files structure" in all-core.sh for other files used.
# This script must be invoked from the project's root.
source framework/scripts/all-core.sh
main "$@"
-40
View File
@@ -1,40 +0,0 @@
#!/bin/sh
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
# Purpose
#
# Test pkgconfig files.
#
# For each of the build pkg-config files, .pc files, check that
# they validate and do some basic sanity testing on the output,
# i.e. that the strings are non-empty.
#
# NOTE: This requires the built pc files to be on the pkg-config
# search path, this can be controlled with env variable
# PKG_CONFIG_PATH. See man(1) pkg-config for details.
#
set -e -u
if [ $# -le 0 ]
then
echo " [!] No package names specified" >&2
echo "Usage: $0 <package name 1> <package name 2> ..." >&2
exit 1
fi
for pc in "$@"; do
printf "testing package config file: ${pc} ... "
pkg-config --validate "${pc}"
version="$(pkg-config --modversion "${pc}")"
test -n "$version"
cflags="$(pkg-config --cflags "${pc}")"
test -n "$cflags"
libs="$(pkg-config --libs "${pc}")"
test -n "$libs"
printf "passed\n"
done
exit 0

Some files were not shown because too many files have changed in this diff Show More