Skip to content

Commit bf4cd4a

Browse files
authored
Fix the unsafe usage of strncpy in portsorch.cpp (#2110)
Originally, strncpy is used in the following way: strncpy(attr.value.chardata, src_string, sizeof(attr.value.chardata)); where attr.value.chardata is a char array. However, this is not safe in case strlen(src_string) >= sizeof(attr.value.chardata) because there will no space in attr.value.chardata to store the terminating character. It will leave the string attr.value.chardata open, the receiver of attr cannot determine the end of the string and suffer buffer overflow. According to SAI API definition, the actually length of SAI_HOSTIF_ATTR_NAME should be SAI_HOSTIF_NAME_SIZE - 1 which is less than sizeof(attr.value.chardata)`. So a safe way to do it should be: strncpy(attr.value.chardata, src_string, SAI_HOSTIF_NAME_SIZE); attr.value.chardata[SAI_HOSTIF_NAME_SIZE - 1] = '\0' Signed-off-by: Stephen Sun <[email protected]>
1 parent c1b4b40 commit bf4cd4a

File tree

1 file changed

+11
-1
lines changed

1 file changed

+11
-1
lines changed

orchagent/portsorch.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2172,7 +2172,12 @@ bool PortsOrch::createVlanHostIntf(Port& vl, string hostif_name)
21722172
attrs.push_back(attr);
21732173

21742174
attr.id = SAI_HOSTIF_ATTR_NAME;
2175-
strncpy(attr.value.chardata, hostif_name.c_str(), sizeof(attr.value.chardata));
2175+
if (hostif_name.length() >= SAI_HOSTIF_NAME_SIZE)
2176+
{
2177+
SWSS_LOG_WARN("Host interface name %s is too long and will be truncated to %d bytes", hostif_name.c_str(), SAI_HOSTIF_NAME_SIZE - 1);
2178+
}
2179+
strncpy(attr.value.chardata, hostif_name.c_str(), SAI_HOSTIF_NAME_SIZE);
2180+
attr.value.chardata[SAI_HOSTIF_NAME_SIZE - 1] = '\0';
21762181
attrs.push_back(attr);
21772182

21782183
sai_status_t status = sai_hostif_api->create_hostif(&vl.m_vlan_info.host_intf_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());
@@ -4186,6 +4191,11 @@ bool PortsOrch::addHostIntfs(Port &port, string alias, sai_object_id_t &host_int
41864191

41874192
attr.id = SAI_HOSTIF_ATTR_NAME;
41884193
strncpy((char *)&attr.value.chardata, alias.c_str(), SAI_HOSTIF_NAME_SIZE);
4194+
if (alias.length() >= SAI_HOSTIF_NAME_SIZE)
4195+
{
4196+
SWSS_LOG_WARN("Host interface name %s is too long and will be truncated to %d bytes", alias.c_str(), SAI_HOSTIF_NAME_SIZE - 1);
4197+
}
4198+
attr.value.chardata[SAI_HOSTIF_NAME_SIZE - 1] = '\0';
41894199
attrs.push_back(attr);
41904200

41914201
sai_status_t status = sai_hostif_api->create_hostif(&host_intfs_id, gSwitchId, (uint32_t)attrs.size(), attrs.data());

0 commit comments

Comments
 (0)