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

Implement RSA verification #4952

Merged
merged 39 commits into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from 28 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
b9f144c
Implement RSA verification
Amxx Mar 12, 2024
41949e6
up
Amxx Mar 12, 2024
0abe46b
simplify
Amxx Mar 13, 2024
0a1691c
test directly from the SigVer15-186-3.rsp
Amxx Mar 13, 2024
1189ae7
update
Amxx Mar 13, 2024
d98a3f9
fix lint
Amxx Mar 13, 2024
2ef35d1
update todo
Amxx Mar 13, 2024
f110d43
up
Amxx Mar 13, 2024
6dcc26d
simplify parser
Amxx Mar 13, 2024
1b2ba49
add RSA to mocks/Stateless.sol
Amxx Mar 13, 2024
fe0927f
Merge branch 'master' into feature/RSA
Amxx Apr 5, 2024
78301ea
Merge branch 'master' into feature/RSA
ernestognw Jun 4, 2024
74d667c
Improve documentation
ernestognw Jun 4, 2024
b6334ea
Add changeset
ernestognw Jun 4, 2024
5379609
Improve comments
ernestognw Jun 4, 2024
667c8b2
Fix
ernestognw Jun 4, 2024
d3eb6a5
Fix test
ernestognw Jun 4, 2024
fbd2130
Nits
ernestognw Jun 4, 2024
cc37629
Improve tests
ernestognw Jun 4, 2024
0127de3
Improve tests 2
ernestognw Jun 4, 2024
445d6fa
Do fix tests
ernestognw Jun 4, 2024
52fdb34
Update .changeset/curvy-crabs-repeat.md
Amxx Jun 4, 2024
f007a74
Add result to test description
ernestognw Jun 4, 2024
d07fb84
Add considerations to _unsafeReadBytes32
ernestognw Jun 4, 2024
b3e56ec
remove extra unsafeReadBytes
Amxx Jun 6, 2024
7596e4d
Merge remote-tracking branch 'amxx/feature/RSA' into feature/RSA
Amxx Jun 6, 2024
5ceb396
doc
Amxx Jun 6, 2024
abe598d
check s < n
Amxx Jun 6, 2024
70a9dea
fix
Amxx Jun 6, 2024
d4096aa
refactor
Amxx Jun 6, 2024
413916f
fix
Amxx Jun 6, 2024
aff3b81
Add replayability warning
ernestognw Jun 6, 2024
84ae125
nit
Amxx Jun 6, 2024
28c8271
Update comment
ernestognw Jun 6, 2024
219100b
Merge remote-tracking branch 'amxx/feature/RSA' into feature/RSA
Amxx Jun 6, 2024
95233b5
test s >= n
Amxx Jun 6, 2024
56eac45
use normal modExp
Amxx Jun 7, 2024
63969dc
Add docs
ernestognw Jun 11, 2024
f50d89a
add replay protection notice in note
cairoeth Jun 11, 2024
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
5 changes: 5 additions & 0 deletions .changeset/curvy-crabs-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`RSA`: Library to verify signatures according to RFC 8017 Signature Verification Operation
1 change: 1 addition & 0 deletions contracts/mocks/Stateless.sol
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {MerkleProof} from "../utils/cryptography/MerkleProof.sol";
import {MessageHashUtils} from "../utils/cryptography/MessageHashUtils.sol";
import {Panic} from "../utils/Panic.sol";
import {Packing} from "../utils/Packing.sol";
import {RSA} from "../utils/cryptography/RSA.sol";
import {SafeCast} from "../utils/math/SafeCast.sol";
import {SafeERC20} from "../token/ERC20/utils/SafeERC20.sol";
import {ShortStrings} from "../utils/ShortStrings.sol";
Expand Down
140 changes: 140 additions & 0 deletions contracts/utils/cryptography/RSA.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Math} from "../math/Math.sol";

/**
* @dev RSA PKCS#1 v1.5 signature verification implementation according to https://datatracker.ietf.org/doc/html/rfc8017[RFC8017].
*
* This library supports PKCS#1 v1.5 padding to avoid malleability via chosen plaintext attacks in practical implementations.
* The padding follows the EMSA-PKCS1-v1_5-ENCODE encoding definition as per section 9.2 of the RFC. This padding makes
* RSA semanticaly secure for signing messages.
*
* Inspired by https://github.com/adria0/SolRsaVerify[Adrià Massanet's work]
*/
library RSA {
/**
* @dev Same as {pkcs1} but using SHA256 to calculate the digest of `data`.
*/
function pkcs1Sha256(
bytes memory data,
bytes memory s,
bytes memory e,
bytes memory n
) internal view returns (bool) {
return pkcs1(sha256(data), s, e, n);
}

/**
* @dev Verifies a PKCSv1.5 signature given a digest according the verification
* method described in https://datatracker.ietf.org/doc/html/rfc8017#section-8.2.2[section 8.2.2 of RFC8017].
*
* IMPORTANT: Although this function allows for it, using n of length 1024 bits is considered unsafe.
* Consider using at least 2048 bits.
*
* @param digest the digest to verify
* @param s is a buffer containing the signature
* @param e is the exponent of the public key
* @param n is the modulus of the public key
*/
function pkcs1(bytes32 digest, bytes memory s, bytes memory e, bytes memory n) internal view returns (bool) {
unchecked {
// cache and check length
uint256 length = n.length;
if (
length < 0x40 || // PKCS#1 padding is slightly less than 0x40 bytes at the bare minimum
length != s.length // signature must have the same length as the finite field
) {
return false;
}

// verify that s < n
bool ok = false;
for (uint256 i = 0; i < length - 0x20; i += 0x20) {
bytes32 si = _unsafeReadBytes32(s, Math.min(i, length - 0x20));
bytes32 ni = _unsafeReadBytes32(n, Math.min(i, length - 0x20));
frangio marked this conversation as resolved.
Show resolved Hide resolved
if (si < ni) {
ok = true;
break;
}
ernestognw marked this conversation as resolved.
Show resolved Hide resolved
}
if (!ok) return false;

// RSAVP1 https://datatracker.ietf.org/doc/html/rfc8017#section-5.2.2
(bool success, bytes memory buffer) = Math.tryModExp(s, e, n);
cairoeth marked this conversation as resolved.
Show resolved Hide resolved
if (!success) {
return false;
}
Amxx marked this conversation as resolved.
Show resolved Hide resolved

// Check that buffer is well encoded:
// buffer ::= 0x00 | 0x01 | PS | 0x00 | DigestInfo
//
// With
// - PS is padding filled with 0xFF
// - DigestInfo ::= SEQUENCE {
// digestAlgorithm AlgorithmIdentifier,
// [optional algorithm parameters]
ernestognw marked this conversation as resolved.
Show resolved Hide resolved
// digest OCTET STRING
// }

// Get AlgorithmIdentifier from the DigestInfo, and set the config accordingly
// - params: includes 00 + first part of DigestInfo
// - mask: filter to check the params
// - offset: length of the suffix (including digest)
bytes32 params; // 0x00 | DigestInfo
bytes32 mask;
uint256 offset;

// Digest is expected at the end of the buffer. Therefore if NULL param is present,
// it should be at 32 (digest) + 2 bytes from the end. To those 34 bytes, we add the
// OID (9 bytes) and its length (2 bytes) to get the position of the DigestInfo sequence,
// which is expected to have a length of 0x31 when the NULL param is present or 0x2f if not.
if (bytes1(_unsafeReadBytes32(buffer, length - 50)) == 0x31) {
offset = 0x34;
// 00 (1 byte) | SEQUENCE length (0x31) = 3031 (2 bytes) | SEQUENCE length (0x0d) = 300d (2 bytes) | OBJECT_IDENTIFIER length (0x09) = 0609 (2 bytes)
// SHA256 OID = 608648016503040201 (9 bytes) | NULL = 0500 (2 bytes) (explicit) | OCTET_STRING length (0x20) = 0420 (2 bytes)
params = 0x003031300d060960864801650304020105000420000000000000000000000000;
mask = 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000; // (20 bytes)
} else if (bytes1(_unsafeReadBytes32(buffer, length - 48)) == 0x2F) {
offset = 0x32;
// 00 (1 byte) | SEQUENCE length (0x2f) = 302f (2 bytes) | SEQUENCE length (0x0b) = 300b (2 bytes) | OBJECT_IDENTIFIER length (0x09) = 0609 (2 bytes)
// SHA256 OID = 608648016503040201 (9 bytes) | NULL = <implicit> | OCTET_STRING length (0x20) = 0420 (2 bytes)
params = 0x00302f300b060960864801650304020104200000000000000000000000000000;
mask = 0xffffffffffffffffffffffffffffffffffff0000000000000000000000000000; // (18 bytes)
} else {
// unknown
return false;
}

// Length is at least 0x40 and offset is at most 0x34, so this is safe. There is always some padding.
uint256 paddingEnd = length - offset;

// The padding has variable (arbitrary) length, so we check it byte per byte in a loop.
// This is required to ensure non-malleability. Not checking would allow an attacker to
// use the padding to manipulate the message in order to create a valid signature out of
// multiple valid signatures.
for (uint256 i = 2; i < paddingEnd; ++i) {
if (bytes1(_unsafeReadBytes32(buffer, i)) != 0xFF) {
return false;
}
}

// All the other parameters are small enough to fit in a bytes32, so we can check them directly.
return
bytes2(0x0001) == bytes2(_unsafeReadBytes32(buffer, 0x00)) && // 00 | 01
// PS was checked in the loop
params == _unsafeReadBytes32(buffer, paddingEnd) & mask && // DigestInfo
// Optional parameters are not checked
digest == _unsafeReadBytes32(buffer, length - 0x20); // Digest
}
}

/// @dev Reads a bytes32 from a bytes array without bounds checking.
function _unsafeReadBytes32(bytes memory array, uint256 offset) private pure returns (bytes32 result) {
// Memory safetiness is guaranteed as long as the provided `array` is a Solidity-allocated bytes array
// and `offset` is within bounds. This is the case for all calls to this private function from {pkcs1}.
assembly ("memory-safe") {
result := mload(add(add(array, 0x20), offset))
}
}
}
17 changes: 17 additions & 0 deletions test/utils/cryptography/RSA.helper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const path = require('path');
const fs = require('fs');

module.exports = function* parse(file) {
const cache = {};
const data = fs.readFileSync(path.resolve(__dirname, file), 'utf8');
for (const line of data.split('\r\n')) {
const groups = line.match(/^(?<key>\w+) = (?<value>\w+)(?<extra>.*)$/)?.groups;
if (groups) {
const { key, value, extra } = groups;
cache[key] = value;
if (groups.key === 'Result') {
yield Object.assign({ extra: extra.trim() }, cache);
}
}
}
};
95 changes: 95 additions & 0 deletions test/utils/cryptography/RSA.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');

const parse = require('./RSA.helper');

async function fixture() {
return { mock: await ethers.deployContract('$RSA') };
}

describe('RSA', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});

// Load test cases from file SigVer15_186-3.rsp from:
// https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/dss/186-2rsatestvectors.zip
describe('SigVer15_186-3.rsp tests', function () {
for (const test of parse('SigVer15_186-3.rsp')) {
const { length } = Buffer.from(test.S, 'hex');

/// For now, RSA only supports digest that are 32bytes long. If we ever extend that, we can use these hashing functions for @noble:
// const { sha1 } = require('@noble/hashes/sha1');
// const { sha224, sha256 } = require('@noble/hashes/sha256');
// const { sha384, sha512 } = require('@noble/hashes/sha512');

if (test.SHAAlg === 'SHA256') {
const result = test.Result === 'P';

it(`signature length ${length} ${test.extra} ${result ? 'works' : 'fails'}`, async function () {
const data = '0x' + test.Msg;
const sig = '0x' + test.S;
const exp = '0x' + test.e;
const mod = '0x' + test.n;

expect(await this.mock.$pkcs1(ethers.sha256(data), sig, exp, mod)).to.equal(result);
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.equal(result);
});
}
}
});

describe('others tests', function () {
it('openssl', async function () {
const data = ethers.toUtf8Bytes('hello world');
const sig =
'0x079bed733b48d69bdb03076cb17d9809072a5a765460bc72072d687dba492afe951d75b814f561f253ee5cc0f3d703b6eab5b5df635b03a5437c0a5c179309812f5b5c97650361c645bc99f806054de21eb187bc0a704ed38d3d4c2871a117c19b6da7e9a3d808481c46b22652d15b899ad3792da5419e50ee38759560002388';
const exp =
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001';
const mod =
'0xdf3edde009b96bc5b03b48bd73fe70a3ad20eaf624d0dc1ba121a45cc739893741b7cf82acf1c91573ec8266538997c6699760148de57e54983191eca0176f518e547b85fe0bb7d9e150df19eee734cf5338219c7f8f7b13b39f5384179f62c135e544cb70be7505751f34568e06981095aeec4f3a887639718a3e11d48c240d';
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.true;
});

// According to RFC4055, pg.5 and RFC8017, pg. 64, for SHA-1, and the SHA-2 family,
// the algorithm parameter has to be NULL and both explicit NULL parameter and implicit
// NULL parameter (ie, absent NULL parameter) are considered to be legal and equivalent.
it('rfc8017 implicit null parameter', async function () {
const data = ethers.toUtf8Bytes('hello world!');
const sig =
'0xa0073057133ff3758e7e111b4d7441f1d8cbe4b2dd5ee4316a14264290dee5ed7f175716639bd9bb43a14e4f9fcb9e84dedd35e2205caac04828b2c053f68176d971ea88534dd2eeec903043c3469fc69c206b2a8694fd262488441ed8852280c3d4994e9d42bd1d575c7024095f1a20665925c2175e089c0d731471f6cc145404edf5559fd2276e45e448086f71c78d0cc6628fad394a34e51e8c10bc39bfe09ed2f5f742cc68bee899d0a41e4c75b7b80afd1c321d89ccd9fe8197c44624d91cc935dfa48de3c201099b5b417be748aef29248527e8bbb173cab76b48478d4177b338fe1f1244e64d7d23f07add560d5ad50b68d6649a49d7bc3db686daaa7';
const exp = '0x03';
const mod =
'0xe932ac92252f585b3a80a4dd76a897c8b7652952fe788f6ec8dd640587a1ee5647670a8ad4c2be0f9fa6e49c605adf77b5174230af7bd50e5d6d6d6d28ccf0a886a514cc72e51d209cc772a52ef419f6a953f3135929588ebe9b351fca61ced78f346fe00dbb6306e5c2a4c6dfc3779af85ab417371cf34d8387b9b30ae46d7a5ff5a655b8d8455f1b94ae736989d60a6f2fd5cadbffbd504c5a756a2e6bb5cecc13bca7503f6df8b52ace5c410997e98809db4dc30d943de4e812a47553dce54844a78e36401d13f77dc650619fed88d8b3926e3d8e319c80c744779ac5d6abe252896950917476ece5e8fc27d5f053d6018d91b502c4787558a002b9283da7';
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.true;
});

it('returns false for a very short n', async function () {
const data = ethers.toUtf8Bytes('hello world!');
const sig = '0x0102';
const exp = '0x03';
const mod = '0x0405';
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false;
});

it('returns false for a signature with different length to n', async function () {
const data = ethers.toUtf8Bytes('hello world!');
const sig = '0x00112233';
const exp = '0x03';
const mod =
'0xe932ac92252f585b3a80a4dd76a897c8b7652952fe788f6ec8dd640587a1ee5647670a8ad4c2be0f9fa6e49c605adf77b5174230af7bd50e5d6d6d6d28ccf0a886a514cc72e51d209cc772a52ef419f6a953f3135929588ebe9b351fca61ced78f346fe00dbb6306e5c2a4c6dfc3779af85ab417371cf34d8387b9b30ae46d7a5ff5a655b8d8455f1b94ae736989d60a6f2fd5cadbffbd504c5a756a2e6bb5cecc13bca7503f6df8b52ace5c410997e98809db4dc30d943de4e812a47553dce54844a78e36401d13f77dc650619fed88d8b3926e3d8e319c80c744779ac5d6abe252896950917476ece5e8fc27d5f053d6018d91b502c4787558a002b9283da7';
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false;
});

it('returns false if the modexp operation fails', async function () {
const data = ethers.toUtf8Bytes('hello world!');
cairoeth marked this conversation as resolved.
Show resolved Hide resolved
const sig =
'0xa0073057133ff3758e7e111b4d7441f1d8cbe4b2dd5ee4316a14264290dee5ed7f175716639bd9bb43a14e4f9fcb9e84dedd35e2205caac04828b2c053f68176d971ea88534dd2eeec903043c3469fc69c206b2a8694fd262488441ed8852280c3d4994e9d42bd1d575c7024095f1a20665925c2175e089c0d731471f6cc145404edf5559fd2276e45e448086f71c78d0cc6628fad394a34e51e8c10bc39bfe09ed2f5f742cc68bee899d0a41e4c75b7b80afd1c321d89ccd9fe8197c44624d91cc935dfa48de3c201099b5b417be748aef29248527e8bbb173cab76b48478d4177b338fe1f1244e64d7d23f07add560d5ad50b68d6649a49d7bc3db686daaa7';
const exp = '0x03';
const mod =
'0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000';
expect(await this.mock.$pkcs1Sha256(data, sig, exp, mod)).to.be.false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test is actually not reverting at the modExp step, but instead here because of sp > np. is there a way we can have more accurate checks when the return data is a boolean? maybe by measuring gas?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It feels like the only way for modExp to fail is if mod = 0. If we check that s < n, then we know that n > 0, and there may be no way for modExp to fail.

});
});
});
Loading
Loading