From 54aa7d8e28b55a65038164b27a141bc13e813458 Mon Sep 17 00:00:00 2001 From: Lukas Nykryn Date: Fri, 6 Jun 2014 10:56:21 +0200 Subject: ipcalc: parse prefix more safely --- src/ipcalc.c | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/ipcalc.c b/src/ipcalc.c index 8decccad..ccb3f6db 100644 --- a/src/ipcalc.c +++ b/src/ipcalc.c @@ -30,6 +30,7 @@ #include #include #include +#include /*! \file ipcalc.c @@ -48,6 +49,24 @@ return host byte order, but there are some exceptions. */ +int safe_atoi(const char *s, int *ret_i) { + char *x = NULL; + long l; + + errno = 0; + l = strtol(s, &x, 0); + + if (!x || x == s || *x || errno) + return errno > 0 ? -errno : -EINVAL; + + if ((long) (int) l != l) + return -ERANGE; + + *ret_i = (int) l; + return 0; +} + + /*! \fn struct in_addr prefix2mask(int bits) \brief creates a netmask from a specified number of bits @@ -286,8 +305,9 @@ int main(int argc, const char **argv) { } if (prefixStr != NULL) { - prefix = atoi(prefixStr); - if (prefix < 0 || ((familyIPv6 && prefix > 128) || (!familyIPv6 && prefix > 32))) { + int r = 0; + r = safe_atoi(prefixStr, &prefix); + if (r != 0 || prefix < 0 || ((familyIPv6 && prefix > 128) || (!familyIPv6 && prefix > 32))) { if (!beSilent) fprintf(stderr, "ipcalc: bad prefix: %s\n", prefixStr); return 1; -- cgit v1.2.1