Skip to content

[Validator] prevent hash collisions caused by reused object hashes #38387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
class FormValidator extends ConstraintValidator
{
private $resolvedGroups;
private $fieldFormConstraints;

/**
* {@inheritdoc}
Expand Down Expand Up @@ -68,7 +67,6 @@ public function validate($form, Constraint $formConstraint)

if ($hasChildren && $form->isRoot()) {
$this->resolvedGroups = new \SplObjectStorage();
$this->fieldFormConstraints = [];
}

if ($groups instanceof GroupSequence) {
Expand All @@ -93,7 +91,6 @@ public function validate($form, Constraint $formConstraint)
$this->resolvedGroups[$field] = (array) $group;
$fieldFormConstraint = new Form();
$fieldFormConstraint->groups = $group;
$this->fieldFormConstraints[] = $fieldFormConstraint;
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint, $group);
}
Expand Down Expand Up @@ -139,18 +136,15 @@ public function validate($form, Constraint $formConstraint)
foreach ($form->all() as $field) {
if ($field->isSubmitted()) {
$this->resolvedGroups[$field] = $groups;
$fieldFormConstraint = new Form();
$this->fieldFormConstraints[] = $fieldFormConstraint;
$this->context->setNode($this->context->getValue(), $field, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $fieldFormConstraint);
$validator->atPath(sprintf('children[%s]', $field->getName()))->validate($field, $formConstraint);
}
}
}

if ($hasChildren && $form->isRoot()) {
// destroy storage to avoid memory leaks
$this->resolvedGroups = new \SplObjectStorage();
$this->fieldFormConstraints = [];
}
} elseif (!$form->isSynchronized()) {
$childrenSynchronized = true;
Expand All @@ -159,11 +153,8 @@ public function validate($form, Constraint $formConstraint)
foreach ($form as $child) {
if (!$child->isSynchronized()) {
$childrenSynchronized = false;

$fieldFormConstraint = new Form();
$this->fieldFormConstraints[] = $fieldFormConstraint;
$this->context->setNode($this->context->getValue(), $child, $this->context->getMetadata(), $this->context->getPropertyPath());
$validator->atPath(sprintf('children[%s]', $child->getName()))->validate($child, $fieldFormConstraint);
$validator->atPath(sprintf('children[%s]', $child->getName()))->validate($child, $formConstraint);
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Form/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
},
"require-dev": {
"doctrine/collections": "~1.0",
"symfony/validator": "^3.4.44|^4.3.4|^5.0",
"symfony/validator": "^4.4.17|^5.1.9",
"symfony/dependency-injection": "^3.4|^4.0|^5.0",
"symfony/expression-language": "^3.4|^4.0|^5.0",
"symfony/config": "^3.4|^4.0|^5.0",
Expand Down
18 changes: 18 additions & 0 deletions src/Symfony/Component/Validator/Context/ExecutionContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ class ExecutionContext implements ExecutionContextInterface
* @var array
*/
private $initializedObjects;
private $cachedObjectsRefs;

/**
* Creates a new execution context.
Expand All @@ -153,6 +154,7 @@ public function __construct(ValidatorInterface $validator, $root, $translator, s
$this->translator = $translator;
$this->translationDomain = $translationDomain;
$this->violations = new ConstraintViolationList();
$this->cachedObjectsRefs = new \SplObjectStorage();
}

/**
Expand Down Expand Up @@ -358,4 +360,20 @@ public function isObjectInitialized($cacheKey): bool
{
return isset($this->initializedObjects[$cacheKey]);
}

/**
* @internal
*
* @param object $object
*
* @return string
*/
public function generateCacheKey($object)
{
if (!isset($this->cachedObjectsRefs[$object])) {
$this->cachedObjectsRefs[$object] = spl_object_hash($object);
}

return $this->cachedObjectsRefs[$object];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\GroupSequence;
use Symfony\Component\Validator\Constraints\IsFalse;
use Symfony\Component\Validator\Constraints\IsNull;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
Expand All @@ -26,6 +29,7 @@
use Symfony\Component\Validator\Constraints\Required;
use Symfony\Component\Validator\Constraints\Traverse;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\Context\ExecutionContextFactory;
Expand Down Expand Up @@ -2135,4 +2139,66 @@ public function testOptionalConstraintIsIgnored()

$this->assertCount(0, $violations);
}

public function testValidatedConstraintsHashesDoNotCollide()
{
$metadata = new ClassMetadata(Entity::class);
$metadata->addPropertyConstraint('initialized', new NotNull(['groups' => 'should_pass']));
$metadata->addPropertyConstraint('initialized', new IsNull(['groups' => 'should_fail']));

$this->metadataFactory->addMetadata($metadata);

$entity = new Entity();
$entity->data = new \stdClass();

$this->assertCount(2, $this->validator->validate($entity, new TestConstraintHashesDoNotCollide()));
}

public function testValidatedConstraintsHashesDoNotCollideWithSameConstraintValidatingDifferentProperties()
{
$value = new \stdClass();

$entity = new Entity();
$entity->firstName = $value;
$entity->setLastName($value);

$validator = $this->validator->startContext($entity);

$constraint = new IsNull();
$validator->atPath('firstName')
->validate($entity->firstName, $constraint);
$validator->atPath('lastName')
->validate($entity->getLastName(), $constraint);

$this->assertCount(2, $validator->getViolations());
}
}

final class TestConstraintHashesDoNotCollide extends Constraint
{
}

final class TestConstraintHashesDoNotCollideValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$value instanceof Entity) {
throw new \LogicException();
}

$this->context->getValidator()
->inContext($this->context)
->atPath('data')
->validate($value, new NotNull())
->validate($value, new NotNull())
->validate($value, new IsFalse());

$this->context->getValidator()
->inContext($this->context)
->validate($value, null, new GroupSequence(['should_pass']))
->validate($value, null, new GroupSequence(['should_fail']));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public function validate($value, $constraints = null, $groups = null)
$this->validateGenericNode(
$value,
$previousObject,
\is_object($value) ? spl_object_hash($value) : null,
\is_object($value) ? $this->generateCacheKey($value) : null,
$metadata,
$this->defaultPropertyPath,
$groups,
Expand Down Expand Up @@ -176,7 +176,7 @@ public function validateProperty($object, $propertyName, $groups = null)

$propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
$groups = $groups ? $this->normalizeGroups($groups) : $this->defaultGroups;
$cacheKey = spl_object_hash($object);
$cacheKey = $this->generateCacheKey($object);
$propertyPath = PropertyPath::append($this->defaultPropertyPath, $propertyName);

$previousValue = $this->context->getValue();
Expand Down Expand Up @@ -224,7 +224,7 @@ public function validatePropertyValue($objectOrClass, $propertyName, $value, $gr
if (\is_object($objectOrClass)) {
$object = $objectOrClass;
$class = \get_class($object);
$cacheKey = spl_object_hash($objectOrClass);
$cacheKey = $this->generateCacheKey($objectOrClass);
$propertyPath = PropertyPath::append($this->defaultPropertyPath, $propertyName);
} else {
// $objectOrClass contains a class name
Expand Down Expand Up @@ -313,7 +313,7 @@ private function validateObject($object, string $propertyPath, array $groups, in

$this->validateClassNode(
$object,
spl_object_hash($object),
$this->generateCacheKey($object),
$classMetadata,
$propertyPath,
$groups,
Expand Down Expand Up @@ -429,7 +429,7 @@ private function validateClassNode($object, ?string $cacheKey, ClassMetadataInte
$defaultOverridden = false;

// Use the object hash for group sequences
$groupHash = \is_object($group) ? spl_object_hash($group) : $group;
$groupHash = \is_object($group) ? $this->generateCacheKey($group, true) : $group;

if ($context->isGroupValidated($cacheKey, $groupHash)) {
// Skip this group when validating the properties and when
Expand Down Expand Up @@ -740,7 +740,7 @@ private function validateInGroup($value, ?string $cacheKey, MetadataInterface $m
// Prevent duplicate validation of constraints, in the case
// that constraints belong to multiple validated groups
if (null !== $cacheKey) {
$constraintHash = spl_object_hash($constraint);
$constraintHash = $this->generateCacheKey($constraint, true);
// instanceof Valid: In case of using a Valid constraint with many groups
// it makes a reference object get validated by each group
if ($constraint instanceof Composite || $constraint instanceof Valid) {
Expand Down Expand Up @@ -772,4 +772,22 @@ private function validateInGroup($value, ?string $cacheKey, MetadataInterface $m
}
}
}

/**
* @param object $object
*/
private function generateCacheKey($object, bool $dependsOnPropertyPath = false): string
{
if ($this->context instanceof ExecutionContext) {
$cacheKey = $this->context->generateCacheKey($object);
} else {
$cacheKey = spl_object_hash($object);
}

if ($dependsOnPropertyPath) {
$cacheKey .= $this->context->getPropertyPath();
}

return $cacheKey;
}
}