Merge remote-tracking branch 'upstream/master' into zd20527

This commit is contained in:
Kareem
2025-09-25 10:37:22 -07:00
27 changed files with 3730 additions and 187 deletions

View File

@@ -28,3 +28,6 @@ jobs:
- name: Build Rust Wrapper
working-directory: wolfssl
run: make -C wrapper/rust
- name: Run Rust Wrapper Tests
working-directory: wolfssl
run: make -C wrapper/rust test

View File

@@ -1830,7 +1830,7 @@ double current_time(void)
(void) date;
/* return seconds.milliseconds */
return ((double) time.Hours * 24) + ((double) time.Minutes * 60)
return ((double) time.Hours * 3600) + ((double) time.Minutes * 60)
+ (double) time.Seconds + ((double) subsec / 1000);
}
#endif /* HAL_RTC_MODULE_ENABLED */

View File

@@ -91,7 +91,7 @@ openssl x509 -req -in server-sm2.csr -days 1000 -extfile ../renewcerts/wolfssl.c
check_result $? "Generate certificate"
rm server-sm2.csr
openssl x509 -in server-sm2-cert.pem -outform DER > server-sm2.der
openssl x509 -in server-sm2-cert.pem -outform DER > server-sm2-cert.der
check_result $? "Convert to DER"
openssl x509 -in server-sm2-cert.pem -text > tmp.pem
check_result $? "Add text"

Binary file not shown.

View File

@@ -48,9 +48,7 @@ AC_SUBST([WOLFSSL_CONFIG_ARGS])
# Store configure options and CFLAGS for debian rules generation
CONFIGURE_OPTIONS="$ac_configure_args"
CONFIGURE_CFLAGS="$CFLAGS"
AC_SUBST([CONFIGURE_OPTIONS])
AC_SUBST([CONFIGURE_CFLAGS])
# shared library versioning
# The three numbers in the libwolfssl.so.*.*.* file name. Unfortunately
@@ -443,6 +441,8 @@ AS_CASE([$ENABLED_WOLFENGINE],
# rand - wolfRand
# v5 - FIPS 140-3 Cert 4718
# cert4718 - alias for v5
# v5.2.3 -- FIPS 140-3 with support for ARM acceleration, derived from Cert 4718
# v5.2.4 -- FIPS 140-3 with support for Linux kernel mode, derived from v5.2.3
# ready - FIPS 140-3 settings with in-tree wolfcrypt sources, feature locked
# dev - FIPS 140-3 settings with in-tree wolfcrypt sources, features freely adjustable
# v5-ready - Alias for ready.
@@ -499,6 +499,24 @@ AS_CASE([$ENABLED_FIPS],
DEF_SP_MATH="no"
DEF_FAST_MATH="yes"
],
[v5.2.3],[
FIPS_VERSION="v5"
HAVE_FIPS_VERSION_MAJOR=5
HAVE_FIPS_VERSION_MINOR=2
HAVE_FIPS_VERSION_PATCH=3
ENABLED_FIPS="yes"
DEF_SP_MATH="yes"
DEF_FAST_MATH="no"
],
[v5.2.4],[
FIPS_VERSION="v5"
HAVE_FIPS_VERSION_MAJOR=5
HAVE_FIPS_VERSION_MINOR=2
HAVE_FIPS_VERSION_PATCH=4
ENABLED_FIPS="yes"
DEF_SP_MATH="yes"
DEF_FAST_MATH="no"
],
[v5-RC12],[
FIPS_VERSION="v5-RC12"
HAVE_FIPS_VERSION_MAJOR=5
@@ -1107,6 +1125,7 @@ then
AC_MSG_ERROR([--enable-all-osp is incompatible with --enable-linuxkm-defaults])
fi
test "$enable_wolfguard" = "" && enable_wolfguard=yes
test "$enable_webserver" = "" && enable_webserver=yes
if test "$ENABLED_SP_MATH" != "yes"
@@ -1382,7 +1401,7 @@ then
test "$enable_aesxts_stream" = "" && test "$enable_aesxts" = "yes" && enable_aesxts_stream=yes
test "$enable_shake128" = "" && enable_shake128=yes
test "$enable_shake256" = "" && enable_shake256=yes
test "$enable_compkey" = "" && test "$ENABLED_LINUXKM_DEFAULTS" != "yes" && enable_compkey=yes
test "$enable_compkey" = "" && enable_compkey=yes
# AFALG lacks AES-ECB
test "$enable_srtp_kdf" = "" && test "$enable_afalg" != "yes" && enable_srtp_kdf=yes
fi
@@ -1411,6 +1430,24 @@ then
AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_HAVE_ISSUER_NAMES"
fi
# wolfGuard
AC_ARG_ENABLE([wolfguard],
[AS_HELP_STRING([--enable-wolfguard],[Enable wolfGuard dependencies (default: disabled)])],
[ ENABLED_WOLFGUARD=$enableval ],
[ ENABLED_WOLFGUARD=no ]
)
if test "$ENABLED_WOLFGUARD" = "yes"
then
test "$enable_ecc" = "" && enable_ecc=yes
test "$enable_sha256" = "" && enable_sha256=yes
test "$enable_aesgcm" = "" && enable_aesgcm=yes
if test "$ENABLED_FIPS" = "no" || test "$HAVE_FIPS_VERSION" -ge 6
then
test "$enable_compkey" = "" && enable_compkey=yes
test "$enable_aesgcm_stream" = "" && enable_aesgcm_stream=yes
fi
fi
# liboqs
ENABLED_LIBOQS="no"
tryliboqsdir=""
@@ -3792,6 +3829,18 @@ then
AM_CFLAGS="$AM_CFLAGS -DHAVE_INTEL_RDRAND"
fi
# INTEL RDSEED
AC_ARG_ENABLE([intelrdseed],
[AS_HELP_STRING([--enable-intelrdseed],[Enable Intel rdseed as preferred RNG seeding source (default: disabled)])],
[ ENABLED_INTELRDSEED=$enableval ],
[ ENABLED_INTELRDSEED=no ]
)
if test "$ENABLED_INTELRDSEED" = "yes"
then
AM_CFLAGS="$AM_CFLAGS -DHAVE_INTEL_RDSEED"
fi
# AMD RDSEED
AC_ARG_ENABLE([amdrand],
[AS_HELP_STRING([--enable-amdrand],[Enable AMD rdseed as preferred RNG seeding source (default: disabled)])],
@@ -5669,6 +5718,9 @@ AC_ARG_ENABLE([pwdbased],
# wolfEntropy Software Jitter SP800-90B certifiable entropy source
if test "$ENABLED_LINUXKM_DEFAULTS" = "yes" && \
test "$ENABLED_AMDRDSEED" != "yes" && \
test "$ENABLED_INTELRDRAND" != "yes" && \
test "$ENABLED_INTELRDSEED" != "yes" && \
(test "$ENABLED_FIPS" = "no" || test "$HAVE_FIPS_VERSION" -ge 6)
then
ENABLED_ENTROPY_MEMUSE_DEFAULT=yes
@@ -5760,7 +5812,7 @@ AS_CASE([$FIPS_VERSION],
(test "$FIPS_VERSION" != "dev" || test "$enable_keygen" != "no")],
[ENABLED_KEYGEN="yes"; AM_CFLAGS="$AM_CFLAGS -DWOLFSSL_KEY_GEN"])
# AS_IF([test "$ENABLED_COMPKEY" = "yes" &&
# AS_IF([test "$ENABLED_COMPKEY" != "yes" &&
# (test "$FIPS_VERSION" != "dev" || test "$enable_compkey" != "yes")],
# [ENABLED_COMPKEY="yes"])
@@ -10650,6 +10702,17 @@ if test "$enable_shared" = "no"; then
fi
fi
if test "$ENABLED_WOLFGUARD" = "yes"; then
if test "$ENABLED_ECC" = "no" ||
test "$ENABLED_SHA256" = "no" ||
test "$ENABLED_AESGCM" = "no" ||
test "$ENABLED_HMAC" = "no" ||
test "$ENABLED_RNG" = "no"
then
AC_MSG_ERROR([--enable-wolfguard requires ECC, SHA256-HMAC, AES-GCM, and RNG.])
fi
fi
if test "x$ENABLED_LINUXKM" = "xyes"; then
AX_SIMD_CC_COMPILER_FLAGS
AC_SUBST([CFLAGS_FPU_DISABLE])
@@ -10714,9 +10777,6 @@ if test "x$ENABLED_LINUXKM" = "xyes"; then
if test "$ENABLED_STACKLOG" = "yes"; then
AC_MSG_ERROR([--enable-stacklog is incompatible with --enable-linuxkm.])
fi
if test "$ENABLED_COMPKEY" = "yes"; then
AC_MSG_ERROR([--enable-compkey is incompatible with --enable-linuxkm.])
fi
fi
AS_IF([test "$ENABLED_ASM" = "no" && (test "$ENABLED_INTELASM" != "no" || \

28
debian/rules.in vendored
View File

@@ -3,7 +3,6 @@
# Store the configure options and CFLAGS used during ./configure
# This file is generated from rules.in by the configure script
CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@
CONFIGURE_CFLAGS = @CONFIGURE_CFLAGS@
ENABLED_FIPS = @ENABLED_FIPS@
# Use debhelper with automatic sequence
@@ -16,18 +15,17 @@ override_dh_auto_configure:
--build=$(DEB_BUILD_GNU_TYPE) \
--host=$(DEB_HOST_GNU_TYPE) \
--prefix=/usr \
--mandir=\$${prefix}/share/man \
--infodir=\$${prefix}/share/info \
--mandir=/usr/share/man \
--infodir=/usr/share/info \
--sysconfdir=/etc \
--localstatedir=/var \
--libdir=\$${prefix}/lib/$(DEB_HOST_MULTIARCH) \
--libexecdir=\$${prefix}/lib/$(DEB_HOST_MULTIARCH) \
--libdir=/usr/lib/$(DEB_HOST_MULTIARCH) \
--libexecdir=/usr/lib/$(DEB_HOST_MULTIARCH) \
--disable-maintainer-mode \
--disable-dependency-tracking \
--enable-shared \
--enable-static \
$(CONFIGURE_OPTIONS) \
CFLAGS="$(CONFIGURE_CFLAGS)"
$(CONFIGURE_OPTIONS)
# Override test to skip them (optional, remove if you want to run tests)
#override_dh_auto_test:
@@ -50,22 +48,6 @@ override_dh_auto_install:
dh_auto_install
# Remove .la files (not needed in modern Debian packages)
find debian/tmp -name '*.la' -delete
# Move libraries to multiarch directory if needed
if [ -d debian/tmp/usr/lib ]; then \
mkdir -p debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH); \
if [ -f debian/tmp/usr/lib/libwolfssl.so.* ]; then \
mv debian/tmp/usr/lib/libwolfssl.so.* debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/; \
fi; \
if [ -f debian/tmp/usr/lib/libwolfssl.so ]; then \
mv debian/tmp/usr/lib/libwolfssl.so debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/; \
fi; \
if [ -f debian/tmp/usr/lib/libwolfssl.a ]; then \
mv debian/tmp/usr/lib/libwolfssl.a debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/; \
fi; \
if [ -d debian/tmp/usr/lib/pkgconfig ]; then \
mv debian/tmp/usr/lib/pkgconfig debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/; \
fi; \
fi
# Set proper permissions and strip symbols
override_dh_strip:

View File

@@ -13,7 +13,8 @@ use warnings;
# ---- SCRIPT SETTINGS -------------------------------------------------------
# output C header file to write cert/key buffers to
my $outputFile = "./wolfssl/certs_test.h";
my $outputFile = "./wolfssl/certs_test.h";
my $outputFileSM = "./wolfssl/certs_test_sm.h";
# ecc keys and certs to be converted
# Used with HAVE_ECC && USE_CERT_BUFFERS_256
@@ -109,6 +110,42 @@ my @fileList_4096 = (
[ "./certs/dh4096.der", "dh_key_der_4096" ],
);
# SM ciphers PRM format in certs/sm2
my @fileList_sm2 = (
[ "./certs/sm2/ca-sm2.pem", "ca_sm2" ],
[ "./certs/sm2/ca-sm2-key.pem", "ca_sm2_key" ],
[ "./certs/sm2/ca-sm2-priv.pem", "ca_sm2_priv" ],
[ "./certs/sm2/client-sm2.pem", "client_sm2" ],
[ "./certs/sm2/client-sm2-key.pem", "client_sm2_key" ],
[ "./certs/sm2/client-sm2-priv.pem", "client_sm2_priv" ],
[ "./certs/sm2/root-sm2.pem", "root_sm2" ],
[ "./certs/sm2/root-sm2-key.pem", "root_sm2_key" ],
[ "./certs/sm2/root-sm2-priv.pem", "root_sm2_priv" ],
[ "./certs/sm2/self-sm2-cert.pem", "self_sm2_cert" ],
[ "./certs/sm2/self-sm2-key.pem", "self_sm2_key" ],
[ "./certs/sm2/self-sm2-priv.pem", "self_sm2_priv" ],
[ "./certs/sm2/server-sm2.pem", "server_sm2" ],
[ "./certs/sm2/server-sm2-cert.pem", "server_sm2_cert" ],
[ "./certs/sm2/server-sm2-key.pem", "server_sm2_key" ],
[ "./certs/sm2/server-sm2-priv.pem", "server_sm2_priv" ],
);
my @fileList_sm2_der = (
[ "./certs/sm2/ca-sm2.der", "ca_sm2_der" ],
[ "./certs/sm2/ca-sm2-key.der", "ca_sm2_key_der" ],
[ "./certs/sm2/ca-sm2-priv.der", "ca_sm2_priv_der" ],
[ "./certs/sm2/client-sm2.der", "client_sm2_der" ],
[ "./certs/sm2/client-sm2-key.der", "client_sm2_key_der" ],
[ "./certs/sm2/client-sm2-priv.der", "client_sm2_priv_der" ],
[ "./certs/sm2/root-sm2.der", "root_sm2_der" ],
[ "./certs/sm2/root-sm2-key.der", "root_sm2_key_der" ],
[ "./certs/sm2/root-sm2-priv.der", "root_sm2_priv_der" ],
[ "./certs/sm2/server-sm2.der", "server_sm2_der" ],
[ "./certs/sm2/server-sm2-cert.der", "server_sm2_cert_der" ],
[ "./certs/sm2/server-sm2-key.der", "server_sm2_key_der" ],
[ "./certs/sm2/server-sm2-priv.der", "server_sm2_priv_der" ],
);
#Falcon Post-Quantum Keys
#Used with HAVE_PQC
my @fileList_falcon = (
@@ -130,15 +167,17 @@ my @fileList_sphincs = (
# ----------------------------------------------------------------------------
my $num_ecc = @fileList_ecc;
my $num_ed = @fileList_ed;
my $num_x = @fileList_x;
my $num_1024 = @fileList_1024;
my $num_2048 = @fileList_2048;
my $num_3072 = @fileList_3072;
my $num_4096 = @fileList_4096;
my $num_falcon = @fileList_falcon;
my $num_sphincs = @fileList_sphincs;
my $num_ecc = @fileList_ecc;
my $num_ed = @fileList_ed;
my $num_x = @fileList_x;
my $num_1024 = @fileList_1024;
my $num_2048 = @fileList_2048;
my $num_3072 = @fileList_3072;
my $num_4096 = @fileList_4096;
my $num_sm2 = @fileList_sm2;
my $num_sm2_der = @fileList_sm2_der;
my $num_falcon = @fileList_falcon;
my $num_sphincs = @fileList_sphincs;
# open our output file, "+>" creates and/or truncates
open OUT_FILE, "+>", $outputFile or die $!;
@@ -2202,9 +2241,68 @@ print OUT_FILE "#endif /* WOLFSSL_CERTS_TEST_H */\n\n";
# close certs_test.h file
close OUT_FILE or die $!;
#---------------------------------------------------------------------------
# open our output file, "+>" creates and/or truncates
open OUT_FILE_SM, "+>", $outputFileSM or die $!;
print OUT_FILE_SM "/* certs_test_sm.h */\n";
print OUT_FILE_SM "/* This file was generated using: ./gencertbuf.pl */\n\n";
print OUT_FILE_SM "#ifndef WOLFSSL_CERTS_TEST_SM_H\n";
print OUT_FILE_SM "#define WOLFSSL_CERTS_TEST_SM_H\n\n";
print OUT_FILE_SM "#if defined(WOLFSSL_SM2) || defined(WOLFSSL_SM3) || defined(WOLFSSL_SM4)\n\n";
print OUT_FILE_SM " /* DER Certs Begin */\n\n";
# convert and print SM2 DER format certs/keys
for (my $i = 0; $i < $num_sm2_der; $i++) {
my $fname = $fileList_sm2_der[$i][0];
my $sname = $fileList_sm2_der[$i][1];
print OUT_FILE_SM "/* $fname */\n";
print OUT_FILE_SM "static const unsigned char $sname\[] =\n";
print OUT_FILE_SM "{\n";
file_to_hex($fname, \*OUT_FILE_SM);
print OUT_FILE_SM "};\n";
# In C89/C90 (which Watcom generally defaults to), sizeof must be a
# compile-time constant expression when used in a static initializer.
# So don't use `static const int sizeof_` here:
print OUT_FILE_SM "#define sizeof_$sname (sizeof($sname))\n\n";
}
print OUT_FILE_SM " /* DER Certs End */\n\n";
# convert and print SM2 PEM format certs/keys
print OUT_FILE_SM "#ifdef WOLFSSL_NO_PEM\n\n";
print OUT_FILE_SM " /* SM PEM Certs disabled */\n\n";
print OUT_FILE_SM "#else\n\n";
for (my $i = 0; $i < $num_sm2; $i++) {
my $fname = $fileList_sm2[$i][0];
my $sname = $fileList_sm2[$i][1];
print OUT_FILE_SM "/* $fname */\n";
print OUT_FILE_SM "static const unsigned char $sname\[] =\n";
print OUT_FILE_SM "{\n";
file_to_hex($fname, \*OUT_FILE_SM);
print OUT_FILE_SM "};\n";
# In C89/C90 (which Watcom generally defaults to), sizeof must be a
# compile-time constant expression when used in a static initializer.
# So don't use `static const int sizeof_` here:
print OUT_FILE_SM "#define sizeof_$sname (sizeof($sname))\n\n";
}
print OUT_FILE_SM "#endif /* WOLFSSL_NO_PEM */\n\n";
print OUT_FILE_SM "#endif /* WOLFSSL_SM2 || WOLFSSL_SM3 || WOLFSSL_SM4 */\n";
print OUT_FILE_SM "#endif /* WOLFSSL_CERTS_TEST_SM_H */\n";
# close certs_test_sm.h file
close OUT_FILE_SM or die $!;
# print file as hex, comma-separated, as needed by C buffer
sub file_to_hex {
my $fileName = $_[0];
my ($fileName, $out_fh) = @_;
$out_fh //= \*OUT_FILE; # default handle
open my $fp, "<", $fileName or die $!;
binmode($fp);
@@ -2215,26 +2313,27 @@ sub file_to_hex {
for (my $i = 0, my $j = 1; $i < $fileLen; $i++, $j++)
{
if ($j == 1) {
print OUT_FILE " ";
print {$out_fh} " ";
}
if ($j != 1) {
print OUT_FILE " ";
print {$out_fh} " ";
}
read($fp, $byte, 1) or die "Error reading $fileName";
my $output = sprintf("0x%02X", ord($byte));
print OUT_FILE $output;
print {$out_fh} $output;
if ($i != ($fileLen - 1)) {
print OUT_FILE ",";
print {$out_fh} ",";
}
if ($j == 10) {
$j = 0;
print OUT_FILE "\n";
print {$out_fh} "\n";
}
}
print OUT_FILE "\n";
print {$out_fh} "\n";
close($fp);
}

View File

@@ -36,9 +36,8 @@
#endif
#if defined(LINUXKM_LKCAPI_REGISTER_DH) && \
(!defined(WOLFSSL_DH_EXTRA) || \
!defined(WOLFSSL_DH_GEN_PUB))
/* not supported without WOLFSSL_DH_EXTRA && WOLFSSL_DH_GEN_PUB */
!defined(WOLFSSL_DH_EXTRA)
/* not supported without WOLFSSL_DH_EXTRA */
#undef LINUXKM_LKCAPI_REGISTER_DH
#if defined(LINUXKM_LKCAPI_REGISTER_ALL_KCONFIG) && defined(CONFIG_CRYPTO_DH)

View File

@@ -11180,8 +11180,10 @@ static WC_INLINE int GrowOutputBuffer(WOLFSSL* ssl, int size)
return BUFFER_E;
if (! WC_SAFE_SUM_WORD32(newSz, (word32)size, newSz))
return BUFFER_E;
#if WOLFSSL_GENERAL_ALIGNMENT > 0
if (! WC_SAFE_SUM_WORD32(newSz, align, newSz))
return BUFFER_E;
#endif
tmp = (byte*)XMALLOC(newSz, ssl->heap, DYNAMIC_TYPE_OUT_BUFFER);
newSz -= align;
WOLFSSL_MSG("growing output buffer");
@@ -32307,6 +32309,8 @@ static int GetEcDiffieHellmanKea(WOLFSSL *ssl,
else {
SendAlert(ssl, alert_fatal, illegal_parameter);
}
#else
(void)ret;
#endif
return ECC_PEERKEY_ERROR;
}
@@ -32349,6 +32353,8 @@ static int GetEcDiffieHellmanKea(WOLFSSL *ssl,
else {
SendAlert(ssl, alert_fatal, illegal_parameter);
}
#else
(void)ret;
#endif
return ECC_PEERKEY_ERROR;
}

191
src/ssl.c
View File

@@ -8806,148 +8806,75 @@ static int isArrayUnique(const char* buf, size_t len)
return 1;
}
/* Set user preference for the client_cert_type exetnsion.
/* Set user preference for the {client,server}_cert_type extension.
* Takes byte array containing cert types the caller can provide to its peer.
* Cert types are in preferred order in the array.
*/
static int set_cert_type(RpkConfig* cfg,
int client, const char* buf, int bufLen)
{
int i;
byte* certTypeCnt;
byte* certTypes;
if (cfg == NULL || bufLen > (client ? MAX_CLIENT_CERT_TYPE_CNT :
MAX_SERVER_CERT_TYPE_CNT)) {
return BAD_FUNC_ARG;
}
if (client) {
certTypeCnt = &cfg->preferred_ClientCertTypeCnt;
certTypes = cfg->preferred_ClientCertTypes;
}
else {
certTypeCnt = &cfg->preferred_ServerCertTypeCnt;
certTypes = cfg->preferred_ServerCertTypes;
}
/* if buf is set to NULL or bufLen is zero, it defaults the setting*/
if (buf == NULL || bufLen == 0) {
*certTypeCnt = 1;
for (i = 0; i < 2; i++)
certTypes[i] = WOLFSSL_CERT_TYPE_X509;
return WOLFSSL_SUCCESS;
}
if (!isArrayUnique(buf, (size_t)bufLen))
return BAD_FUNC_ARG;
for (i = 0; i < bufLen; i++) {
if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
return BAD_FUNC_ARG;
certTypes[i] = (byte)buf[i];
}
*certTypeCnt = bufLen;
return WOLFSSL_SUCCESS;
}
int wolfSSL_set_client_cert_type(WOLFSSL* ssl, const char* buf, int buflen)
{
if (ssl == NULL)
return BAD_FUNC_ARG;
return set_cert_type(&ssl->options.rpkConfig, 1, buf, buflen);
}
int wolfSSL_set_server_cert_type(WOLFSSL* ssl, const char* buf, int buflen)
{
if (ssl == NULL)
return BAD_FUNC_ARG;
return set_cert_type(&ssl->options.rpkConfig, 0, buf, buflen);
}
int wolfSSL_CTX_set_client_cert_type(WOLFSSL_CTX* ctx,
const char* buf, int bufLen)
const char* buf, int buflen)
{
int i;
if (ctx == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) {
if (ctx == NULL)
return BAD_FUNC_ARG;
}
/* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/
if (buf == NULL || bufLen == 0) {
ctx->rpkConfig.preferred_ClientCertTypeCnt = 1;
ctx->rpkConfig.preferred_ClientCertTypes[0]= WOLFSSL_CERT_TYPE_X509;
ctx->rpkConfig.preferred_ClientCertTypes[1]= WOLFSSL_CERT_TYPE_X509;
return WOLFSSL_SUCCESS;
}
if (!isArrayUnique(buf, (size_t)bufLen))
return BAD_FUNC_ARG;
for (i = 0; i < bufLen; i++){
if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
return BAD_FUNC_ARG;
ctx->rpkConfig.preferred_ClientCertTypes[i] = (byte)buf[i];
}
ctx->rpkConfig.preferred_ClientCertTypeCnt = bufLen;
return WOLFSSL_SUCCESS;
return set_cert_type(&ctx->rpkConfig, 1, buf, buflen);
}
/* Set user preference for the server_cert_type exetnsion.
* Takes byte array containing cert types the caller can provide to its peer.
* Cert types are in preferred order in the array.
*/
int wolfSSL_CTX_set_server_cert_type(WOLFSSL_CTX* ctx,
const char* buf, int bufLen)
const char* buf, int buflen)
{
int i;
if (ctx == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) {
if (ctx == NULL)
return BAD_FUNC_ARG;
}
/* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/
if (buf == NULL || bufLen == 0) {
ctx->rpkConfig.preferred_ServerCertTypeCnt = 1;
ctx->rpkConfig.preferred_ServerCertTypes[0]= WOLFSSL_CERT_TYPE_X509;
ctx->rpkConfig.preferred_ServerCertTypes[1]= WOLFSSL_CERT_TYPE_X509;
return WOLFSSL_SUCCESS;
}
if (!isArrayUnique(buf, (size_t)bufLen))
return BAD_FUNC_ARG;
for (i = 0; i < bufLen; i++){
if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
return BAD_FUNC_ARG;
ctx->rpkConfig.preferred_ServerCertTypes[i] = (byte)buf[i];
}
ctx->rpkConfig.preferred_ServerCertTypeCnt = bufLen;
return WOLFSSL_SUCCESS;
}
/* Set user preference for the client_cert_type exetnsion.
* Takes byte array containing cert types the caller can provide to its peer.
* Cert types are in preferred order in the array.
*/
int wolfSSL_set_client_cert_type(WOLFSSL* ssl,
const char* buf, int bufLen)
{
int i;
if (ssl == NULL || bufLen > MAX_CLIENT_CERT_TYPE_CNT) {
return BAD_FUNC_ARG;
}
/* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/
if (buf == NULL || bufLen == 0) {
ssl->options.rpkConfig.preferred_ClientCertTypeCnt = 1;
ssl->options.rpkConfig.preferred_ClientCertTypes[0]
= WOLFSSL_CERT_TYPE_X509;
ssl->options.rpkConfig.preferred_ClientCertTypes[1]
= WOLFSSL_CERT_TYPE_X509;
return WOLFSSL_SUCCESS;
}
if (!isArrayUnique(buf, (size_t)bufLen))
return BAD_FUNC_ARG;
for (i = 0; i < bufLen; i++){
if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
return BAD_FUNC_ARG;
ssl->options.rpkConfig.preferred_ClientCertTypes[i] = (byte)buf[i];
}
ssl->options.rpkConfig.preferred_ClientCertTypeCnt = bufLen;
return WOLFSSL_SUCCESS;
}
/* Set user preference for the server_cert_type exetnsion.
* Takes byte array containing cert types the caller can provide to its peer.
* Cert types are in preferred order in the array.
*/
int wolfSSL_set_server_cert_type(WOLFSSL* ssl,
const char* buf, int bufLen)
{
int i;
if (ssl == NULL || bufLen > MAX_SERVER_CERT_TYPE_CNT) {
return BAD_FUNC_ARG;
}
/* if buf is set to NULL or bufLen is set to zero, it defaults the setting*/
if (buf == NULL || bufLen == 0) {
ssl->options.rpkConfig.preferred_ServerCertTypeCnt = 1;
ssl->options.rpkConfig.preferred_ServerCertTypes[0]
= WOLFSSL_CERT_TYPE_X509;
ssl->options.rpkConfig.preferred_ServerCertTypes[1]
= WOLFSSL_CERT_TYPE_X509;
return WOLFSSL_SUCCESS;
}
if (!isArrayUnique(buf, (size_t)bufLen))
return BAD_FUNC_ARG;
for (i = 0; i < bufLen; i++){
if (buf[i] != WOLFSSL_CERT_TYPE_RPK && buf[i] != WOLFSSL_CERT_TYPE_X509)
return BAD_FUNC_ARG;
ssl->options.rpkConfig.preferred_ServerCertTypes[i] = (byte)buf[i];
}
ssl->options.rpkConfig.preferred_ServerCertTypeCnt = bufLen;
return WOLFSSL_SUCCESS;
return set_cert_type(&ctx->rpkConfig, 0, buf, buflen);
}
/* get negotiated certificate type value and return it to the second parameter.

View File

@@ -6201,7 +6201,8 @@ static int DoPreSharedKeys(WOLFSSL* ssl, const byte* input, word32 inputSz,
if (ret != 0)
return ret;
if (binderLen != current->binderLen ||
XMEMCMP(binder, current->binder, binderLen) != 0) {
ConstantCompare(binder, current->binder,
binderLen) != 0) {
WOLFSSL_ERROR_VERBOSE(BAD_BINDER);
return BAD_BINDER;
}

View File

@@ -401,7 +401,7 @@ static WC_INLINE int wc_XChaCha20Poly1305_crypt_oneshot(
goto out;
}
if ((long int)dst_space < dst_len) {
if (dst_len < 0 || (long int)dst_space < dst_len) {
ret = BUFFER_E;
goto out;
}

View File

@@ -551,7 +551,7 @@ void wolfSSL_SetDebugMemoryCb(DebugMemoryCb cb)
wc_Memory** list is the list that new buckets are prepended to
*/
static int wc_create_memory_buckets(byte* buffer, word32 bufSz,
word32 buckSz, byte buckNum, wc_Memory** list) {
word32 buckSz, word32 buckNum, wc_Memory** list) {
byte* pt = buffer;
int ret = 0;
byte memSz = (byte)sizeof(wc_Memory);

View File

@@ -38,7 +38,10 @@ To enable the RNG acceleration add the following:
```c
#define WC_NO_HASHDRBG
#define CUSTOM_RAND_GENERATE_BLOCK wc_pico_rng_gen_block
#define WC_RESEED_INTERVAL (1000000)
```
NOTE: the value for `WC_RESEED_INTERVAL` here is just an example. You should find what is
most appropriate for your application and use case.
In CMake you should add the following linking to both wolfSSL and the end
application:

2913
wolfssl/certs_test_sm.h Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -18,6 +18,7 @@ nobase_include_HEADERS+= \
wolfssl/sniffer.h \
wolfssl/callbacks.h \
wolfssl/certs_test.h \
wolfssl/certs_test_sm.h \
wolfssl/test.h \
wolfssl/version.h \
wolfssl/ocsp.h \

View File

@@ -3,6 +3,10 @@ all:
+$(MAKE) -C wolfssl-sys
+$(MAKE) -C wolfssl
.PHONY: test
test:
+$(MAKE) -C wolfssl test
.PHONY: clean
clean:
+$(MAKE) -C wolfssl-sys clean

View File

@@ -8,6 +8,10 @@ Then build the wolfssl Rust wrapper with:
make -C wrapper/rust
Run tests with:
make -C wrapper/rust test
## Repository Directory Structure
| Repository Directory | Description |

View File

@@ -13,4 +13,8 @@ EXTRA_DIST += wrapper/rust/wolfssl-sys/src/lib.rs
EXTRA_DIST += wrapper/rust/wolfssl/Cargo.lock
EXTRA_DIST += wrapper/rust/wolfssl/Cargo.toml
EXTRA_DIST += wrapper/rust/wolfssl/Makefile
EXTRA_DIST += wrapper/rust/wolfssl/build.rs
EXTRA_DIST += wrapper/rust/wolfssl/src/lib.rs
EXTRA_DIST += wrapper/rust/wolfssl/src/wolfcrypt.rs
EXTRA_DIST += wrapper/rust/wolfssl/src/wolfcrypt/random.rs
EXTRA_DIST += wrapper/rust/wolfssl/tests/test_random.rs

View File

@@ -2,6 +2,299 @@
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "bindgen"
version = "0.72.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
dependencies = [
"bitflags",
"cexpr",
"clang-sys",
"itertools",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn",
]
[[package]]
name = "bitflags"
version = "2.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]]
name = "cfg-if"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "libc"
version = "0.2.175"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543"
[[package]]
name = "libloading"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
dependencies = [
"cfg-if",
"windows-targets",
]
[[package]]
name = "log"
version = "0.4.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
[[package]]
name = "memchr"
version = "2.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.101"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23d7fd106d8c02486a8d64e778353d1cffe08ce79ac2e82f540c86d0facf6912"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b9458fa0bfeeac22b5ca447c63aaf45f28439a709ccd244698632f9aa6394d6"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
version = "2.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
[[package]]
name = "windows-link"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
[[package]]
name = "windows-targets"
version = "0.53.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91"
dependencies = [
"windows-link",
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
[[package]]
name = "windows_aarch64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
[[package]]
name = "windows_i686_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
[[package]]
name = "windows_i686_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
[[package]]
name = "windows_i686_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
[[package]]
name = "windows_x86_64_gnu"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
[[package]]
name = "windows_x86_64_msvc"
version = "0.53.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
[[package]]
name = "wolfssl"
version = "0.1.0"
dependencies = [
"wolfssl-sys",
]
[[package]]
name = "wolfssl-sys"
version = "0.1.0"
dependencies = [
"bindgen",
]

View File

@@ -4,3 +4,4 @@ version = "0.1.0"
edition = "2024"
[dependencies]
wolfssl-sys = { path = "../wolfssl-sys" }

View File

@@ -1,6 +1,11 @@
.PHONY: all
all:
cargo build
cargo doc
.PHONY: test
test:
cargo test
.PHONY: clean
clean:

View File

@@ -0,0 +1,32 @@
use std::io::Result;
/// Perform crate build.
fn main() {
if let Err(e) = run_build() {
eprintln!("Build failed: {}", e);
std::process::exit(1);
}
}
/// Perform all build steps.
///
/// Returns `Ok(())` if successful, or an error if any step fails.
fn run_build() -> Result<()> {
setup_wolfssl_link()?;
Ok(())
}
/// Instruct cargo to link against wolfssl C library
///
/// Returns `Ok(())` if successful, or an error if any step fails.
fn setup_wolfssl_link() -> Result<()> {
let wrapper_dir = std::env::current_dir()?.display().to_string();
let wolfssl_base_dir = format!("{}/../../..", wrapper_dir);
let wolfssl_lib_dir = format!("{}/src/.libs", wolfssl_base_dir);
println!("cargo:rustc-link-search={}", wolfssl_lib_dir);
println!("cargo:rustc-link-lib=wolfssl");
println!("cargo:rustc-link-arg=-Wl,-rpath,{}", wolfssl_lib_dir);
Ok(())
}

View File

@@ -0,0 +1 @@
pub mod wolfcrypt;

View File

@@ -0,0 +1 @@
pub mod random;

View File

@@ -0,0 +1,146 @@
/*!
This crate provides a Rust wrapper for the wolfCrypt library's random number
generator (RNG).
It leverages the `wolfssl-sys` crate for low-level FFI bindings, encapsulating
the raw C functions in a memory-safe and easy-to-use Rust API.
The primary component is the `RNG` struct, which manages the lifecycle of a
wolfSSL `WC_RNG` object. It ensures proper initialization and deallocation.
# Examples
```rust
use wolfssl::wolfcrypt::random::RNG;
fn main() {
// Create a RNG instance.
let mut rng = RNG::new().expect("Failed to create RNG");
// Generate a single random byte value.
let byte = rng.generate_byte().expect("Failed to generate a single byte");
// Generate a random block.
let mut buffer = [0u32; 8];
rng.generate_block(&mut buffer).expect("Failed to generate a block");
}
```
*/
use wolfssl_sys as ws;
use std::mem::{size_of, MaybeUninit};
/// A cryptographically secure random number generator based on the wolfSSL
/// library.
///
/// This struct wraps the wolfssl `WC_RNG` type, providing a high-level API
/// for generating random bytes and blocks of data. The `Drop` implementation
/// ensures that the underlying wolfSSL RNG context is correctly freed when the
/// `RNG` struct goes out of scope, preventing memory leaks.
pub struct RNG {
wc_rng: ws::WC_RNG,
}
impl RNG {
/// Initialize a new `RNG` instance.
///
/// This function wraps the wolfssl library function `wc_InitRng`, which
/// performs the necessary initialization for the RNG context.
///
/// # Returns
///
/// A Result which is Ok(RNG) on success or an Err containing the wolfSSL
/// library return code on failure.
pub fn new() -> Result<Self, i32> {
let mut rng: MaybeUninit<RNG> = MaybeUninit::uninit();
let rc = unsafe { ws::wc_InitRng(&mut (*rng.as_mut_ptr()).wc_rng) };
if rc == 0 {
let rng = unsafe { rng.assume_init() };
Ok(rng)
} else {
Err(rc)
}
}
/// Initialize a new `RNG` instance and provide a nonce input.
///
/// This function wraps the wolfssl library function `wc_InitRngNonce`,
/// which performs the necessary initialization for the RNG context and
/// accepts a nonce input buffer.
///
/// # Returns
///
/// A Result which is Ok(RNG) on success or an Err containing the wolfSSL
/// library return code on failure.
pub fn new_with_nonce<T>(nonce: &mut [T]) -> Result<Self, i32> {
let ptr = nonce.as_mut_ptr() as *mut u8;
let size: u32 = (nonce.len() * size_of::<T>()) as u32;
let mut rng: MaybeUninit<RNG> = MaybeUninit::uninit();
let rc = unsafe {
ws::wc_InitRngNonce(&mut (*rng.as_mut_ptr()).wc_rng, ptr, size)
};
if rc == 0 {
let rng = unsafe { rng.assume_init() };
Ok(rng)
} else {
Err(rc)
}
}
/// Generate a single cryptographically secure random byte.
///
/// This method calls the `wc_RNG_GenerateByte` wolfSSL library function to
/// retrieve a random byte from the underlying wolfSSL RNG context.
///
/// # Returns
///
/// A `Result` which is `Ok(u8)` containing the random byte on success or
/// an `Err` with the wolfssl library return code on failure.
pub fn generate_byte(&mut self) -> Result<u8, i32> {
let mut b: u8 = 0;
let rc = unsafe { ws::wc_RNG_GenerateByte(&mut self.wc_rng, &mut b) };
if rc == 0 {
Ok(b)
} else {
Err(rc)
}
}
/// Fill a mutable slice with cryptographically secure random data.
///
/// This is a generic function that can fill a slice of any type `T` with
/// random bytes. It calculates the total size of the slice in bytes and
/// calls the underlying `wc_RNG_GenerateBlock` wolfssl library function.
///
/// # Parameters
///
/// * `buf`: A mutable slice of any type `T` to be filled with random data.
///
/// # Returns
///
/// A `Result` which is `Ok(())` on success or an `Err` with the wolfssl
/// library return code on failure.
pub fn generate_block<T>(&mut self, buf: &mut [T]) -> Result<(), i32> {
let ptr = buf.as_mut_ptr() as *mut u8;
let size: u32 = (buf.len() * size_of::<T>()) as u32;
let rc = unsafe { ws::wc_RNG_GenerateBlock(&mut self.wc_rng, ptr, size) };
if rc == 0 {
Ok(())
} else {
Err(rc)
}
}
}
impl Drop for RNG {
/// Safely free the underlying wolfSSL RNG context.
///
/// This calls the `wc_FreeRng` wolfssl library function.
///
/// The Rust Drop trait guarantees that this method is called when the RNG
/// struct goes out of scope, automatically cleaning up resources and
/// preventing memory leaks.
fn drop(&mut self) {
unsafe { ws::wc_FreeRng(&mut self.wc_rng); }
}
}

View File

@@ -0,0 +1,58 @@
use wolfssl::wolfcrypt::random::RNG;
// Test that RNG::new() returns successfully and that drop() does not panic.
#[test]
fn test_rng_new_and_drop() {
let _rng = RNG::new().expect("Failed to create RNG");
}
// Test that RNG::new_with_nonce() returns successfully and that drop() does
// not panic.
#[test]
fn test_rng_new_with_nonce_and_drop() {
let mut nonce = [1, 2, 3, 4];
let _rng = RNG::new_with_nonce(&mut nonce).expect("Failed to create RNG");
}
// Test that generate_byte() returns random values.
#[test]
fn test_rng_generate_byte() {
// Since a single 0x00 or 0xFF could occur occasionally, we'll combine four
// bytes into a u32 and make sure they aren't all 0x00 or all 0xFF.
let mut rng = RNG::new().expect("Failed to create RNG");
let mut v: u32 = 0;
for _i in 0..4 {
let byte = rng.generate_byte().expect("Failed to generate a single byte");
v = (v << 8) | (byte as u32);
}
assert_ne!(v, 0u32);
assert_ne!(v, 0xFFFF_FFFFu32);
}
// Test that generate_block works for a slice of u8.
#[test]
fn test_rng_generate_block_u8() {
let mut rng = RNG::new().expect("Failed to create RNG");
let mut buffer = [0u8; 32];
rng.generate_block(&mut buffer).expect("Failed to generate a block of bytes");
// Check if the buffer has been modified from its initial state.
let all_zeros = [0u8; 32];
assert_ne!(buffer, all_zeros);
}
// Test that generate_block works for a slice of u32.
#[test]
fn test_rng_generate_block_u32() {
let mut rng = RNG::new().expect("Failed to create RNG");
let mut buffer = [0u32; 8];
rng.generate_block(&mut buffer).expect("Failed to generate a block of u32");
// Check if the buffer has been modified.
let all_zeros = [0u32; 8];
assert_ne!(buffer, all_zeros);
// Check that the last u32 is populated so the size of the buffer was
// calculated properly.
assert_ne!(buffer[buffer.len() - 1], 0u32);
assert_ne!(buffer[buffer.len() - 1], 0xFFFF_FFFFu32);
}