From e150d3153af30530ce61d751bc166e099f1ead7a Mon Sep 17 00:00:00 2001 From: Khwahish Patel Date: Wed, 5 Mar 2025 12:29:52 +0530 Subject: [PATCH] rufuse large RSA keys --- libp2p/crypto/rsa.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/libp2p/crypto/rsa.py b/libp2p/crypto/rsa.py index 5f14ce95..6673919a 100644 --- a/libp2p/crypto/rsa.py +++ b/libp2p/crypto/rsa.py @@ -9,6 +9,9 @@ from Crypto.Signature import ( pkcs1_15, ) +from libp2p.crypto.exceptions import ( + CryptographyError, +) from libp2p.crypto.keys import ( KeyPair, KeyType, @@ -16,9 +19,26 @@ from libp2p.crypto.keys import ( PublicKey, ) +MAX_RSA_KEY_SIZE = 4096 + + +def validate_rsa_key_size(key: RsaKey) -> None: + """ + Validate that an RSA key's size is within acceptable bounds. + + :param key: The RSA key to validate + :raises CryptographyError: If the key size exceeds the maximum allowed size + """ + key_size = key.size_in_bits() + if key_size > MAX_RSA_KEY_SIZE: + msg = f"RSA key size {key_size} " + msg += f"exceeds maximum allowed size {MAX_RSA_KEY_SIZE}" + raise CryptographyError(msg) + class RSAPublicKey(PublicKey): def __init__(self, impl: RsaKey) -> None: + validate_rsa_key_size(impl) self.impl = impl def to_bytes(self) -> bytes: @@ -27,6 +47,7 @@ class RSAPublicKey(PublicKey): @classmethod def from_bytes(cls, key_bytes: bytes) -> "RSAPublicKey": rsakey = RSA.import_key(key_bytes) + validate_rsa_key_size(rsakey) return cls(rsakey) def get_type(self) -> KeyType: @@ -43,10 +64,15 @@ class RSAPublicKey(PublicKey): class RSAPrivateKey(PrivateKey): def __init__(self, impl: RsaKey) -> None: + validate_rsa_key_size(impl) self.impl = impl @classmethod def new(cls, bits: int = 2048, e: int = 65537) -> "RSAPrivateKey": + if bits > MAX_RSA_KEY_SIZE: + msg = f"Requested RSA key size {bits} " + msg += f"exceeds maximum allowed size {MAX_RSA_KEY_SIZE}" + raise CryptographyError(msg) private_key_impl = RSA.generate(bits, e=e) return cls(private_key_impl)