net: dsa: ensure port names are NULL-terminated after DSA_PORT_NAME_LENGTH truncation
authorVladimir Oltean <vladimir.oltean@nxp.com>
Mon, 27 Sep 2021 11:22:03 +0000 (14:22 +0300)
committerRamon Fried <rfried.dev@gmail.com>
Tue, 28 Sep 2021 15:50:57 +0000 (18:50 +0300)
strncpy() simply bails out when copying a source string whose size
exceeds the destination string size, potentially leaving the destination
string unterminated.

One possible way to address is to pass DSA_PORT_NAME_LENGTH - 1 and a
previously zero-initialized destination string, but this is more
difficult to maintain.

The chosen alternative is to use strlcpy(), which properly limits the
copy len in the (srclen >= size) case to "size - 1", and which is also
more efficient than the strncpy() byte-by-byte implementation by using
memcpy. The destination string returned by strlcpy() is always NULL
terminated.

Signed-off-by: Vladimir Oltean <vladimir.oltean@nxp.com>
Reviewed-by: Ramon Fried <rfried.dev@gmail.com>
net/dsa-uclass.c

index 8a29188..bf762cd 100644 (file)
@@ -216,7 +216,7 @@ static int dsa_port_of_to_pdata(struct udevice *pdev)
 
        label = ofnode_read_string(dev_ofnode(pdev), "label");
        if (label)
-               strncpy(port_pdata->name, label, DSA_PORT_NAME_LENGTH);
+               strlcpy(port_pdata->name, label, DSA_PORT_NAME_LENGTH);
 
        eth_pdata = dev_get_plat(pdev);
        eth_pdata->priv_pdata = port_pdata;
@@ -421,7 +421,7 @@ static int dsa_post_bind(struct udevice *dev)
                        struct dsa_port_pdata *port_pdata;
 
                        port_pdata = dev_get_parent_plat(pdev);
-                       strncpy(port_pdata->name, name, DSA_PORT_NAME_LENGTH);
+                       strlcpy(port_pdata->name, name, DSA_PORT_NAME_LENGTH);
                        pdev->name = port_pdata->name;
                }