From 98c39d5104d6a5f47f65fbeaba8a66a85e6a5579 Mon Sep 17 00:00:00 2001 From: Vincent Dupont Date: Fri, 19 Jun 2020 11:20:37 +0200 Subject: [PATCH] can: add proper checks for ifnum validity Most functions were using asserts, but in some cases it might not be a programmatic error to pass an invalid ifnum. This makes sure the code does not crash by testing it at runtim and returning an error. --- sys/can/conn/raw.c | 23 +++++++++++++++++++---- sys/can/dll.c | 4 +++- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/sys/can/conn/raw.c b/sys/can/conn/raw.c index 8f3ca76f62..64ec1d5257 100644 --- a/sys/can/conn/raw.c +++ b/sys/can/conn/raw.c @@ -42,7 +42,11 @@ int conn_can_raw_create(conn_can_raw_t *conn, struct can_filter *filter, size_t int ifnum, int flags) { assert(conn != NULL); - assert(ifnum < CAN_DLL_NUMOF); + if (ifnum < 0 || ifnum >= CAN_DLL_NUMOF) { + memset(conn, 0, sizeof (*conn)); + conn->ifnum = -1; + return -ENODEV; + } DEBUG("conn_can_raw_create: create conn=%p, ifnum=%d flags=%d\n", (void *)conn, ifnum, flags); @@ -121,7 +125,11 @@ static void _tx_conf_timeout(void *arg) int conn_can_raw_send(conn_can_raw_t *conn, const struct can_frame *frame, int flags) { assert(conn != NULL); - assert(conn->ifnum < CAN_DLL_NUMOF); + + if (conn->ifnum < 0 || conn->ifnum >= CAN_DLL_NUMOF) { + return -ENODEV; + } + assert((conn->flags & CONN_CAN_RECVONLY) == 0); assert(frame != NULL); @@ -201,7 +209,11 @@ static void _rx_timeout(void *arg) int conn_can_raw_recv(conn_can_raw_t *conn, struct can_frame *frame, uint32_t timeout) { assert(conn != NULL); - assert(conn->ifnum < CAN_DLL_NUMOF); + + if (conn->ifnum < 0 || conn->ifnum >= CAN_DLL_NUMOF) { + return -ENODEV; + } + assert(frame != NULL); xtimer_t timer; @@ -256,7 +268,10 @@ int conn_can_raw_recv(conn_can_raw_t *conn, struct can_frame *frame, uint32_t ti int conn_can_raw_close(conn_can_raw_t *conn) { assert(conn != NULL); - assert(conn->ifnum < CAN_DLL_NUMOF); + + if (conn->ifnum < 0 || conn->ifnum >= CAN_DLL_NUMOF) { + return -ENODEV; + } DEBUG("conn_can_raw_close: conn=%p\n", (void *)conn); diff --git a/sys/can/dll.c b/sys/can/dll.c index 6ff0a06564..adf9dfb4e4 100644 --- a/sys/can/dll.c +++ b/sys/can/dll.c @@ -470,7 +470,9 @@ int raw_can_power_up(int ifnum) int raw_can_set_bitrate(int ifnum, uint32_t bitrate, uint32_t sample_point) { - assert(ifnum < candev_nb); + if (ifnum < 0 || ifnum >= candev_nb) { + return -1; + } int res = 0; int ret;