1 // SPDX-License-Identifier: ISC
2 /*
3  * Copyright (C) 2019 Linaro Limited
4  * Copyright (C) 2004-2007, 2011, 2012  Internet Systems Consortium, Inc. ("ISC")
5  * Copyright (C) 1999-2001, 2003  Internet Software Consortium.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
12  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
14  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
16  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17  * PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <limits.h>
21 #include <string_ext.h>
22 
23 /* Making a portable memcmp that has no internal branches and loops always
24  * once for every byte without early-out shortcut has a few challenges.
25  *
26  * Inspired by 'timingsafe_memcmp()' from the BSD system and
27  * https://github.com/libressl-portable/openbsd/blob/master/src/lib/libc/string/timingsafe_memcmp.c
28  *
29  * Sadly, that one is not portable C: It makes assumptions on the representation
30  * of negative integers and assumes sign-preserving right-shift of negative
31  * signed values. This is a rewrite from scratch that should not suffer from
32  * such issues.
33  *
34  * 2015-12-12, J. Perlinger (perlinger-at-ntp-dot-org)
35  */
consttime_memcmp(const void * p1,const void * p2,size_t nb)36 int consttime_memcmp(const void *p1, const void *p2, size_t nb) {
37 	const unsigned char *ucp1 = p1;
38 	const unsigned char *ucp2 = p2;
39 	unsigned int isLT = 0u;
40 	unsigned int isGT = 0u;
41 	volatile unsigned int mask = (1u << CHAR_BIT);
42 
43 	for (/*NOP*/; 0 != nb; --nb, ++ucp1, ++ucp2) {
44 		isLT |= mask &
45 		    ((unsigned int)*ucp1 - (unsigned int)*ucp2);
46 		isGT |= mask &
47 		    ((unsigned int)*ucp2 - (unsigned int)*ucp1);
48 		mask &= ~(isLT | isGT);
49 	}
50 	return (int)(isGT >> CHAR_BIT) - (int)(isLT >> CHAR_BIT);
51 }
52