diff options
Diffstat (limited to 'src/libstrongswan/utils')
-rw-r--r-- | src/libstrongswan/utils/chunk.h | 13 | ||||
-rw-r--r-- | src/libstrongswan/utils/utils.c | 19 | ||||
-rw-r--r-- | src/libstrongswan/utils/utils.h | 5 |
3 files changed, 37 insertions, 0 deletions
diff --git a/src/libstrongswan/utils/chunk.h b/src/libstrongswan/utils/chunk.h index 48405b77e..2ec7f7543 100644 --- a/src/libstrongswan/utils/chunk.h +++ b/src/libstrongswan/utils/chunk.h @@ -310,6 +310,19 @@ static inline bool chunk_equals(chunk_t a, chunk_t b) } /** + * Compare two chunks for equality, constant time for cryptographic purposes. + * + * Note that this function is constant time only for chunks with the same + * length, i.e. it does not protect against guessing the length of one of the + * chunks. + */ +static inline bool chunk_equals_const(chunk_t a, chunk_t b) +{ + return a.ptr != NULL && b.ptr != NULL && + a.len == b.len && memeq_const(a.ptr, b.ptr, a.len); +} + +/** * Compare two chunks (given as pointers) for equality (useful as callback), * NULL chunks are never equal. */ diff --git a/src/libstrongswan/utils/utils.c b/src/libstrongswan/utils/utils.c index 02a720945..3d5e3dfc9 100644 --- a/src/libstrongswan/utils/utils.c +++ b/src/libstrongswan/utils/utils.c @@ -112,6 +112,25 @@ void memwipe_noinline(void *ptr, size_t n) /** * Described in header. */ +bool memeq_const(const void *x, const void *y, size_t len) +{ + const u_char *a, *b; + u_int bad = 0; + size_t i; + + a = (const u_char*)x; + b = (const u_char*)y; + + for (i = 0; i < len; i++) + { + bad |= a[i] != b[i]; + } + return !bad; +} + +/** + * Described in header. + */ void *memstr(const void *haystack, const char *needle, size_t n) { const u_char *pos = haystack; diff --git a/src/libstrongswan/utils/utils.h b/src/libstrongswan/utils/utils.h index 7c48d949f..2675acae8 100644 --- a/src/libstrongswan/utils/utils.h +++ b/src/libstrongswan/utils/utils.h @@ -185,6 +185,11 @@ static inline bool memeq(const void *x, const void *y, size_t len) } /** + * Same as memeq(), but with a constant runtime, safe for cryptographic use. + */ +bool memeq_const(const void *x, const void *y, size_t len); + +/** * Calling memcpy() with NULL pointers, even with n == 0, results in undefined * behavior according to the C standard. This version is guaranteed to not * access the pointers if n is 0. |