with initial implementation from Rouven Wessling

with initial implementation from Rouven Wessling

Contents

Request for Comments: Timing attack safe string comparison function

Introduction

Timing attacks are not a widely recognized problem, since they require significant skill and resources of the attacker. To prevent these attacks constant-time string comparisons can be used. These implementations are rather hard to get right, without leaking timing information.

While high profile applications and frameworks already ship with time-constant string comparison functions, this RFC aims to make it simpler for PHP developers to protect their applications. Additionally there's less chance of unexpected timing differences in lower level languages.

The password_verify function implemented in PHP 5.5 already does a time-constant string comparison, however in many projects bcrypt can not be used for some reason (legacy project, interfacing with other systems, etc.), but they'd still benefit from this functionality.

Proposal

Implement a new function called hash_compare as part of ext/hash.

Signature bool hash_compare(string knownString, string userString)

The time this function takes is based only on the length of the user supplied string.

Users have to be mindful, as it is important that the user supplied string (or a hash of that string) is used as the the second parameter not the first.

Backward Incompatible Changes

None.

Proposed PHP Version(s)

Next PHP 5.x

Impact to Existing Extensions

None.

Patches and Tests

References

Differences between this RFC and the implementation

  • The function is now called hash_equals
  • Both arguments passed to the function have to be strings, otherwise an E_WARNING is raised.

Versions

Version Changed Date
1.1 Added section about differences between RFC and implementation
1.0 Moved function to ext/hash. Started voting.
0.2 Renamed to hash_compare, added link to Zend Framework 2, removed information leak when knownString is empty (Thank you Tjerk
0.1 Initial publication

Votes

An option needs 50%+1 votes to win

Timing attack safe string comparison function (95.7% approved)
User Vote
ajf Yes
andrey Yes
brianlmoon Yes
bwoebi Yes
chregu Yes
cpriest Yes
datibbaw Yes
derick Yes
indeyets Yes
klaussilveira Yes
krakjoe Yes
lstrojny Yes
malukenho Yes
mariuz Yes
nikic Yes
pajoye Yes
pollita Yes
seld Yes
shm No
stas Yes
treffynnon Yes
yohgaki Yes
zhangzhenyu Yes