From 9d06d7e3064a2fd17376334e18e672212c447797 Mon Sep 17 00:00:00 2001 From: Ismail Khoffi Date: Tue, 28 Aug 2018 06:37:38 +0100 Subject: [PATCH] update secret connection to use a little endian encoded nonce (#2264) * update secret connection to use a little endian encoded nonce * update encoding of chunk length to be little endian, too * update comment * Change comment slightly to trigger circelci --- p2p/conn/secret_connection.go | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/p2p/conn/secret_connection.go b/p2p/conn/secret_connection.go index 75199ee6b..3628eb4a3 100644 --- a/p2p/conn/secret_connection.go +++ b/p2p/conn/secret_connection.go @@ -123,7 +123,7 @@ func (sc *SecretConnection) Write(data []byte) (n int, err error) { data = nil } chunkLength := len(chunk) - binary.BigEndian.PutUint32(frame, uint32(chunkLength)) + binary.LittleEndian.PutUint32(frame, uint32(chunkLength)) copy(frame[dataLenSize:], chunk) aead, err := chacha20poly1305.New(sc.sendSecret[:]) @@ -172,7 +172,7 @@ func (sc *SecretConnection) Read(data []byte) (n int, err error) { incrNonce(sc.recvNonce) // end decryption - var chunkLength = binary.BigEndian.Uint32(frame) // read the first two bytes + var chunkLength = binary.LittleEndian.Uint32(frame) // read the first four bytes if chunkLength > dataMaxSize { return 0, errors.New("chunkLength is greater than dataMaxSize") } @@ -332,13 +332,12 @@ func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKey, signature [] //-------------------------------------------------------------------------------- -// increment nonce big-endian by 1 with wraparound. +// Increment nonce little-endian by 1 with wraparound. +// Due to chacha20poly1305 expecting a 12 byte nonce we do not use the first four +// bytes. We only increment a 64 bit unsigned int in the remaining 8 bytes +// (little-endian in nonce[4:]). func incrNonce(nonce *[aeadNonceSize]byte) { - for i := aeadNonceSize - 1; 0 <= i; i-- { - nonce[i]++ - // if this byte wrapped around to zero, we need to increment the next byte - if nonce[i] != 0 { - return - } - } + counter := binary.LittleEndian.Uint64(nonce[4:]) + counter++ + binary.LittleEndian.PutUint64(nonce[4:], counter) }