Skip to content

Commit 6291ca7

Browse files
committed
bug: Fix unsafe use of strncpy
While working on the MicroPython v1.20.0 update I came across the following error: ``` $~/badgePython/components/pywpa2enterprise/modwpa2enterprise.c:25:5: error: 'strncpy' specified bound 32 equals destination size [-Werror=stringop-truncation] strncpy((char*) wifi_config.sta.ssid, aSsid, 32); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ cc1: some warnings being treated as errors ``` The error message indicates that the `strncpy()` function call in the provided code can potentially write more than 32 bytes to the destination buffer, which could result in a buffer overflow and undefined behavior. To resolve this error, you can use `strlcpy()` instead of `strncpy()`. `strlcpy()` is a safer alternative to `strncpy()`, as it guarantees null-termination of the destination string and does not write more than the specified destination size. Thus, the modified version should look like this: ```c strlcpy((char*) wifi_config.sta.ssid, aSsid, sizeof(wifi_config.sta.ssid)); ``` This will copy at most `sizeof(wifi_config.sta.ssid)` bytes from `aSsid` to `wifi_config.sta.ssid`, ensuring that the destination buffer is not overflowed.
1 parent e667fb9 commit 6291ca7

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

components/pywpa2enterprise/modwpa2enterprise.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ STATIC mp_obj_t mod_wpa2enterprise_connect (mp_uint_t n_args, const mp_obj_t *ar
2222
const char* aPassword = mp_obj_str_get_str(args[3]);
2323
int phase2 = mp_obj_get_int(args[4]);
2424
wifi_config_t wifi_config = {0};
25-
strncpy((char*) wifi_config.sta.ssid, aSsid, 32);
25+
strlcpy((char*) wifi_config.sta.ssid, aSsid, sizeof(wifi_config.sta.ssid));
2626
WIFI_SORT_ERRCHECK(esp_wifi_stop());
2727
WIFI_SORT_ERRCHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
2828
WIFI_SORT_ERRCHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );

0 commit comments

Comments
 (0)