From 83ef49956257fc928fe064e1d6b5f4e52a9f02b8 Mon Sep 17 00:00:00 2001 From: "Alfred E. Heggestad" Date: Thu, 4 Jan 2018 14:07:31 +0100 Subject: [PATCH] mem: add secure memory functions (#102) the use case for these functions is secure code like SRTP and TLS. memcmp() should not be used when comparing secret data such as shared keys, because the content may affect the timing. instead the compare function should always take the same to execute, independently of the content. --- include/re_mem.h | 6 ++++++ src/mem/mod.mk | 1 + src/mem/secure.c | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 src/mem/secure.c diff --git a/include/re_mem.h b/include/re_mem.h index a1db178..d09d5e2 100644 --- a/include/re_mem.h +++ b/include/re_mem.h @@ -37,3 +37,9 @@ void mem_threshold_set(ssize_t n); struct re_printf; int mem_status(struct re_printf *pf, void *unused); int mem_get_stat(struct memstat *mstat); + + +/* Secure memory functions */ +int mem_seccmp(const volatile uint8_t *volatile s1, + const volatile uint8_t *volatile s2, + size_t n); diff --git a/src/mem/mod.mk b/src/mem/mod.mk index aaa284a..0de616b 100644 --- a/src/mem/mod.mk +++ b/src/mem/mod.mk @@ -5,3 +5,4 @@ # SRCS += mem/mem.c +SRCS += mem/secure.c diff --git a/src/mem/secure.c b/src/mem/secure.c new file mode 100644 index 0000000..6cf64d9 --- /dev/null +++ b/src/mem/secure.c @@ -0,0 +1,37 @@ +/** + * @file mem/secure.c Secure memory functions + * + * Copyright (C) 2010 Creytiv.com + */ + +#include +#include + + +/** + * Compare two byte strings in constant time. This function can be used + * by secure code to compare secret data, such as authentication tags, + * to avoid side-channel attacks. + * + * @param s1 First byte string + * @param s2 Second byte string + * @param n Number of bytes + * + * @return a negative number if argument errors + * 0 if both byte strings matching + * a positive number if not matching + */ +int mem_seccmp(const volatile uint8_t *volatile s1, + const volatile uint8_t *volatile s2, + size_t n) +{ + uint8_t val = 0; + + if (!s1 || !s2) + return -1; + + while (n--) + val |= *s1++ ^ *s2++; + + return val; +}