Skip to content
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
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,17 @@

All notable changes to this project. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) with [Semantic Versioning](https://semver.org/).

## [1.2.3] - 2026-11-14

### Security

- `create_response()` verifies the signature before it reads the fields. Before the check it reads at most 128 KiB of `Ds_MerchantParameters` and 128 characters of `Ds_Signature`, and rejects JSON nested deeper than 32 levels. Before, an unsigned payload posted to the notification URL was decoded and read first: deeply nested JSON could exhaust a small thread stack and crash the process (Python 3.12 and 3.13 with a 1 MiB thread stack), and `Ds_Signature` was normalized whatever its length.
- Signatures are compared in constant time, with `hmac.compare_digest`.

### Fixed

- `create_response()` raises `ValueError` for any malformed payload: a field that is not ASCII text, a `Ds_MerchantParameters` that is not a Base64-encoded JSON object, or a signed field that cannot be read. A missing `Ds_Order`, or one longer than 16 characters, fails the signature check. Before, these raised `TypeError`, `AttributeError`, `RecursionError`, `decimal.InvalidOperation` or a PyCryptodome `ValueError`.

## [1.2.2] - 2026-10-17

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ RedSys notifies the result both as a server-to-server POST to `merchant_url` and

### 3. Verify and read the response

`create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters` and raises `ValueError` on signature mismatch.
`create_response()` takes the received `Ds_Signature` and `Ds_MerchantParameters`, verifies the signature before it reads any field, and raises `ValueError` on signature mismatch or a malformed payload: a `Ds_Signature` over 128 characters, a `Ds_MerchantParameters` over 128 KiB or that is not a Base64-encoded JSON object nested at most 32 levels, or a signed field that cannot be read.

```python
response = client.create_response(signature, merchant_parameters) # as RedSys posted them back
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "python-redsys"
version = "1.2.2"
version = "1.2.3"
description = "A simple, lightweight client to handle payments through the RedSys platform."
authors = ["David Díaz <d.diazp@gmail.com>", "Andrés Reverón Molina <andres@reveronmolina.me>"]
license = "MIT"
Expand Down
2 changes: 1 addition & 1 deletion redsys/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__version__ = "1.2.2"
__version__ = "1.2.3"
__version_info__ = tuple(int(num) if num.isdigit() else num for num in __version__.replace("-", ".", 1).split("."))
71 changes: 59 additions & 12 deletions redsys/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
import re
from abc import ABC
from abc import abstractmethod
from itertools import accumulate
from operator import sub as subtract
from typing import Any
from typing import Dict

from Crypto.Cipher import DES3

from redsys.request import Request
from redsys.response import ORDER
from redsys.response import Response

# Calculated parameters
Expand All @@ -19,6 +22,34 @@
SIGNATURE = "Ds_Signature"
DEFAULT_SIGNATURE_VERSION = "HMAC_SHA256_V1"

# Real notifications take a few KiB; the caps bound the work done before the signature is checked.
_MAX_MERCHANT_PARAMETERS_LENGTH = 128 * 1024
_MAX_SIGNATURE_LENGTH = 128
# RedSys payloads nest two or three levels; deeper JSON can exhaust a small thread
# stack inside the C JSON decoder and kill the process.
_MAX_JSON_DEPTH = 32
_NOT_BRACKETS = bytes(sorted(set(range(256)) - set(b"[]{}")))
_BRACKET_WEIGHTS = bytes.maketrans(b"[{]}", b"\x02\x02\x00\x00")
_NOT_ALPHANUMERIC = re.compile(b"[^a-zA-Z0-9]")


def _json_depth_exceeds(text: bytes, limit: int) -> bool:
"""Whether JSON text nests deeper than ``limit``; brackets inside strings do not count."""
if text.count(b"[") + text.count(b"{") <= limit:
return False
# Bytes operations only: the text may be attacker-sized, and a byte loop costs ten times more.
outside_strings = b"".join(text.replace(b"\\\\", b"").replace(b'\\"', b"").split(b'"')[::2])
# Opening brackets weigh 2 and closing ones 0: the running sum minus the position is the depth.
weights = outside_strings.translate(_BRACKET_WEIGHTS, _NOT_BRACKETS)
return max(map(subtract, accumulate(weights), range(1, len(weights) + 1)), default=0) > limit


def _received_field(value: str, name: str, max_length: int) -> bytes:
"""A received Base64 field as bytes; Base64 is ASCII text."""
if not isinstance(value, str) or len(value) > max_length or not value.isascii():
raise ValueError(f"{name} is not Base64 text of at most {max_length} characters.")
return value.encode()


class Client(ABC):
"""
Expand All @@ -44,8 +75,11 @@ def encode_parameters(parameters: Dict[str, Any]) -> bytes:

@staticmethod
def decode_parameters(parameters: bytes) -> Dict[str, Any]:
"""Decodes the merchant parameters from base64"""
return json.loads(base64.b64decode(parameters).decode())
"""Decodes the merchant parameters from base64; JSON nested deeper than any RedSys payload raises ValueError"""
text = base64.b64decode(parameters)
if _json_depth_exceeds(text, _MAX_JSON_DEPTH):
raise ValueError(f"JSON nests deeper than {_MAX_JSON_DEPTH} levels.")
return json.loads(text.decode())

@staticmethod
def sign_hmac256(encrypted_order: bytes, merchant_parameters: bytes) -> bytes:
Expand Down Expand Up @@ -91,15 +125,28 @@ def create_response(
Checks if the received signature corresponds to the sent signature.

Both the `signature` and `merchant parameters` are plain strings, not bytes.
The fields are read only after the signature matches; a malformed payload
raises `ValueError` too.
"""
decoded_parameters = self.decode_parameters(merchant_parameters.encode())
response = Response(decoded_parameters)
calculated_signature = self.generate_signature(response.order, merchant_parameters.encode())
# Remove any non-alphanumeric characters from the signature
not_alphanumeric = re.compile("[^a-zA-Z0-9]")
safe_signature = re.sub(not_alphanumeric, "", signature)

safe_calculated_signature = re.sub(not_alphanumeric, "", calculated_signature.decode())
if safe_signature != safe_calculated_signature:
received_signature = _received_field(signature, SIGNATURE, _MAX_SIGNATURE_LENGTH)
encoded_parameters = _received_field(merchant_parameters, MERCHANT_PARAMETERS, _MAX_MERCHANT_PARAMETERS_LENGTH)
try:
decoded_parameters = self.decode_parameters(encoded_parameters)
except ValueError as error:
raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object: {error}") from error
if not isinstance(decoded_parameters, dict):
raise ValueError(f"{MERCHANT_PARAMETERS} is not a Base64-encoded JSON object.")
order = decoded_parameters.get(ORDER)
# encrypt_3DES takes at most 16 ASCII bytes; any other order cannot verify, so it signs as ''.
if not (isinstance(order, str) and order.isascii() and len(order) <= 16):
order = ""
calculated_signature = self.generate_signature(order, encoded_parameters)
# Signatures may arrive in URL-safe Base64; only the alphanumeric core is compared.
if not hmac.compare_digest(
_NOT_ALPHANUMERIC.sub(b"", received_signature), _NOT_ALPHANUMERIC.sub(b"", calculated_signature)
):
raise ValueError("The provided signature is not valid.")
return response
try:
return Response(decoded_parameters)
except (ValueError, ArithmeticError) as error:
raise ValueError(f"{MERCHANT_PARAMETERS} holds a field that is not valid.") from error
122 changes: 122 additions & 0 deletions redsys/tests/test_client.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import base64
import hmac
import json
from decimal import ROUND_HALF_UP
from decimal import Decimal as D
from unittest import mock

import pytest

from redsys import client as client_module
from redsys.client import RedirectClient
from redsys.constants import EUR
from redsys.constants import STANDARD_PAYMENT
Expand Down Expand Up @@ -87,3 +92,120 @@ def test_create_response_invalid(self):
bad_signature = b"sadfe2r3q2fdssaf3"
with pytest.raises(ValueError, match="The provided signature is not valid"):
self.client.create_response(bad_signature.decode(), encoded_params.decode())


SECRET = "sq7HjrUOBfKmC576ILgskD5srU870gJ7"
ORDER = "000000000001"


def _nested(depth):
value = []
for _ in range(depth - 1):
value = [value]
return value


class TestCreateResponseHardening:
@pytest.fixture(autouse=True)
def set_up(self):
self.client = RedirectClient(SECRET)

def _signed(self, fields, order=ORDER):
encoded = self.client.encode_parameters(fields)
return self.client.generate_signature(order, encoded).decode(), encoded.decode()

def _unsigned(self, raw):
return "x", base64.b64encode(raw).decode()

@pytest.mark.parametrize(
"signature, merchant_parameters",
[
(b"x", "e30="),
("A" * 129, "e30="),
("x", 7),
("x", "ée30="),
("x", "AAAA"),
("x", base64.b64encode(b"\xff\xfe").decode()),
("x", base64.b64encode(b"[1, 2]").decode()),
],
ids=[
"signature bytes",
"signature too long",
"parameters not text",
"parameters not ascii",
"not base64 json",
"not utf-8",
"json array",
],
)
def test_malformed_payload_raises_value_error(self, signature, merchant_parameters):
with pytest.raises(ValueError) as raised:
self.client.create_response(signature, merchant_parameters)
assert "The provided signature is not valid" not in str(raised.value)

def test_oversized_parameters_are_rejected_before_decoding(self, monkeypatch):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters) - 1)
with mock.patch.object(RedirectClient, "decode_parameters") as decode, pytest.raises(
ValueError, match="at most"
):
self.client.create_response(signature, merchant_parameters)
decode.assert_not_called()

def test_parameters_at_the_limit_are_accepted(self, monkeypatch):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
monkeypatch.setattr(client_module, "_MAX_MERCHANT_PARAMETERS_LENGTH", len(merchant_parameters))
assert self.client.create_response(signature, merchant_parameters).is_paid

def test_deep_nesting_is_rejected_before_parsing(self):
raw = json.dumps({"Ds_Order": ORDER, "x": _nested(32)}).encode()
with mock.patch("redsys.client.json.loads") as parse, pytest.raises(ValueError, match="nests deeper"):
self.client.create_response(*self._unsigned(raw))
parse.assert_not_called()

def test_nesting_at_the_limit_is_accepted(self):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "x": _nested(31)})
assert self.client.create_response(signature, merchant_parameters).is_paid

@pytest.mark.parametrize(
"text, depth",
[
('{"a": "[[[[", "b": [1, {"c": "]]]]"}]}', 3),
('{"a": "x\\"[[", "b": "\\\\", "c": [[]], "d": "\\\\\\"]]"}', 3),
('{"a": "' + "]" * 40 + '", "b": ' + "[" * 30 + "]" * 30 + "}", 31),
],
)
def test_depth_ignores_brackets_inside_strings(self, text, depth):
padded = ("[" + text + "," + ",".join(["[]"] * 40) + "]").encode()
assert client_module._json_depth_exceeds(padded, depth + 1) is False
assert client_module._json_depth_exceeds(padded, depth) is True

@pytest.mark.parametrize("fields", [{"Ds_Response": "0000"}, {"Ds_Order": "1" * 20}, {"Ds_Order": 1}])
def test_order_that_cannot_sign_fails_verification(self, fields):
signature, merchant_parameters = self._signed(fields)
with pytest.raises(ValueError, match="The provided signature is not valid"):
self.client.create_response(signature, merchant_parameters)

def test_fields_are_not_read_without_a_matching_signature(self):
raw = json.dumps({"Ds_Order": ORDER, "Ds_Amount": "not a number"}).encode()
invalid = pytest.raises(ValueError, match="The provided signature is not valid")
with mock.patch("redsys.client.Response") as response, invalid:
self.client.create_response(*self._unsigned(raw))
response.assert_not_called()

def test_signed_invalid_field_raises_value_error(self):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Amount": "not a number"})
with pytest.raises(ValueError, match="holds a field"):
self.client.create_response(signature, merchant_parameters)

def test_signatures_compare_in_constant_time(self):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000"})
with mock.patch("redsys.client.hmac.compare_digest", wraps=hmac.compare_digest) as compare:
self.client.create_response(signature, merchant_parameters)
compare.assert_called_once()

def test_url_safe_signature_is_accepted(self):
signature, merchant_parameters = self._signed({"Ds_Order": ORDER, "Ds_Response": "0000", "Ds_Amount": "1056"})
response = self.client.create_response(signature.replace("+", "-").replace("/", "_"), merchant_parameters)
assert response.is_paid
assert response.amount == D("10.56")
Loading