checksums.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  1. """
  2. Misago saves parsed strings in database.
  3. Those strings are "trusted" and contain HTML that is rendered by templates
  4. without additional sanitization step.
  5. While this greatly improves speed, it also means that SQLInjections may
  6. escalate to Code Injection vulnerabilities.
  7. Because of this you should use this module to generate checksum for each model
  8. that contains parsed strings. Each checksum should be generated from markup as
  9. well as additional unique values that are specific for that model, like its PK,
  10. post date, etc ect.
  11. That way even if few items will contain the same content, they will have
  12. different checksums, and as long as attacker has no access to filesystem,
  13. he'll wont know SECRET_KEY and thus won't be able to generate valid checksums
  14. for injected content
  15. Because SHA256 is used for checksum generation, make sure you are storing them
  16. in char fields with max_length=64
  17. """
  18. from hashlib import sha256
  19. from django.utils import six
  20. def make_checksum(parsed, unique_values=None):
  21. unique_values = unique_values or []
  22. seeds = [parsed] + [six.text_type(v) for v in unique_values]
  23. return sha256('+'.join(seeds).encode("utf-8")).hexdigest()
  24. def is_checksum_valid(parsed, checksum, unique_values=None):
  25. return checksum == make_checksum(parsed, unique_values)