wifi configuration formation and password encryption

Signed-off-by: fengye <fengye10@huawei.com>
This commit is contained in:
fengye 2022-09-09 09:57:39 +00:00
parent baba51816c
commit ce5e2c083c
22 changed files with 1134 additions and 291 deletions

View File

@ -49,7 +49,8 @@
"wifi_feature_with_ap_intf",
"wifi_feature_with_ap_num",
"wifi_feature_with_auth_disable",
"wifi_feature_with_dhcp_disable"
"wifi_feature_with_dhcp_disable",
"wifi_feature_with_encryption"
],
"adapted_system_type": [
"standard"

View File

@ -152,6 +152,7 @@ if (defined(ohos_lite)) {
include_dirs = [
"//commonlibrary/c_utils/base/include",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/include",
"//base/security/huks/interfaces/innerkits/huks_standard/main/include",
"//foundation/arkui/ace_engine/frameworks/base/utils",
"//foundation/arkui/ace_engine/frameworks",
"//foundation/systemabilitymgr/safwk/interfaces/innerkits/safwk/",
@ -243,6 +244,10 @@ if (defined(ohos_lite)) {
defines += [ "FEATURE_AP_SUPPORT" ]
}
if (wifi_feature_with_encryption) {
defines += [ "FEATURE_ENCRYPTION_SUPPORT" ]
}
deps = [ ":wifi_p2p_service_impl" ]
external_deps = [
"ability_base:want",
@ -345,6 +350,7 @@ if (defined(ohos_lite)) {
"netmanager_base:net_conn_manager_if",
"safwk:system_ability_fwk",
"samgr:samgr_proxy",
"huks:libhukssdk"
]
defines = [
"FEATURE_AP_SUPPORT",
@ -356,6 +362,10 @@ if (defined(ohos_lite)) {
defines += [ "PERMISSION_ALWAYS_GRANT" ]
}
if (wifi_feature_with_encryption) {
defines += [ "FEATURE_ENCRYPTION_SUPPORT" ]
}
part_name = "wifi"
subsystem_name = "communication"
}

View File

@ -87,11 +87,13 @@ bool GroupNegotiationState::ProcessGroupStartedEvt(InternalMessage &msg) const
}
if (groupManager.GetCurrentGroup().IsPersistent()) {
p2pStateMachine.UpdatePersistentGroups();
p2pStateMachine.UpdateGroupManager();
const WifiP2pDevice &owner = groupManager.GetCurrentGroup().GetOwner();
WifiP2pGroupInfo copy = groupManager.GetCurrentGroup();
copy.SetNetworkId(groupManager.GetGroupNetworkId(owner, groupManager.GetCurrentGroup().GetGroupName()));
groupManager.SetCurrentGroup(copy);
groupManager.AddOrUpdateGroup(groupManager.GetCurrentGroup());
p2pStateMachine.UpdatePersistentGroups();
} else {
WifiP2pGroupInfo copy = groupManager.GetCurrentGroup();
copy.SetNetworkId(TEMPORARY_NET_ID);
@ -229,5 +231,5 @@ bool GroupNegotiationState::ExecuteStateMsg(InternalMessage *msg)
return NOT_EXECUTED;
}
}
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS

View File

@ -328,13 +328,7 @@ bool P2pEnabledState::P2pSettingsInitialization()
result = false;
}
std::map<int, WifiP2pGroupInfo> wpaGroups;
retCode = WifiP2PHalInterface::GetInstance().ListNetworks(wpaGroups);
if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) {
WIFI_LOGE("Failed to get listNetworks.");
result = false;
}
groupManager.UpdateGroupsNetwork(wpaGroups);
p2pStateMachine.UpdateGroupManager();
p2pStateMachine.UpdatePersistentGroups();
return result;
}

View File

@ -85,7 +85,8 @@ bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) c
WIFI_LOGW("Some configuration settings failed!");
}
ret = WifiP2PHalInterface::GetInstance().GroupAdd(true, netId, freq);
(void)WifiP2PHalInterface::GetInstance().SaveConfig();
p2pStateMachine.UpdateGroupManager();
p2pStateMachine.UpdatePersistentGroups();
}
} else if (netId == PERSISTENT_NET_ID || netId == TEMPORARY_NET_ID) {
/**
@ -95,7 +96,8 @@ bool P2pGroupOperatingState::ProcessCmdCreateGroup(const InternalMessage &msg) c
if (config.GetPassphrase().empty() && config.GetGroupName().empty()) {
WifiSettings::GetInstance().SetExplicitGroup(true);
ret = WifiP2PHalInterface::GetInstance().GroupAdd((netId == PERSISTENT_NET_ID) ? true : false, netId, freq);
(void)WifiP2PHalInterface::GetInstance().SaveConfig();
p2pStateMachine.UpdateGroupManager();
p2pStateMachine.UpdatePersistentGroups();
} else if (!config.GetPassphrase().empty() && !config.GetGroupName().empty() &&
config.GetPassphrase().length() >= MIN_PSK_LEN && config.GetPassphrase().length() <= MAX_PSK_LEN) {
WifiSettings::GetInstance().SetExplicitGroup(true);
@ -133,11 +135,12 @@ bool P2pGroupOperatingState::ProcessGroupStartedEvt(const InternalMessage &msg)
/**
* Update groups.
*/
p2pStateMachine.UpdatePersistentGroups();
p2pStateMachine.UpdateGroupManager();
group.SetNetworkId(groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName()));
WIFI_LOGI("the group network id is %{public}d set id is %{public}d",
group.GetNetworkId(),
p2pStateMachine.groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName()));
p2pStateMachine.UpdatePersistentGroups();
} else {
group.SetNetworkId(TEMPORARY_NET_ID);
WIFI_LOGI("This is a temporary group.");
@ -301,13 +304,13 @@ bool P2pGroupOperatingState::ProcessCmdDeleteGroup(const InternalMessage &msg) c
}
ret = WifiP2PHalInterface::GetInstance().RemoveNetwork(networkId);
(void)WifiP2PHalInterface::GetInstance().SaveConfig();
groupManager.RemoveGroup(group);
if (ret) {
WIFI_LOGE("P2P group deletion failed.");
p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteGroup, WIFI_OPT_FAILED);
} else {
WIFI_LOGI("The P2P group is deleted successfully.");
p2pStateMachine.UpdateGroupManager();
p2pStateMachine.UpdatePersistentGroups();
p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteGroup, WIFI_OPT_SUCCESS);
}
@ -352,5 +355,5 @@ bool P2pGroupOperatingState::ExecuteStateMsg(InternalMessage *msg)
return NOT_EXECUTED;
}
}
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS

View File

@ -237,11 +237,12 @@ bool P2pIdleState::ProcessGroupStartedEvt(InternalMessage &msg) const
/**
* Update groups.
*/
p2pStateMachine.UpdatePersistentGroups();
p2pStateMachine.UpdateGroupManager();
group.SetNetworkId(groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName()));
WIFI_LOGI("the group network id is %{public}d set id is %{public}d",
group.GetNetworkId(),
p2pStateMachine.groupManager.GetGroupNetworkId(group.GetOwner(), group.GetGroupName()));
p2pStateMachine.UpdatePersistentGroups();
}
group.SetP2pGroupStatus(P2pGroupStatus::GS_STARTED);
p2pStateMachine.groupManager.SetCurrentGroup(group);
@ -380,5 +381,5 @@ bool P2pIdleState::ExecuteStateMsg(InternalMessage *msg)
return NOT_EXECUTED;
}
}
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS

View File

@ -178,37 +178,28 @@ void P2pStateMachine::InitializeThisDevice()
deviceManager.GetThisDevice().SetSecondaryDeviceType(p2pVendorCfg.GetSecondaryDeviceType());
}
void P2pStateMachine::UpdatePersistentGroups() const
void P2pStateMachine::UpdateGroupManager() const
{
std::map<int, WifiP2pGroupInfo> mapGroups;
WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().ListNetworks(mapGroups);
if (retCode != WifiErrorNo::WIFI_IDL_OPT_OK) {
WIFI_LOGE("Failed to get p2p networks.");
std::map<int, WifiP2pGroupInfo> wpaGroups;
WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().ListNetworks(wpaGroups);
if (retCode == WifiErrorNo::WIFI_IDL_OPT_FAILED) {
WIFI_LOGE("Failed to get listNetworks");
return;
}
for (auto iter : mapGroups) {
WifiP2pGroupInfo &p2pGroupInfo = iter.second;
if (deviceManager.GetThisDevice() == p2pGroupInfo.GetOwner()) {
p2pGroupInfo.SetOwner(deviceManager.GetThisDevice());
}
groupManager.UpdateWpaGroup(p2pGroupInfo);
for (auto wpaGroup = wpaGroups.begin(); wpaGroup != wpaGroups.end(); ++wpaGroup) {
groupManager.UpdateWpaGroup(wpaGroup->second);
}
groupManager.UpdateGroupsNetwork(wpaGroups);
}
void P2pStateMachine::UpdatePersistentGroups() const
{
WIFI_LOGI("UpdatePersistentGroups");
std::vector<WifiP2pGroupInfo> groups;
groups = groupManager.GetGroups();
for (auto it : groups) {
if (mapGroups.find(it.GetNetworkId()) == mapGroups.end()) {
WifiP2pGroupInfo removeGroup;
removeGroup.SetNetworkId(it.GetNetworkId());
groupManager.RemoveGroup(removeGroup);
}
}
WifiSettings::GetInstance().SetWifiP2pGroupInfo(groups);
if (retCode == WifiErrorNo::WIFI_IDL_OPT_OK) {
BroadcastPersistentGroupsChanged();
}
WifiSettings::GetInstance().SyncWifiP2pGroupInfoConfig();
BroadcastPersistentGroupsChanged();
}
bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfigInternal &config) const
@ -274,6 +265,7 @@ bool P2pStateMachine::ReawakenPersistentGroup(WifiP2pConfigInternal &config) con
if (WifiErrorNo::WIFI_IDL_OPT_OK !=
WifiP2PHalInterface::GetInstance().Reinvoke(networkId, device.GetDeviceAddress())) {
WIFI_LOGE("Failed to reinvoke.");
UpdateGroupManager();
UpdatePersistentGroups();
return false;
} else {
@ -324,6 +316,7 @@ void P2pStateMachine::RemoveGroupByNetworkId(int networkId) const
if (WifiP2PHalInterface::GetInstance().RemoveNetwork(networkId) != WifiErrorNo::WIFI_IDL_OPT_OK) {
WIFI_LOGE("failed to remove networkId, networkId is %{public}d.", networkId);
}
UpdateGroupManager();
UpdatePersistentGroups();
BroadcastPersistentGroupsChanged();
}
@ -829,6 +822,7 @@ bool P2pStateMachine::SetGroupConfig(const WifiP2pConfigInternal &config, bool n
{
WifiErrorNo ret;
IdlP2pGroupConfig wpaConfig;
WifiP2pGroupInfo group;
if (newGroup) {
WIFI_LOGI("SetGroupConfig, new group");
wpaConfig.ssid = config.GetGroupName();
@ -864,6 +858,10 @@ bool P2pStateMachine::SetGroupConfig(const WifiP2pConfigInternal &config, bool n
wpaConfig.disabled = knownConfig.disabled;
wpaConfig.mode = knownConfig.mode;
}
group.SetGroupName(config.GetGroupName());
group.SetPassphrase(config.GetPassphrase());
group.SetNetworkId(config.GetNetId());
groupManager.AddOrUpdateGroup(group);
ret = WifiP2PHalInterface::GetInstance().P2pSetGroupConfig(config.GetNetId(), wpaConfig);
if (ret == WifiErrorNo::WIFI_IDL_OPT_FAILED) {
return false;
@ -896,12 +894,16 @@ bool P2pStateMachine::DealCreateNewGroupWithConfig(const WifiP2pConfigInternal &
}
if (ret == WIFI_IDL_OPT_FAILED || netId == TEMPORARY_NET_ID) {
WIFI_LOGD("Remove network %{public}d!", createdNetId);
WifiP2PHalInterface::GetInstance().RemoveNetwork(createdNetId);
WIFI_LOGD("Remove network %{public}d!", createdNetId);
WifiP2PHalInterface::GetInstance().RemoveNetwork(createdNetId);
WifiP2pGroupInfo removedInfo;
removedInfo.SetNetworkId(createdNetId);
groupManager.RemoveGroup(removedInfo);
}
(void)WifiP2PHalInterface::GetInstance().SaveConfig();
return (ret == WIFI_IDL_OPT_FAILED) ? false : true ;
UpdateGroupManager();
UpdatePersistentGroups();
return (ret == WIFI_IDL_OPT_FAILED) ? false : true;
}
bool P2pStateMachine::IsInterfaceReuse() const

View File

@ -158,6 +158,10 @@ private:
* @param status - new device status
*/
virtual void UpdateOwnDevice(P2pDeviceStatus status);
/**
* @Description - Update groupManager from wpa_supplicant.
*/
virtual void UpdateGroupManager() const;
/**
* @Description - Update persistent groups and broadcast persistent groups status update event.
*/
@ -415,7 +419,7 @@ private:
static bool m_isNeedDhcp;
std::string p2pDevIface;
};
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS
#endif // OHOS_P2P_STATE_MACHINE_H

View File

@ -49,6 +49,19 @@ bool WifiP2pGroupManager::AddGroup(const WifiP2pGroupInfo &group)
groupsInfo.push_back(group);
return true;
}
bool WifiP2pGroupManager::AddOrUpdateGroup(const WifiP2pGroupInfo &group)
{
std::unique_lock<std::mutex> lock(groupMutex);
for (auto it = groupsInfo.begin(); it != groupsInfo.end(); ++it) {
if (*it == group) {
groupsInfo.erase(it);
break;
}
}
groupsInfo.push_back(group);
return true;
}
bool WifiP2pGroupManager::RemoveGroup(const WifiP2pGroupInfo &group)
{
std::unique_lock<std::mutex> lock(groupMutex);
@ -242,5 +255,5 @@ void WifiP2pGroupManager::UpdateGroupsNetwork(std::map<int, WifiP2pGroupInfo> wp
}
}
}
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS

View File

@ -62,6 +62,13 @@ public:
*/
virtual bool AddGroup(const WifiP2pGroupInfo &group);
/**
* @Description - Adding or Updating a P2P group.
* @param group - P2P group to be modified or add
* @return true: adding or Updating succeeded false: adding or Updating failed
*/
virtual bool AddOrUpdateGroup(const WifiP2pGroupInfo &group);
/**
* @Description - Remove a P2P group.
* @param group - P2P group to be removed
@ -204,7 +211,7 @@ private:
std::mutex groupMutex;
WifiP2pLinkedInfo p2pConnInfo; /* group connection information */
};
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS
#endif // OHOS_P2P_GROUP_MANAGER_H

View File

@ -753,6 +753,8 @@ void StaStateMachine::ConvertFreqToChannel()
LOGE("GetDeviceConfig failed!");
return;
}
int tempBand = config.band;
int tempChannel = config.channel;
if (linkedInfo.frequency >= FREQ_2G_MIN && linkedInfo.frequency <= FREQ_2G_MAX) {
config.band = linkedInfo.band = static_cast<int>(BandType::BAND_2GHZ);
config.channel = (linkedInfo.frequency - FREQ_2G_MIN) / CENTER_FREQ_DIFF + CHANNEL_2G_MIN;
@ -762,9 +764,10 @@ void StaStateMachine::ConvertFreqToChannel()
config.band = linkedInfo.band = static_cast<int>(BandType::BAND_5GHZ);
config.channel = (linkedInfo.frequency - FREQ_5G_MIN) / CENTER_FREQ_DIFF + CHANNEL_5G_MIN;
}
WifiSettings::GetInstance().AddDeviceConfig(config);
WifiSettings::GetInstance().SyncDeviceConfig();
if (tempBand != config.band || tempChannel != config.channel) {
WifiSettings::GetInstance().AddDeviceConfig(config);
WifiSettings::GetInstance().SyncDeviceConfig();
}
return;
}

View File

@ -39,6 +39,7 @@ local_base_sources = [
"net_helper/raw_socket.cpp",
"utils/wifi_common_event_helper.cpp",
"utils/wifi_global_func.cpp",
"utils/wifi_encryption_util.cpp",
]
local_base_include_dirs = [
@ -49,6 +50,7 @@ local_base_include_dirs = [
"$WIFI_ROOT_DIR/services/wifi_standard/wifi_framework/wifi_toolkit/config",
"//commonlibrary/c_utils/base/include",
"//base/hiviewdfx/hilog/interfaces/native/innerkits/include",
"//base/security/huks/interfaces/innerkits/huks_standard/main/include",
"$WIFI_ROOT_DIR/frameworks/native/interfaces",
"$DHCP_ROOT_DIR/interfaces/inner_api/interfaces",
"$DHCP_ROOT_DIR/interfaces/inner_api/include",
@ -94,12 +96,16 @@ if (defined(ohos_lite)) {
]
defines = [ "AP_INSTANCE_MAX_NUM=$wifi_feature_with_ap_num" ]
if (wifi_feature_with_encryption) {
defines += [ "FEATURE_ENCRYPTION_SUPPORT" ]
}
external_deps = [
"ability_base:want",
"c_utils:utils",
"common_event_service:cesfwk_innerkits",
"eventhandler:libeventhandler",
"huks:libhukssdk"
]
cflags_cc = [

View File

@ -71,6 +71,20 @@ public:
*/
int SetConfigFilePath(const std::string &fileName);
/**
* @Description read and parses the network section of ini config file, need call SetConfigFilePath first
*
* @return int - 0 Success; >0 parse failed
*/
int ReadNetworkSection(T &item, std::ifstream &fs, std::string &line, const std::string &mFileName);
/**
* @Description read and parses the networks of ini config file, need call SetConfigFilePath first
*
* @return int - 0 Success; >0 parse failed
*/
int ReadNetwork(T &item, std::ifstream &fs, std::string &line, const std::string &mFileName);
/**
* @Description read and parses the ini config file, need call SetConfigFilePath first
*
@ -120,6 +134,59 @@ int WifiConfigFileImpl<T>::SetConfigFilePath(const std::string &fileName)
return 0;
}
template<typename T>
int WifiConfigFileImpl<T>::ReadNetworkSection(T &item, std::ifstream &fs, std::string &line, const std::string &mFileName)
{
int sectionError = 0;
while (std::getline(fs, line)) {
TrimString(line);
if (line.empty()) {
continue;
}
if (line[0] == '<' && line[line.length()-1] == '>') {
return sectionError;
}
std::string::size_type npos = line.find("=");
if (npos == std::string::npos) {
LOGE("Invalid config line");
sectionError++;
continue;
}
std::string key = line.substr(0, npos);
std::string value = line.substr(npos + 1);
TrimString(key);
TrimString(value);
/* template function, needing specialization */
sectionError +=SetTClassKeyValue(item, key, value, mFileName);
}
LOGE("Section config not end correctly");
sectionError++;
return sectionError;
}
template<typename T>
int WifiConfigFileImpl<T>::ReadNetwork(T &item, std::ifstream &fs, std::string &line, const std::string &mFileName)
{
int networkError = 0;
while (std::getline(fs, line)) {
TrimString(line);
if (line.empty()) {
continue;
}
if (line[0] == '<' && line[line.length()-1] == '>') {
networkError += ReadNetworkSection(item, fs, line, mFileName);
} else if (line.compare("}") == 0) {
return networkError;
} else {
LOGE("Invalid config line");
networkError++;
}
}
LOGE("Network config not end correctly");
networkError++;
return networkError;
}
template<typename T>
int WifiConfigFileImpl<T>::LoadConfig()
{
@ -133,35 +200,23 @@ int WifiConfigFileImpl<T>::LoadConfig()
return -1;
}
mValues.clear();
bool bSection = false;
T item;
std::string line;
int ConfigError;
while (std::getline(fs, line)) {
TrimString(line);
if (line.empty()) {
continue;
}
if (line[0] == '[' && line[line.length() - 1] == ']') {
if (bSection) {
mValues.push_back(item);
}
bSection = true;
if (line[0] == '[' && line[line.length() - 1] == '{') {
ClearTClass(item); /* template function, needing specialization */
continue;
}
std::string::size_type npos = line.find("=");
if (npos == std::string::npos) {
continue;
}
std::string key = line.substr(0, npos);
std::string value = line.substr(npos + 1);
TrimString(key);
TrimString(value);
/* template function, needing specialization */
SetTClassKeyValue(item, key, value);
}
if (bSection) {
mValues.push_back(item);
ConfigError = ReadNetwork(item, fs, line, mFileName);
if (ConfigError > 0) {
LOGE("Parse network failed.");
continue;
}
mValues.push_back(item);
}
}
fs.close();
return 0;
@ -186,8 +241,9 @@ int WifiConfigFileImpl<T>::SaveConfig()
* here use template function GetTClassName OutTClassString, needing
* specialization.
*/
ss << "[" << GetTClassName<T>() << "_" << (i + 1) << "]" << std::endl;
ss << OutTClassString(item) << std::endl;
ss << "[" << GetTClassName<T>() << "_" << (i + 1) << "] {" << std::endl;
ss << OutTClassString(item, mFileName) << std::endl;
ss << "}" << std::endl;
}
std::string content = ss.str();
int ret = fwrite(content.c_str(), 1, content.length(), fp);
@ -223,6 +279,6 @@ int WifiConfigFileImpl<T>::SetValue(const std::vector<T> &results)
mValues = results;
return 0;
}
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -21,6 +21,7 @@
#include <vector>
#include "wifi_internal_msg.h"
#include "wifi_p2p_msg.h"
namespace OHOS {
namespace Wifi {
/* ----------------- template function begin ----------------------- */
@ -38,6 +39,7 @@ void ClearTClass(T &item)
return;
}
/**
* @Description Set item's data, input key is the item's member and input value is the
* member's value
@ -46,15 +48,17 @@ void ClearTClass(T &item)
* @param item - T &item
* @param key - Item key
* @param value - Item value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <typename T>
void SetTClassKeyValue(T &item, const std::string &key, const std::string &value)
int SetTClassKeyValue(T &item, const std::string &key, const std::string &value, const std::string &fileName)
{
/* fixed compile warning, -Werror,-Wunused-parameter */
item;
std::ostringstream ss;
ss << key << value << std::endl;
return;
return 0;
}
/**
@ -75,10 +79,11 @@ std::string GetTClassName()
*
* @tparam T - typename
* @param item - item
* @param fileName - fileName
* @return std::string - output item's total member=value string
*/
template <typename T>
std::string OutTClassString(T &item)
std::string OutTClassString(T &item, const std::string &fileName)
{
/* fixed compile warning, -Werror,-Wunused-parameter */
item;
@ -105,9 +110,12 @@ void ClearTClass<WifiDeviceConfig>(WifiDeviceConfig &item);
* @param item - WifiDeviceConfig &item
* @param key - WifiDeviceConfig struct member name
* @param value - the WifiDeviceConfig item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<WifiDeviceConfig>(WifiDeviceConfig &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<WifiDeviceConfig>(WifiDeviceConfig &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output WifiDeviceConfig class name
@ -124,10 +132,11 @@ std::string GetTClassName<WifiDeviceConfig>();
*
* @tparam
* @param item - WifiDeviceConfig &item
* @param fileName - fileName
* @return std::string - output total member=value string about the WifiDeviceConfig item
*/
template <>
std::string OutTClassString<WifiDeviceConfig>(WifiDeviceConfig &item);
std::string OutTClassString<WifiDeviceConfig>(WifiDeviceConfig &item, const std::string &fileName);
/**
* @Description Clear and init HotspotConfig
@ -145,9 +154,12 @@ void ClearTClass<HotspotConfig>(HotspotConfig &item);
* @param item - HotspotConfig &item
* @param key - HotspotConfig struct member name
* @param value - the HotspotConfig item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<HotspotConfig>(HotspotConfig &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<HotspotConfig>(HotspotConfig &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output HotspotConfig class name
@ -164,10 +176,11 @@ std::string GetTClassName<HotspotConfig>();
*
* @tparam
* @param item - HotspotConfig &item
* @param fileName - fileName
* @return std::string - output total member=value string about the HotspotConfig item
*/
template <>
std::string OutTClassString<HotspotConfig>(HotspotConfig &item);
std::string OutTClassString<HotspotConfig>(HotspotConfig &item, const std::string &fileName);
/**
* @Description Clear and init P2pVendorConfig
@ -185,9 +198,12 @@ void ClearTClass<P2pVendorConfig>(P2pVendorConfig &item);
* @param item - P2pVendorConfig &item
* @param key - P2pVendorConfig struct member name
* @param value - the P2pVendorConfig item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template<>
void SetTClassKeyValue<P2pVendorConfig>(P2pVendorConfig &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<P2pVendorConfig>(P2pVendorConfig &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output P2pVendorConfig class name
@ -204,10 +220,11 @@ std::string GetTClassName<P2pVendorConfig>();
*
* @tparam
* @param item - P2pVendorConfig &item
* @param fileName - fileName
* @return std::string - output total member=value string about the P2pVendorConfig item
*/
template<>
std::string OutTClassString<P2pVendorConfig>(P2pVendorConfig &item);
std::string OutTClassString<P2pVendorConfig>(P2pVendorConfig &item, const std::string &fileName);
/**
* @Description Clear and init StationInfo
@ -225,9 +242,12 @@ void ClearTClass<StationInfo>(StationInfo &item);
* @param item - StationInfo &item
* @param key - StationInfo struct member name
* @param value - the StationInfo item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<StationInfo>(StationInfo &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<StationInfo>(StationInfo &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output StationInfo class name
@ -244,10 +264,11 @@ std::string GetTClassName<StationInfo>();
*
* @tparam
* @param item - StationInfo &item
* @param fileName - fileName
* @return std::string - output total member=value string about the StationInfo item
*/
template <>
std::string OutTClassString<StationInfo>(StationInfo &item);
std::string OutTClassString<StationInfo>(StationInfo &item, const std::string &fileName);
/**
* @Description Clear and init WifiConfig
@ -265,9 +286,12 @@ void ClearTClass<WifiConfig>(WifiConfig &item);
* @param item - WifiConfig &item
* @param key - WifiConfig struct member name
* @param value - the WifiConfig item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<WifiConfig>(WifiConfig &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<WifiConfig>(WifiConfig &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output WifiConfig class name
@ -284,10 +308,11 @@ std::string GetTClassName<WifiConfig>();
*
* @tparam
* @param item - WifiConfig &item
* @param fileName - fileName
* @return std::string - output total member=value string about the WifiConfig item
*/
template <>
std::string OutTClassString<WifiConfig>(WifiConfig &item);
std::string OutTClassString<WifiConfig>(WifiConfig &item, const std::string &fileName);
/**
* @Description Clear and init WifiP2pGroupInfo
@ -305,9 +330,12 @@ void ClearTClass<WifiP2pGroupInfo>(WifiP2pGroupInfo &item);
* @param item - WifiP2pGroupInfo &item
* @param key - WifiP2pGroupInfo struct member name
* @param value - the WifiP2pGroupInfo item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template<>
void SetTClassKeyValue<WifiP2pGroupInfo>(WifiP2pGroupInfo &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<WifiP2pGroupInfo>(WifiP2pGroupInfo &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output WifiP2pGroupInfo class name
@ -324,10 +352,11 @@ std::string GetTClassName<WifiP2pGroupInfo>();
*
* @tparam
* @param item - WifiP2pGroupInfo &item
* @param fileName - fileName
* @return std::string - output total member=value string about the WifiP2pGroupInfo item
*/
template<>
std::string OutTClassString<WifiP2pGroupInfo>(WifiP2pGroupInfo &item);
std::string OutTClassString<WifiP2pGroupInfo>(WifiP2pGroupInfo &item, const std::string &fileName);
/**
* @Description Clear and init TrustListPolicy
@ -345,9 +374,12 @@ void ClearTClass<TrustListPolicy>(TrustListPolicy &item);
* @param item - TrustListPolicy &item
* @param key - TrustListPolicy struct member name
* @param value - the TrustListPolicy item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<TrustListPolicy>(TrustListPolicy &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<TrustListPolicy>(TrustListPolicy &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output TrustListPolicy class name
@ -364,10 +396,11 @@ std::string GetTClassName<TrustListPolicy>();
*
* @tparam
* @param item - TrustListPolicy &item
* @param fileName - fileName
* @return std::string - output total member=value string about the TrustListPolicy item
*/
template <>
std::string OutTClassString<TrustListPolicy>(TrustListPolicy &item);
std::string OutTClassString<TrustListPolicy>(TrustListPolicy &item, const std::string &fileName);
/**
* @Description Clear and init MovingFreezePolicy
@ -385,9 +418,12 @@ void ClearTClass<MovingFreezePolicy>(MovingFreezePolicy &item);
* @param item - MovingFreezePolicy &item
* @param key - MovingFreezePolicy struct member name
* @param value - the MovingFreezePolicy item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<MovingFreezePolicy>(MovingFreezePolicy &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<MovingFreezePolicy>(MovingFreezePolicy &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output MovingFreezePolicy class name
@ -404,10 +440,11 @@ std::string GetTClassName<MovingFreezePolicy>();
*
* @tparam
* @param item - MovingFreezePolicy &item
* @param fileName - fileName
* @return std::string - output total member=value string about the MovingFreezePolicy item
*/
template <>
std::string OutTClassString<MovingFreezePolicy>(MovingFreezePolicy &item);
std::string OutTClassString<MovingFreezePolicy>(MovingFreezePolicy &item, const std::string &fileName);
/**
* @Description Clear and init WifiStoreRandomMac
@ -425,9 +462,12 @@ void ClearTClass<WifiStoreRandomMac>(WifiStoreRandomMac &item);
* @param item - WifiStoreRandomMac &item
* @param key - WifiStoreRandomMac struct member name
* @param value - the WifiStoreRandomMac item member value
* @param fileName - fileName
* @return int - parse error: 0 Success, >0 parse failed
*/
template <>
void SetTClassKeyValue<WifiStoreRandomMac>(WifiStoreRandomMac &item, const std::string &key, const std::string &value);
int SetTClassKeyValue<WifiStoreRandomMac>(WifiStoreRandomMac &item, const std::string &key, const std::string &value,
const std::string &fileName);
/**
* @Description Output WifiStoreRandomMac class name
@ -444,11 +484,12 @@ std::string GetTClassName<WifiStoreRandomMac>();
*
* @tparam
* @param item - WifiStoreRandomMac &item
* @param fileName - fileName
* @return std::string - output total member=value string about the WifiStoreRandomMac item
*/
template <>
std::string OutTClassString<WifiStoreRandomMac>(WifiStoreRandomMac &item);
std::string OutTClassString<WifiStoreRandomMac>(WifiStoreRandomMac &item, const std::string &fileName);
/* ----------template function specialization declare end----------- */
} // namespace Wifi
} // namespace OHOS
#endif
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -18,7 +18,9 @@
#include "wifi_global_func.h"
#include "wifi_log.h"
#include "wifi_config_country_freqs.h"
#ifdef FEATURE_ENCRYPTION_SUPPORT
#include "wifi_encryption_util.h"
#endif
namespace OHOS {
namespace Wifi {
WifiSettings &WifiSettings::GetInstance()
@ -140,7 +142,9 @@ int WifiSettings::Init()
InitScanControlInfo();
ReloadTrustListPolicies();
ReloadMovingFreezePolicy();
#ifdef FEATURE_ENCRYPTION_SUPPORT
SetUpHks();
#endif
return 0;
}

View File

@ -23,7 +23,6 @@
#include <mutex>
#include <algorithm>
#include "wifi_config_file_impl.h"
constexpr int RANDOM_STR_LEN = 6;
constexpr int MSEC = 1000;
constexpr int FOREGROUND_SCAN_CONTROL_TIMES = 4;
@ -1160,6 +1159,6 @@ private:
WifiConfigFileImpl<WifiStoreRandomMac> mSavedWifiStoreRandomMac;
bool explicitGroup;
};
} // namespace Wifi
} // namespace OHOS
} // namespace Wifi
} // namespace OHOS
#endif

View File

@ -0,0 +1,156 @@
/*
* Copyright (C) 2022-2022 Huawei Device Co., Ltd.
* 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 "wifi_encryption_util.h"
#include <iterator>
#include <sstream>
#include "wifi_logger.h"
#include "wifi_global_func.h"
DEFINE_WIFILOG_LABEL("WifiConfigEncryption");
namespace OHOS {
namespace Wifi {
int32_t SetUpHks()
{
int32_t ret = HksInitialize();
if (ret != HKS_SUCCESS) {
WIFI_LOGE("wifi encryption init failed");
}
return ret;
}
int32_t GetKey(const WifiEncryptionInfo &wifiEncryptionInfo, const struct HksParamSet *genParamSet)
{
struct HksBlob authId = wifiEncryptionInfo.keyAlias;
int32_t keyExist = HksKeyExist(&authId, nullptr);
if (keyExist == HKS_ERROR_NOT_EXIST) {
int32_t ret = HksGenerateKey(&authId, genParamSet, nullptr);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("generate key failed");
return ret;
} else {
return ret;
}
}else if (keyExist != HKS_SUCCESS) {
WIFI_LOGE("search key failed");
return keyExist;
}
return keyExist;
}
int32_t WifiEncryption(const WifiEncryptionInfo &wifiEncryptionInfo, const std::string &inputString,
EncryptedData &encryptedData)
{
if (inputString.length() == 0) {
return HKS_SUCCESS;
}
struct HksBlob authId = wifiEncryptionInfo.keyAlias;
struct HksBlob plainText = { inputString.length(), (uint8_t *)&inputString[0] };
uint8_t nonce[NONCE_SIZE] = {0};
struct HksBlob randomIV = {NONCE_SIZE, nonce};
int32_t ret =HksGenerateRandom(NULL, &randomIV);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("wifi encryption generate IV failed");
return ret;
}
struct HksParam IVParam[] = {
{ .tag = HKS_TAG_NONCE, .blob = { .size = NONCE_SIZE, .data = nonce } },
};
struct HksParamSet *encryParamSet = nullptr;
HksInitParamSet(&encryParamSet);
HksAddParams(encryParamSet, g_genParam, sizeof(g_genParam) / sizeof(HksParam));
HksAddParams(encryParamSet, IVParam, sizeof(IVParam) / sizeof(HksParam));
HksBuildParamSet(&encryParamSet);
ret = GetKey(wifiEncryptionInfo, encryParamSet);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("wifi encryption failed");
return ret;
}
uint8_t cipherBuf[AES_COMMON_SIZE] = {0};
HksBlob cipherData = {
.size = AES_COMMON_SIZE,
.data = cipherBuf
};
ret = HksEncrypt(&authId, encryParamSet, &plainText, &cipherData);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("Hks encryption failed");
return ret;
}
encryptedData.encryptedPassword = ConvertArrayToHex(cipherBuf, cipherData.size);
encryptedData.IV = ConvertArrayToHex(nonce, NONCE_SIZE);
HksFreeParamSet(&encryParamSet);
return ret;
}
int32_t WifiDecryption(const WifiEncryptionInfo &wifiEncryptionInfo, const EncryptedData &encryptedData,
std::string &decryptedData)
{
if (encryptedData.encryptedPassword.size() == 0) {
return HKS_SUCCESS;
}
struct HksBlob authId = wifiEncryptionInfo.keyAlias;
uint8_t cipherBuf[AES_COMMON_SIZE] = {0};
int length = AES_COMMON_SIZE;
int retStrToArrat = HexStringToVec(encryptedData.encryptedPassword, cipherBuf, AES_COMMON_SIZE, length);
if (retStrToArrat != 0) {
return HKS_FAILURE;
}
uint8_t nonce[NONCE_SIZE] = {0};
int lengthIV = NONCE_SIZE;
retStrToArrat = HexStringToVec(encryptedData.IV, nonce, NONCE_SIZE, lengthIV);
if (retStrToArrat != 0) {
return HKS_FAILURE;
}
struct HksParam IVParam[] = {
{ .tag = HKS_TAG_NONCE, .blob = { .size = NONCE_SIZE, .data = nonce } },
};
struct HksBlob cipherData = { length, cipherBuf };
struct HksParamSet *decryParamSet = nullptr;
HksInitParamSet(&decryParamSet);
HksAddParams(decryParamSet, g_genParam, sizeof(g_genParam) / sizeof(HksParam));
HksAddParams(decryParamSet, IVParam, sizeof(IVParam) / sizeof(HksParam));
HksBuildParamSet(&decryParamSet);
int ret = HksKeyExist(&authId, nullptr);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("wifi decryption key not exist");
return ret;
}
uint8_t plainBuff[AES_COMMON_SIZE] = {0};
HksBlob plainText = {
.size = AES_COMMON_SIZE,
.data = plainBuff
};
ret = HksDecrypt(&authId, decryParamSet, &cipherData, &plainText);
if (ret != HKS_SUCCESS) {
WIFI_LOGE("Hks decryption failed");
return ret;
}
std::string temp(plainText.data, plainText.data + plainText.size);
decryptedData = temp;
HksFreeParamSet(&decryParamSet);
return ret;
}
} // namespace Wifi
} // namespace OHOS

View File

@ -0,0 +1,87 @@
/*
* Copyright (C) 2022-2022 Huawei Device Co., Ltd.
* 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.
*/
#ifndef OHOS_WIFI_CONFIG_HKS_H
#define OHOS_WIFI_CONFIG_HKS_H
#include <string>
#include <vector>
#include "hks_api.h"
#include "hks_type.h"
#include "hks_param.h"
namespace OHOS {
namespace Wifi {
static constexpr uint32_t AES_COMMON_SIZE = 256;
static constexpr uint32_t AAD_SIZE = 16;
static constexpr uint32_t NONCE_SIZE = 16;
const uint8_t AAD[AAD_SIZE] = {0};
static struct HksParam g_genParam[] = {
{ .tag = HKS_TAG_KEY_STORAGE_FLAG, .uint32Param = HKS_STORAGE_PERSISTENT },
{ .tag = HKS_TAG_ALGORITHM, .uint32Param = HKS_ALG_AES },
{ .tag = HKS_TAG_KEY_SIZE, .uint32Param = HKS_AES_KEY_SIZE_256 },
{ .tag = HKS_TAG_PURPOSE, .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT },
{ .tag = HKS_TAG_DIGEST, .uint32Param = HKS_DIGEST_NONE },
{ .tag = HKS_TAG_PADDING, .uint32Param = HKS_PADDING_NONE },
{ .tag = HKS_TAG_IS_KEY_ALIAS, .boolParam = true },
{ .tag = HKS_TAG_KEY_GENERATE_TYPE, .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT },
{ .tag = HKS_TAG_BLOCK_MODE, .uint32Param = HKS_MODE_GCM },
{ .tag = HKS_TAG_ASSOCIATED_DATA, .blob = { .size = AAD_SIZE, .data = (uint8_t *)AAD } },
};
class EncryptedData final {
public:
std::string encryptedPassword = "";
std::string IV = "";
EncryptedData(const std::string password, const std::string inputIV)
{
encryptedPassword = password;
IV = inputIV;
}
EncryptedData() {}
~EncryptedData() {}
};
class WifiEncryptionInfo {
public:
std::string fileName;
static constexpr char WIFI_ENCRY_KEY[] = "WifiEncryHksAes";
struct HksBlob keyAlias;
void SetFile(const std::string file)
{
fileName = WIFI_ENCRY_KEY + file;
keyAlias = { fileName.length(), (uint8_t *)&fileName[0] };
}
WifiEncryptionInfo(const std::string file)
{
SetFile(file);
}
WifiEncryptionInfo() {}
~WifiEncryptionInfo() {}
};
int32_t SetUpHks();
int32_t GetKey(const WifiEncryptionInfo &wifiEncryptionInfo, const struct HksParamSet *genParamSet);
int32_t WifiEncryption(const WifiEncryptionInfo &wifiEncryptionInfo, const std::string &inputString,
EncryptedData &encryptedData);
int32_t WifiDecryption(const WifiEncryptionInfo &wifiEncryptionInfo, const EncryptedData &encryptedData,
std::string &decryptedData);
}
}
#endif

View File

@ -288,6 +288,70 @@ int HexStringToVec(const std::string &str, std::vector<char> &vec)
return 0;
}
int HexStringToVec(const std::string &str, uint8_t plainText[], int plainLength, int &resultLength)
{
if (plainLength < 0) {
return false;
}
std::vector<char> result;
result.clear();
int ret = HexStringToVec(str, result);
if (ret == -1 || static_cast<int>(result.size()) > plainLength) {
return -1;
}
for(std::vector<char>::size_type i = 0; i < result.size(); ++i) {
plainText[i] = result[i];
}
resultLength = static_cast<int>(result.size());
return 0;
}
static char ConvertArrayChar(uint8_t ch)
{
constexpr int maxDecNum = 9;
constexpr int numDiffForHexAlphabet = 10;
if (ch >= 0 && ch <= maxDecNum) {
return '0' + ch;
}
if (ch >= 0xa && ch <= 0xf) {
return ch + 'a' - numDiffForHexAlphabet;
}
return '0';
}
std::string ConvertArrayToHex(const uint8_t plainText[], int size)
{
constexpr int bitWidth = 4;
std::stringstream ss;
for (int i = 0; i < size; i++) {
ss << ConvertArrayChar(plainText[i] >> bitWidth) << ConvertArrayChar (plainText[i] & 0xf);
}
return ss.str();
}
static bool ValidateChar(const char ch)
{
if (ch > '~' || ch < ' ') {
return false;
}
return true;
}
std::string ValidateString(const std::string &str)
{
std::stringstream ss;
ss << "\"";
for(char ch : str)
{
if (ValidateChar(ch)) {
ss << ch;
}
}
ss << "\"";
return ss.str();
}
void TransformFrequencyIntoChannel(const std::vector<int> &freqVector, std::vector<int> &chanVector)
{
int channel;

View File

@ -225,6 +225,33 @@ std::string Vec2Stream(const std::string &prefix, const std::vector<char> &vecCh
*/
int HexStringToVec(const std::string &str, std::vector<char> &vec);
/**
* @Description Convert a hex type string to uint8_t*.
*
* @param str - input hex string, eg: 010203...
* @param plainText - output uint8_t* result, eg: [1,2,3,...]
* @param plainLength - input maxLength of uint8_t* result, eg: 256
* @param resultLength - output Length of uint8_t* result, eg: 16
* @return int - convert result, 0 success, -1 failed
*/
int HexStringToVec(const std::string &str, uint8_t plainText[], int plainLength, int &resultLength);
/**
* @Description Convert a uint8_t* to Hex string.
*
* @param plainText - input uint8_t*, eg: [1,2,3,...]
* @param size - input uint8_t* size, eg: 16
* @return string - convert Hex string, eg: 010203...
*/
std::string ConvertArrayToHex(const uint8_t plainText[], int size);
/**
* @Description Convert a string to validate string for write.
*
* @param str - input string
* @return string - validate string wrapped by ""
*/
std::string ValidateString(const std::string &str);
/**
* @Description Check is a valid 5G frequency.
*

View File

@ -22,4 +22,5 @@ declare_args() {
wifi_feature_with_ap_num = 1
wifi_feature_with_auth_disable = false
wifi_feature_with_dhcp_disable = false
wifi_feature_with_encryption = true
}