diff --git a/src/lib/shell/MainLoopMW320.cpp b/src/lib/shell/MainLoopMW320.cpp index 0ec5da55fa7136..ea7ca5de0a70df 100644 --- a/src/lib/shell/MainLoopMW320.cpp +++ b/src/lib/shell/MainLoopMW320.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include @@ -29,11 +28,7 @@ extern "C" { #include "wlan.h" -#include "network_flash_storage.h" -void test_wlan_scan(int argc, char ** argv); } -#include "AppTask.h" -#include "mw320_ota.h" using chip::FormatCHIPError; using chip::Shell::Engine; @@ -156,6 +151,7 @@ int TokenizeLine(char * buffer, char ** tokens, int max_tokens) } // namespace extern const char * mw320_get_verstr(void); +extern void save_network(char * ssid, char * pwd); namespace chip { namespace Shell { @@ -183,7 +179,8 @@ static void AtExitShell(void) static CHIP_ERROR VersionHandler(int argc, char ** argv) { - streamer_printf(streamer_get(), "mw320 firmware: %s\r\n", mw320_get_verstr()); + // streamer_printf(streamer_get(), "CHIP %s\r\n", CHIP_VERSION_STRING); + streamer_printf(streamer_get(), "CHIP %s\r\n", mw320_get_verstr()); return CHIP_NO_ERROR; } @@ -201,12 +198,12 @@ static CHIP_ERROR SetDefAPHandler(int argc, char ** argv) { VerifyOrReturnError(argc == 2, CHIP_ERROR_INVALID_ARGUMENT); PRINTF("[%s], [%s] \r\n", argv[0], argv[1]); - GetAppTask().SaveNetwork(argv[0], argv[1]); + save_network(argv[0], argv[1]); return CHIP_NO_ERROR; } -static CHIP_ERROR WlanStateHandler(int argc, char ** argv) +static CHIP_ERROR wlan_state_handler(int argc, char ** argv) { enum wlan_connection_state state; int result; @@ -240,7 +237,7 @@ static CHIP_ERROR WlanStateHandler(int argc, char ** argv) return CHIP_NO_ERROR; } -static CHIP_ERROR WlanAbortHandler(int argc, char ** argv) +static CHIP_ERROR wlan_abort_handler(int argc, char ** argv) { #ifdef WIFI_CONN_ABORT_SUPPORT wlan_abort_connect(); @@ -248,81 +245,15 @@ static CHIP_ERROR WlanAbortHandler(int argc, char ** argv) return CHIP_NO_ERROR; } -static CHIP_ERROR WlanConnHandler(int argc, char ** argv) -{ - VerifyOrReturnError(argc == 2, CHIP_ERROR_INVALID_ARGUMENT); - PRINTF("[%s], [%s] \r\n", argv[0], argv[1]); - //::connect_wifi_network(argv[0], argv[1]); - chip::DeviceLayer::Internal::ConnectivityUtils::ConnectWiFiNetwork(argv[0], argv[1]); - return CHIP_NO_ERROR; -} - -static CHIP_ERROR WlanScanHandler(int argc, char ** argv) -{ - test_wlan_scan(0, NULL); - return CHIP_NO_ERROR; -} - -static CHIP_ERROR FactoryRstHandler(int argc, char **argv) -{ - // Eraseing the saved parameters - ::erase_all_params(); - // Do factory reset from Matter Stack - chip::Server::GetInstance().ScheduleFactoryReset(); - if (argc == 1) { - if (!strcmp(argv[0], "1")) { - // Set default AP - GetAppTask().SaveNetwork((char*)DEFAP_SSID, (char*)DEFAP_PWD); - // Set op_state to working - GetAppTask().SetOpState(work_state); - } - } - // Reboot the device - ::mw320_dev_reset(1000); - - return CHIP_NO_ERROR; -} - -static CHIP_ERROR SetOpStatHandler(int argc, char ** argv) -{ - op_state_t opstat; - VerifyOrReturnError(argc == 1, CHIP_ERROR_INVALID_ARGUMENT); - opstat = (op_state_t)atoi(argv[0]); - VerifyOrReturnError(opstat < max_op_state, CHIP_ERROR_INVALID_ARGUMENT); - PRINTF("Operation State: %d\r\n", (int)opstat); - GetAppTask().SetOpState(opstat); - return CHIP_NO_ERROR; -} - -static CHIP_ERROR GetOpStatHandler(int argc, char ** argv) -{ - op_state_t opstat = GetAppTask().GetOpState(); - PRINTF("Current operation state: %d \r\n", (int)opstat); - return CHIP_NO_ERROR; -} - -static CHIP_ERROR CmdRebootHandler(int argc, char ** argv) -{ - ::mw320_dev_reset(1000); - return CHIP_NO_ERROR; -} - - static void RegisterMetaCommands(void) { static shell_command_t sCmds[] = { { &ShutdownHandler, "shutdown", "Exit the shell application" }, { &VersionHandler, "version", "Output the software version" }, { &SetPinCodeHandler, "pincode", "Set the pin code" }, - { &SetDefAPHandler, "set-defap", "Set default AP SSID/PWD" }, - { &WlanStateHandler, "wlan-stat", "Check the wifi status" }, - { &WlanAbortHandler, "wlan-abort", "Abort the scan/reconnect" }, - { &WlanConnHandler, "wlan-connect", "Connect to AP" }, - { &WlanScanHandler, "wlan-scan", "Scan the environment"}, - { &FactoryRstHandler, "factory-reset", "Do factory reset"}, - { &SetOpStatHandler, "set-opstate", "Set the Operation State [0:factory_rest|1:work]"}, - { &GetOpStatHandler, "get-opstate", "Get the Operation State [0:factory_rest|1:work]"}, - { &CmdRebootHandler, "reboot", "Reboot the device"}, + { &SetDefAPHandler, "set_defap", "Set default AP SSID/PWD" }, + { &wlan_state_handler, "wlan-stat", "Check the wifi status" }, + { &wlan_abort_handler, "wlan-abort", "Abort the scan/reconnect" }, }; std::atexit(AtExitShell); diff --git a/src/platform/nxp/mw320/BUILD.gn b/src/platform/nxp/mw320/BUILD.gn index 94025ca12eabdd..cbae110382f1b0 100644 --- a/src/platform/nxp/mw320/BUILD.gn +++ b/src/platform/nxp/mw320/BUILD.gn @@ -23,11 +23,6 @@ if (chip_enable_openthread) { import("//build_overrides/openthread.gni") } -if (chip_crypto == "platform") { - import("//build_overrides/mbedtls.gni") -} - - static_library("mw320") { sources = [ "../../FreeRTOS/SystemTimeSupport.cpp", @@ -66,8 +61,8 @@ static_library("mw320") { if (chip_with_factory_data == 1) { sources += [ - "MW320FactoryDataProvider.cpp", - "MW320FactoryDataProvider.h", + "FactoryDataProvider.cpp", + "FactoryDataProvider.h", ] } @@ -83,17 +78,6 @@ static_library("mw320") { public_deps = [ "${chip_root}/src/platform:platform_base" ] - if (chip_crypto == "platform") { - if (chip_crypto_flavour == "tinycrypt") { - sources += [ - "${chip_root}/src/platform/nxp/common/crypto/CHIPCryptoPALTinyCrypt.cpp", - ] - public_deps += [ - "${mbedtls_root}:mbedtls", - ] - } - } - if (chip_enable_openthread) { sources += [ "../../OpenThread/OpenThreadUtils.cpp", diff --git a/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h b/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h index 8905ffca845efe..8806abb7d61db0 100644 --- a/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h +++ b/src/platform/nxp/mw320/CHIPDevicePlatformConfig.h @@ -56,11 +56,6 @@ #define CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE 8192 #endif // CHIP_DEVICE_CONFIG_THREAD_TASK_STACK_SIZE */ -//#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 -//#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 -//#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 - -// mdns/mdns_sd ++ -//#define CHIP_DEVICE_CONFIG_ENABLE_COMMISSIONABLE_DISCOVERY 1 -#define CHIP_DEVICE_CONFIG_ENABLE_DNSSD 1 -// mdns/dns_sd -- +#define CHIP_DEVICE_CONFIG_ENABLE_WIFI_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY 0 +#define CHIP_DEVICE_CONFIG_ENABLE_THREAD_TELEMETRY_FULL 0 diff --git a/src/platform/nxp/mw320/ConfigurationManagerImpl.h b/src/platform/nxp/mw320/ConfigurationManagerImpl.h index 06aa35fa39aa17..9a182ae9e37bdb 100644 --- a/src/platform/nxp/mw320/ConfigurationManagerImpl.h +++ b/src/platform/nxp/mw320/ConfigurationManagerImpl.h @@ -112,6 +112,8 @@ inline CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * b wifi_get_device_mac_addr(&mac_addr); memcpy(buf, mac_addr.mac, 6); + PRINTF("MAC: %02x:%02x:%02x:%02x:%02x:%02x \r\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); + // return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; return CHIP_NO_ERROR; } diff --git a/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp b/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp index 0e96a78c5db785..802fe2708e3e26 100644 --- a/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp +++ b/src/platform/nxp/mw320/ConnectivityManagerImpl.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #if INET_CONFIG_ENABLE_TCP_ENDPOINT #include @@ -46,7 +45,6 @@ void test_wlan_scan(int argc, char ** argv); void test_wlan_add(int argc, char ** argv); static struct wlan_network sta_network; } -#include "AppTask.h" #if CHIP_DEVICE_CONFIG_ENABLE_WPA #include @@ -117,14 +115,6 @@ CHIP_ERROR ConnectivityManagerImpl::_Init() void ConnectivityManagerImpl::_OnPlatformEvent(const ChipDeviceEvent * event) { // Forward the event to the generic base classes as needed. - switch (event->Type) - { - case DeviceEventType::kCommissioningComplete: - PRINTF("====> DeviceEventType::kCommissioningComplete\r\n"); - break; - default: - break; - } } #if CHIP_DEVICE_CONFIG_ENABLE_WPA @@ -345,11 +335,7 @@ ConnectivityManagerImpl::ConnectWiFiNetworkAsync(ByteSpan ssid, ByteSpan credent // memcpy(sCfgSSID, ssidStr, ssid.size()); sCfgSSIDLen = ssid.size(); - - ChipLogProgress(DeviceLayer, "ConnectWiFiNetworkAsync: [ssid, pwd]=[%s, %s]", ssidStr, keyStr); - // Do connection - chip::DeviceLayer::Internal::ConnectivityUtils::ConnectWiFiNetwork(ssidStr, keyStr); - + // mpConnectCallback = apCallback; #if (MW320_CONNECT_SCAN_SYNC == 1) if (mpConnectCallback != nullptr) diff --git a/src/platform/nxp/mw320/ConnectivityUtils.cpp b/src/platform/nxp/mw320/ConnectivityUtils.cpp index f3c50102cd5539..a4e881c1e96df0 100644 --- a/src/platform/nxp/mw320/ConnectivityUtils.cpp +++ b/src/platform/nxp/mw320/ConnectivityUtils.cpp @@ -294,7 +294,7 @@ CHIP_ERROR ConnectivityUtils::GetInterfaceIPv6Addrs(const char * ifname, uint8_t return CHIP_NO_ERROR; } - for (i = 0; i < CONFIG_MAX_IPV6_ADDRESSES; i++) + for (i = 0; i < MAX_IPV6_ADDRESSES; i++) { if (sta_network.ip.ipv6[i].addr_state == IP6_ADDR_INVALID) { @@ -341,46 +341,39 @@ CHIP_ERROR ConnectivityUtils::GetWiFiRssi(const char * ifname, int8_t & rssi) return err; } - CHIP_ERROR ConnectivityUtils::GetWiFiBeaconRxCount(const char * ifname, uint32_t & beaconRxCount) { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef GET_FROM_SDK int ret; - static wifi_pkt_stats_t stats; + wifi_pkt_stats_t stats; ret = wifi_get_log(&stats); if (ret != WM_SUCCESS) { ChipLogError(DeviceLayer, "wifi_get_log failed "); } + beaconRxCount = stats.bcn_rcv_cnt; ChipLogProgress(DeviceLayer, "GetWiFiBeaconRxCount [%ld] -> working in sdk", beaconRxCount); -#else - beaconRxCount = 1024; - ChipLogProgress(DeviceLayer, "GetWiFiBeaconRxCount [%ld]", beaconRxCount); -#endif //GET_FROM_SDK + return err; } CHIP_ERROR ConnectivityUtils::GetWiFiBeaconLostCount(const char * ifname, uint32_t & beaconLostCount) { CHIP_ERROR err = CHIP_NO_ERROR; -#ifdef GET_FROM_SDK int ret; - static wifi_pkt_stats_t stats; + wifi_pkt_stats_t stats; - ret = wifi_get_log(&g_stats); + ret = wifi_get_log(&stats); if (ret != WM_SUCCESS) { ChipLogError(DeviceLayer, "wifi_get_log failed "); } + beaconLostCount = stats.bcn_miss_cnt; ChipLogProgress(DeviceLayer, "GetWiFiBeaconLostCount [%ld] -> working in sdk", beaconLostCount); -#else - beaconLostCount = 0; - ChipLogProgress(DeviceLayer, "GetWiFiBeaconLostCount [%ld]", beaconLostCount); -#endif //GET_FROM_SDK + return err; } @@ -400,47 +393,6 @@ CHIP_ERROR ConnectivityUtils::GetEthInterfaceName(char * ifname, size_t bufSize) return err; } -extern "C" { - void test_wlan_add(int argc, char ** argv); -}; - -CHIP_ERROR ConnectivityUtils::ConnectWiFiNetwork(const char * ssid, const char * key) -{ - CHIP_ERROR err = CHIP_NO_ERROR; - int ret_mcuXpresso; - char arg0[] = "wlan-add"; - char arg1[32]; - char arg2[] = "ssid"; - char arg3[32]; - char arg4[] = "wpa2"; - char arg5[64]; - char * argv[] = { &arg0[0], &arg1[0], &arg2[0], &arg3[0], &arg4[0], &arg5[0], NULL }; - int argc = (int) (sizeof(argv) / sizeof(argv[0])) - 1; - - sprintf((char *) arg1, "%s", ssid); - sprintf((char *) arg3, "%s", ssid); - sprintf((char *) arg5, "%s", key); - test_wlan_add(argc, &argv[0]); - ret_mcuXpresso = wlan_connect(argv[1]); - if (ret_mcuXpresso == WLAN_ERROR_STATE) - { - ChipLogProgress(DeviceLayer, "Error: connect manager not running"); - err = CHIP_ERROR_CONNECTION_CLOSED_UNEXPECTEDLY; - } - if (ret_mcuXpresso == -WM_E_INVAL) - { - ChipLogProgress(DeviceLayer, "Error: specify a network to connect"); - err = CHIP_ERROR_INVALID_ARGUMENT; - } - else - { - ChipLogProgress(DeviceLayer, - "Connecting to network...\r\nUse 'wlan-stat' for " - "current connection status."); - } - return err; -} - } // namespace Internal } // namespace DeviceLayer } // namespace chip diff --git a/src/platform/nxp/mw320/ConnectivityUtils.h b/src/platform/nxp/mw320/ConnectivityUtils.h index 4e4babf31bbf64..ff8575dd2f2bbf 100644 --- a/src/platform/nxp/mw320/ConnectivityUtils.h +++ b/src/platform/nxp/mw320/ConnectivityUtils.h @@ -56,7 +56,6 @@ class ConnectivityUtils static CHIP_ERROR GetEthInterfaceName(char * ifname, size_t bufSize); // static CHIP_ERROR GetEthPHYRate(const char * ifname, app::Clusters::EthernetNetworkDiagnostics::PHYRateEnum & pHYRate); // static CHIP_ERROR GetEthFullDuplex(const char * ifname, bool & fullDuplex); - static CHIP_ERROR ConnectWiFiNetwork(const char * ssid, const char * key); private: static uint16_t Map2400MHz(const uint8_t inChannel); diff --git a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp index 849d385dacec38..f669ce4b937751 100644 --- a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp +++ b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.cpp @@ -184,15 +184,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetNetworkInterfaces(NetworkInterface ** return CHIP_NO_ERROR; } -void DiagnosticDataProviderImpl::ReleaseNetworkInterfaces(NetworkInterface * netifp) -{ - while (netifp) - { - NetworkInterface * del = netifp; - netifp = netifp->Next; - delete del; - } -} + CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiChannelNumber(uint16_t & channelNumber) { return ConnectivityUtils::GetWiFiChannelNumber(ConnectivityMgrImpl().GetWiFiIfName(), channelNumber); @@ -205,7 +197,7 @@ CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiRssi(int8_t & rssi) CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconRxCount(uint32_t & beaconRxCount) { - return ConnectivityUtils::GetWiFiBeaconRxCount(ConnectivityMgrImpl().GetWiFiIfName(), beaconRxCount); + return ConnectivityUtils::GetWiFiBeaconLostCount(ConnectivityMgrImpl().GetWiFiIfName(), beaconRxCount); } CHIP_ERROR DiagnosticDataProviderImpl::GetWiFiBeaconLostCount(uint32_t & beaconLostCount) diff --git a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h index 40a9e4156e38f5..4707f39e61ee79 100644 --- a/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h +++ b/src/platform/nxp/mw320/DiagnosticDataProviderImpl.h @@ -55,7 +55,6 @@ class DiagnosticDataProviderImpl : public DiagnosticDataProvider CHIP_ERROR GetActiveNetworkFaults(GeneralFaults & networkFaults) override; CHIP_ERROR GetNetworkInterfaces(NetworkInterface ** netifpp) override; - void ReleaseNetworkInterfaces(NetworkInterface * netifp) override; // Wi-Fi Diagnostics CHIP_ERROR GetWiFiChannelNumber(uint16_t & channelNumber) override; diff --git a/src/platform/nxp/mw320/FactoryDataProvider.cpp b/src/platform/nxp/mw320/FactoryDataProvider.cpp new file mode 100644 index 00000000000000..5b36958f306d5b --- /dev/null +++ b/src/platform/nxp/mw320/FactoryDataProvider.cpp @@ -0,0 +1,336 @@ +/* + * + * Copyright (c) 2022 Project CHIP Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "FactoryDataProvider.h" +#include "CHIPDevicePlatformConfig.h" +#include +#include +#include +#include +#include + +/* Grab symbol for the base address from the linker file. */ +extern uint8_t * __FACTORY_DATA_START; +extern uint32_t __FACTORY_DATA_SIZE; + +namespace chip { +namespace { + +CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P256Keypair & keypair) +{ + Crypto::P256SerializedKeypair serialized_keypair; + ReturnErrorOnFailure(serialized_keypair.SetLength(privateKey.size() + publicKey.size())); + memcpy(serialized_keypair.Bytes(), publicKey.data(), publicKey.size()); + memcpy(serialized_keypair.Bytes() + publicKey.size(), privateKey.data(), privateKey.size()); + return keypair.Deserialize(serialized_keypair); +} +} // namespace + +namespace DeviceLayer { + +FactoryDataProvider & FactoryDataProvider::GetDefaultInstance() +{ + static FactoryDataProvider sInstance; + return sInstance; +} + +static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = + BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; +static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; +static constexpr size_t kMaxCertLen = 600; +static constexpr size_t kMaxKeyLen = 32; + +static constexpr size_t kVerifierId = 1; +static constexpr size_t kSaltId = 2; +static constexpr size_t kIcId = 3; +static constexpr size_t kDacPrivateKeyId = 4; +static constexpr size_t kDacCertificateId = 5; +static constexpr size_t kPaiCertificateId = 6; +static constexpr size_t kDiscriminatorId = 7; + +static constexpr size_t kMaxId = kDiscriminatorId; +static uint16_t maxLengths[kMaxId + 1]; + +static uint8_t ReadDataMemCpy(uint16_t num, uint32_t src, uint8_t * dst) +{ + memcpy(dst, (void *) (src), num); + return 0; +} + +// format: [type:1][len:2][data:var] +CHIP_ERROR SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length) +{ + CHIP_ERROR err = CHIP_ERROR_NOT_FOUND; + uint8_t * addr = __FACTORY_DATA_START; + uint8_t type = 0; + + while (addr < (__FACTORY_DATA_START + __FACTORY_DATA_SIZE)) + { + type = addr[0]; + length = *((uint16_t *) (addr + 1)); + + if ((type > kMaxId) || (length > maxLengths[type])) + { + break; + } + + if (searchedType == type) + { + if (bufLength < length) + { + err = CHIP_ERROR_BUFFER_TOO_SMALL; + } + else + { + memcpy(pBuf, addr + 3, length); + err = CHIP_NO_ERROR; + } + break; + } + else + { + /* Jump past 2 bytes of length and then use length to jump to next data */ + addr = addr + 3 + length; + } + } + + return err; +} + +CHIP_ERROR FactoryDataProvider::Init() +{ + maxLengths[kVerifierId] = kSpake2pSerializedVerifier_MaxBase64Len; + maxLengths[kSaltId] = kSpake2pSalt_MaxBase64Len; + maxLengths[kIcId] = 4; + maxLengths[kDacPrivateKeyId] = kMaxKeyLen; + maxLengths[kDacCertificateId] = kMaxCertLen; + maxLengths[kPaiCertificateId] = kMaxCertLen; + maxLengths[kDiscriminatorId] = 4; + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) +{ + constexpr uint8_t kCdForAllExamples[] = CHIP_DEVICE_CONFIG_CERTIFICATION_DECLARATION; + + return CopySpanToMutableSpan(ByteSpan{ kCdForAllExamples }, outBuffer); +} + +CHIP_ERROR FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) +{ + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) +{ + uint16_t certificateSize = 0; + + ReturnErrorOnFailure(SearchForId(kDacCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); + outBuffer.reduce_size(certificateSize); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) +{ + uint16_t certificateSize = 0; + + ReturnErrorOnFailure(SearchForId(kPaiCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); + outBuffer.reduce_size(certificateSize); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) +{ + CHIP_ERROR res; + + Crypto::P256ECDSASignature signature; + Crypto::P256Keypair keypair; + VerifyOrReturnError(!outSignBuffer.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(!messageToSign.empty(), CHIP_ERROR_INVALID_ARGUMENT); + VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); + + // In a non-exemplary implementation, the public key is not needed here. It is used here merely because + // Crypto::P256Keypair is only (currently) constructable from raw keys if both private/public keys are present. + + Crypto::P256PublicKey dacPublicKey; + uint8_t certBuf[kMaxCertLen]; + MutableByteSpan dacCertSpan(certBuf); + uint16_t certificateSize = 0; + CHIP_ERROR err = CHIP_NO_ERROR; + + err = SearchForId(kDacCertificateId, dacCertSpan.data(), dacCertSpan.size(), certificateSize); + ReturnErrorOnFailure(err); + dacCertSpan.reduce_size(certificateSize); + +#if (!defined(MBEDTLS_USE_TINYCRYPT)) + /* Skip fetching public key if using tiny_crypt + In mbedtls_pk_parse_subpubkey(), + If using tiny_crypt => pk_get_ueccpubkey() + If not using tiny_crypt => pk_get_ecpubkey() (needed) + */ + /* Extract Public Key of DAC certificate from itself */ + err = Crypto::ExtractPubkeyFromX509Cert(dacCertSpan, dacPublicKey); + ReturnErrorOnFailure(err); +#endif // MBEDTLS_USE_TINYCRYPT + + /* Get private key of DAC certificate from reserved section */ + uint8_t keyBuf[kMaxKeyLen]; + MutableByteSpan dacPrivateKeySpan(keyBuf); + uint16_t keySize = 0; + ReturnErrorOnFailure(SearchForId(kDacPrivateKeyId, dacPrivateKeySpan.data(), dacPrivateKeySpan.size(), keySize)); + dacPrivateKeySpan.reduce_size(keySize); + + ReturnErrorOnFailure(LoadKeypairFromRaw(ByteSpan(dacPrivateKeySpan.data(), dacPrivateKeySpan.size()), + ByteSpan(dacPublicKey.Bytes(), dacPublicKey.Length()), keypair)); + ReturnErrorOnFailure(keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature)); + + res = CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer); + return res; +} + +CHIP_ERROR FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) +{ + uint32_t discriminator = 0; + uint16_t temp = 0; + + ReturnErrorOnFailure(SearchForId(kDiscriminatorId, (uint8_t *) &discriminator, sizeof(discriminator), temp)); + setupDiscriminator = (uint16_t) (discriminator & 0x0000FFFF); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) +{ + uint16_t temp = 0; + + return SearchForId(kIcId, (uint8_t *) &iterationCount, sizeof(iterationCount), temp); +} + +CHIP_ERROR FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) +{ + char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 }; + uint16_t saltB64Len = 0; + + ReturnErrorOnFailure(SearchForId(kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); + size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); + + ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(saltBuf.data(), saltB64, saltLen); + saltBuf.reduce_size(saltLen); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) +{ + char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 }; + uint16_t verifierB64Len = 0; + + ReturnErrorOnFailure(SearchForId(kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); + + verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); + ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); + memcpy(verifierBuf.data(), verifierB64, verifierLen); + verifierBuf.reduce_size(verifierLen); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +#if CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER +CHIP_ERROR FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetVendorId(uint16_t & vendorId) +{ + vendorId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetProductName(char * buf, size_t bufSize) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetProductId(uint16_t & productId) +{ + productId = static_cast(CHIP_DEVICE_CONFIG_DEVICE_PRODUCT_ID); + return CHIP_NO_ERROR; +} + +CHIP_ERROR FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) +{ + return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; +} + +CHIP_ERROR FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) +{ + return CHIP_ERROR_NOT_IMPLEMENTED; +} + +CHIP_ERROR FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) +{ +#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) +#endif + + return CHIP_ERROR_NOT_IMPLEMENTED; +} +#endif /* CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER */ +} // namespace DeviceLayer +} // namespace chip diff --git a/src/platform/nxp/mw320/MW320FactoryDataProvider.h b/src/platform/nxp/mw320/FactoryDataProvider.h similarity index 78% rename from src/platform/nxp/mw320/MW320FactoryDataProvider.h rename to src/platform/nxp/mw320/FactoryDataProvider.h index acb8ed15ac4676..07afa4a393c5f7 100644 --- a/src/platform/nxp/mw320/MW320FactoryDataProvider.h +++ b/src/platform/nxp/mw320/FactoryDataProvider.h @@ -30,42 +30,19 @@ namespace DeviceLayer { * and Device Instance Info. */ -class MW320FactoryDataProvider : public CommissionableDataProvider, - public Credentials::DeviceAttestationCredentialsProvider, +class FactoryDataProvider : public CommissionableDataProvider, + public Credentials::DeviceAttestationCredentialsProvider +#if CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER + , public DeviceInstanceInfoProvider +#endif // CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER { public: - // Default factory data IDs - enum FactoryDataId - { - kVerifierId = 1, - kSaltId, - kIcId, - kDacPrivateKeyId, - kDacCertificateId, - kPaiCertificateId, - kDiscriminatorId, - kSetupPasscodeId, - kVidId, - kPidId, - kCertDeclarationId, - kVendorNameId, - kProductNameId, - kSerialNumberId, - kManufacturingDateId, - kHardwareVersionId, - kHardwareVersionStrId, - kUniqueId, - kMaxId - }; - static constexpr uint16_t kNumberOfIds = FactoryDataId::kMaxId; + static FactoryDataProvider & GetDefaultInstance(); - static MW320FactoryDataProvider & GetDefaultInstance(); - - MW320FactoryDataProvider(); + FactoryDataProvider() {} CHIP_ERROR Init(); - CHIP_ERROR SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length); // ===== Members functions that implement the CommissionableDataProvider CHIP_ERROR GetSetupDiscriminator(uint16_t & setupDiscriminator) override; @@ -83,6 +60,7 @@ class MW320FactoryDataProvider : public CommissionableDataProvider, CHIP_ERROR GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) override; CHIP_ERROR SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) override; +#if CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER // ===== Members functions that implement the GenericDeviceInstanceInfoProvider CHIP_ERROR GetVendorName(char * buf, size_t bufSize) override; CHIP_ERROR GetVendorId(uint16_t & vendorId) override; @@ -97,9 +75,7 @@ class MW320FactoryDataProvider : public CommissionableDataProvider, CHIP_ERROR GetHardwareVersion(uint16_t & hardwareVersion) override; CHIP_ERROR GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) override; - -protected: - uint16_t maxLengths[kNumberOfIds]; +#endif // CHIP_DEVICE_CONFIG_ENABLE_DEVICE_INSTANCE_INFO_PROVIDER }; } // namespace DeviceLayer diff --git a/src/platform/nxp/mw320/MW320FactoryDataProvider.cpp b/src/platform/nxp/mw320/MW320FactoryDataProvider.cpp deleted file mode 100644 index f22e22a305c26e..00000000000000 --- a/src/platform/nxp/mw320/MW320FactoryDataProvider.cpp +++ /dev/null @@ -1,433 +0,0 @@ -/* - * - * Copyright (c) 2022 Project CHIP Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "MW320FactoryDataProvider.h" -#include "CHIPDevicePlatformConfig.h" -#include -#include -#include -#include -#include -#include -#include -#include - -extern "C" { -#include "hkdf-sha.h" -} - -/* Grab symbol for the base address from the linker file. */ -extern uint8_t * __FACTORY_DATA_START; -extern uint32_t __FACTORY_DATA_SIZE; - -namespace chip { -namespace { - -CHIP_ERROR LoadKeypairFromRaw(ByteSpan privateKey, ByteSpan publicKey, Crypto::P256Keypair & keypair) -{ - Crypto::P256SerializedKeypair serialized_keypair; - ReturnErrorOnFailure(serialized_keypair.SetLength(privateKey.size() + publicKey.size())); - memcpy(serialized_keypair.Bytes(), publicKey.data(), publicKey.size()); - memcpy(serialized_keypair.Bytes() + publicKey.size(), privateKey.data(), privateKey.size()); - return keypair.Deserialize(serialized_keypair); -} -} // namespace - -namespace DeviceLayer { -static constexpr size_t kSpake2pSerializedVerifier_MaxBase64Len = - BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_VerifierSerialized_Length) + 1; -static constexpr size_t kSpake2pSalt_MaxBase64Len = BASE64_ENCODED_LEN(chip::Crypto::kSpake2p_Max_PBKDF_Salt_Length) + 1; -static constexpr size_t kMaxKeyLen = 32; -static constexpr size_t kHashLen = 4; -static constexpr size_t kDataSizeLen = 4; -static constexpr size_t kHashId = 0xCE47BA5E; - -static uint32_t factoryDataStartAddress = 0; - -static uint8_t ReadDataMemCpy(uint16_t num, uint32_t src, uint8_t * dst) -{ - memcpy(dst, (void *) (src), num); - return 0; -} - -MW320FactoryDataProvider & MW320FactoryDataProvider::GetDefaultInstance() -{ - static MW320FactoryDataProvider sInstance; - return sInstance; -} - -MW320FactoryDataProvider::MW320FactoryDataProvider() -{ - maxLengths[FactoryDataId::kVerifierId] = kSpake2pSerializedVerifier_MaxBase64Len; - maxLengths[FactoryDataId::kSaltId] = kSpake2pSalt_MaxBase64Len; - maxLengths[FactoryDataId::kIcId] = 4; - maxLengths[FactoryDataId::kDacPrivateKeyId] = kMaxKeyLen; - maxLengths[FactoryDataId::kDacCertificateId] = Credentials::kMaxDERCertLength; - maxLengths[FactoryDataId::kPaiCertificateId] = Credentials::kMaxDERCertLength; - maxLengths[FactoryDataId::kDiscriminatorId] = sizeof(uint32_t); - maxLengths[FactoryDataId::kSetupPasscodeId] = sizeof(uint32_t); - maxLengths[FactoryDataId::kVidId] = sizeof(uint16_t); - maxLengths[FactoryDataId::kPidId] = sizeof(uint16_t); - maxLengths[FactoryDataId::kCertDeclarationId] = Credentials::kMaxCMSSignedCDMessage; - maxLengths[FactoryDataId::kVendorNameId] = ConfigurationManager::kMaxVendorNameLength; - maxLengths[FactoryDataId::kProductNameId] = ConfigurationManager::kMaxProductNameLength; - maxLengths[FactoryDataId::kSerialNumberId] = ConfigurationManager::kMaxSerialNumberLength; - maxLengths[FactoryDataId::kManufacturingDateId] = ConfigurationManager::kMaxManufacturingDateLength; - maxLengths[FactoryDataId::kHardwareVersionId] = sizeof(uint16_t); - maxLengths[FactoryDataId::kHardwareVersionStrId] = ConfigurationManager::kMaxHardwareVersionStringLength; - maxLengths[FactoryDataId::kUniqueId] = ConfigurationManager::kMaxUniqueIDLength; -} - - -CHIP_ERROR MW320FactoryDataProvider::Init() -{ - uint8_t sha256Output[SHA256HashSize] = {0}; - uint32_t start = (uint32_t)__FACTORY_DATA_START; - uint32_t sum = 0; - uint32_t size; - uint32_t hashId; - uint8_t hashReadFromFlash[kHashLen]; - - // Make sure the buffer is sufficient - for (uint8_t i = 1; i < MW320FactoryDataProvider::kNumberOfIds; i++) - { - sum += maxLengths[i]; - } - if(sum > (uint32_t)__FACTORY_DATA_SIZE) - { - ChipLogError(DeviceLayer, - "Max size of factory data: %" PRIu32 " is bigger than reserved factory data size: %" PRIu32, - sum, (uint32_t)__FACTORY_DATA_SIZE - ); - } - /* Before trying to verify the hash, make sure there is a hash there by checking its tag */ - hashId = *(uint32_t*)start; - if (hashId != kHashId) - { - ChipLogProgress(NotSpecified, "Inconsist HashId [%04lx, %04x] ", hashId, kHashId); - return CHIP_ERROR_NOT_FOUND; - } - start += sizeof(kHashId); - /* Read length of factory data from internal flash and 4 byte from computed SHA256 hash over factory data */ - size = *(uint32_t*)start; - start += sizeof(size); - - memcpy(hashReadFromFlash, (uint8_t *)start, sizeof(hashReadFromFlash)); - start += sizeof(hashReadFromFlash); - - /* Calculate SHA256 on the factory data and compare with stored value */ - { - SHA256Context ctx; - SHA256Reset(&ctx); - SHA256Input(&ctx, (uint8_t *)start, size); - SHA256Result(&ctx, sha256Output); - } - if (memcmp(&sha256Output[0], &hashReadFromFlash[0], kHashLen) != 0) - { - ChipLogProgress(NotSpecified, "Incorrect SHA256 [%02x%02x%02x%02x, %02x%02x%02x%02x] ", - sha256Output[0], sha256Output[1], sha256Output[2], sha256Output[3], - hashReadFromFlash[0], hashReadFromFlash[1], hashReadFromFlash[2], hashReadFromFlash[3]); - return CHIP_ERROR_NOT_FOUND; - } - /* Set factory data start address after hash id, hash and hash size */ - factoryDataStartAddress = start; - return CHIP_NO_ERROR; -} - -// format: [type:1][len:2][data:var] -CHIP_ERROR MW320FactoryDataProvider::SearchForId(uint8_t searchedType, uint8_t * pBuf, size_t bufLength, uint16_t & length) -{ - CHIP_ERROR err = CHIP_ERROR_NOT_FOUND; - uint8_t * addr = (uint8_t *)factoryDataStartAddress; - uint8_t type = 0; - - while ((uint32_t)addr < (factoryDataStartAddress + __FACTORY_DATA_SIZE)) - { - type = addr[0]; - length = *((uint16_t *) (addr + 1)); - - if ((type > MW320FactoryDataProvider::kNumberOfIds) || (length > maxLengths[type])) - { - break; - } - - if (searchedType == type) - { - if ((type >= MW320FactoryDataProvider::kNumberOfIds) || (length > maxLengths[type])) - { - ChipLogError(DeviceLayer, "Failed validity check for factory data with: id=%" PRIu8 ", length=%" PRIu16, type, length); - break; - } - if (bufLength < length) - { - err = CHIP_ERROR_BUFFER_TOO_SMALL; - } - else - { - memcpy(pBuf, addr + 3, length); - err = CHIP_NO_ERROR; - } - break; - } - else - { - /* Jump past 2 bytes of length and then use length to jump to next data */ - addr = addr + 3 + length; - } - } - - return err; -} - - -CHIP_ERROR MW320FactoryDataProvider::GetCertificationDeclaration(MutableByteSpan & outBuffer) -{ - uint16_t declarationSize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kCertDeclarationId, outBuffer.data(), outBuffer.size(), declarationSize)); - outBuffer.reduce_size(declarationSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetFirmwareInformation(MutableByteSpan & out_firmware_info_buffer) -{ - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetDeviceAttestationCert(MutableByteSpan & outBuffer) -{ - uint16_t certificateSize = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); - outBuffer.reduce_size(certificateSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetProductAttestationIntermediateCert(MutableByteSpan & outBuffer) -{ - uint16_t certificateSize = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kPaiCertificateId, outBuffer.data(), outBuffer.size(), certificateSize)); - outBuffer.reduce_size(certificateSize); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::SignWithDeviceAttestationKey(const ByteSpan & messageToSign, MutableByteSpan & outSignBuffer) -{ - Crypto::P256ECDSASignature signature; - Crypto::P256Keypair keypair; - Crypto::P256SerializedKeypair serializedKeypair; - - VerifyOrReturnError(IsSpanUsable(outSignBuffer), CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(IsSpanUsable(messageToSign), CHIP_ERROR_INVALID_ARGUMENT); - VerifyOrReturnError(outSignBuffer.size() >= signature.Capacity(), CHIP_ERROR_BUFFER_TOO_SMALL); - - /* Get private key of DAC certificate from reserved section */ - uint8_t keyBuf[kMaxKeyLen]; - MutableByteSpan dacPrivateKeySpan(keyBuf); - uint16_t keySize = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDacPrivateKeyId, dacPrivateKeySpan.data(), dacPrivateKeySpan.size(), keySize)); - dacPrivateKeySpan.reduce_size(keySize); - - /* Only the private key is used when signing */ - ReturnErrorOnFailure(serializedKeypair.SetLength(Crypto::kP256_PublicKey_Length + dacPrivateKeySpan.size())); - memcpy(serializedKeypair.Bytes() + Crypto::kP256_PublicKey_Length, dacPrivateKeySpan.data(), dacPrivateKeySpan.size()); - - ReturnErrorOnFailure(keypair.Deserialize(serializedKeypair)); - ReturnErrorOnFailure(keypair.ECDSA_sign_msg(messageToSign.data(), messageToSign.size(), signature)); - return CopySpanToMutableSpan(ByteSpan{ signature.ConstBytes(), signature.Length() }, outSignBuffer); -} - -CHIP_ERROR MW320FactoryDataProvider::GetSetupDiscriminator(uint16_t & setupDiscriminator) -{ - uint32_t discriminator = 0; - uint16_t temp = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kDiscriminatorId, (uint8_t *) &discriminator, sizeof(discriminator), temp)); - setupDiscriminator = (uint16_t)(discriminator & 0x0000FFFF); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::SetSetupDiscriminator(uint16_t setupDiscriminator) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR MW320FactoryDataProvider::GetSpake2pIterationCount(uint32_t & iterationCount) -{ - uint16_t temp = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kIcId, (uint8_t *) &iterationCount, sizeof(iterationCount), temp)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetSpake2pSalt(MutableByteSpan & saltBuf) -{ - char saltB64[kSpake2pSalt_MaxBase64Len] = { 0 }; - uint16_t saltB64Len = 0; - - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSaltId, (uint8_t *) (&saltB64[0]), sizeof(saltB64), saltB64Len)); - size_t saltLen = chip::Base64Decode32(saltB64, saltB64Len, reinterpret_cast(saltB64)); - - ReturnErrorCodeIf(saltLen > saltBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(saltBuf.data(), saltB64, saltLen); - saltBuf.reduce_size(saltLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetSpake2pVerifier(MutableByteSpan & verifierBuf, size_t & verifierLen) -{ - char verifierB64[kSpake2pSerializedVerifier_MaxBase64Len] = { 0 }; - uint16_t verifierB64Len = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVerifierId, (uint8_t *) &verifierB64[0], sizeof(verifierB64), verifierB64Len)); - - verifierLen = chip::Base64Decode32(verifierB64, verifierB64Len, reinterpret_cast(verifierB64)); - ReturnErrorCodeIf(verifierLen > verifierBuf.size(), CHIP_ERROR_BUFFER_TOO_SMALL); - memcpy(verifierBuf.data(), verifierB64, verifierLen); - verifierBuf.reduce_size(verifierLen); - - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetSetupPasscode(uint32_t & setupPasscode) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSetupPasscodeId, (uint8_t *) &setupPasscode, sizeof(setupPasscode), length)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::SetSetupPasscode(uint32_t setupPasscode) -{ - return CHIP_ERROR_NOT_IMPLEMENTED; -} - -CHIP_ERROR MW320FactoryDataProvider::GetVendorName(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVendorNameId, (uint8_t *)buf, bufSize, length)); - buf[length] = '\0'; - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetVendorId(uint16_t & vendorId) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kVidId, (uint8_t *) &vendorId, sizeof(vendorId), length)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetProductName(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kProductNameId, (uint8_t *)buf, bufSize, length)); - buf[length] = '\0'; - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetProductId(uint16_t & productId) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kPidId, (uint8_t *) &productId, sizeof(productId), length)); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetPartNumber(char * buf, size_t bufSize) -{ - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -} - -CHIP_ERROR MW320FactoryDataProvider::GetProductURL(char * buf, size_t bufSize) -{ - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -} - -CHIP_ERROR MW320FactoryDataProvider::GetProductLabel(char * buf, size_t bufSize) -{ - return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE; -} - -CHIP_ERROR MW320FactoryDataProvider::GetSerialNumber(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kSerialNumberId, (uint8_t *)buf, bufSize, length)); - buf[length] = '\0'; - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetManufacturingDate(uint16_t & year, uint8_t & month, uint8_t & day) -{ - uint16_t length = 0; - uint8_t date[ConfigurationManager::kMaxManufacturingDateLength]; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kManufacturingDateId, date, ConfigurationManager::kMaxManufacturingDateLength, length)); - date[length] = '\0'; - if (length == 10 && isdigit(date[0]) && isdigit(date[1]) && isdigit(date[2]) && - isdigit(date[3]) && date[4] == '-' && isdigit(date[5]) && isdigit(date[6]) && - date[7] == '-' && isdigit(date[8]) && isdigit(date[9])) - { - year = 1000 * (date[0] - '0') + 100 * (date[1] - '0') + 10 * (date[2] - '0') + date[3] - '0'; - month = 10 * (date[5] - '0') + date[6] - '0'; - day = 10 * (date[8] - '0') + date[9] - '0'; - } - else - { - ChipLogError(DeviceLayer, "Manufacturing date is not formatted correctly: YYYY-MM-DD."); - return CHIP_ERROR_INVALID_ARGUMENT; - } - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetHardwareVersion(uint16_t & hardwareVersion) -{ - uint16_t length = 0; - ReturnErrorOnFailure( - SearchForId(FactoryDataId::kHardwareVersionId, (uint8_t *) &hardwareVersion, sizeof(hardwareVersion), length) - ); - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetHardwareVersionString(char * buf, size_t bufSize) -{ - uint16_t length = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kHardwareVersionStrId, (uint8_t *)buf, bufSize, length)); buf[length] = '\0'; - return CHIP_NO_ERROR; -} - -CHIP_ERROR MW320FactoryDataProvider::GetRotatingDeviceIdUniqueId(MutableByteSpan & uniqueIdSpan) -{ - ChipError err = CHIP_ERROR_WRONG_KEY_TYPE; -#if CHIP_ENABLE_ROTATING_DEVICE_ID && defined(CHIP_DEVICE_CONFIG_ROTATING_DEVICE_ID_UNIQUE_ID) - char uniqueId[ConfigurationManager::kMaxUniqueIDLength] = { 0 }; - uint16_t uniqueIdLen = 0; - ReturnErrorOnFailure(SearchForId(FactoryDataId::kUniqueId, (uint8_t *) (&uniqueId[0]), sizeof(uniqueId), uniqueIdLen)); - static_assert( - ConfigurationManager::kRotatingDeviceIDUniqueIDLength >= ConfigurationManager::kMinRotatingDeviceIDUniqueIDLength, - "Length of unique ID for rotating device ID is smaller than minimum." - ); - VerifyOrReturnValue((uniqueIdLen <= uniqueIdSpan.size()), CHIP_ERROR_BUFFER_TOO_SMALL, - ChipLogProgress(NotSpecified, "GetRotatingDeviceIdUniqueId: %u, %u", uniqueIdLen, uniqueIdSpan.size())); - VerifyOrReturnValue((uniqueIdLen == ConfigurationManager::kRotatingDeviceIDUniqueIDLength), CHIP_ERROR_BUFFER_TOO_SMALL, - ChipLogProgress(NotSpecified, "kRotatingDeviceIDUniqueIDLength: %u \r\n", ConfigurationManager::kRotatingDeviceIDUniqueIDLength)); - memcpy(uniqueIdSpan.data(), uniqueId, uniqueIdLen); - uniqueIdSpan.reduce_size(uniqueIdLen); -#endif - return err; - -} - -} // namespace DeviceLayer -} // namespace chip diff --git a/src/platform/nxp/mw320/PlatformManagerImpl.cpp b/src/platform/nxp/mw320/PlatformManagerImpl.cpp index 54f3a93f273e75..d6751849c7a899 100644 --- a/src/platform/nxp/mw320/PlatformManagerImpl.cpp +++ b/src/platform/nxp/mw320/PlatformManagerImpl.cpp @@ -46,19 +46,7 @@ sys_mutex_t PlatformManagerImpl::rngMutexHandle = NULL; static int app_entropy_source(void * data, unsigned char * output, size_t len, size_t * olen) { - static uint8_t rnd_offset=0; - uint8_t *prand=NULL; - - ChipLogProgress(NotSpecified, "app_entropy_source: len: %u", len); - prand = get_uninit_mem_hash_buff(rnd_offset); - if (prand != NULL) { - memcpy(output, prand, len); - *olen = len; - } else { - *olen = 0; - } - - rnd_offset += len/8; + *olen = len; return 0; } diff --git a/src/platform/nxp/mw320/args.gni b/src/platform/nxp/mw320/args.gni index 4d06050a6311ea..d13db9cc73b095 100644 --- a/src/platform/nxp/mw320/args.gni +++ b/src/platform/nxp/mw320/args.gni @@ -33,8 +33,8 @@ chip_inet_config_enable_dns_resolver = false chip_detail_logging = false chip_build_tests = false chip_progress_logging = true -chip_access_control_policy_logging_verbosity = 1 -enable_im_pretty_print = false +chip_access_control_policy_logging_verbosity = 2 +enable_im_pretty_print = true chip_mdns = "minimal" mbedtls_target = "${chip_root}/third_party/nxp/mw320_sdk:mbedtls" diff --git a/src/platform/nxp/mw320/mw320_ota.cpp b/src/platform/nxp/mw320/mw320_ota.cpp index 48989609e32c2c..0b4fa1615fa7f2 100644 --- a/src/platform/nxp/mw320/mw320_ota.cpp +++ b/src/platform/nxp/mw320/mw320_ota.cpp @@ -186,7 +186,7 @@ static int verify_load_firmware(uint32_t flash_addr, uint32_t size) return WM_SUCCESS; } -void mw320_dev_reset(unsigned int delay_ms) +static void mw320_dev_reset(unsigned int delay_ms) { vTaskDelay(1000 / portTICK_PERIOD_MS); NVIC_SystemReset(); diff --git a/src/platform/nxp/mw320/mw320_ota.h b/src/platform/nxp/mw320/mw320_ota.h index a0ad305eaa3584..9a289c22c86ccd 100644 --- a/src/platform/nxp/mw320/mw320_ota.h +++ b/src/platform/nxp/mw320/mw320_ota.h @@ -23,7 +23,6 @@ fw_update_id_t mw320_fw_update_begin(void); int mw320_fw_update_wrblock(fw_update_id_t fwup_id, unsigned char * pblock, unsigned int blksize); int mw320_fw_update_end(fw_update_id_t fwup_id, int rst_delay_sec); int mw320_fw_update_abort(fw_update_id_t fwup_id); -void mw320_dev_reset(unsigned int delay_ms); #define MW320_OTA_TEST 0 #if (MW320_OTA_TEST == 1) diff --git a/third_party/nxp/mw320_sdk/BUILD.gn b/third_party/nxp/mw320_sdk/BUILD.gn index 361ced98f4f2b9..e88f2e842e725e 100644 --- a/third_party/nxp/mw320_sdk/BUILD.gn +++ b/third_party/nxp/mw320_sdk/BUILD.gn @@ -31,6 +31,13 @@ group("mw320_sdk") { public_deps = [ mw320_sdk_target ] } +if (chip_crypto == "tinycrypt") { + assert( + mbedtls_repo == + "//third_party/connectedhomeip/third_party/nxp/libs/mbedtls", + "mbedtls_repo must be set to nxp mbedtls-tinycrypt library when chip_crypto == \"tinycrypt\"") +} + config("mbedtls_mw320_config") { defines = [ "MBEDTLS_CONFIG_FILE=", @@ -72,7 +79,8 @@ config("mbedtls_mw320_config") { ] } - if (chip_crypto == "platform" && chip_crypto_flavour == "tinycrypt") { + #if (mbedtls_use_tinycrypt) { + if (chip_crypto == "tinycrypt") { defines += [ "MBEDTLS_USE_TINYCRYPT", "MBEDTLS_OPTIMIZE_TINYCRYPT_ASM", @@ -81,24 +89,24 @@ config("mbedtls_mw320_config") { include_dirs = [ chip_root ] - if (chip_crypto == "platform" && chip_crypto_flavour == "tinycrypt") { - include_dirs += [ "${chip_root}/third_party/openthread/ot-nxp/third_party/tinycrypt/inc" ] -# include_dirs += [ "${chip_root}/third_party/openthread/ot-nxp/src/common" ] + #if (mbedtls_use_tinycrypt) { + if (chip_crypto == "tinycrypt") { + include_dirs += [ "${mbedtls_repo}/repo/include/tinycrypt" ] } } mbedtls_target("mbedtls") { import("${mw320_sdk_build_root}/mw320_sdk.gni") - if (chip_crypto == "platform" && chip_crypto_flavour == "tinycrypt") { + #if (mbedtls_use_tinycrypt) { + if (chip_crypto == "tinycrypt") { if (!defined(sources)) { sources = [] } sources += [ - "${chip_root}/third_party/openthread/ot-nxp/third_party/tinycrypt/src/ecc.c", - "${chip_root}/third_party/openthread/ot-nxp/third_party/tinycrypt/src/ecc_dh.c", - "${chip_root}/third_party/openthread/ot-nxp/third_party/tinycrypt/src/ecc_dsa.c", - "${chip_root}/third_party/openthread/ot-nxp/third_party/tinycrypt/src/tinycrypt_util.c", + "${mbedtls_repo}/repo/tinycrypt/ecc.c", + "${mbedtls_repo}/repo/tinycrypt/ecc_dh.c", + "${mbedtls_repo}/repo/tinycrypt/ecc_dsa.c", ] } public_configs = [ ":mbedtls_mw320_config" ] diff --git a/third_party/nxp/mw320_sdk/mw320_sdk.gni b/third_party/nxp/mw320_sdk/mw320_sdk.gni index a2cd01f0e502b1..d0836c1ae326ef 100644 --- a/third_party/nxp/mw320_sdk/mw320_sdk.gni +++ b/third_party/nxp/mw320_sdk/mw320_sdk.gni @@ -22,16 +22,12 @@ declare_args() { # Location of the mw320 SDK. mw320_sdk_root = "${chip_root}/third_party/nxp/mw320_sdk/repo" + #mbedtls_use_tinycrypt = false chip_with_factory_data = 0 - chip_crypto_flavour = "tinycrypt" } assert(mw320_sdk_root != "", "mw320_sdk_root must be specified") -if (chip_crypto == "platform") { - assert(chip_crypto_flavour == "tinycrypt", "chosse tinycrypt as crypto platform") -} - # Defines an mw320 SDK build target. # # Parameters: @@ -44,10 +40,6 @@ template("mw320_sdk") { assert(mw320_sdk_root != "", "mw320_sdk_root must be specified") - if (chip_crypto == "platform") { - print("ECC crypto lib: ", chip_crypto_flavour) - } - sdk_target_name = target_name config("${sdk_target_name}_config") { @@ -93,11 +85,7 @@ template("mw320_sdk") { "${mw320_sdk_root}/middleware/lwip/src/include", "${mw320_sdk_root}/middleware/lwip/src/include/lwip", "${mw320_sdk_root}/middleware/lwip/src/include/lwip/apps", - "${mw320_sdk_root}/boards/rdmw320_r0/mbedtls_common/", - "${mw320_sdk_root}/middleware/wifi/wps", - "${mw320_sdk_root}/middleware/wifi/incl/port/mbedtls", - "${mw320_sdk_root}/middleware/wifi/port/mbedtls", - "${mw320_sdk_root}/middleware/mbedtls/include", + "${mw320_sdk_root}/boards/rdmw320_r0/mbedtls_common", ] defines = [ @@ -168,7 +156,6 @@ template("mw320_sdk") { "${mw320_sdk_root}/boards/rdmw320_r0/wifi_examples/mw_wifi_cli/lpm.c", "${mw320_sdk_root}/boards/rdmw320_r0/wifi_examples/mw_wifi_cli/network_flash_storage.c", "${mw320_sdk_root}/boards/rdmw320_r0/wifi_examples/mw_wifi_cli/pin_mux.c", - "${mw320_sdk_root}/boards/rdmw320_r0/mbedtls_common/sha224-256.c", "${mw320_sdk_root}/components/boot2_utils/boot_flags.c", "${mw320_sdk_root}/components/boot2_utils/crc32.c", "${mw320_sdk_root}/components/boot2_utils/keystore.c", @@ -249,7 +236,7 @@ template("mw320_sdk") { "${mw320_sdk_root}/middleware/wifi/dhcpd/dhcp-server.c", "${mw320_sdk_root}/middleware/wifi/dhcpd/dns-server.c", "${mw320_sdk_root}/middleware/wifi/nw_utils/iperf.c", - "${mw320_sdk_root}/middleware/wifi/nw_utils/wifi_ping.c", + "${mw320_sdk_root}/middleware/wifi/nw_utils/ping.c", "${mw320_sdk_root}/middleware/wifi/port/lwip/net.c", "${mw320_sdk_root}/middleware/wifi/port/lwip/wifi_netif.c", "${mw320_sdk_root}/middleware/wifi/port/os/os.c", @@ -283,9 +270,6 @@ template("mw320_sdk") { "${mw320_sdk_root}/middleware/wifi/wifidriver/wifi-uap.c", "${mw320_sdk_root}/middleware/wifi/wifidriver/wifi.c", "${mw320_sdk_root}/middleware/wifi/wifidriver/wifi_pwrmgr.c", - "${mw320_sdk_root}/middleware/wifi/wifidriver/wifi-wps.c", - "${mw320_sdk_root}/middleware/wifi/wifidriver/sdio.c", - "${mw320_sdk_root}/middleware/wifi/wifidriver/firmware_dnld.c", "${mw320_sdk_root}/middleware/wifi/wlcmgr/wlan.c", "${mw320_sdk_root}/middleware/wifi/wlcmgr/wlan_basic_cli.c", "${mw320_sdk_root}/middleware/wifi/wlcmgr/wlan_tests.c",