Skip to content

compare strings in constant time #120

@syndrome2

Description

@syndrome2

I understand that on a well-tuned system, the success of a timing attack is doubtful, but why not increase the security for free?
compare_in_constant_time.patch.txt

diff '--color=auto' -ru a/shadow.c b/shadow.c
--- a/shadow.c	2022-01-26 18:01:11.000000000 +0200
+++ b/shadow.c	2023-07-19 08:27:01.806569020 +0300
@@ -41,6 +41,19 @@
 #define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
 #endif

+int compare_in_constant_time(const char * str1, const char * str2)
+{
+	char result = 0;
+	while (1)
+	{
+		char a = *str1 ^ *str2;
+		result = result | a;
+		if ((*str1 == 0) || (*str2 == 0)) {break;}
+		str1++; str2++;
+	}
+	return (int)result;
+}
+
 void
 shadowauth(const char *myname, int persist)
 {
@@ -94,7 +107,7 @@
 		errx(1, "Authentication failed");
 	}
 	explicit_bzero(rbuf, sizeof(rbuf));
-	if (strcmp(encrypted, hash) != 0) {
+	if (compare_in_constant_time(encrypted, hash) != 0) {
 		syslog(LOG_AUTHPRIV | LOG_NOTICE, "failed auth for %s", myname);
 		errx(1, "Authentication failed");
 	}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions