Skip to content

Commit ac91e5d

Browse files
CoderZhiclaude
authored andcommitted
fix: harden deserialization and message handlers against panics (#4844)
* fix: harden deserialization and message handlers against panics Replace five panic-prone paths reachable from peer-controlled or untrusted input with explicit error returns / safe fallbacks: - action.envelope.LoadProto: return ErrInvalidAct on unknown TxType instead of panicking on TxType >= 5. - evm.ExtractRevertMessage: bound-check the Error(string) ABI payload and reject non-UTF-8 messages; fall back to hex on malformed input. - evm.StateDBAdapter.AddLog: guard the in-contract-transfer topic check against empty topics. - chainservice.Filter / ReportFullness: reject blocks with nil Header or nil Header.Core before dereferencing Height. - endorsement.Endorsement.LoadProto: return an error on nil proto instead of panicking before signature/delegate verification. Add unit tests covering each new error path. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address three HIGH-severity peer-reachable attack vectors Findings #6, #7, #9 from the security audit, all read-verified: #6 nodeinfo: HandleNodeInfo dereferenced msg.Info without a nil check, so any peer could crash a node by broadcasting NODE_INFO with Info=nil. Now guarded; non-panic test added. #7 actsync: RequestActionsFromNeighbors had no upper bound on the number of in-flight requests, letting a peer drown a node in outbound traffic. Cap added; tests cover cap respected under flood, dedup must not double-count, concurrent flood respects cap. #9 server/itx: admin mux (/pause, /unpause, /producer-keys, pprof) was bound to 0.0.0.0, letting any peer that could reach the admin port halt block production with an unauthenticated POST to /pause. Now bound to 127.0.0.1. (Finding #8 — actpool cross-shard eviction — has been moved to a separate PR for independent review.) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(evm): reject malformed revert payloads instead of silent hex fallback Change ExtractRevertMessage signature to (string, error) and propagate the error from ExecuteContract so a tx with a malformed Error(string) revert payload invalidates the action rather than landing with a junk hex string in the receipt. erigonstore callers swallow the error with a local hex fallback since they already return vm.ErrExecutionReverted to their caller. Drop the utf8.Valid gate — honest contracts can revert with non-UTF-8 bytes, so rejecting on that would fork the chain on legitimate input. Added a regression test pinning the non-UTF-8 happy path. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent e804e4c commit ac91e5d

15 files changed

Lines changed: 378 additions & 23 deletions

File tree

‎action/envelope.go‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
package action
77

88
import (
9-
"fmt"
109
"math/big"
1110

1211
"github.com/ethereum/go-ethereum/common"
@@ -320,7 +319,7 @@ func (elp *envelope) loadProtoTxCommon(pbAct *iotextypes.ActionCore) error {
320319
elp.common = &tx
321320
}
322321
default:
323-
panic(fmt.Sprintf("unsupported action type = %d", pbAct.TxType))
322+
return errors.Wrapf(ErrInvalidAct, "unsupported tx type = %d", pbAct.TxType)
324323
}
325324
return err
326325
}

‎action/envelope_test.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,14 @@ func createEnvelope(chainID uint32) (Envelope, *Transfer) {
140140
return evlp, tsf
141141
}
142142

143+
func TestEnvelope_LoadProto_UnsupportedTxType(t *testing.T) {
144+
req := require.New(t)
145+
evlp := &envelope{}
146+
err := evlp.LoadProto(&iotextypes.ActionCore{TxType: 5})
147+
req.Error(err)
148+
req.ErrorIs(err, ErrInvalidAct)
149+
}
150+
143151
func TestEnvelope_Hash(t *testing.T) {
144152
r := require.New(t)
145153
blob := createTestBlobTxData()

‎action/protocol/execution/evm/evm.go‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ package evm
88
import (
99
"bytes"
1010
"context"
11-
"encoding/hex"
1211
"math"
1312
"math/big"
1413
"time"
@@ -374,7 +373,11 @@ func ExecuteContract(
374373

375374
if ps.featureCtx.SetRevertMessageToReceipt && receipt.Status == uint64(iotextypes.ReceiptStatus_ErrExecutionReverted) && len(retval) >= 4 && bytes.Equal(retval[:4], _revertSelector) {
376375
// in case of the execution revert error, parse the retVal and add to receipt
377-
receipt.SetExecutionRevertMsg(ExtractRevertMessage(retval))
376+
msg, err := ExtractRevertMessage(retval)
377+
if err != nil {
378+
return nil, nil, err
379+
}
380+
receipt.SetExecutionRevertMsg(msg)
378381
}
379382
return retval, receipt, nil
380383
}
@@ -963,18 +966,21 @@ func SimulateAndCollectAccessList(
963966
return stateDB.AccessedSlots(), nil
964967
}
965968

966-
// ExtractRevertMessage extracts the revert message from the return value
967-
func ExtractRevertMessage(ret []byte) string {
968-
if len(ret) < 4 {
969-
return hex.EncodeToString(ret)
970-
}
971-
if !bytes.Equal(ret[:4], _revertSelector) {
972-
return hex.EncodeToString(ret)
969+
// ExtractRevertMessage extracts the revert message from the return value.
970+
// Returns an error if the payload is not a well-formed Error(string) revert.
971+
func ExtractRevertMessage(ret []byte) (string, error) {
972+
if len(ret) < 4 || !bytes.Equal(ret[:4], _revertSelector) {
973+
return "", errors.New("malformed revert payload: missing Error(string) selector")
973974
}
974975
data := ret[4:]
976+
if len(data) < 64 {
977+
return "", errors.New("malformed revert payload: data shorter than offset+length header")
978+
}
975979
msgLength := byteutil.BytesToUint64BigEndian(data[56:64])
976-
revertMsg := string(data[64 : 64+msgLength])
977-
return revertMsg
980+
if msgLength > uint64(len(data)-64) {
981+
return "", errors.New("malformed revert payload: declared length exceeds available data")
982+
}
983+
return string(data[64 : 64+msgLength]), nil
978984
}
979985

980986
func validateAuthorization(evm *vm.EVM, sdb stateDB, auth *types.SetCodeAuthorization, isBlackListed IsBlackListedFunc, blockHeight uint64) (authority common.Address, err error) {

‎action/protocol/execution/evm/evm_test.go‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@
66
package evm
77

88
import (
9+
"bytes"
910
"context"
1011
"crypto/ecdsa"
12+
"encoding/binary"
1113
"errors"
1214
"math/big"
1315
"testing"
@@ -606,3 +608,91 @@ func TestEIP7702BlacklistLogic(t *testing.T) {
606608
r.NoError(err, "converting authority to io address should succeed")
607609
r.Equal(ioAddr.String(), convertedAddr.String(), "converted address should match expected io address")
608610
}
611+
612+
func TestExtractRevertMessage(t *testing.T) {
613+
r := require.New(t)
614+
615+
// Build a well-formed Error(string) payload for the given message.
616+
wellFormed := func(msg string) []byte {
617+
out := append([]byte{}, _revertSelector...)
618+
offset := make([]byte, 32)
619+
offset[31] = 0x20
620+
out = append(out, offset...)
621+
length := make([]byte, 32)
622+
binary.BigEndian.PutUint64(length[24:32], uint64(len(msg)))
623+
out = append(out, length...)
624+
data := []byte(msg)
625+
if pad := len(data) % 32; pad != 0 {
626+
data = append(data, make([]byte, 32-pad)...)
627+
}
628+
return append(out, data...)
629+
}
630+
631+
for _, tc := range []struct {
632+
name string
633+
in []byte
634+
want string
635+
wantErr bool
636+
}{
637+
{"nil", nil, "", true},
638+
{"shorter than selector", []byte{0x01, 0x02}, "", true},
639+
{"non-revert prefix", []byte{0x01, 0x02, 0x03, 0x04, 0x05}, "", true},
640+
{
641+
"selector only, truncated length offset",
642+
append(append([]byte{}, _revertSelector...), bytes.Repeat([]byte{0xff}, 50)...),
643+
"", true,
644+
},
645+
{
646+
"msgLength exceeds remaining payload",
647+
func() []byte {
648+
out := append([]byte{}, _revertSelector...)
649+
out = append(out, bytes.Repeat([]byte{0x00}, 32)...) // offset
650+
length := make([]byte, 32)
651+
binary.BigEndian.PutUint64(length[24:32], 1<<20) // claim 1MB message
652+
out = append(out, length...)
653+
out = append(out, []byte("short")...) // but only provide 5 bytes
654+
return out
655+
}(),
656+
"", true,
657+
},
658+
{"well-formed hello", wellFormed("hello"), "hello", false},
659+
{"well-formed empty", wellFormed(""), "", false},
660+
{"well-formed with emoji", wellFormed("nope 🚫"), "nope 🚫", false},
661+
{
662+
// Regression guard: utf8.Valid check was intentionally removed so
663+
// honest-but-non-UTF-8 reverts remain consensus-compatible.
664+
"well-formed but non-UTF-8 string",
665+
func() []byte {
666+
out := append([]byte{}, _revertSelector...)
667+
offset := make([]byte, 32)
668+
offset[31] = 0x20
669+
out = append(out, offset...)
670+
length := make([]byte, 32)
671+
length[31] = 0x02
672+
out = append(out, length...)
673+
out = append(out, 0xff, 0xfe)
674+
out = append(out, make([]byte, 30)...)
675+
return out
676+
}(),
677+
"\xff\xfe", false,
678+
},
679+
{
680+
// Boundary: msgLength exactly equals len(data)-64.
681+
"msgLength exactly fills payload",
682+
wellFormed("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), // 32 bytes, no padding required
683+
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", false,
684+
},
685+
} {
686+
t.Run(tc.name, func(t *testing.T) {
687+
r.NotPanics(func() {
688+
got, err := ExtractRevertMessage(tc.in)
689+
if tc.wantErr {
690+
r.Error(err)
691+
} else {
692+
r.NoError(err)
693+
}
694+
r.Equal(tc.want, got)
695+
})
696+
})
697+
}
698+
}

‎action/protocol/execution/evm/evmstatedbadapter.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,7 @@ func (stateDB *StateDBAdapter) AddLog(evmLog *types.Log) {
926926
copy(topic[:], evmTopic.Bytes())
927927
topics = append(topics, topic)
928928
}
929-
if topics[0] == _inContractTransfer {
929+
if len(topics) > 0 && topics[0] == _inContractTransfer {
930930
if len(topics) != 3 {
931931
log.T(stateDB.ctx).Panic("Invalid in contract transfer topics")
932932
}

‎actsync/actionsync.go‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package actsync
33
import (
44
"context"
55
"sync"
6+
"sync/atomic"
67
"time"
78

89
"github.com/iotexproject/go-pkgs/hash"
@@ -33,6 +34,7 @@ type (
3334
ActionSync struct {
3435
lifecycle.Readiness
3536
actions sync.Map
37+
pending atomic.Int64 // number of live entries in `actions`; bounded by cfg.Size
3638
syncChan chan hash.Hash256
3739
wg sync.WaitGroup
3840
helper *Helper
@@ -104,15 +106,24 @@ func (as *ActionSync) RequestAction(_ context.Context, hash hash.Hash256) {
104106
if !as.IsReady() {
105107
return
106108
}
109+
// Bound the pending request set: a peer can flood us with forged ACTION_HASH
110+
// messages that never resolve, so cap the live map by cfg.Size. Reserve the
111+
// slot atomically before touching the map to prevent OOM and unbounded
112+
// per-hash unicast amplification by triggerSync.
113+
if as.pending.Add(1) > int64(as.cfg.Size) {
114+
as.pending.Add(-1)
115+
counterMtc.WithLabelValues("capacityExceeded").Inc()
116+
log.L().Debug("action sync request capacity exceeded", log.Hex("hash", hash[:]))
117+
return
118+
}
107119
// check if the action is already requested
108-
_, ok := as.actions.LoadOrStore(hash, &actionMsg{})
109-
if ok {
120+
if _, ok := as.actions.LoadOrStore(hash, &actionMsg{}); ok {
121+
as.pending.Add(-1)
110122
log.L().Debug("Action already requested", log.Hex("hash", hash[:]))
111123
return
112124
}
113125
log.L().Debug("Requesting action", log.Hex("hash", hash[:]))
114126
as.trigger(hash)
115-
return
116127
}
117128

118129
// ReceiveAction receives an action
@@ -121,7 +132,9 @@ func (as *ActionSync) ReceiveAction(_ context.Context, hash hash.Hash256) {
121132
return
122133
}
123134
log.L().Debug("received action", log.Hex("hash", hash[:]))
124-
as.actions.Delete(hash)
135+
if _, loaded := as.actions.LoadAndDelete(hash); loaded {
136+
as.pending.Add(-1)
137+
}
125138
}
126139

127140
func (as *ActionSync) sync() {

‎actsync/actionsync_test.go‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,102 @@ func TestActionSync(t *testing.T) {
126126
r.False(ok, "action should be removed after received")
127127
}
128128
})
129+
t.Run("capacityBound", func(t *testing.T) {
130+
// Forged-hash flood: every request is for a unique hash that never
131+
// resolves via ReceiveAction. The live map must not grow past cfg.Size.
132+
const cap = 8
133+
bs := NewActionSync(Config{
134+
Size: cap,
135+
Interval: time.Hour, // disable trigger churn for the duration of this test
136+
}, &Helper{
137+
P2PNeighbor: func() ([]peer.AddrInfo, error) {
138+
return neighbors, nil
139+
},
140+
UnicastOutbound: func(_ context.Context, _ peer.AddrInfo, _ proto.Message) error {
141+
return nil
142+
},
143+
})
144+
r.NoError(bs.Start(context.Background()))
145+
defer func() { r.NoError(bs.Stop(context.Background())) }()
146+
for i := 0; i < cap*4; i++ {
147+
bs.RequestAction(context.Background(), hash.Hash256b([]byte{0xff, byte(i), byte(i >> 8)}))
148+
}
149+
r.Equal(int64(cap), bs.pending.Load(), "pending count must not exceed configured cap")
150+
stored := 0
151+
bs.actions.Range(func(_, _ any) bool { stored++; return true })
152+
r.Equal(cap, stored, "live entries must match the cap")
153+
// ReceiveAction on a hash we already stored must drop the counter so a new request can land.
154+
var sample hash.Hash256
155+
bs.actions.Range(func(k, _ any) bool { sample = k.(hash.Hash256); return false })
156+
bs.ReceiveAction(context.Background(), sample)
157+
r.Equal(int64(cap-1), bs.pending.Load(), "ReceiveAction must release the slot")
158+
bs.RequestAction(context.Background(), hash.Hash256b([]byte("fresh")))
159+
r.Equal(int64(cap), bs.pending.Load(), "freed slot can be reused")
160+
})
161+
t.Run("duplicateRequestDoesNotDoubleCount", func(t *testing.T) {
162+
// LoadOrStore must observe an existing entry and refund the slot, otherwise a
163+
// peer that repeats the same forged hash would still grow the counter and
164+
// eventually wedge the pool at the cap with one real hash.
165+
bs := NewActionSync(Config{
166+
Size: 4,
167+
Interval: time.Hour,
168+
}, &Helper{
169+
P2PNeighbor: func() ([]peer.AddrInfo, error) {
170+
return neighbors, nil
171+
},
172+
UnicastOutbound: func(_ context.Context, _ peer.AddrInfo, _ proto.Message) error {
173+
return nil
174+
},
175+
})
176+
r.NoError(bs.Start(context.Background()))
177+
defer func() { r.NoError(bs.Stop(context.Background())) }()
178+
dup := hash.Hash256b([]byte("dup"))
179+
for i := 0; i < 50; i++ {
180+
bs.RequestAction(context.Background(), dup)
181+
}
182+
r.Equal(int64(1), bs.pending.Load(), "repeated requests for the same hash must collapse to one slot")
183+
// ReceiveAction on an unknown hash must not decrement.
184+
bs.ReceiveAction(context.Background(), hash.Hash256b([]byte("missing")))
185+
r.Equal(int64(1), bs.pending.Load(), "ReceiveAction for an unknown hash must be a no-op for the counter")
186+
bs.ReceiveAction(context.Background(), dup)
187+
r.Equal(int64(0), bs.pending.Load())
188+
})
189+
t.Run("concurrentFloodRespectsCap", func(t *testing.T) {
190+
// Under contention the atomic reserve+undo must hold the cap exactly;
191+
// otherwise a peer can race the check and force the map past the limit.
192+
const cap = 16
193+
bs := NewActionSync(Config{
194+
Size: cap,
195+
Interval: time.Hour,
196+
}, &Helper{
197+
P2PNeighbor: func() ([]peer.AddrInfo, error) {
198+
return neighbors, nil
199+
},
200+
UnicastOutbound: func(_ context.Context, _ peer.AddrInfo, _ proto.Message) error {
201+
return nil
202+
},
203+
})
204+
r.NoError(bs.Start(context.Background()))
205+
defer func() { r.NoError(bs.Stop(context.Background())) }()
206+
const goroutines = 32
207+
const perG = 200
208+
wg := sync.WaitGroup{}
209+
for g := 0; g < goroutines; g++ {
210+
wg.Add(1)
211+
go func(g int) {
212+
defer wg.Done()
213+
for k := 0; k < perG; k++ {
214+
bs.RequestAction(context.Background(), hash.Hash256b([]byte{byte(g), byte(k), byte(k >> 8)}))
215+
}
216+
}(g)
217+
}
218+
wg.Wait()
219+
r.LessOrEqual(bs.pending.Load(), int64(cap), "pending must never exceed configured cap, even under contention")
220+
stored := 0
221+
bs.actions.Range(func(_, _ any) bool { stored++; return true })
222+
r.LessOrEqual(stored, cap, "live entries must never exceed the cap")
223+
r.EqualValues(stored, bs.pending.Load(), "counter and map size must agree")
224+
})
129225
t.Run("requestWhenStopping", func(t *testing.T) {
130226
count := atomic.Int32{}
131227
as := NewActionSync(Config{

‎chainservice/chainservice.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ func (cs *ChainService) Filter(messageType iotexrpc.MessageType, msg proto.Messa
136136
return true
137137
}
138138
blk, ok := msg.(*iotextypes.Block)
139-
if !ok || blk == nil {
139+
if !ok || blk == nil || blk.Header == nil || blk.Header.Core == nil {
140140
return false
141141
}
142142
if blk.Header.Core.Height > atomic.LoadUint64(&cs.lastReceivedBlockHeight) {
@@ -156,7 +156,7 @@ func (cs *ChainService) ReportFullness(_ context.Context, messageType iotexrpc.M
156156
switch messageType {
157157
case iotexrpc.MessageType_BLOCK:
158158
blk, ok := msg.(*iotextypes.Block)
159-
if !ok || blk == nil {
159+
if !ok || blk == nil || blk.Header == nil || blk.Header.Core == nil {
160160
return
161161
}
162162
if blk.Header.Core.Height > atomic.LoadUint64(&cs.lastReceivedBlockHeight) {

0 commit comments

Comments
 (0)