I'm the author of the pull request that prompted the discussion, though, so I'm probably biased. :)
It'd simply be nice if the scope of the discussion was about how all languages have more or less the same flaws. Anyone writing code with security in mind should understand how to avoid those flaws.
There are many ways to alleviate the problem specified in the pull request that may be better. Pecl is one route that was mentioned on internals. Also, possibly just cache the hex value in memory and avoid the bin2hex conversion outright (with randomization of your cold cache times).
Edit: As an aside, I want to also greatly express that the requirement to attack the bin2hex vulnerability is so high for most cases the attacker would require complete, private, 1-hop, uninterrupted access to a single target machine. Usually this implies the attack not being remote but I do understand the mental exercise.
Especially since all this does is patch the behavior of one function. :|
And if you have PECL, you might as well go all the way and install libsodium.
Not really viable against a native code memcmp. Potentially viable against a comparison implemented in PHP or Java.
Here's a video looking at actually implementing such attacks over LAN and internet: http://rdist.root.org/2010/11/09/blackhat-2010-video-on-remo...
> Would a good hosting company block an attack like this at the hardware level? No, there's no generic way to defeat this. The only real limit is how granular your attacker can measure. If you're on shared hosting, you're probably the most vulnerable you can get to this (but also the most screwed already, so you probably don't cate).
That said, while it's not instant game over, you don't really want this vulnerability if you can avoid it. Especially in things like authentication libraries.
For optimal security, OP mentions that we should fix the underlying code, but I kind of disagree. Understanding all the underlying code is a lot of work and, except for extremely secure application, is not really needed. Also, hindering performance for security is not always the way to go (he mentions returning only at the end).
If you have ultra-secure tasks to do, you might want to do something like calculating the execution time of the function and sleep()'ing to add padding. Example code (doesn't work):
function login(){
execstart = utime()
// whatever code
execduration = utime() - execstart;
sleep( execduration % 100 ); // pad on at 100 boundary
}You'd have to carefully choose your padding so the execution time is (normally) not revealed in the code.
So, there are a few problems with this technique.
1. It ignores the local timing leak
An attacker who can get code running on the server (shared hosts for example), can carefully monitor the CPU usage to see when the process is actually doing work, vs when it sleeps. So really, its not hiding anything.
2. The resolution of the sleep call is WAY too high. We're talking about detecting differences down to 15 nanoseconds. Sleeping for blocks of microseconds or even milliseconds will be far to granular. It will introduce block-like patterns in the requests that should be pretty easy to detect with statistical means.
3. It's basically identical to a random delay. Considering it depends on the system clock, and the original request comes in at a random point, it's functionally identical to calling sleep(random(1, 100)). And over time (many requests), that will average out.
Now, what if we took a different approach. What if we made the operation fixed-time?
execstart = utime()
// whatever code
// clamp to always take 500 microseconds
sleep( 500 - utime() - execduration)
That might work (assuming you have a high enough resolution sleep function). Again, it suffers the local attacker problem (which may or may not matter in your case).However, there are two reasons I wouldn't recommend it: It requires guesswork and idle CPU.
You would either need to actively guess every single operation (and remember to clamp it) or clamp the overall application.
If you do it for every operation, that sleep time can become expensive (if you have a lot of them).
If you do it on the application level, and if you do too little, an attacker can use other expensive control (like larger input introducing memory allocation latency) to increase the runtime past the sleep clamp (hence allowing them to attack the vulnerability anyway). If you do too much, the attacker can leverage it to DOS your site (since even a sleeping process is non-trivially expensive).
There are two valid ways of protection IMHO:
1. Make sensitive operations actually constant time.
2. Implement strong IP based protections to prevent the large amount of requests that would be needed to collect enough data to analyze noisy environments. (I need to add this to the post now that I write it).
Personally, you should be doing #2 anyway. But since I also believe in defense-in-depth, I'd do #1 as well.
For the precision of sleep, http://php.net/manual/en/function.time-nanosleep.php might be more appropriate
Also, you would only need to slightly clamp very important functions, so DoS attacks aren't that likely on it (and a constant timed function would also take the same time).
Accessing RAM requires system level access (privileged users, super user really) or running as the same user as the other process.
So unless the server is horribly misconfigured, or you exploit another vulnerability, reading from RAM isn't as likely as monitoring the CPU.
I'm leaning toward the approach of having a simple clamping library at the application level that (a) throws an exception if the sensitive code takes longer than the 'clamp time'; and (b) has some simple heuristic to determine the clamp time, such as "double the maximum execution time recorded during the first 20 runs". It might have a drawback if the CPU is not idle, but the benefit is that it is dead simple to implement. (Assuming the platform supports nanosecond wait times)
You only really need to worry about timing attacks for values that the attacker doesn't know, and you don't want them to know.
So it's only things like encryption keys, passwords, session identifiers, reset tokens, etc that you need to worry about.
> And programmers who touch sensitive code can easily forget the requirement for constant-time behaviour.
And that's why I support the discussion we were having on PHP's internals list where we talked about making functions which are commonly used with secrets timing safe by default. As long as there isn't a non-trivial performance penalty to it at least.
As far as worrying about it, I'd rather people understand SQLi and XSS better. They are both FAR bigger surface areas than a timing attack ever will be. And likely going to be the bigger threat to 99.99% of applications.
Sorry, it appears that I didn't actually define constant time anywhere. What I really mean is that:
Runtime does not depend in any way on the *value* of secret data.
So while actual runtime may vary, it's not varying because of the value of something we want to protect.So it's not about keeping "absolute" time constant, but only the impact of the secret on runtime.
Your sleep hack is probably less secure. I remember reading somewhere that doing random sleep() calls is flawed and doesn't completely mitigate the attack, but does increase the number of requests needed to get a good statistical analysis.
An approach where you watch the clock will be inherently less portable and actually much harder. Not only will the timing calls be hardware or OS specific, but so will the worst-case time. Imagine having to deal with a chip going into low power mode during your computation. Also you probably don't want to count time that your thread wasn't scheduled to run, so now you're talking about integrating with the scheduler.
https://news.ycombinator.com/formatdoc
>Text after a blank line that is indented by two or more spaces is reproduced verbatim. (This is intended for code.)
I never knew that this
functionality existedNot saying it's not an issue, but I'm not so sure it's a big deal either.
The code for the tool (and a presentation pdf) is here if you're interested: https://github.com/aj-code/TimingIntrusionTool5000
Oh, well yeah that's what I did. Guess I'll have to look further.
> the 10th percentile measurement is much better
That sounds like something to try, thanks!
I would imagine that you can prevent length leaks by looping through the characters of the known value and then returning that comparison with an additional check of length.
function timingSafeEquals($safe, $user) {
$safeLen = strlen($safe);
$userLen = strlen($user);
$result = 0;
for ($i = 0; $i < $userLen; $i++) {
$result |= (ord($safe[$i]) ^ ord($user[$i]));
}
return $result === 0 && $userLen === $safeLen;
}However, leaking the length is much less of a problem than allowing the attacker to guess characters one by one.
But imagine the loop would be the string we know (i.e. the password). Looping through the 10-character pass should be identical every time, regardless of what the user entered.
+1 for recommending checking the PHP source code to be sure, though
See: http://lxr.php.net/xref/PHP_TRUNK/Zend/zend_builtin_function...
The problem you'll run into with PHP specifically is that reading an undefined string offset (past the end) will result in a notice: http://3v4l.org/nIkf5
Which means that errors are triggered. So you can increase the length of the user string and note a linear increase in runtime until you increase it past the length of the string, at which point it becomes MUCH slower on a per-character basis (even if you don't do anything with the notice, the error mechanism is still triggered internally, which isn't cheap).
Actually, my original code was more robust as it never read past the end of the string, preventing the notice:
/**
* A timing safe equals comparison
*
* To prevent leaking length information, it is important
* that user input is always used as the second parameter.
*
* @param string $safe The internal (safe) value to be checked
* @param string $user The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
*/
function timingSafeEquals($safe, $user) {
// Prevent issues if string length is 0
$safe .= chr(0);
$user .= chr(0);
$safeLen = strlen($safe);
$userLen = strlen($user);
// Set the result to the difference between the lengths
$result = $safeLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information
for ($i = 0; $i < $userLen; $i++) {
// Using % here is a trick to prevent notices
// It's safe, since if the lengths are different
// $result is already non-0
$result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
}
// They are only identical strings if $result is exactly 0...
return $result === 0;
}
There are a few problems here though that are non-trivial as are explained in the post: http://security.stackexchange.com/questions/49849/timing-saf...Basically, while it may keep the length %64 safe (since cache lines are 64 bites wide), it doesn't keep the length safe in general. Some length information will be leaked on larger strings. And considering it's impossible to protect the length in the general case, making a function which says it protects length is a lie. Therefore I don't even try and hence save the complexity.
But let me ask this: what cases would you have where are you trying to protect the length? Anything with variable length input (like a password) should likely be one-way hashed anyway. So you'd be comparing fixed-length hashes. So where's the possible leak?
It just has to exhibit the "correct matching strings return faster" property, whatever more complicated search it does.
But that's how you can make them faster http://homakov.blogspot.com/2014/07/timing-attack-666-faster...