Skip to content

Commit

Permalink
feat(mtproto): improve replay attack mitigation
Browse files Browse the repository at this point in the history
Use message id buffer.
  • Loading branch information
ernado committed Feb 21, 2021
1 parent 72f9f60 commit ea71050
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
28 changes: 15 additions & 13 deletions mtproto/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ type Conn struct {

// Wrappers for external world, like current time, logs or PRNG.
// Should be immutable.
clock clock.Clock
rand io.Reader
cipher Cipher
log *zap.Logger
messageID MessageIDSource
clock clock.Clock
rand io.Reader
cipher Cipher
log *zap.Logger
messageID MessageIDSource
messageIDBuf *proto.MessageIDBuf // replay attack protection

// use session() to access authKey, salt or sessionID.
sessionMux sync.RWMutex
Expand Down Expand Up @@ -92,14 +93,15 @@ func New(addr string, opt Options) *Conn {
opt.setDefaults()

conn := &Conn{
addr: addr,
transport: opt.Transport,
clock: opt.Clock,
rand: opt.Random,
cipher: opt.Cipher,
log: opt.Logger,
ping: map[int64]func(){},
messageID: opt.MessageID,
addr: addr,
transport: opt.Transport,
clock: opt.Clock,
rand: opt.Random,
cipher: opt.Cipher,
log: opt.Logger,
ping: map[int64]func(){},
messageID: opt.MessageID,
messageIDBuf: proto.NewMessageIDBuf(100),

ackSendChan: make(chan int64),
ackInterval: opt.AckInterval,
Expand Down
3 changes: 3 additions & 0 deletions mtproto/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ func (c *Conn) read(ctx context.Context, b *bin.Buffer) (*crypto.EncryptedMessag
if err := checkMessageID(c.clock.Now(), msg.MessageID); err != nil {
return nil, xerrors.Errorf("bad message id: %w", err)
}
if !c.messageIDBuf.Consume(msg.MessageID) {
return nil, xerrors.Errorf("duplicate or too low message id: %w", errRejected)
}

return msg, nil
}
Expand Down

0 comments on commit ea71050

Please sign in to comment.