MCPcopy Create free account
hub / github.com/Snapchat/KeyDB / time_independent_strcmp

Function time_independent_strcmp

src/acl.cpp:128–159  ·  view source on GitHub ↗

Return zero if strings are the same, non-zero if they are not. * The comparison is performed in a way that prevents an attacker to obtain * information about the nature of the strings just monitoring the execution * time of the function. * * Note that limiting the comparison length to strings up to 512 bytes we * can avoid leaking any information about the password length and any * possible

Source from the content-addressed store, hash-verified

126 * possible branch misprediction related leak.
127 */
128int time_independent_strcmp(char *a, char *b) {
129 char bufa[CONFIG_AUTHPASS_MAX_LEN], bufb[CONFIG_AUTHPASS_MAX_LEN];
130 /* The above two strlen perform len(a) + len(b) operations where either
131 * a or b are fixed (our password) length, and the difference is only
132 * relative to the length of the user provided string, so no information
133 * leak is possible in the following two lines of code. */
134 unsigned int alen = strlen(a);
135 unsigned int blen = strlen(b);
136 unsigned int j;
137 int diff = 0;
138
139 /* We can't compare strings longer than our static buffers.
140 * Note that this will never pass the first test in practical circumstances
141 * so there is no info leak. */
142 if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1;
143
144 memset(bufa,0,sizeof(bufa)); /* Constant time. */
145 memset(bufb,0,sizeof(bufb)); /* Constant time. */
146 /* Again the time of the following two copies is proportional to
147 * len(a) + len(b) so no info is leaked. */
148 memcpy(bufa,a,alen);
149 memcpy(bufb,b,blen);
150
151 /* Always compare all the chars in the two buffers without
152 * conditional expressions. */
153 for (j = 0; j < sizeof(bufa); j++) {
154 diff |= (bufa[j] ^ bufb[j]);
155 }
156 /* Length must be equal as well. */
157 diff |= alen ^ blen;
158 return diff; /* If zero strings are the same. */
159}
160
161/* Given an SDS string, returns the SHA256 hex representation as a
162 * new SDS string. */

Callers 2

ACLListMatchSdsSecureFunction · 0.85
ACLCheckUserCredentialsFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected