diff --git a/src/core/common/string.cpp b/src/core/common/string.cpp index f6916e657..612054f91 100644 --- a/src/core/common/string.cpp +++ b/src/core/common/string.cpp @@ -172,6 +172,8 @@ bool IsValidUtf8String(const char *aString, size_t aLength) if ((byte & 0x80) == 0) { + // We don't allow control characters. + VerifyOrExit(!iscntrl(byte), ret = false); continue; } diff --git a/src/core/common/string.hpp b/src/core/common/string.hpp index 8d84c79bb..307079396 100644 --- a/src/core/common/string.hpp +++ b/src/core/common/string.hpp @@ -237,6 +237,7 @@ private: /** * This function validates whether a given byte sequence (string) follows UTF-8 encoding. + * Control characters are not allowed. * * @param[in] aString A null-terminated byte sequence. * @@ -248,6 +249,7 @@ bool IsValidUtf8String(const char *aString); /** * This function validates whether a given byte sequence (string) follows UTF-8 encoding. + * Control characters are not allowed. * * @param[in] aString A byte sequence. * @param[in] aLength Length of the sequence. diff --git a/src/core/mac/mac_types.cpp b/src/core/mac/mac_types.cpp index 62d6780c5..a2c50620b 100644 --- a/src/core/mac/mac_types.cpp +++ b/src/core/mac/mac_types.cpp @@ -155,6 +155,7 @@ Error NetworkName::Set(const char *aNameString) Error error; NameData data(aNameString, kMaxSize + 1); + VerifyOrExit(data.GetLength() >= 1, error = kErrorInvalidArgs); VerifyOrExit(IsValidUtf8String(aNameString), error = kErrorInvalidArgs); error = Set(data); diff --git a/src/core/meshcop/meshcop_tlvs.cpp b/src/core/meshcop/meshcop_tlvs.cpp index 874afd778..f2c72b238 100644 --- a/src/core/meshcop/meshcop_tlvs.cpp +++ b/src/core/meshcop/meshcop_tlvs.cpp @@ -137,7 +137,7 @@ void NetworkNameTlv::SetNetworkName(const Mac::NameData &aNameData) bool NetworkNameTlv::IsValid(void) const { - return IsValidUtf8String(mNetworkName, GetLength()); + return GetLength() >= 1 && IsValidUtf8String(mNetworkName, GetLength()); } void SteeringDataTlv::CopyTo(SteeringData &aSteeringData) const diff --git a/tests/unit/test_string.cpp b/tests/unit/test_string.cpp index 71083cbea..c03846090 100644 --- a/tests/unit/test_string.cpp +++ b/tests/unit/test_string.cpp @@ -138,6 +138,8 @@ void TestUtf8(void) VerifyOrQuit(!IsValidUtf8String("\xef\x80")); VerifyOrQuit(!IsValidUtf8String("\xf7\x80\x80")); VerifyOrQuit(!IsValidUtf8String("\xff")); + VerifyOrQuit(!IsValidUtf8String("NUL\x00NUL", 7)); // UTF-8 NUL + VerifyOrQuit(!IsValidUtf8String("abcde\x11")); // control character printf(" -- PASS\n"); }