Using a timestamp as a key for processed messages leads to key collisions in the database
The executor uses a nanosecond timestamp as the database key for processed message batches, and multiple batches created in quick succession can share the same timestamp, causing key collisions. This leads to overwriting or deleting processed messages, so after a restart the executor may fail to resume correctly and miss broadcasting critical Cosmos transactions.
Originally disclosed on Code4rena
Submitted by RadiantLabs
Finding description and impact
The executor’s MsgsToProcessedMsgs() converts messages to processed msgs:
276: // MsgsToProcessedMsgs converts msgs to processed msgs.
277: // It splits msgs into chunks of 5 msgs and creates processed msgs for each chunk.
278: func MsgsToProcessedMsgs(queues map[string][]sdk.Msg) []btypes.ProcessedMsgs {
279: res := make([]btypes.ProcessedMsgs, 0)
280: for sender := range queues {
281: msgs := queues[sender]
282: for i := 0; i < len(msgs); i += 5 {
283: end := i + 5
284: if end > len(msgs) {
285: end = len(msgs)
286: }
287:
288: res = append(res, btypes.ProcessedMsgs{
289: Sender: sender,
290: Msgs: slices.Clone(msgs[i:end]),
291: Timestamp: types.CurrentNanoTimestamp(),
292: Save: true,
293: })
294: }
295: }
296: return res
297: }
Messages are put into batches which will later get broadcasted as a single Cosmos SDK transaction. Additionally, processed messages are persisted to storage to ensure the executor can resume where it left off in case it restarts.
The issue is that the Timestamp (in nanoseconds) in line 291 (and the other instances linked to the submission) is very likely shared between batches, which results in key collisions in the database, as the Key() is based on the Timestamp.
opinit-bots/node/broadcaster/types/db.go::Key()
70: func (p ProcessedMsgs) Key() []byte {
71: return prefixedProcessedMsgs(types.MustInt64ToUint64(p.Timestamp))
72: }
This leads to wrongly deleting processed messages in the database,
opinit-bots/node/broadcaster/db.go::DeleteProcessedMsgs()
88: // DeleteProcessedMsgs deletes processed messages
89: func DeleteProcessedMsgs(db types.BasicDB, processedMsgs btypes.ProcessedMsgs) error {
90: return db.Delete(processedMsgs.Key())
91: }
Or, overwriting processed messages:
opinit-bots/node/broadcaster/db.go::SaveProcessedMsgsBatch()
093: // SaveProcessedMsgsBatch saves all processed messages in the batch
094: func SaveProcessedMsgsBatch(db types.BasicDB, cdc codec.Codec, processedMsgsBatch []btypes.ProcessedMsgs) error {
095: for _, processedMsgs := range processedMsgsBatch {
096: if !processedMsgs.Save {
097: continue
098: }
099:
100: data, err := processedMsgs.Value(cdc)
101: if err != nil {
102: return err
103: }
104:
105: err = db.Set(processedMsgs.Key(), data)
106: if err != nil {
107: return err
108: }
109: }
110: return nil
111: }
Similarly, when broadcasting a Cosmos transaction to the host/child node, the timestamp is also used as the key for PendingTxInfo when storing it in the db for eventual restarts.
Ultimately, this leads to scenarios where after an executor restart, it will not resume correctly and misses to broadcast critical Cosmos transactions (e.g., finalizing a L1->L2 token deposit).
Proof of Concept
We prepared a quick PoC that demonstrates how MsgsToProcessedMsgs() constructs batches of messages (ProcessedMsgs) with the same timestamp.
func TestEndBlockHandlerMultipleBatches(t *testing.T) {
childCodec, _, _ := childprovider.GetCodec("init")
child := NewMockChild(nil, childCodec, "sender0", "sender1", 1)
db, err := db.NewMemDB()
defer func() {
require.NoError(t, db.Close())
}()
hostdb := db.WithPrefix([]byte("test_host"))
require.NoError(t, err)
hostNode := node.NewTestNode(nodetypes.NodeConfig{}, hostdb, nil, nil, nil, nil)
h := Host{
BaseHost: hostprovider.NewTestBaseHost(0, hostNode, ophosttypes.QueryBridgeResponse{}, nodetypes.NodeConfig{}, nil),
child: child,
stage: hostdb.NewStage(),
}
msgQueue := h.GetMsgQueue()
require.Empty(t, msgQueue["sender0"])
// append a bunch of messages to the msg queue
var numMessages = 100
for i := 0; i < numMessages; i++ {
h.AppendMsgQueue(&opchildtypes.MsgUpdateOracle{}, "sender0")
}
msgQueue = h.GetMsgQueue()
require.Len(t, msgQueue["sender0"], numMessages)
h.AppendProcessedMsgs(broadcaster.MsgsToProcessedMsgs(h.GetMsgQueue())...)
msgs := h.GetProcessedMsgs()
require.Len(t, msgs, 20) // 100 messages / 5 messages per batch = 20 batches
// Verify that at least one of the batches has the same timestamp
for i := 0; i < len(msgs)-1; i++ {
if msgs[i].Timestamp == msgs[i+1].Timestamp {
// assert that the db key is the same
require.Equal(t, msgs[i].Key(), msgs[i+1].Key(), fmt.Sprintf("DB key do not match - %s == %s", msgs[i].Key(), msgs[i+1].Key()))
require.Fail(t, fmt.Sprintf("timestamps of batch %d and %d are the same. %d == %d", i, i+1, msgs[i].Timestamp, msgs[i+1].Timestamp))
}
}
}
Recommended mitigation steps
Consider using a truly unique identifier instead of the timestamp to avoid key collisions in the database.
There is an issue on mac approximating time in microseconds. It is occasionally possible in such cases.
beer-1 (Initia) confirmed and commented:
Mitigation here.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Impact
After an executor restart, it may not resume correctly and could miss broadcasting critical Cosmos transactions, such as finalizing a token deposit.
What the attacker needed
Executor processes multiple batches quickly; system clock resolution is coarse (e.g., microseconds)
The fix
The issue was fixed by using a truly unique identifier instead of the timestamp for database keys.
How it was found
- Append many messages to the message queue for a sender.
- Convert the queued messages into processed message batches using the conversion function.
- Observe that multiple batches are created.
- Check the timestamps of consecutive batches and find that at least one pair has the same timestamp.
- Verify that the database keys for those batches are identical.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A program saves its progress in a database so it can pick up where it left off after a restart. It labels each saved batch with the current time in nanoseconds, but two batches created very close together can get the same label. When that happens, one batch overwrites the other, and after a restart the program may skip important actions.
What is Race condition?
Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.