Skip to content
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

Feature Request: "strict" parameter for from_buffer #156

Open
James-E-A opened this issue Feb 11, 2025 · 1 comment
Open

Feature Request: "strict" parameter for from_buffer #156

James-E-A opened this issue Feb 11, 2025 · 1 comment

Comments

@James-E-A
Copy link
Contributor

I appreciate that from_buffer explicitly fails when given a buffer that's too small for the given type, but is there any reason it doesn't (or couldn't, on an opt-in basis) fail when given a buffer that's too big for the given type?


For example,

Current code:

def verify_bool(signature, message, pk_bytes):
	with ffi.from_buffer(signature) as sig,\
	     ffi.from_buffer(message) as m,\
	     ffi.from_buffer('CRYPTO_PUBLICKEYBYTES_t', pk_bytes) as pk:

		if len(pk) < len(pk_bytes):
			# https://github.com/python-cffi/cffi/blob/v1.17.1/src/c/_cffi_backend.c#L7347
			raise ValueError(f"buffer is too large ({len(pk_bytes)} bytes) for '{ffi.getctype('CRYPTO_PUBLICKEYBYTES_t')}' ({len(pk)} bytes)")

		errno = lib.crypto_sign_verify(sig, len(sig), m, len(m), pk)

		return (errno == 0)

Ideal code:

def verify_bool(signature, message, pk_bytes):
	with ffi.from_buffer(signature) as sig,\
	     ffi.from_buffer(message) as m,\
	     ffi.from_buffer('CRYPTO_PUBLICKEYBYTES_t', pk_bytes, strict=True) as pk:

		errno = lib.crypto_sign_verify(sig, len(sig), m, len(m), pk)

		return (errno == 0)
@arigo
Copy link
Contributor

arigo commented Feb 11, 2025

The call to the C function would likely corrupt or crash the whole process if the pointer is from a Python buffer object that has got less than the number of bytes expected from the C type, but more is fine. That's the same idea for why ffi.from_buffer('int[]', b) rounds down the original buffer's size to a multiple of sizeof('int'). The latter is documented, but maybe we should also document the former.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants