Skip to content

Commit

Permalink
Check for canonical public keys and signatures
Browse files Browse the repository at this point in the history
Only enabled inside tests for now.
  • Loading branch information
sipa committed Sep 20, 2012
1 parent bfc24bd commit 58bc86e
Show file tree
Hide file tree
Showing 12 changed files with 245 additions and 62 deletions.
8 changes: 4 additions & 4 deletions src/main.cpp
Expand Up @@ -327,7 +327,7 @@ bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
if (!EvalScript(stack, vin[i].scriptSig, *this, i, false, 0))
return false;

if (whichType == TX_SCRIPTHASH)
Expand Down Expand Up @@ -1292,11 +1292,11 @@ bool CTransaction::ConnectInputs(MapPrevTx inputs,
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, false, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());

return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
Expand Down Expand Up @@ -1350,7 +1350,7 @@ bool CTransaction::ClientConnectInputs()
return false;

// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
if (!VerifySignature(txPrev, *this, i, true, false, 0))
return error("ConnectInputs() : VerifySignature failed");

///// this is redundant with the mempool.mapNextTx stuff,
Expand Down
2 changes: 1 addition & 1 deletion src/rpcrawtransaction.cpp
Expand Up @@ -469,7 +469,7 @@ Value signrawtransaction(const Array& params, bool fHelp)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0))
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, true, 0))
fComplete = false;
}

Expand Down
92 changes: 79 additions & 13 deletions src/script.cpp
Expand Up @@ -236,7 +236,68 @@ const char* GetOpName(opcodetype opcode)
}
}

bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
bool IsCanonicalPubKey(const valtype &vchPubKey) {
if (vchPubKey.size() < 33)
return error("Non-canonical public key: too short");
if (vchPubKey[0] == 0x04) {
if (vchPubKey.size() != 65)
return error("Non-canonical public key: invalid length for uncompressed key");
} else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
if (vchPubKey.size() != 33)
return error("Non-canonical public key: invalid length for compressed key");
} else {
return error("Non-canonical public key: compressed nor uncompressed");
}
return true;
}

bool IsCanonicalSignature(const valtype &vchSig) {
// See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
// A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
// Where R and S are not negative (their first byte has its highest bit not set), and not
// excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
// in which case a single 0 byte is necessary and even required).
if (vchSig.size() < 9)
return error("Non-canonical signature: too short");
if (vchSig.size() > 73)
return error("Non-canonical signature: too long");
if (vchSig[vchSig.size() - 1] & 0x7C)
return error("Non-canonical signature: unknown hashtype byte");
if (vchSig[0] != 0x30)
return error("Non-canonical signature: wrong type");
if (vchSig[1] != vchSig.size()-3)
return error("Non-canonical signature: wrong length marker");
unsigned int nLenR = vchSig[3];
if (5 + nLenR >= vchSig.size())
return error("Non-canonical signature: S length misplaced");
unsigned int nLenS = vchSig[5+nLenR];
if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
return error("Non-canonical signature: R+S length mismatch");

const unsigned char *R = &vchSig[4];
if (R[-2] != 0x02)
return error("Non-canonical signature: R value type mismatch");
if (nLenR == 0)
return error("Non-canonical signature: R length is zero");
if (R[0] & 0x80)
return error("Non-canonical signature: R value negative");
if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
return error("Non-canonical signature: R value excessively padded");

const unsigned char *S = &vchSig[6+nLenR];
if (S[-2] != 0x02)
return error("Non-canonical signature: S value type mismatch");
if (nLenS == 0)
return error("Non-canonical signature: S length is zero");
if (S[0] & 0x80)
return error("Non-canonical signature: S value negative");
if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
return error("Non-canonical signature: S value excessively padded");

return true;
}

bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType)
{
CAutoBN_CTX pctx;
CScript::const_iterator pc = script.begin();
Expand Down Expand Up @@ -922,7 +983,9 @@ bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, co
// Drop the signature, since there's no way for a signature to sign itself
scriptCode.FindAndDelete(CScript(vchSig));

bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
bool fSuccess = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
if (fSuccess)
fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);

popstack(stack);
popstack(stack);
Expand Down Expand Up @@ -982,8 +1045,11 @@ bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, co
valtype& vchPubKey = stacktop(-ikey);

// Check signature
if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
{
bool fOk = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
if (fOk)
fOk = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);

if (fOk) {
isig++;
nSigsCount--;
}
Expand Down Expand Up @@ -1550,14 +1616,14 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vecto
}

bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType)
bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
{
vector<vector<unsigned char> > stack, stackCopy;
if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
if (!EvalScript(stack, scriptSig, txTo, nIn, fStrictEncodings, nHashType))
return false;
if (fValidatePayToScriptHash)
stackCopy = stack;
if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
if (!EvalScript(stack, scriptPubKey, txTo, nIn, fStrictEncodings, nHashType))
return false;
if (stack.empty())
return false;
Expand All @@ -1575,7 +1641,7 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C
CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
popstack(stackCopy);

if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
if (!EvalScript(stackCopy, pubKey2, txTo, nIn, fStrictEncodings, nHashType))
return false;
if (stackCopy.empty())
return false;
Expand Down Expand Up @@ -1618,7 +1684,7 @@ bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransa
}

// Test solution
return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, 0);
return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, true, 0);
}

bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
Expand All @@ -1631,7 +1697,7 @@ bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTrans
return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
}

bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
{
assert(nIn < txTo.vin.size());
const CTxIn& txin = txTo.vin[nIn];
Expand All @@ -1642,7 +1708,7 @@ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsig
if (txin.prevout.hash != txFrom.GetHash())
return false;

return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, fStrictEncodings, nHashType);
}

static CScript PushAll(const vector<valtype>& values)
Expand Down Expand Up @@ -1760,9 +1826,9 @@ CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsign
Solver(scriptPubKey, txType, vSolutions);

vector<valtype> stack1;
EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
EvalScript(stack1, scriptSig1, CTransaction(), 0, true, 0);
vector<valtype> stack2;
EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
EvalScript(stack2, scriptSig2, CTransaction(), 0, true, 0);

return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
}
Expand Down
9 changes: 5 additions & 4 deletions src/script.h
Expand Up @@ -581,9 +581,10 @@ class CScript : public std::vector<unsigned char>



bool IsCanonicalPubKey(const std::vector<unsigned char> &vchPubKey);
bool IsCanonicalSignature(const std::vector<unsigned char> &vchSig);


bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType);
bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType);
bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet);
int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions);
bool IsStandard(const CScript& scriptPubKey);
Expand All @@ -594,8 +595,8 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::
bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL);
bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
bool fValidatePayToScriptHash, int nHashType);
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType);
bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);
bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType);

// Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders,
// combine them intelligently and return the result.
Expand Down
10 changes: 5 additions & 5 deletions src/test/DoS_tests.cpp
Expand Up @@ -278,7 +278,7 @@ BOOST_AUTO_TEST_CASE(DoS_checkSig)
mst1 = boost::posix_time::microsec_clock::local_time();
for (unsigned int i = 0; i < 5; i++)
for (unsigned int j = 0; j < tx.vin.size(); j++)
BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, SIGHASH_ALL));
BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, true, SIGHASH_ALL));
mst2 = boost::posix_time::microsec_clock::local_time();
msdiff = mst2 - mst1;
long nManyValidate = msdiff.total_milliseconds();
Expand All @@ -289,13 +289,13 @@ BOOST_AUTO_TEST_CASE(DoS_checkSig)
// Empty a signature, validation should fail:
CScript save = tx.vin[0].scriptSig;
tx.vin[0].scriptSig = CScript();
BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, SIGHASH_ALL));
BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, true, SIGHASH_ALL));
tx.vin[0].scriptSig = save;

// Swap signatures, validation should fail:
std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig);
BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, SIGHASH_ALL));
BOOST_CHECK(!VerifySignature(orphans[1], tx, 1, true, SIGHASH_ALL));
BOOST_CHECK(!VerifySignature(orphans[0], tx, 0, true, true, SIGHASH_ALL));
BOOST_CHECK(!VerifySignature(orphans[1], tx, 1, true, true, SIGHASH_ALL));
std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig);

// Exercise -maxsigcachesize code:
Expand All @@ -305,7 +305,7 @@ BOOST_AUTO_TEST_CASE(DoS_checkSig)
BOOST_CHECK(SignSignature(keystore, orphans[0], tx, 0));
BOOST_CHECK(tx.vin[0].scriptSig != oldSig);
for (unsigned int j = 0; j < tx.vin.size(); j++)
BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, SIGHASH_ALL));
BOOST_CHECK(VerifySignature(orphans[j], tx, j, true, true, SIGHASH_ALL));
mapArgs.erase("-maxsigcachesize");

LimitOrphanTxSize(0);
Expand Down
87 changes: 87 additions & 0 deletions src/test/canonical_tests.cpp
@@ -0,0 +1,87 @@
//
// Unit tests for canonical signatures

#include "json/json_spirit_writer_template.h"
#include <boost/test/unit_test.hpp>
#include <openssl/ecdsa.h>

#include "key.h"
#include "script.h"
#include "util.h"

using namespace std;
using namespace json_spirit;


// In script_tests.cpp
extern Array read_json(const std::string& filename);

BOOST_AUTO_TEST_SUITE(canonical_tests)

// OpenSSL-based test for canonical signature (without test for hashtype byte)
bool static IsCanonicalSignature_OpenSSL_inner(const std::vector<unsigned char>& vchSig)
{
if (vchSig.size() == 0)
return false;
const unsigned char *input = &vchSig[0];
ECDSA_SIG *psig = NULL;
d2i_ECDSA_SIG(&psig, &input, vchSig.size());
if (psig == NULL)
return false;
unsigned char buf[256];
unsigned char *pbuf = buf;
unsigned int nLen = i2d_ECDSA_SIG(psig, NULL);
if (nLen != vchSig.size()) {
ECDSA_SIG_free(psig);
return false;
}
nLen = i2d_ECDSA_SIG(psig, &pbuf);
ECDSA_SIG_free(psig);
return (memcmp(&vchSig[0], &buf[0], nLen) == 0);
}

// OpenSSL-based test for canonical signature
bool static IsCanonicalSignature_OpenSSL(const std::vector<unsigned char> &vchSignature) {
if (vchSignature.size() < 1)
return false;
if (vchSignature.size() > 127)
return false;
if (vchSignature[vchSignature.size() - 1] & 0x7C)
return false;

std::vector<unsigned char> vchSig(vchSignature);
vchSig.pop_back();
if (!IsCanonicalSignature_OpenSSL_inner(vchSig))
return false;
return true;
}

BOOST_AUTO_TEST_CASE(script_canon)
{
Array tests = read_json("sig_canonical.json");

BOOST_FOREACH(Value &tv, tests) {
string test = tv.get_str();
if (IsHex(test)) {
std::vector<unsigned char> sig = ParseHex(test);
BOOST_CHECK_MESSAGE(IsCanonicalSignature(sig), test);
BOOST_CHECK_MESSAGE(IsCanonicalSignature_OpenSSL(sig), test);
}
}
}

BOOST_AUTO_TEST_CASE(script_noncanon)
{
Array tests = read_json("sig_noncanonical.json");

BOOST_FOREACH(Value &tv, tests) {
string test = tv.get_str();
if (IsHex(test)) {
std::vector<unsigned char> sig = ParseHex(test);
BOOST_CHECK_MESSAGE(!IsCanonicalSignature(sig), test);
BOOST_CHECK_MESSAGE(!IsCanonicalSignature_OpenSSL(sig), test);
}
}
}

BOOST_AUTO_TEST_SUITE_END()
7 changes: 7 additions & 0 deletions src/test/data/sig_canonical.json
@@ -0,0 +1,7 @@
[
"300602010002010001",
"3008020200ff020200ff01",
"304402203932c892e2e550f3af8ee4ce9c215a87f9bb831dcac87b2838e2c2eaa891df0c022030b61dd36543125d56b9f9f3a1f9353189e5af33cdda8d77a5209aec03978fa001",
"30450220076045be6f9eca28ff1ec606b833d0b87e70b2a630f5e3a496b110967a40f90a0221008fffd599910eefe00bc803c688c2eca1d2ba7f6b180620eaa03488e6585db6ba01",
"3046022100876045be6f9eca28ff1ec606b833d0b87e70b2a630f5e3a496b110967a40f90a0221008fffd599910eefe00bc803c688c2eca1d2ba7f6b180620eaa03488e6585db6ba01"
]
22 changes: 22 additions & 0 deletions src/test/data/sig_noncanonical.json
@@ -0,0 +1,22 @@
[
"non-hex strings are ignored",

"too short:", "30050201FF020001",
"too long:", "30470221005990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba6105022200002d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"hashtype:", "304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed11",
"type:", "314402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"total length:", "304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"S len oob:", "301F01205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb101",
"R+S:", "304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed0001",

"R type:", "304401205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"R len = 0:", "3024020002202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"R<0:", "304402208990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"R padded:", "30450221005990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610502202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",


"S type:", "304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba610501202d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"S len = 0:", "302402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba6105020001",
"S<0:", "304402205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba61050220fd5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01",
"S padded:", "304502205990e0584b2b238e1dfaad8d6ed69ecc1a4a13ac85fc0b31d0df395eb1ba61050221002d5876262c288beb511d061691bf26777344b702b00f8fe28621fe4e566695ed01"
]

0 comments on commit 58bc86e

Please sign in to comment.