From e5b9e841294464b13aa6770a3502ef247b1bb485 Mon Sep 17 00:00:00 2001 From: Con Kolivas Date: Tue, 20 Jan 2015 11:09:49 +1100 Subject: [PATCH] Add a helper function to check a hex string is valid --- src/libckpool.c | 26 +++++++++++++++++++++++++- src/libckpool.h | 4 +++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/libckpool.c b/src/libckpool.c index 5d992e2e..d5873d8c 100644 --- a/src/libckpool.c +++ b/src/libckpool.c @@ -1,5 +1,5 @@ /* - * Copyright 2014 Con Kolivas + * Copyright 2014-2015 Con Kolivas * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free @@ -1351,6 +1351,30 @@ const int hex2bin_tbl[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; +bool _validhex(const char *buf, const char *file, const char *func, const int line) +{ + unsigned int i, slen; + bool ret = false; + + slen = strlen(buf); + if (!slen || slen % 2) { + LOGDEBUG("Invalid hex due to length %u from %s %s:%d", slen, file, func, line); + goto out; + } + for (i = 0; i < slen; i++) { + uchar idx = buf[i]; + + if (hex2bin_tbl[idx] == -1) { + LOGDEBUG("Invalid hex due to value %u at offset %d from %s %s:%d", + idx, i, file, func, line); + goto out; + } + } + ret = true; +out: + return ret; +} + /* Does the reverse of bin2hex but does not allocate any ram */ bool _hex2bin(void *vp, const void *vhexstr, size_t len, const char *file, const char *func, const int line) { diff --git a/src/libckpool.h b/src/libckpool.h index a52628fe..65fb4ae4 100644 --- a/src/libckpool.h +++ b/src/libckpool.h @@ -1,5 +1,5 @@ /* - * Copyright 2014 Con Kolivas + * Copyright 2014-2015 Con Kolivas * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free @@ -495,6 +495,8 @@ void _dealloc(void **ptr); extern const int hex2bin_tbl[]; void __bin2hex(void *vs, const void *vp, size_t len); void *bin2hex(const void *vp, size_t len); +bool _validhex(const char *buf, const char *file, const char *func, const int line); +#define validhex(buf) _validhex(buf, __FILE__, __func__, __LINE__) bool _hex2bin(void *p, const void *vhexstr, size_t len, const char *file, const char *func, const int line); #define hex2bin(p, vhexstr, len) _hex2bin(p, vhexstr, len, __FILE__, __func__, __LINE__) char *http_base64(const char *src);