Backport of abf5ccc29c45d53ec17541179bb5f0a75b28915d from master
Thanks Florian Apolloner and Carl Meyer for review. This is a security fix.