diff --git a/src/nacl/signing.py b/src/nacl/signing.py index 497fd3352..aca4d1422 100644 --- a/src/nacl/signing.py +++ b/src/nacl/signing.py @@ -102,8 +102,20 @@ def verify(self, smessage, signature=None, encoder=encoding.RawEncoder): :rtype: :class:`bytes` """ if signature is not None: - # If we were given the message and signature separately, combine - # them. + # If we were given the message and signature separately, validate + # signature size and combine them. + if not isinstance(signature, bytes): + raise exc.TypeError( + "Verification signature must be created from %d bytes" % + nacl.bindings.crypto_sign_BYTES, + ) + + if len(signature) != nacl.bindings.crypto_sign_BYTES: + raise exc.ValueError( + "The signature must be exactly %d bytes long" % + nacl.bindings.crypto_sign_BYTES, + ) + smessage = signature + encoder.decode(smessage) else: # Decode the signed message diff --git a/tests/test_signing.py b/tests/test_signing.py index 3e2cf3595..1fadd04b3 100644 --- a/tests/test_signing.py +++ b/tests/test_signing.py @@ -168,6 +168,24 @@ def test_invalid_signed_message(self): forged = SignedMessage(signature + message) skey.verify_key.verify(forged) + def test_invalid_signature_length(self): + skey = SigningKey.generate() + message = b"hello" + signature = skey.sign(message).signature + + # Sanity checks + assert skey.verify_key.verify(message, signature) + assert skey.verify_key.verify(signature + message) + + with pytest.raises(ValueError): + skey.verify_key.verify(message, b"") + + with pytest.raises(ValueError): + skey.verify_key.verify(message, signature * 2) + + with pytest.raises(ValueError): + skey.verify_key.verify(signature + message, b"") + def test_base64_smessage_with_detached_sig_matches_with_attached_sig(self): sk = SigningKey.generate() vk = sk.verify_key @@ -238,3 +256,13 @@ def test_wrong_types(): VerifyKey, sk) check_type_error("VerifyKey must be created from 32 bytes", VerifyKey, sk.verify_key) + + def verify_detached_signature(x): + sk.verify_key.verify(b"", x) + + check_type_error("Verification signature must be created from 64 bytes", + verify_detached_signature, 13) + check_type_error("Verification signature must be created from 64 bytes", + verify_detached_signature, sk) + check_type_error("Verification signature must be created from 64 bytes", + verify_detached_signature, sk.verify_key)