Added submodule contents into tree

This commit is contained in:
darktux
2024-04-05 01:58:27 +02:00
parent 01a752555c
commit 9b991208cd
4934 changed files with 1657477 additions and 5 deletions

View File

@@ -0,0 +1,92 @@
set(libs
${mbedtls_target}
)
set(executables_libs
metatest
query_included_headers
selftest
udp_proxy
)
set(executables_mbedcrypto
benchmark
query_compile_time_config
zeroize
)
if(TEST_CPP)
set(cpp_dummy_build_cpp "${CMAKE_CURRENT_BINARY_DIR}/cpp_dummy_build.cpp")
set(generate_cpp_dummy_build "${CMAKE_CURRENT_SOURCE_DIR}/generate_cpp_dummy_build.sh")
add_custom_command(
OUTPUT "${cpp_dummy_build_cpp}"
COMMAND "${generate_cpp_dummy_build}" "${cpp_dummy_build_cpp}"
DEPENDS "${generate_cpp_dummy_build}"
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
)
add_executable(cpp_dummy_build "${cpp_dummy_build_cpp}")
target_include_directories(cpp_dummy_build PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include)
target_link_libraries(cpp_dummy_build ${mbedcrypto_target} ${CMAKE_THREAD_LIBS_INIT})
endif()
if(USE_SHARED_MBEDTLS_LIBRARY AND
NOT ${CMAKE_SYSTEM_NAME} MATCHES "[Ww][Ii][Nn]")
add_executable(dlopen "dlopen.c")
target_include_directories(dlopen PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include)
target_link_libraries(dlopen ${CMAKE_DL_LIBS})
endif()
if(GEN_FILES)
find_package(Perl REQUIRED)
add_custom_command(
OUTPUT
${CMAKE_CURRENT_BINARY_DIR}/query_config.c
COMMAND
${PERL}
${CMAKE_CURRENT_SOURCE_DIR}/../../scripts/generate_query_config.pl
${CMAKE_CURRENT_SOURCE_DIR}/../../include/mbedtls/mbedtls_config.h
${CMAKE_CURRENT_SOURCE_DIR}/../../include/psa/crypto_config.h
${CMAKE_CURRENT_SOURCE_DIR}/../../scripts/data_files/query_config.fmt
${CMAKE_CURRENT_BINARY_DIR}/query_config.c
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/../../scripts/generate_query_config.pl
${CMAKE_CURRENT_SOURCE_DIR}/../../include/mbedtls/mbedtls_config.h
${CMAKE_CURRENT_SOURCE_DIR}/../../include/psa/crypto_config.h
${CMAKE_CURRENT_SOURCE_DIR}/../../scripts/data_files/query_config.fmt
)
# this file will also be used in another directory, so create a target, see
# https://gitlab.kitware.com/cmake/community/-/wikis/FAQ#how-can-i-add-a-dependency-to-a-source-file-which-is-generated-in-a-subdirectory
add_custom_target(generate_query_config_c
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/query_config.c)
else()
link_to_source(query_config.c)
endif()
foreach(exe IN LISTS executables_libs executables_mbedcrypto)
set(extra_sources "")
if(exe STREQUAL "query_compile_time_config")
list(APPEND extra_sources
${CMAKE_CURRENT_SOURCE_DIR}/query_config.h
${CMAKE_CURRENT_BINARY_DIR}/query_config.c)
endif()
add_executable(${exe} ${exe}.c $<TARGET_OBJECTS:mbedtls_test>
${extra_sources})
target_include_directories(${exe} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../tests/include)
target_include_directories(${exe} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../library)
if(exe STREQUAL "query_compile_time_config")
target_include_directories(${exe} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
endif()
# This emulates "if ( ... IN_LIST ... )" which becomes available in CMake 3.3
list(FIND executables_libs ${exe} exe_index)
if (${exe_index} GREATER -1)
target_link_libraries(${exe} ${libs} ${CMAKE_THREAD_LIBS_INIT})
else()
target_link_libraries(${exe} ${mbedcrypto_target} ${CMAKE_THREAD_LIBS_INIT})
endif()
endforeach()
install(TARGETS ${executables_libs} ${executables_mbedcrypto}
DESTINATION "bin"
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
build
Makefile
cmake_package

View File

@@ -0,0 +1,38 @@
cmake_minimum_required(VERSION 3.5.1)
#
# Simulate configuring and building Mbed TLS as the user might do it. We'll
# skip installing it, and use the build directory directly instead.
#
set(MbedTLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
set(MbedTLS_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/mbedtls")
execute_process(
COMMAND "${CMAKE_COMMAND}"
"-H${MbedTLS_SOURCE_DIR}"
"-B${MbedTLS_BINARY_DIR}"
"-DENABLE_PROGRAMS=NO"
"-DENABLE_TESTING=NO"
# Turn on generated files explicitly in case this is a release
"-DGEN_FILES=ON")
execute_process(
COMMAND "${CMAKE_COMMAND}"
--build "${MbedTLS_BINARY_DIR}")
#
# Locate the package.
#
set(MbedTLS_DIR "${MbedTLS_BINARY_DIR}/cmake")
find_package(MbedTLS REQUIRED)
#
# At this point, the Mbed TLS targets should have been imported, and we can now
# link to them from our own program.
#
add_executable(cmake_package cmake_package.c)
target_link_libraries(cmake_package
MbedTLS::mbedcrypto MbedTLS::mbedtls MbedTLS::mbedx509)

View File

@@ -0,0 +1,27 @@
/*
* Simple program to test that Mbed TLS builds correctly as a CMake package.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#include "mbedtls/version.h"
/* The main reason to build this is for testing the CMake build, so the program
* doesn't need to do very much. It calls a single library function to ensure
* linkage works, but that is all. */
int main()
{
/* This version string is 18 bytes long, as advised by version.h. */
char version[18];
mbedtls_version_get_string_full(version);
mbedtls_printf("Built against %s\n", version);
return 0;
}

View File

@@ -0,0 +1,3 @@
build
Makefile
cmake_package_install

View File

@@ -0,0 +1,41 @@
cmake_minimum_required(VERSION 3.5.1)
#
# Simulate configuring and building Mbed TLS as the user might do it. We'll
# install into a directory inside our own build directory.
#
set(MbedTLS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
set(MbedTLS_INSTALL_DIR "${CMAKE_CURRENT_BINARY_DIR}/mbedtls")
set(MbedTLS_BINARY_DIR "${MbedTLS_INSTALL_DIR}${CMAKE_FILES_DIRECTORY}")
execute_process(
COMMAND "${CMAKE_COMMAND}"
"-H${MbedTLS_SOURCE_DIR}"
"-B${MbedTLS_BINARY_DIR}"
"-DENABLE_PROGRAMS=NO"
"-DENABLE_TESTING=NO"
# Turn on generated files explicitly in case this is a release
"-DGEN_FILES=ON"
"-DCMAKE_INSTALL_PREFIX=${MbedTLS_INSTALL_DIR}")
execute_process(
COMMAND "${CMAKE_COMMAND}"
--build "${MbedTLS_BINARY_DIR}"
--target install)
#
# Locate the package.
#
list(INSERT CMAKE_PREFIX_PATH 0 "${MbedTLS_INSTALL_DIR}")
find_package(MbedTLS REQUIRED)
#
# At this point, the Mbed TLS targets should have been imported, and we can now
# link to them from our own program.
#
add_executable(cmake_package_install cmake_package_install.c)
target_link_libraries(cmake_package_install
MbedTLS::mbedcrypto MbedTLS::mbedtls MbedTLS::mbedx509)

View File

@@ -0,0 +1,28 @@
/*
* Simple program to test that Mbed TLS builds correctly as an installable CMake
* package.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#include "mbedtls/version.h"
/* The main reason to build this is for testing the CMake build, so the program
* doesn't need to do very much. It calls a single library function to ensure
* linkage works, but that is all. */
int main()
{
/* This version string is 18 bytes long, as advised by version.h. */
char version[18];
mbedtls_version_get_string_full(version);
mbedtls_printf("Built against %s\n", version);
return 0;
}

View File

@@ -0,0 +1,3 @@
build
Makefile
cmake_subproject

View File

@@ -0,0 +1,23 @@
cmake_minimum_required(VERSION 3.5.1)
# Test the target renaming support by adding a prefix to the targets built
set(MBEDTLS_TARGET_PREFIX subproject_test_)
# We use the parent Mbed TLS directory as the MBEDTLS_DIR for this test. Other
# projects that use Mbed TLS as a subproject are likely to add by their own
# relative paths.
set(MBEDTLS_DIR ../../../)
# Add Mbed TLS as a subdirectory.
add_subdirectory(${MBEDTLS_DIR} build)
# Link against all the Mbed TLS libraries. Verifies that the targets have been
# created using the specified prefix
set(libs
subproject_test_mbedcrypto
subproject_test_mbedx509
subproject_test_mbedtls
)
add_executable(cmake_subproject cmake_subproject.c)
target_link_libraries(cmake_subproject ${libs} ${CMAKE_THREAD_LIBS_INIT})

View File

@@ -0,0 +1,28 @@
/*
* Simple program to test that CMake builds with Mbed TLS as a subdirectory
* work correctly.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#include "mbedtls/version.h"
/* The main reason to build this is for testing the CMake build, so the program
* doesn't need to do very much. It calls a single library function to ensure
* linkage works, but that is all. */
int main()
{
/* This version string is 18 bytes long, as advised by version.h. */
char version[18];
mbedtls_version_get_string_full(version);
mbedtls_printf("Built against %s\n", version);
return 0;
}

View File

@@ -0,0 +1,92 @@
/*
* Test dynamic loading of libmbed*
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/x509_crt.h"
#endif
#if defined(__APPLE__)
#define SO_SUFFIX ".dylib"
#else
#define SO_SUFFIX ".so"
#endif
#define CRYPTO_SO_FILENAME "libmbedcrypto" SO_SUFFIX
#define X509_SO_FILENAME "libmbedx509" SO_SUFFIX
#define TLS_SO_FILENAME "libmbedtls" SO_SUFFIX
#include <dlfcn.h>
#define CHECK_DLERROR(function, argument) \
do \
{ \
char *CHECK_DLERROR_error = dlerror(); \
if (CHECK_DLERROR_error != NULL) \
{ \
fprintf(stderr, "Dynamic loading error for %s(%s): %s\n", \
function, argument, CHECK_DLERROR_error); \
mbedtls_exit(MBEDTLS_EXIT_FAILURE); \
} \
} \
while (0)
int main(void)
{
#if defined(MBEDTLS_MD_C) || defined(MBEDTLS_SSL_TLS_C)
unsigned n;
#endif
#if defined(MBEDTLS_SSL_TLS_C)
void *tls_so = dlopen(TLS_SO_FILENAME, RTLD_NOW);
CHECK_DLERROR("dlopen", TLS_SO_FILENAME);
const int *(*ssl_list_ciphersuites)(void) =
dlsym(tls_so, "mbedtls_ssl_list_ciphersuites");
CHECK_DLERROR("dlsym", "mbedtls_ssl_list_ciphersuites");
const int *ciphersuites = ssl_list_ciphersuites();
for (n = 0; ciphersuites[n] != 0; n++) {/* nothing to do, we're just counting */
;
}
mbedtls_printf("dlopen(%s): %u ciphersuites\n",
TLS_SO_FILENAME, n);
dlclose(tls_so);
CHECK_DLERROR("dlclose", TLS_SO_FILENAME);
#endif /* MBEDTLS_SSL_TLS_C */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
void *x509_so = dlopen(X509_SO_FILENAME, RTLD_NOW);
CHECK_DLERROR("dlopen", X509_SO_FILENAME);
const mbedtls_x509_crt_profile *profile =
dlsym(x509_so, "mbedtls_x509_crt_profile_default");
CHECK_DLERROR("dlsym", "mbedtls_x509_crt_profile_default");
mbedtls_printf("dlopen(%s): Allowed md mask: %08x\n",
X509_SO_FILENAME, (unsigned) profile->allowed_mds);
dlclose(x509_so);
CHECK_DLERROR("dlclose", X509_SO_FILENAME);
#endif /* MBEDTLS_X509_CRT_PARSE_C */
#if defined(MBEDTLS_MD_C)
void *crypto_so = dlopen(CRYPTO_SO_FILENAME, RTLD_NOW);
CHECK_DLERROR("dlopen", CRYPTO_SO_FILENAME);
const int *(*md_list)(void) =
dlsym(crypto_so, "mbedtls_md_list");
CHECK_DLERROR("dlsym", "mbedtls_md_list");
const int *mds = md_list();
for (n = 0; mds[n] != 0; n++) {/* nothing to do, we're just counting */
;
}
mbedtls_printf("dlopen(%s): %u hashes\n",
CRYPTO_SO_FILENAME, n);
dlclose(crypto_so);
CHECK_DLERROR("dlclose", CRYPTO_SO_FILENAME);
#endif /* MBEDTLS_MD_C */
return 0;
}

View File

@@ -0,0 +1,42 @@
#!/bin/sh
# Run the shared library dynamic loading demo program.
# This is only expected to work when Mbed TLS is built as a shared library.
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
. "${0%/*}/../demo_common.sh"
msg "Test the dynamic loading of libmbed*"
program="$programs_dir/test/dlopen"
library_dir="$root_dir/library"
# Skip this test if we don't have a shared library build. Detect this
# through the absence of the demo program.
if [ ! -e "$program" ]; then
msg "$0: this demo requires a shared library build."
# Exit with a success status so that this counts as a pass for run_demos.py.
exit
fi
# ELF-based Unix-like (Linux, *BSD, Solaris, ...)
if [ -n "${LD_LIBRARY_PATH-}" ]; then
LD_LIBRARY_PATH="$library_dir:$LD_LIBRARY_PATH"
else
LD_LIBRARY_PATH="$library_dir"
fi
export LD_LIBRARY_PATH
# OSX/macOS
if [ -n "${DYLD_LIBRARY_PATH-}" ]; then
DYLD_LIBRARY_PATH="$library_dir:$DYLD_LIBRARY_PATH"
else
DYLD_LIBRARY_PATH="$library_dir"
fi
export DYLD_LIBRARY_PATH
msg "Running dynamic loading test program: $program"
msg "Loading libraries from: $library_dir"
"$program"

View File

@@ -0,0 +1,78 @@
#!/bin/sh
DEFAULT_OUTPUT_FILE=programs/test/cpp_dummy_build.cpp
if [ "$1" = "--help" ]; then
cat <<EOF
Usage: $0 [OUTPUT]
Generate a C++ dummy build program that includes all the headers.
OUTPUT defaults to "programs/test/cpp_dummy_build.cpp".
Run this program from the root of an Mbed TLS directory tree or from
its "programs" or "programs/test" subdirectory.
EOF
exit
fi
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -e
# Ensure a reproducible order for *.h
export LC_ALL=C
print_cpp () {
cat <<'EOF'
/* Automatically generated file. Do not edit.
*
* This program is a dummy C++ program to ensure Mbed TLS library header files
* can be included and built with a C++ compiler.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*
*/
#include "mbedtls/build_info.h"
EOF
for header in include/mbedtls/*.h include/psa/*.h; do
case ${header#include/} in
mbedtls/mbedtls_config.h) :;; # not meant for direct inclusion
mbedtls/config_*.h) :;; # not meant for direct inclusion
psa/crypto_config.h) :;; # not meant for direct inclusion
psa/crypto_ajdust_config*.h) :;; # not meant for direct inclusion
# Some of the psa/crypto_*.h headers are not meant to be included
# directly. They do have include guards that make them no-ops if
# psa/crypto.h has been included before. Since psa/crypto.h comes
# before psa/crypto_*.h in the wildcard enumeration, we don't need
# to skip those headers.
*) echo "#include \"${header#include/}\"";;
esac
done
cat <<'EOF'
int main()
{
mbedtls_platform_context *ctx = NULL;
mbedtls_platform_setup(ctx);
mbedtls_printf("CPP Build test passed\n");
mbedtls_platform_teardown(ctx);
}
EOF
}
if [ -d include/mbedtls ]; then
:
elif [ -d ../include/mbedtls ]; then
cd ..
elif [ -d ../../include/mbedtls ]; then
cd ../..
else
echo >&2 "This script must be run from an Mbed TLS source tree."
exit 3
fi
print_cpp >"${1:-$DEFAULT_OUTPUT_FILE}"

View File

@@ -0,0 +1,359 @@
/** \file metatest.c
*
* \brief Test features of the test framework.
*
* When you run this program, it runs a single "meta-test". A meta-test
* performs an operation which should be caught as a failure by our
* test framework. The meta-test passes if this program calls `exit` with
* a nonzero status, or aborts, or is terminated by a signal, or if the
* framework running the program considers the run an error (this happens
* with Valgrind for a memory leak). The non-success of the meta-test
* program means that the test failure has been caught correctly.
*
* Some failures are purely functional: the logic of the code causes the
* test result to be set to FAIL. Other failures come from extra
* instrumentation which is not present in a normal build; for example,
* Asan or Valgrind to detect memory leaks. This is reflected by the
* "platform" associated with each meta-test.
*
* Use the companion script `tests/scripts/run-metatests.sh` to run all
* the meta-tests for a given platform and validate that they trigger a
* detected failure as expected.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <mbedtls/platform.h>
#include <mbedtls/platform_util.h>
#include "test/helpers.h"
#include "test/threading_helpers.h"
#include "test/macros.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_THREADING_C)
#include <mbedtls/threading.h>
#endif
/* This is an external variable, so the compiler doesn't know that we're never
* changing its value.
*/
volatile int false_but_the_compiler_does_not_know = 0;
/* Hide calls to calloc/free from static checkers such as
* `gcc-12 -Wuse-after-free`, to avoid compile-time complaints about
* code where we do mean to cause a runtime error. */
void * (* volatile calloc_but_the_compiler_does_not_know)(size_t, size_t) = mbedtls_calloc;
void(*volatile free_but_the_compiler_does_not_know)(void *) = mbedtls_free;
/* Set n bytes at the address p to all-bits-zero, in such a way that
* the compiler should not know that p is all-bits-zero. */
static void set_to_zero_but_the_compiler_does_not_know(volatile void *p, size_t n)
{
memset((void *) p, false_but_the_compiler_does_not_know, n);
}
/****************************************************************/
/* Test framework features */
/****************************************************************/
void meta_test_fail(const char *name)
{
(void) name;
mbedtls_test_fail("Forced test failure", __LINE__, __FILE__);
}
/****************************************************************/
/* Platform features */
/****************************************************************/
void null_pointer_dereference(const char *name)
{
(void) name;
volatile char *volatile p;
set_to_zero_but_the_compiler_does_not_know(&p, sizeof(p));
/* Undefined behavior (read from null data pointer) */
mbedtls_printf("%p -> %u\n", p, (unsigned) *p);
}
void null_pointer_call(const char *name)
{
(void) name;
unsigned(*volatile p)(void);
set_to_zero_but_the_compiler_does_not_know(&p, sizeof(p));
/* Undefined behavior (execute null function pointer) */
/* The pointer representation may be truncated, but we don't care:
* the only point of printing it is to have some use of the pointer
* to dissuade the compiler from optimizing it away. */
mbedtls_printf("%lx() -> %u\n", (unsigned long) (uintptr_t) p, p());
}
/****************************************************************/
/* Memory */
/****************************************************************/
void read_after_free(const char *name)
{
(void) name;
volatile char *p = calloc_but_the_compiler_does_not_know(1, 1);
*p = 'a';
free_but_the_compiler_does_not_know((void *) p);
/* Undefined behavior (read after free) */
mbedtls_printf("%u\n", (unsigned) *p);
}
void double_free(const char *name)
{
(void) name;
volatile char *p = calloc_but_the_compiler_does_not_know(1, 1);
*p = 'a';
free_but_the_compiler_does_not_know((void *) p);
/* Undefined behavior (double free) */
free_but_the_compiler_does_not_know((void *) p);
}
void read_uninitialized_stack(const char *name)
{
(void) name;
char buf[1];
if (false_but_the_compiler_does_not_know) {
buf[0] = '!';
}
char *volatile p = buf;
if (*p != 0) {
/* Unspecified result (read from uninitialized memory) */
mbedtls_printf("%u\n", (unsigned) *p);
}
}
void memory_leak(const char *name)
{
(void) name;
volatile char *p = calloc_but_the_compiler_does_not_know(1, 1);
mbedtls_printf("%u\n", (unsigned) *p);
/* Leak of a heap object */
}
/****************************************************************/
/* Threading */
/****************************************************************/
void mutex_lock_not_initialized(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
memset(&mutex, 0, sizeof(mutex));
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
TEST_ASSERT(mbedtls_mutex_lock(&mutex) == 0);
exit:
;
#endif
}
void mutex_unlock_not_initialized(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
memset(&mutex, 0, sizeof(mutex));
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
TEST_ASSERT(mbedtls_mutex_unlock(&mutex) == 0);
exit:
;
#endif
}
void mutex_free_not_initialized(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
memset(&mutex, 0, sizeof(mutex));
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
mbedtls_mutex_free(&mutex);
#endif
}
void mutex_double_init(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
mbedtls_mutex_init(&mutex);
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
mbedtls_mutex_init(&mutex);
mbedtls_mutex_free(&mutex);
#endif
}
void mutex_double_free(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
mbedtls_mutex_init(&mutex);
mbedtls_mutex_free(&mutex);
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
mbedtls_mutex_free(&mutex);
#endif
}
void mutex_leak(const char *name)
{
(void) name;
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
mbedtls_mutex_init(&mutex);
#endif
/* This mutex usage error is detected by our test framework's mutex usage
* verification framework. See tests/src/threading_helpers.c. Other
* threading implementations (e.g. pthread without our instrumentation)
* might consider this normal usage. */
}
/****************************************************************/
/* Command line entry point */
/****************************************************************/
typedef struct {
/** Command line argument that will trigger that metatest.
*
* Conventionally matches "[a-z0-9_]+". */
const char *name;
/** Platform under which that metatest is valid.
*
* - "any": should work anywhere.
* - "asan": triggers ASan (Address Sanitizer).
* - "msan": triggers MSan (Memory Sanitizer).
* - "pthread": requires MBEDTLS_THREADING_PTHREAD and MBEDTLS_TEST_HOOKS,
* which enables MBEDTLS_TEST_MUTEX_USAGE internally in the test
* framework (see tests/src/threading_helpers.c).
*/
const char *platform;
/** Function that performs the metatest.
*
* The function receives the name as an argument. This allows using the
* same function to perform multiple variants of a test based on the name.
*
* When executed on a conforming platform, the function is expected to
* either cause a test failure (mbedtls_test_fail()), or cause the
* program to abort in some way (e.g. by causing a segfault or by
* triggering a sanitizer).
*
* When executed on a non-conforming platform, the function may return
* normally or may have unpredictable behavior.
*/
void (*entry_point)(const char *name);
} metatest_t;
/* The list of availble meta-tests. Remember to register new functions here!
*
* Note that we always compile all the functions, so that `metatest --list`
* will always list all the available meta-tests.
*
* See the documentation of metatest_t::platform for the meaning of
* platform values.
*/
metatest_t metatests[] = {
{ "test_fail", "any", meta_test_fail },
{ "null_dereference", "any", null_pointer_dereference },
{ "null_call", "any", null_pointer_call },
{ "read_after_free", "asan", read_after_free },
{ "double_free", "asan", double_free },
{ "read_uninitialized_stack", "msan", read_uninitialized_stack },
{ "memory_leak", "asan", memory_leak },
{ "mutex_lock_not_initialized", "pthread", mutex_lock_not_initialized },
{ "mutex_unlock_not_initialized", "pthread", mutex_unlock_not_initialized },
{ "mutex_free_not_initialized", "pthread", mutex_free_not_initialized },
{ "mutex_double_init", "pthread", mutex_double_init },
{ "mutex_double_free", "pthread", mutex_double_free },
{ "mutex_leak", "pthread", mutex_leak },
{ NULL, NULL, NULL }
};
static void help(FILE *out, const char *argv0)
{
mbedtls_fprintf(out, "Usage: %s list|TEST\n", argv0);
mbedtls_fprintf(out, "Run a meta-test that should cause a test failure.\n");
mbedtls_fprintf(out, "With 'list', list the available tests and their platform requirement.\n");
}
int main(int argc, char *argv[])
{
const char *argv0 = argc > 0 ? argv[0] : "metatest";
if (argc != 2) {
help(stderr, argv0);
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
/* Support "-help", "--help", "--list", etc. */
const char *command = argv[1];
while (*command == '-') {
++command;
}
if (strcmp(argv[1], "help") == 0) {
help(stdout, argv0);
mbedtls_exit(MBEDTLS_EXIT_SUCCESS);
}
if (strcmp(argv[1], "list") == 0) {
for (const metatest_t *p = metatests; p->name != NULL; p++) {
mbedtls_printf("%s %s\n", p->name, p->platform);
}
mbedtls_exit(MBEDTLS_EXIT_SUCCESS);
}
#if defined(MBEDTLS_TEST_MUTEX_USAGE)
mbedtls_test_mutex_usage_init();
#endif
for (const metatest_t *p = metatests; p->name != NULL; p++) {
if (strcmp(argv[1], p->name) == 0) {
mbedtls_printf("Running metatest %s...\n", argv[1]);
p->entry_point(argv[1]);
#if defined(MBEDTLS_TEST_MUTEX_USAGE)
mbedtls_test_mutex_usage_check();
#endif
int result = (int) mbedtls_test_get_result();
mbedtls_printf("Running metatest %s... done, result=%d\n",
argv[1], result);
mbedtls_exit(result == MBEDTLS_TEST_RESULT_SUCCESS ?
MBEDTLS_EXIT_SUCCESS :
MBEDTLS_EXIT_FAILURE);
}
}
mbedtls_fprintf(stderr, "%s: FATAL: No such metatest: %s\n",
argv0, command);
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}

View File

@@ -0,0 +1,66 @@
/*
* Query the Mbed TLS compile time configuration
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/platform.h"
#define USAGE \
"usage: %s [ -all | -any | -l ] <MBEDTLS_CONFIG> ...\n\n" \
"This program takes command line arguments which correspond to\n" \
"the string representation of Mbed TLS compile time configurations.\n\n" \
"If \"--all\" and \"--any\" are not used, then, if all given arguments\n" \
"are defined in the Mbed TLS build, 0 is returned; otherwise 1 is\n" \
"returned. Macro expansions of configurations will be printed (if any).\n" \
"-l\tPrint all available configuration.\n" \
"-all\tReturn 0 if all configurations are defined. Otherwise, return 1\n" \
"-any\tReturn 0 if any configuration is defined. Otherwise, return 1\n" \
"-h\tPrint this usage\n"
#include <string.h>
#include "query_config.h"
int main(int argc, char *argv[])
{
int i;
if (argc < 2 || strcmp(argv[1], "-h") == 0) {
mbedtls_printf(USAGE, argv[0]);
return MBEDTLS_EXIT_FAILURE;
}
if (strcmp(argv[1], "-l") == 0) {
list_config();
return 0;
}
if (strcmp(argv[1], "-all") == 0) {
for (i = 2; i < argc; i++) {
if (query_config(argv[i]) != 0) {
return 1;
}
}
return 0;
}
if (strcmp(argv[1], "-any") == 0) {
for (i = 2; i < argc; i++) {
if (query_config(argv[i]) == 0) {
return 0;
}
}
return 1;
}
for (i = 1; i < argc; i++) {
if (query_config(argv[i]) != 0) {
return 1;
}
}
return 0;
}

View File

@@ -0,0 +1,34 @@
/*
* Query Mbed TLS compile time configurations from mbedtls_config.h
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#ifndef MBEDTLS_PROGRAMS_TEST_QUERY_CONFIG_H
#define MBEDTLS_PROGRAMS_TEST_QUERY_CONFIG_H
#include "mbedtls/build_info.h"
/** Check whether a given configuration symbol is enabled.
*
* \param config The symbol to query (e.g. "MBEDTLS_RSA_C").
* \return \c 0 if the symbol was defined at compile time
* (in MBEDTLS_CONFIG_FILE or mbedtls_config.h),
* \c 1 otherwise.
*
* \note This function is defined in `programs/test/query_config.c`
* which is automatically generated by
* `scripts/generate_query_config.pl`.
*/
int query_config(const char *config);
/** List all enabled configuration symbols
*
* \note This function is defined in `programs/test/query_config.c`
* which is automatically generated by
* `scripts/generate_query_config.pl`.
*/
void list_config(void);
#endif /* MBEDTLS_PROGRAMS_TEST_QUERY_CONFIG_H */

View File

@@ -0,0 +1,29 @@
/* Ad hoc report on included headers. */
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include <psa/crypto.h>
#include <mbedtls/platform.h>
int main(void)
{
/* Which PSA platform header? */
#if defined(PSA_CRYPTO_PLATFORM_H)
mbedtls_printf("PSA_CRYPTO_PLATFORM_H\n");
#endif
#if defined(PSA_CRYPTO_PLATFORM_ALT_H)
mbedtls_printf("PSA_CRYPTO_PLATFORM_ALT_H\n");
#endif
/* Which PSA struct header? */
#if defined(PSA_CRYPTO_STRUCT_H)
mbedtls_printf("PSA_CRYPTO_STRUCT_H\n");
#endif
#if defined(PSA_CRYPTO_STRUCT_ALT_H)
mbedtls_printf("PSA_CRYPTO_STRUCT_ALT_H\n");
#endif
}

View File

@@ -0,0 +1,584 @@
/*
* Self-test demonstration program
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include "mbedtls/entropy.h"
#include "mbedtls/hmac_drbg.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/dhm.h"
#include "mbedtls/gcm.h"
#include "mbedtls/ccm.h"
#include "mbedtls/cmac.h"
#include "mbedtls/md5.h"
#include "mbedtls/ripemd160.h"
#include "mbedtls/sha1.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"
#include "mbedtls/sha3.h"
#include "mbedtls/des.h"
#include "mbedtls/aes.h"
#include "mbedtls/camellia.h"
#include "mbedtls/aria.h"
#include "mbedtls/chacha20.h"
#include "mbedtls/poly1305.h"
#include "mbedtls/chachapoly.h"
#include "mbedtls/base64.h"
#include "mbedtls/bignum.h"
#include "mbedtls/rsa.h"
#include "mbedtls/x509.h"
#include "mbedtls/pkcs5.h"
#include "mbedtls/ecp.h"
#include "mbedtls/ecjpake.h"
#include "mbedtls/timing.h"
#include "mbedtls/nist_kw.h"
#include "mbedtls/debug.h"
#include <limits.h>
#include <string.h>
#include "mbedtls/platform.h"
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
#include "mbedtls/memory_buffer_alloc.h"
#endif
#if defined MBEDTLS_SELF_TEST
/* Sanity check for malloc. This is not expected to fail, and is rather
* intended to display potentially useful information about the platform,
* in particular the behavior of malloc(0). */
static int calloc_self_test(int verbose)
{
int failures = 0;
void *empty1 = mbedtls_calloc(0, 1);
void *empty2 = mbedtls_calloc(0, 1);
void *buffer1 = mbedtls_calloc(1, 1);
void *buffer2 = mbedtls_calloc(1, 1);
unsigned int buffer_3_size = 256;
unsigned int buffer_4_size = 4097; /* Allocate more than the usual page size */
unsigned char *buffer3 = mbedtls_calloc(buffer_3_size, 1);
unsigned char *buffer4 = mbedtls_calloc(buffer_4_size, 1);
if (empty1 == NULL && empty2 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(0,1): passed (NULL)\n");
}
} else if (empty1 == NULL || empty2 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(0,1): failed (mix of NULL and non-NULL)\n");
}
++failures;
} else if (empty1 == empty2) {
if (verbose) {
mbedtls_printf(" CALLOC(0,1): passed (same non-null)\n");
}
empty2 = NULL;
} else {
if (verbose) {
mbedtls_printf(" CALLOC(0,1): passed (distinct non-null)\n");
}
}
mbedtls_free(empty1);
mbedtls_free(empty2);
empty1 = mbedtls_calloc(1, 0);
empty2 = mbedtls_calloc(1, 0);
if (empty1 == NULL && empty2 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(1,0): passed (NULL)\n");
}
} else if (empty1 == NULL || empty2 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(1,0): failed (mix of NULL and non-NULL)\n");
}
++failures;
} else if (empty1 == empty2) {
if (verbose) {
mbedtls_printf(" CALLOC(1,0): passed (same non-null)\n");
}
empty2 = NULL;
} else {
if (verbose) {
mbedtls_printf(" CALLOC(1,0): passed (distinct non-null)\n");
}
}
if (buffer1 == NULL || buffer2 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(1): failed (NULL)\n");
}
++failures;
} else if (buffer1 == buffer2) {
if (verbose) {
mbedtls_printf(" CALLOC(1): failed (same buffer twice)\n");
}
++failures;
buffer2 = NULL;
} else {
if (verbose) {
mbedtls_printf(" CALLOC(1): passed\n");
}
}
mbedtls_free(buffer1);
buffer1 = mbedtls_calloc(1, 1);
if (buffer1 == NULL) {
if (verbose) {
mbedtls_printf(" CALLOC(1 again): failed (NULL)\n");
}
++failures;
} else {
if (verbose) {
mbedtls_printf(" CALLOC(1 again): passed\n");
}
}
for (unsigned int i = 0; i < buffer_3_size; i++) {
if (buffer3[i] != 0) {
++failures;
if (verbose) {
mbedtls_printf(" CALLOC(%u): failed (memory not initialized to 0)\n",
buffer_3_size);
}
break;
}
}
for (unsigned int i = 0; i < buffer_4_size; i++) {
if (buffer4[i] != 0) {
++failures;
if (verbose) {
mbedtls_printf(" CALLOC(%u): failed (memory not initialized to 0)\n",
buffer_4_size);
}
break;
}
}
if (verbose) {
mbedtls_printf("\n");
}
mbedtls_free(empty1);
mbedtls_free(empty2);
mbedtls_free(buffer1);
mbedtls_free(buffer2);
mbedtls_free(buffer3);
mbedtls_free(buffer4);
return failures;
}
#endif /* MBEDTLS_SELF_TEST */
static int test_snprintf(size_t n, const char *ref_buf, int ref_ret)
{
int ret;
char buf[10] = "xxxxxxxxx";
const char ref[10] = "xxxxxxxxx";
ret = mbedtls_snprintf(buf, n, "%s", "123");
if (ret < 0 || (size_t) ret >= n) {
ret = -1;
}
if (strncmp(ref_buf, buf, sizeof(buf)) != 0 ||
ref_ret != ret ||
memcmp(buf + n, ref + n, sizeof(buf) - n) != 0) {
return 1;
}
return 0;
}
static int run_test_snprintf(void)
{
return test_snprintf(0, "xxxxxxxxx", -1) != 0 ||
test_snprintf(1, "", -1) != 0 ||
test_snprintf(2, "1", -1) != 0 ||
test_snprintf(3, "12", -1) != 0 ||
test_snprintf(4, "123", 3) != 0 ||
test_snprintf(5, "123", 3) != 0;
}
/*
* Check if a seed file is present, and if not create one for the entropy
* self-test. If this fails, we attempt the test anyway, so no error is passed
* back.
*/
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_ENTROPY_C)
#if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
static void create_entropy_seed_file(void)
{
int result;
size_t output_len = 0;
unsigned char seed_value[MBEDTLS_ENTROPY_BLOCK_SIZE];
/* Attempt to read the entropy seed file. If this fails - attempt to write
* to the file to ensure one is present. */
result = mbedtls_platform_std_nv_seed_read(seed_value,
MBEDTLS_ENTROPY_BLOCK_SIZE);
if (0 == result) {
return;
}
result = mbedtls_platform_entropy_poll(NULL,
seed_value,
MBEDTLS_ENTROPY_BLOCK_SIZE,
&output_len);
if (0 != result) {
return;
}
if (MBEDTLS_ENTROPY_BLOCK_SIZE != output_len) {
return;
}
mbedtls_platform_std_nv_seed_write(seed_value, MBEDTLS_ENTROPY_BLOCK_SIZE);
}
#endif
int mbedtls_entropy_self_test_wrapper(int verbose)
{
#if defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
create_entropy_seed_file();
#endif
return mbedtls_entropy_self_test(verbose);
}
#endif
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
int mbedtls_memory_buffer_alloc_free_and_self_test(int verbose)
{
if (verbose != 0) {
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_memory_buffer_alloc_status();
#endif
}
mbedtls_memory_buffer_alloc_free();
return mbedtls_memory_buffer_alloc_self_test(verbose);
}
#endif
typedef struct {
const char *name;
int (*function)(int);
} selftest_t;
const selftest_t selftests[] =
{
{ "calloc", calloc_self_test },
#if defined(MBEDTLS_MD5_C)
{ "md5", mbedtls_md5_self_test },
#endif
#if defined(MBEDTLS_RIPEMD160_C)
{ "ripemd160", mbedtls_ripemd160_self_test },
#endif
#if defined(MBEDTLS_SHA1_C)
{ "sha1", mbedtls_sha1_self_test },
#endif
#if defined(MBEDTLS_SHA224_C)
{ "sha224", mbedtls_sha224_self_test },
#endif
#if defined(MBEDTLS_SHA256_C)
{ "sha256", mbedtls_sha256_self_test },
#endif
#if defined(MBEDTLS_SHA384_C)
{ "sha384", mbedtls_sha384_self_test },
#endif
#if defined(MBEDTLS_SHA512_C)
{ "sha512", mbedtls_sha512_self_test },
#endif
#if defined(MBEDTLS_SHA3_C)
{ "sha3", mbedtls_sha3_self_test },
#endif
#if defined(MBEDTLS_DES_C)
{ "des", mbedtls_des_self_test },
#endif
#if defined(MBEDTLS_AES_C)
{ "aes", mbedtls_aes_self_test },
#endif
#if defined(MBEDTLS_GCM_C) && defined(MBEDTLS_AES_C)
{ "gcm", mbedtls_gcm_self_test },
#endif
#if defined(MBEDTLS_CCM_C) && defined(MBEDTLS_AES_C)
{ "ccm", mbedtls_ccm_self_test },
#endif
#if defined(MBEDTLS_NIST_KW_C) && defined(MBEDTLS_AES_C)
{ "nist_kw", mbedtls_nist_kw_self_test },
#endif
#if defined(MBEDTLS_CMAC_C)
{ "cmac", mbedtls_cmac_self_test },
#endif
#if defined(MBEDTLS_CHACHA20_C)
{ "chacha20", mbedtls_chacha20_self_test },
#endif
#if defined(MBEDTLS_POLY1305_C)
{ "poly1305", mbedtls_poly1305_self_test },
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
{ "chacha20-poly1305", mbedtls_chachapoly_self_test },
#endif
#if defined(MBEDTLS_BASE64_C)
{ "base64", mbedtls_base64_self_test },
#endif
#if defined(MBEDTLS_BIGNUM_C)
{ "mpi", mbedtls_mpi_self_test },
#endif
#if defined(MBEDTLS_RSA_C)
{ "rsa", mbedtls_rsa_self_test },
#endif
#if defined(MBEDTLS_CAMELLIA_C)
{ "camellia", mbedtls_camellia_self_test },
#endif
#if defined(MBEDTLS_ARIA_C)
{ "aria", mbedtls_aria_self_test },
#endif
#if defined(MBEDTLS_CTR_DRBG_C)
{ "ctr_drbg", mbedtls_ctr_drbg_self_test },
#endif
#if defined(MBEDTLS_HMAC_DRBG_C)
{ "hmac_drbg", mbedtls_hmac_drbg_self_test },
#endif
#if defined(MBEDTLS_ECP_C)
{ "ecp", mbedtls_ecp_self_test },
#endif
#if defined(MBEDTLS_ECJPAKE_C)
{ "ecjpake", mbedtls_ecjpake_self_test },
#endif
#if defined(MBEDTLS_DHM_C)
{ "dhm", mbedtls_dhm_self_test },
#endif
#if defined(MBEDTLS_ENTROPY_C)
{ "entropy", mbedtls_entropy_self_test_wrapper },
#endif
#if defined(MBEDTLS_PKCS5_C)
{ "pkcs5", mbedtls_pkcs5_self_test },
#endif
/* Heap test comes last */
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
{ "memory_buffer_alloc", mbedtls_memory_buffer_alloc_free_and_self_test },
#endif
{ NULL, NULL }
};
#endif /* MBEDTLS_SELF_TEST */
int main(int argc, char *argv[])
{
#if defined(MBEDTLS_SELF_TEST)
const selftest_t *test;
#endif /* MBEDTLS_SELF_TEST */
char **argp;
int v = 1; /* v=1 for verbose mode */
int exclude_mode = 0;
int suites_tested = 0, suites_failed = 0;
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && defined(MBEDTLS_SELF_TEST)
unsigned char buf[1000000];
#endif
void *pointer;
/*
* Check some basic platform requirements as specified in README.md
*/
if (SIZE_MAX < INT_MAX || SIZE_MAX < UINT_MAX) {
mbedtls_printf("SIZE_MAX must be at least as big as INT_MAX and UINT_MAX\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
if (sizeof(int) < 4) {
mbedtls_printf("int must be at least 32 bits\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
if (sizeof(size_t) < 4) {
mbedtls_printf("size_t must be at least 32 bits\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
uint32_t endian_test = 0x12345678;
char *p = (char *) &endian_test;
if (!(p[0] == 0x12 && p[1] == 0x34 && p[2] == 0x56 && p[3] == 0x78) &&
!(p[3] == 0x12 && p[2] == 0x34 && p[1] == 0x56 && p[0] == 0x78)) {
mbedtls_printf("Mixed-endian platforms are not supported\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
/*
* The C standard doesn't guarantee that all-bits-0 is the representation
* of a NULL pointer. We do however use that in our code for initializing
* structures, which should work on every modern platform. Let's be sure.
*/
memset(&pointer, 0, sizeof(void *));
if (pointer != NULL) {
mbedtls_printf("all-bits-zero is not a NULL pointer\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
/*
* The C standard allows padding bits in the representation
* of standard integer types, but our code does currently not
* support them.
*
* Here we check that the underlying C implementation doesn't
* use padding bits, and fail cleanly if it does.
*
* The check works by casting the maximum value representable
* by a given integer type into the unpadded integer type of the
* same bit-width and checking that it agrees with the maximum value
* of that unpadded type. For example, for a 4-byte int,
* MAX_INT should be 0x7fffffff in int32_t. This assumes that
* CHAR_BIT == 8, which is checked in check_config.h.
*
* We assume that [u]intxx_t exist and that they don't
* have padding bits, as the standard requires.
*/
#define CHECK_PADDING_SIGNED(TYPE, NAME) \
do \
{ \
if (sizeof(TYPE) == 2 || sizeof(TYPE) == 4 || \
sizeof(TYPE) == 8) { \
if ((sizeof(TYPE) == 2 && \
(int16_t) NAME ## _MAX != 0x7FFF) || \
(sizeof(TYPE) == 4 && \
(int32_t) NAME ## _MAX != 0x7FFFFFFF) || \
(sizeof(TYPE) == 8 && \
(int64_t) NAME ## _MAX != 0x7FFFFFFFFFFFFFFF)) \
{ \
mbedtls_printf("Type '" #TYPE "' has padding bits\n"); \
mbedtls_exit(MBEDTLS_EXIT_FAILURE); \
} \
} else { \
mbedtls_printf("Padding checks only implemented for types of size 2, 4 or 8" \
" - cannot check type '" #TYPE "' of size %" MBEDTLS_PRINTF_SIZET "\n", \
sizeof(TYPE)); \
mbedtls_exit(MBEDTLS_EXIT_FAILURE); \
} \
} while (0)
#define CHECK_PADDING_UNSIGNED(TYPE, NAME) \
do \
{ \
if ((sizeof(TYPE) == 2 && \
(uint16_t) NAME ## _MAX != 0xFFFF) || \
(sizeof(TYPE) == 4 && \
(uint32_t) NAME ## _MAX != 0xFFFFFFFF) || \
(sizeof(TYPE) == 8 && \
(uint64_t) NAME ## _MAX != 0xFFFFFFFFFFFFFFFF)) \
{ \
mbedtls_printf("Type '" #TYPE "' has padding bits\n"); \
mbedtls_exit(MBEDTLS_EXIT_FAILURE); \
} \
} while (0)
CHECK_PADDING_SIGNED(short, SHRT);
CHECK_PADDING_SIGNED(int, INT);
CHECK_PADDING_SIGNED(long, LONG);
CHECK_PADDING_SIGNED(long long, LLONG);
CHECK_PADDING_SIGNED(ptrdiff_t, PTRDIFF);
CHECK_PADDING_UNSIGNED(unsigned short, USHRT);
CHECK_PADDING_UNSIGNED(unsigned, UINT);
CHECK_PADDING_UNSIGNED(unsigned long, ULONG);
CHECK_PADDING_UNSIGNED(unsigned long long, ULLONG);
CHECK_PADDING_UNSIGNED(size_t, SIZE);
#undef CHECK_PADDING_SIGNED
#undef CHECK_PADDING_UNSIGNED
/*
* Make sure we have a snprintf that correctly zero-terminates
*/
if (run_test_snprintf() != 0) {
mbedtls_printf("the snprintf implementation is broken\n");
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
for (argp = argv + (argc >= 1 ? 1 : argc); *argp != NULL; ++argp) {
if (strcmp(*argp, "--quiet") == 0 ||
strcmp(*argp, "-q") == 0) {
v = 0;
} else if (strcmp(*argp, "--exclude") == 0 ||
strcmp(*argp, "-x") == 0) {
exclude_mode = 1;
} else {
break;
}
}
if (v != 0) {
mbedtls_printf("\n");
}
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
mbedtls_memory_buffer_alloc_init(buf, sizeof(buf));
#endif
if (*argp != NULL && exclude_mode == 0) {
/* Run the specified tests */
for (; *argp != NULL; argp++) {
for (test = selftests; test->name != NULL; test++) {
if (!strcmp(*argp, test->name)) {
if (test->function(v) != 0) {
suites_failed++;
}
suites_tested++;
break;
}
}
if (test->name == NULL) {
mbedtls_printf(" Test suite %s not available -> failed\n\n", *argp);
suites_failed++;
}
}
} else {
/* Run all the tests except excluded ones */
for (test = selftests; test->name != NULL; test++) {
if (exclude_mode) {
char **excluded;
for (excluded = argp; *excluded != NULL; ++excluded) {
if (!strcmp(*excluded, test->name)) {
break;
}
}
if (*excluded) {
if (v) {
mbedtls_printf(" Skip: %s\n", test->name);
}
continue;
}
}
if (test->function(v) != 0) {
suites_failed++;
}
suites_tested++;
}
}
#else
(void) exclude_mode;
mbedtls_printf(" MBEDTLS_SELF_TEST not defined.\n");
#endif
if (v != 0) {
mbedtls_printf(" Executed %d test suites\n\n", suites_tested);
if (suites_failed > 0) {
mbedtls_printf(" [ %d tests FAIL ]\n\n", suites_failed);
} else {
mbedtls_printf(" [ All tests PASS ]\n\n");
}
}
if (suites_failed > 0) {
mbedtls_exit(MBEDTLS_EXIT_FAILURE);
}
mbedtls_exit(MBEDTLS_EXIT_SUCCESS);
}

View File

@@ -0,0 +1,966 @@
/*
* UDP proxy: emulate an unreliable UDP connection for DTLS testing
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/*
* Warning: this is an internal utility program we use for tests.
* It does break some abstractions from the NET layer, and is thus NOT an
* example of good general usage.
*/
#include "mbedtls/build_info.h"
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#include <stdlib.h>
#if defined(MBEDTLS_HAVE_TIME)
#include <time.h>
#define mbedtls_time time
#define mbedtls_time_t time_t
#endif
#define mbedtls_printf printf
#define mbedtls_calloc calloc
#define mbedtls_free free
#define mbedtls_exit exit
#define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS
#define MBEDTLS_EXIT_FAILURE EXIT_FAILURE
#endif /* MBEDTLS_PLATFORM_C */
#if !defined(MBEDTLS_NET_C)
int main(void)
{
mbedtls_printf("MBEDTLS_NET_C not defined.\n");
mbedtls_exit(0);
}
#else
#include "mbedtls/net_sockets.h"
#include "mbedtls/error.h"
#include "mbedtls/ssl.h"
#include "mbedtls/timing.h"
#include <string.h>
/* For select() */
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
#include <winsock2.h>
#include <windows.h>
#if defined(_MSC_VER)
#if defined(_WIN32_WCE)
#pragma comment( lib, "ws2.lib" )
#else
#pragma comment( lib, "ws2_32.lib" )
#endif
#endif /* _MSC_VER */
#else /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
#if defined(MBEDTLS_HAVE_TIME) || (defined(MBEDTLS_TIMING_C) && !defined(MBEDTLS_TIMING_ALT))
#include <sys/time.h>
#endif
#include <sys/select.h>
#include <sys/types.h>
#include <unistd.h>
#endif /* ( _WIN32 || _WIN32_WCE ) && !EFIX64 && !EFI32 */
#define MAX_MSG_SIZE 16384 + 2048 /* max record/datagram size */
#define DFL_SERVER_ADDR "localhost"
#define DFL_SERVER_PORT "4433"
#define DFL_LISTEN_ADDR "localhost"
#define DFL_LISTEN_PORT "5556"
#define DFL_PACK 0
#if defined(MBEDTLS_TIMING_C)
#define USAGE_PACK \
" pack=%%d default: 0 (don't pack)\n" \
" options: t > 0 (pack for t milliseconds)\n"
#else
#define USAGE_PACK
#endif
#define USAGE \
"\n usage: udp_proxy param=<>...\n" \
"\n acceptable parameters:\n" \
" server_addr=%%s default: localhost\n" \
" server_port=%%d default: 4433\n" \
" listen_addr=%%s default: localhost\n" \
" listen_port=%%d default: 4433\n" \
"\n" \
" duplicate=%%d default: 0 (no duplication)\n" \
" duplicate about 1:N packets randomly\n" \
" delay=%%d default: 0 (no delayed packets)\n" \
" delay about 1:N packets randomly\n" \
" delay_ccs=0/1 default: 0 (don't delay ChangeCipherSpec)\n" \
" delay_cli=%%s Handshake message from client that should be\n" \
" delayed. Possible values are 'ClientHello',\n" \
" 'Certificate', 'CertificateVerify', and\n" \
" 'ClientKeyExchange'.\n" \
" May be used multiple times, even for the same\n" \
" message, in which case the respective message\n" \
" gets delayed multiple times.\n" \
" delay_srv=%%s Handshake message from server that should be\n" \
" delayed. Possible values are 'HelloRequest',\n" \
" 'ServerHello', 'ServerHelloDone', 'Certificate'\n" \
" 'ServerKeyExchange', 'NewSessionTicket',\n" \
" 'HelloVerifyRequest' and ''CertificateRequest'.\n" \
" May be used multiple times, even for the same\n" \
" message, in which case the respective message\n" \
" gets delayed multiple times.\n" \
" drop=%%d default: 0 (no dropped packets)\n" \
" drop about 1:N packets randomly\n" \
" mtu=%%d default: 0 (unlimited)\n" \
" drop packets larger than N bytes\n" \
" bad_ad=0/1 default: 0 (don't add bad ApplicationData)\n" \
" bad_cid=%%d default: 0 (don't corrupt Connection IDs)\n" \
" duplicate 1:N packets containing a CID,\n" \
" modifying CID in first instance of the packet.\n" \
" protect_hvr=0/1 default: 0 (don't protect HelloVerifyRequest)\n" \
" protect_len=%%d default: (don't protect packets of this size)\n" \
" inject_clihlo=0/1 default: 0 (don't inject fake ClientHello)\n" \
"\n" \
" seed=%%d default: (use current time)\n" \
USAGE_PACK \
"\n"
/*
* global options
*/
#define MAX_DELAYED_HS 10
static struct options {
const char *server_addr; /* address to forward packets to */
const char *server_port; /* port to forward packets to */
const char *listen_addr; /* address for accepting client connections */
const char *listen_port; /* port for accepting client connections */
int duplicate; /* duplicate 1 in N packets (none if 0) */
int delay; /* delay 1 packet in N (none if 0) */
int delay_ccs; /* delay ChangeCipherSpec */
char *delay_cli[MAX_DELAYED_HS]; /* handshake types of messages from
* client that should be delayed. */
uint8_t delay_cli_cnt; /* Number of entries in delay_cli. */
char *delay_srv[MAX_DELAYED_HS]; /* handshake types of messages from
* server that should be delayed. */
uint8_t delay_srv_cnt; /* Number of entries in delay_srv. */
int drop; /* drop 1 packet in N (none if 0) */
int mtu; /* drop packets larger than this */
int bad_ad; /* inject corrupted ApplicationData record */
unsigned bad_cid; /* inject corrupted CID record */
int protect_hvr; /* never drop or delay HelloVerifyRequest */
int protect_len; /* never drop/delay packet of the given size*/
int inject_clihlo; /* inject fake ClientHello after handshake */
unsigned pack; /* merge packets into single datagram for
* at most \c merge milliseconds if > 0 */
unsigned int seed; /* seed for "random" events */
} opt;
static void exit_usage(const char *name, const char *value)
{
if (value == NULL) {
mbedtls_printf(" unknown option or missing value: %s\n", name);
} else {
mbedtls_printf(" option %s: illegal value: %s\n", name, value);
}
mbedtls_printf(USAGE);
mbedtls_exit(1);
}
static void get_options(int argc, char *argv[])
{
int i;
char *p, *q;
opt.server_addr = DFL_SERVER_ADDR;
opt.server_port = DFL_SERVER_PORT;
opt.listen_addr = DFL_LISTEN_ADDR;
opt.listen_port = DFL_LISTEN_PORT;
opt.pack = DFL_PACK;
/* Other members default to 0 */
opt.delay_cli_cnt = 0;
opt.delay_srv_cnt = 0;
memset(opt.delay_cli, 0, sizeof(opt.delay_cli));
memset(opt.delay_srv, 0, sizeof(opt.delay_srv));
for (i = 1; i < argc; i++) {
p = argv[i];
if ((q = strchr(p, '=')) == NULL) {
exit_usage(p, NULL);
}
*q++ = '\0';
if (strcmp(p, "server_addr") == 0) {
opt.server_addr = q;
} else if (strcmp(p, "server_port") == 0) {
opt.server_port = q;
} else if (strcmp(p, "listen_addr") == 0) {
opt.listen_addr = q;
} else if (strcmp(p, "listen_port") == 0) {
opt.listen_port = q;
} else if (strcmp(p, "duplicate") == 0) {
opt.duplicate = atoi(q);
if (opt.duplicate < 0 || opt.duplicate > 20) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay") == 0) {
opt.delay = atoi(q);
if (opt.delay < 0 || opt.delay > 20 || opt.delay == 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay_ccs") == 0) {
opt.delay_ccs = atoi(q);
if (opt.delay_ccs < 0 || opt.delay_ccs > 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "delay_cli") == 0 ||
strcmp(p, "delay_srv") == 0) {
uint8_t *delay_cnt;
char **delay_list;
size_t len;
char *buf;
if (strcmp(p, "delay_cli") == 0) {
delay_cnt = &opt.delay_cli_cnt;
delay_list = opt.delay_cli;
} else {
delay_cnt = &opt.delay_srv_cnt;
delay_list = opt.delay_srv;
}
if (*delay_cnt == MAX_DELAYED_HS) {
mbedtls_printf(" too many uses of %s: only %d allowed\n",
p, MAX_DELAYED_HS);
exit_usage(p, NULL);
}
len = strlen(q);
buf = mbedtls_calloc(1, len + 1);
if (buf == NULL) {
mbedtls_printf(" Allocation failure\n");
exit(1);
}
memcpy(buf, q, len + 1);
delay_list[(*delay_cnt)++] = buf;
} else if (strcmp(p, "drop") == 0) {
opt.drop = atoi(q);
if (opt.drop < 0 || opt.drop > 20 || opt.drop == 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "pack") == 0) {
#if defined(MBEDTLS_TIMING_C)
opt.pack = (unsigned) atoi(q);
#else
mbedtls_printf(" option pack only defined if MBEDTLS_TIMING_C is enabled\n");
exit(1);
#endif
} else if (strcmp(p, "mtu") == 0) {
opt.mtu = atoi(q);
if (opt.mtu < 0 || opt.mtu > MAX_MSG_SIZE) {
exit_usage(p, q);
}
} else if (strcmp(p, "bad_ad") == 0) {
opt.bad_ad = atoi(q);
if (opt.bad_ad < 0 || opt.bad_ad > 1) {
exit_usage(p, q);
}
}
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
else if (strcmp(p, "bad_cid") == 0) {
opt.bad_cid = (unsigned) atoi(q);
}
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
else if (strcmp(p, "protect_hvr") == 0) {
opt.protect_hvr = atoi(q);
if (opt.protect_hvr < 0 || opt.protect_hvr > 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "protect_len") == 0) {
opt.protect_len = atoi(q);
if (opt.protect_len < 0) {
exit_usage(p, q);
}
} else if (strcmp(p, "inject_clihlo") == 0) {
opt.inject_clihlo = atoi(q);
if (opt.inject_clihlo < 0 || opt.inject_clihlo > 1) {
exit_usage(p, q);
}
} else if (strcmp(p, "seed") == 0) {
opt.seed = atoi(q);
if (opt.seed == 0) {
exit_usage(p, q);
}
} else {
exit_usage(p, NULL);
}
}
}
static const char *msg_type(unsigned char *msg, size_t len)
{
if (len < 1) {
return "Invalid";
}
switch (msg[0]) {
case MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC: return "ChangeCipherSpec";
case MBEDTLS_SSL_MSG_ALERT: return "Alert";
case MBEDTLS_SSL_MSG_APPLICATION_DATA: return "ApplicationData";
case MBEDTLS_SSL_MSG_CID: return "CID";
case MBEDTLS_SSL_MSG_HANDSHAKE: break; /* See below */
default: return "Unknown";
}
if (len < 13 + 12) {
return "Invalid handshake";
}
/*
* Our handshake message are less than 2^16 bytes long, so they should
* have 0 as the first byte of length, frag_offset and frag_length.
* Otherwise, assume they are encrypted.
*/
if (msg[14] || msg[19] || msg[22]) {
return "Encrypted handshake";
}
switch (msg[13]) {
case MBEDTLS_SSL_HS_HELLO_REQUEST: return "HelloRequest";
case MBEDTLS_SSL_HS_CLIENT_HELLO: return "ClientHello";
case MBEDTLS_SSL_HS_SERVER_HELLO: return "ServerHello";
case MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST: return "HelloVerifyRequest";
case MBEDTLS_SSL_HS_NEW_SESSION_TICKET: return "NewSessionTicket";
case MBEDTLS_SSL_HS_CERTIFICATE: return "Certificate";
case MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE: return "ServerKeyExchange";
case MBEDTLS_SSL_HS_CERTIFICATE_REQUEST: return "CertificateRequest";
case MBEDTLS_SSL_HS_SERVER_HELLO_DONE: return "ServerHelloDone";
case MBEDTLS_SSL_HS_CERTIFICATE_VERIFY: return "CertificateVerify";
case MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE: return "ClientKeyExchange";
case MBEDTLS_SSL_HS_FINISHED: return "Finished";
default: return "Unknown handshake";
}
}
#if defined(MBEDTLS_TIMING_C)
/* Return elapsed time in milliseconds since the first call */
static unsigned elapsed_time(void)
{
static int initialized = 0;
static struct mbedtls_timing_hr_time hires;
if (initialized == 0) {
(void) mbedtls_timing_get_timer(&hires, 1);
initialized = 1;
return 0;
}
return mbedtls_timing_get_timer(&hires, 0);
}
typedef struct {
mbedtls_net_context *ctx;
const char *description;
unsigned packet_lifetime;
unsigned num_datagrams;
unsigned char data[MAX_MSG_SIZE];
size_t len;
} ctx_buffer;
static ctx_buffer outbuf[2];
static int ctx_buffer_flush(ctx_buffer *buf)
{
int ret;
mbedtls_printf(" %05u flush %s: %u bytes, %u datagrams, last %u ms\n",
elapsed_time(), buf->description,
(unsigned) buf->len, buf->num_datagrams,
elapsed_time() - buf->packet_lifetime);
ret = mbedtls_net_send(buf->ctx, buf->data, buf->len);
buf->len = 0;
buf->num_datagrams = 0;
return ret;
}
static unsigned ctx_buffer_time_remaining(ctx_buffer *buf)
{
unsigned const cur_time = elapsed_time();
if (buf->num_datagrams == 0) {
return (unsigned) -1;
}
if (cur_time - buf->packet_lifetime >= opt.pack) {
return 0;
}
return opt.pack - (cur_time - buf->packet_lifetime);
}
static int ctx_buffer_append(ctx_buffer *buf,
const unsigned char *data,
size_t len)
{
int ret;
if (len > (size_t) INT_MAX) {
return -1;
}
if (len > sizeof(buf->data)) {
mbedtls_printf(" ! buffer size %u too large (max %u)\n",
(unsigned) len, (unsigned) sizeof(buf->data));
return -1;
}
if (sizeof(buf->data) - buf->len < len) {
if ((ret = ctx_buffer_flush(buf)) <= 0) {
mbedtls_printf("ctx_buffer_flush failed with -%#04x", (unsigned int) -ret);
return ret;
}
}
memcpy(buf->data + buf->len, data, len);
buf->len += len;
if (++buf->num_datagrams == 1) {
buf->packet_lifetime = elapsed_time();
}
return (int) len;
}
#endif /* MBEDTLS_TIMING_C */
static int dispatch_data(mbedtls_net_context *ctx,
const unsigned char *data,
size_t len)
{
int ret;
#if defined(MBEDTLS_TIMING_C)
ctx_buffer *buf = NULL;
if (opt.pack > 0) {
if (outbuf[0].ctx == ctx) {
buf = &outbuf[0];
} else if (outbuf[1].ctx == ctx) {
buf = &outbuf[1];
}
if (buf == NULL) {
return -1;
}
return ctx_buffer_append(buf, data, len);
}
#endif /* MBEDTLS_TIMING_C */
ret = mbedtls_net_send(ctx, data, len);
if (ret < 0) {
mbedtls_printf("net_send returned -%#04x\n", (unsigned int) -ret);
}
return ret;
}
typedef struct {
mbedtls_net_context *dst;
const char *way;
const char *type;
unsigned len;
unsigned char buf[MAX_MSG_SIZE];
} packet;
/* Print packet. Outgoing packets come with a reason (forward, dupl, etc.) */
void print_packet(const packet *p, const char *why)
{
#if defined(MBEDTLS_TIMING_C)
if (why == NULL) {
mbedtls_printf(" %05u dispatch %s %s (%u bytes)\n",
elapsed_time(), p->way, p->type, p->len);
} else {
mbedtls_printf(" %05u dispatch %s %s (%u bytes): %s\n",
elapsed_time(), p->way, p->type, p->len, why);
}
#else
if (why == NULL) {
mbedtls_printf(" dispatch %s %s (%u bytes)\n",
p->way, p->type, p->len);
} else {
mbedtls_printf(" dispatch %s %s (%u bytes): %s\n",
p->way, p->type, p->len, why);
}
#endif
fflush(stdout);
}
/*
* In order to test the server's behaviour when receiving a ClientHello after
* the connection is established (this could be a hard reset from the client,
* but the server must not drop the existing connection before establishing
* client reachability, see RFC 6347 Section 4.2.8), we memorize the first
* ClientHello we see (which can't have a cookie), then replay it after the
* first ApplicationData record - then we're done.
*
* This is controlled by the inject_clihlo option.
*
* We want an explicit state and a place to store the packet.
*/
typedef enum {
ICH_INIT, /* haven't seen the first ClientHello yet */
ICH_CACHED, /* cached the initial ClientHello */
ICH_INJECTED, /* ClientHello already injected, done */
} inject_clihlo_state_t;
static inject_clihlo_state_t inject_clihlo_state;
static packet initial_clihlo;
int send_packet(const packet *p, const char *why)
{
int ret;
mbedtls_net_context *dst = p->dst;
/* save initial ClientHello? */
if (opt.inject_clihlo != 0 &&
inject_clihlo_state == ICH_INIT &&
strcmp(p->type, "ClientHello") == 0) {
memcpy(&initial_clihlo, p, sizeof(packet));
inject_clihlo_state = ICH_CACHED;
}
/* insert corrupted CID record? */
if (opt.bad_cid != 0 &&
strcmp(p->type, "CID") == 0 &&
(rand() % opt.bad_cid) == 0) {
unsigned char buf[MAX_MSG_SIZE];
memcpy(buf, p->buf, p->len);
/* The CID resides at offset 11 in the DTLS record header. */
buf[11] ^= 1;
print_packet(p, "modified CID");
if ((ret = dispatch_data(dst, buf, p->len)) <= 0) {
mbedtls_printf(" ! dispatch returned %d\n", ret);
return ret;
}
}
/* insert corrupted ApplicationData record? */
if (opt.bad_ad &&
strcmp(p->type, "ApplicationData") == 0) {
unsigned char buf[MAX_MSG_SIZE];
memcpy(buf, p->buf, p->len);
if (p->len <= 13) {
mbedtls_printf(" ! can't corrupt empty AD record");
} else {
++buf[13];
print_packet(p, "corrupted");
}
if ((ret = dispatch_data(dst, buf, p->len)) <= 0) {
mbedtls_printf(" ! dispatch returned %d\n", ret);
return ret;
}
}
print_packet(p, why);
if ((ret = dispatch_data(dst, p->buf, p->len)) <= 0) {
mbedtls_printf(" ! dispatch returned %d\n", ret);
return ret;
}
/* Don't duplicate Application Data, only handshake covered */
if (opt.duplicate != 0 &&
strcmp(p->type, "ApplicationData") != 0 &&
rand() % opt.duplicate == 0) {
print_packet(p, "duplicated");
if ((ret = dispatch_data(dst, p->buf, p->len)) <= 0) {
mbedtls_printf(" ! dispatch returned %d\n", ret);
return ret;
}
}
/* Inject ClientHello after first ApplicationData */
if (opt.inject_clihlo != 0 &&
inject_clihlo_state == ICH_CACHED &&
strcmp(p->type, "ApplicationData") == 0) {
print_packet(&initial_clihlo, "injected");
if ((ret = dispatch_data(dst, initial_clihlo.buf,
initial_clihlo.len)) <= 0) {
mbedtls_printf(" ! dispatch returned %d\n", ret);
return ret;
}
inject_clihlo_state = ICH_INJECTED;
}
return 0;
}
#define MAX_DELAYED_MSG 5
static size_t prev_len;
static packet prev[MAX_DELAYED_MSG];
void clear_pending(void)
{
memset(&prev, 0, sizeof(prev));
prev_len = 0;
}
void delay_packet(packet *delay)
{
if (prev_len == MAX_DELAYED_MSG) {
return;
}
memcpy(&prev[prev_len++], delay, sizeof(packet));
}
int send_delayed(void)
{
uint8_t offset;
int ret;
for (offset = 0; offset < prev_len; offset++) {
ret = send_packet(&prev[offset], "delayed");
if (ret != 0) {
return ret;
}
}
clear_pending();
return 0;
}
/*
* Avoid dropping or delaying a packet that was already dropped or delayed
* ("held") twice: this only results in uninteresting timeouts. We can't rely
* on type to identify packets, since during renegotiation they're all
* encrypted. So, rely on size mod 2048 (which is usually just size).
*
* We only hold packets at the level of entire datagrams, not at the level
* of records. In particular, if the peer changes the way it packs multiple
* records into a single datagram, we don't necessarily count the number of
* times a record has been held correctly. However, the only known reason
* why a peer would change datagram packing is disabling the latter on
* retransmission, in which case we'd hold involved records at most
* HOLD_MAX + 1 times.
*/
static unsigned char held[2048] = { 0 };
#define HOLD_MAX 2
int handle_message(const char *way,
mbedtls_net_context *dst,
mbedtls_net_context *src)
{
int ret;
packet cur;
size_t id;
uint8_t delay_idx;
char **delay_list;
uint8_t delay_list_len;
/* receive packet */
if ((ret = mbedtls_net_recv(src, cur.buf, sizeof(cur.buf))) <= 0) {
mbedtls_printf(" ! mbedtls_net_recv returned %d\n", ret);
return ret;
}
cur.len = ret;
cur.type = msg_type(cur.buf, cur.len);
cur.way = way;
cur.dst = dst;
print_packet(&cur, NULL);
id = cur.len % sizeof(held);
if (strcmp(way, "S <- C") == 0) {
delay_list = opt.delay_cli;
delay_list_len = opt.delay_cli_cnt;
} else {
delay_list = opt.delay_srv;
delay_list_len = opt.delay_srv_cnt;
}
/* Check if message type is in the list of messages
* that should be delayed */
for (delay_idx = 0; delay_idx < delay_list_len; delay_idx++) {
if (delay_list[delay_idx] == NULL) {
continue;
}
if (strcmp(delay_list[delay_idx], cur.type) == 0) {
/* Delay message */
delay_packet(&cur);
/* Remove entry from list */
mbedtls_free(delay_list[delay_idx]);
delay_list[delay_idx] = NULL;
return 0;
}
}
/* do we want to drop, delay, or forward it? */
if ((opt.mtu != 0 &&
cur.len > (unsigned) opt.mtu) ||
(opt.drop != 0 &&
strcmp(cur.type, "CID") != 0 &&
strcmp(cur.type, "ApplicationData") != 0 &&
!(opt.protect_hvr &&
strcmp(cur.type, "HelloVerifyRequest") == 0) &&
cur.len != (size_t) opt.protect_len &&
held[id] < HOLD_MAX &&
rand() % opt.drop == 0)) {
++held[id];
} else if ((opt.delay_ccs == 1 &&
strcmp(cur.type, "ChangeCipherSpec") == 0) ||
(opt.delay != 0 &&
strcmp(cur.type, "CID") != 0 &&
strcmp(cur.type, "ApplicationData") != 0 &&
!(opt.protect_hvr &&
strcmp(cur.type, "HelloVerifyRequest") == 0) &&
cur.len != (size_t) opt.protect_len &&
held[id] < HOLD_MAX &&
rand() % opt.delay == 0)) {
++held[id];
delay_packet(&cur);
} else {
/* forward and possibly duplicate */
if ((ret = send_packet(&cur, "forwarded")) != 0) {
return ret;
}
/* send previously delayed messages if any */
ret = send_delayed();
if (ret != 0) {
return ret;
}
}
return 0;
}
int main(int argc, char *argv[])
{
int ret = 1;
int exit_code = MBEDTLS_EXIT_FAILURE;
uint8_t delay_idx;
mbedtls_net_context listen_fd, client_fd, server_fd;
#if defined(MBEDTLS_TIMING_C)
struct timeval tm;
#endif
struct timeval *tm_ptr = NULL;
int nb_fds;
fd_set read_fds;
mbedtls_net_init(&listen_fd);
mbedtls_net_init(&client_fd);
mbedtls_net_init(&server_fd);
get_options(argc, argv);
/*
* Decisions to drop/delay/duplicate packets are pseudo-random: dropping
* exactly 1 in N packets would lead to problems when a flight has exactly
* N packets: the same packet would be dropped on every resend.
*
* In order to be able to reproduce problems reliably, the seed may be
* specified explicitly.
*/
if (opt.seed == 0) {
#if defined(MBEDTLS_HAVE_TIME)
opt.seed = (unsigned int) mbedtls_time(NULL);
#else
opt.seed = 1;
#endif /* MBEDTLS_HAVE_TIME */
mbedtls_printf(" . Pseudo-random seed: %u\n", opt.seed);
}
srand(opt.seed);
/*
* 0. "Connect" to the server
*/
mbedtls_printf(" . Connect to server on UDP/%s/%s ...",
opt.server_addr, opt.server_port);
fflush(stdout);
if ((ret = mbedtls_net_connect(&server_fd, opt.server_addr, opt.server_port,
MBEDTLS_NET_PROTO_UDP)) != 0) {
mbedtls_printf(" failed\n ! mbedtls_net_connect returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 1. Setup the "listening" UDP socket
*/
mbedtls_printf(" . Bind on UDP/%s/%s ...",
opt.listen_addr, opt.listen_port);
fflush(stdout);
if ((ret = mbedtls_net_bind(&listen_fd, opt.listen_addr, opt.listen_port,
MBEDTLS_NET_PROTO_UDP)) != 0) {
mbedtls_printf(" failed\n ! mbedtls_net_bind returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 2. Wait until a client connects
*/
accept:
mbedtls_net_free(&client_fd);
mbedtls_printf(" . Waiting for a remote connection ...");
fflush(stdout);
if ((ret = mbedtls_net_accept(&listen_fd, &client_fd,
NULL, 0, NULL)) != 0) {
mbedtls_printf(" failed\n ! mbedtls_net_accept returned %d\n\n", ret);
goto exit;
}
mbedtls_printf(" ok\n");
/*
* 3. Forward packets forever (kill the process to terminate it)
*/
clear_pending();
memset(held, 0, sizeof(held));
nb_fds = client_fd.fd;
if (nb_fds < server_fd.fd) {
nb_fds = server_fd.fd;
}
if (nb_fds < listen_fd.fd) {
nb_fds = listen_fd.fd;
}
++nb_fds;
#if defined(MBEDTLS_TIMING_C)
if (opt.pack > 0) {
outbuf[0].ctx = &server_fd;
outbuf[0].description = "S <- C";
outbuf[0].num_datagrams = 0;
outbuf[0].len = 0;
outbuf[1].ctx = &client_fd;
outbuf[1].description = "S -> C";
outbuf[1].num_datagrams = 0;
outbuf[1].len = 0;
}
#endif /* MBEDTLS_TIMING_C */
while (1) {
#if defined(MBEDTLS_TIMING_C)
if (opt.pack > 0) {
unsigned max_wait_server, max_wait_client, max_wait;
max_wait_server = ctx_buffer_time_remaining(&outbuf[0]);
max_wait_client = ctx_buffer_time_remaining(&outbuf[1]);
max_wait = (unsigned) -1;
if (max_wait_server == 0) {
ctx_buffer_flush(&outbuf[0]);
} else {
max_wait = max_wait_server;
}
if (max_wait_client == 0) {
ctx_buffer_flush(&outbuf[1]);
} else {
if (max_wait_client < max_wait) {
max_wait = max_wait_client;
}
}
if (max_wait != (unsigned) -1) {
tm.tv_sec = max_wait / 1000;
tm.tv_usec = (max_wait % 1000) * 1000;
tm_ptr = &tm;
} else {
tm_ptr = NULL;
}
}
#endif /* MBEDTLS_TIMING_C */
FD_ZERO(&read_fds);
FD_SET(server_fd.fd, &read_fds);
FD_SET(client_fd.fd, &read_fds);
FD_SET(listen_fd.fd, &read_fds);
if ((ret = select(nb_fds, &read_fds, NULL, NULL, tm_ptr)) < 0) {
perror("select");
goto exit;
}
if (FD_ISSET(listen_fd.fd, &read_fds)) {
goto accept;
}
if (FD_ISSET(client_fd.fd, &read_fds)) {
if ((ret = handle_message("S <- C",
&server_fd, &client_fd)) != 0) {
goto accept;
}
}
if (FD_ISSET(server_fd.fd, &read_fds)) {
if ((ret = handle_message("S -> C",
&client_fd, &server_fd)) != 0) {
goto accept;
}
}
}
exit_code = MBEDTLS_EXIT_SUCCESS;
exit:
#ifdef MBEDTLS_ERROR_C
if (exit_code != MBEDTLS_EXIT_SUCCESS) {
char error_buf[100];
mbedtls_strerror(ret, error_buf, 100);
mbedtls_printf("Last error was: -0x%04X - %s\n\n", (unsigned int) -ret, error_buf);
fflush(stdout);
}
#endif
for (delay_idx = 0; delay_idx < MAX_DELAYED_HS; delay_idx++) {
mbedtls_free(opt.delay_cli[delay_idx]);
mbedtls_free(opt.delay_srv[delay_idx]);
}
mbedtls_net_free(&client_fd);
mbedtls_net_free(&server_fd);
mbedtls_net_free(&listen_fd);
mbedtls_exit(exit_code);
}
#endif /* MBEDTLS_NET_C */

View File

@@ -0,0 +1,120 @@
#!/bin/sh
# -*-sh-basic-offset: 4-*-
# Usage: udp_proxy_wrapper.sh [PROXY_PARAM...] -- [SERVER_PARAM...]
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
set -u
MBEDTLS_BASE="$(dirname -- "$0")/../.."
TPXY_BIN="$MBEDTLS_BASE/programs/test/udp_proxy"
SRV_BIN="$MBEDTLS_BASE/programs/ssl/ssl_server2"
: ${VERBOSE:=0}
stop_proxy() {
if [ -n "${tpxy_pid:-}" ]; then
echo
echo " * Killing proxy (pid $tpxy_pid) ..."
kill $tpxy_pid
fi
}
stop_server() {
if [ -n "${srv_pid:-}" ]; then
echo
echo " * Killing server (pid $srv_pid) ..."
kill $srv_pid >/dev/null 2>/dev/null
fi
}
cleanup() {
stop_server
stop_proxy
exit 129
}
trap cleanup INT TERM HUP
# Extract the proxy parameters
tpxy_cmd_snippet='"$TPXY_BIN"'
while [ $# -ne 0 ] && [ "$1" != "--" ]; do
tail="$1" quoted=""
while [ -n "$tail" ]; do
case "$tail" in
*\'*) quoted="${quoted}${tail%%\'*}'\\''" tail="${tail#*\'}";;
*) quoted="${quoted}${tail}"; tail=; false;;
esac
done
tpxy_cmd_snippet="$tpxy_cmd_snippet '$quoted'"
shift
done
unset tail quoted
if [ $# -eq 0 ]; then
echo " * No server arguments (must be preceded by \" -- \") - exit"
exit 3
fi
shift
dtls_enabled=
ipv6_in_use=
server_port_orig=
server_addr_orig=
for param; do
case "$param" in
server_port=*) server_port_orig="${param#*=}";;
server_addr=*:*) server_addr_orig="${param#*=}"; ipv6_in_use=1;;
server_addr=*) server_addr_orig="${param#*=}";;
dtls=[!0]*) dtls_enabled=1;;
esac
done
if [ -z "$dtls_enabled" ] || [ -n "$ipv6_in_use" ]; then
echo >&2 "$0: Couldn't find DTLS enabling, or IPv6 is in use - immediate fallback to server application..."
if [ $VERBOSE -gt 0 ]; then
echo "[ $SRV_BIN $* ]"
fi
exec "$SRV_BIN" "$@"
fi
if [ -z "$server_port_orig" ]; then
server_port_orig=4433
fi
echo " * Server port: $server_port_orig"
tpxy_cmd_snippet="$tpxy_cmd_snippet \"listen_port=\$server_port_orig\""
tpxy_cmd_snippet="$tpxy_cmd_snippet \"server_port=\$server_port\""
if [ -n "$server_addr_orig" ]; then
echo " * Server address: $server_addr_orig"
tpxy_cmd_snippet="$tpxy_cmd_snippet \"server_addr=\$server_addr_orig\""
tpxy_cmd_snippet="$tpxy_cmd_snippet \"listen_addr=\$server_addr_orig\""
fi
server_port=$(( server_port_orig + 1 ))
set -- "$@" "server_port=$server_port"
echo " * Intermediate port: $server_port"
echo " * Start proxy in background ..."
if [ $VERBOSE -gt 0 ]; then
echo "[ $tpxy_cmd_snippet ]"
fi
eval exec "$tpxy_cmd_snippet" >/dev/null 2>&1 &
tpxy_pid=$!
if [ $VERBOSE -gt 0 ]; then
echo " * Proxy ID: $TPXY_PID"
fi
echo " * Starting server ..."
if [ $VERBOSE -gt 0 ]; then
echo "[ $SRV_BIN $* ]"
fi
exec "$SRV_BIN" "$@" >&2 &
srv_pid=$!
wait $srv_pid
stop_proxy
return 0

View File

@@ -0,0 +1,72 @@
/*
* Zeroize application for debugger-driven testing
*
* This is a simple test application used for debugger-driven testing to check
* whether calls to mbedtls_platform_zeroize() are being eliminated by compiler
* optimizations. This application is used by the GDB script at
* tests/scripts/test_zeroize.gdb: the script sets a breakpoint at the last
* return statement in the main() function of this program. The debugger
* facilities are then used to manually inspect the memory and verify that the
* call to mbedtls_platform_zeroize() was not eliminated.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
#include "mbedtls/build_info.h"
#include <stdio.h>
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#define BUFFER_LEN 1024
void usage(void)
{
mbedtls_printf("Zeroize is a simple program to assist with testing\n");
mbedtls_printf("the mbedtls_platform_zeroize() function by using the\n");
mbedtls_printf("debugger. This program takes a file as input and\n");
mbedtls_printf("prints the first %d characters. Usage:\n\n", BUFFER_LEN);
mbedtls_printf(" zeroize <FILE>\n");
}
int main(int argc, char **argv)
{
int exit_code = MBEDTLS_EXIT_FAILURE;
FILE *fp;
char buf[BUFFER_LEN];
char *p = buf;
char *end = p + BUFFER_LEN;
int c;
if (argc != 2) {
mbedtls_printf("This program takes exactly 1 argument\n");
usage();
mbedtls_exit(exit_code);
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
mbedtls_printf("Could not open file '%s'\n", argv[1]);
mbedtls_exit(exit_code);
}
while ((c = fgetc(fp)) != EOF && p < end - 1) {
*p++ = (char) c;
}
*p = '\0';
if (p - buf != 0) {
mbedtls_printf("%s\n", buf);
exit_code = MBEDTLS_EXIT_SUCCESS;
} else {
mbedtls_printf("The file is empty!\n");
}
fclose(fp);
mbedtls_platform_zeroize(buf, sizeof(buf));
mbedtls_exit(exit_code); // GDB_BREAK_HERE -- don't remove this comment!
}