Merge rade/counter_nonce (PR #617)
replace random nonces with message sequence numbers Fixes #564.
This commit is contained in:
commit
17be43ff9e
7 files changed
+190
-367
No files matched your search
@@ -442,11 +442,10 @@ func (conn *LocalConnection) sendProtocolMsg(m ProtocolMsg) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (conn *LocalConnection) receiveTCP(decoder *gob.Decoder) {
|
func (conn *LocalConnection) receiveTCP(decoder *gob.Decoder) {
|
||||||
defer conn.Decryptor.Shutdown()
|
|
||||||
usingPassword := conn.SessionKey != nil
|
usingPassword := conn.SessionKey != nil
|
||||||
var receiver TCPReceiver
|
var receiver TCPReceiver
|
||||||
if usingPassword {
|
if usingPassword {
|
||||||
receiver = NewEncryptedTCPReceiver(conn.SessionKey)
|
receiver = NewEncryptedTCPReceiver(conn.SessionKey, conn.outbound)
|
||||||
} else {
|
} else {
|
||||||
receiver = NewSimpleTCPReceiver()
|
receiver = NewSimpleTCPReceiver()
|
||||||
}
|
}
|
||||||
@@ -489,11 +488,6 @@ func (conn *LocalConnection) handleProtocolMsg(tag ProtocolTag, payload []byte)
|
|||||||
nil)
|
nil)
|
||||||
case ProtocolFragmentationReceived:
|
case ProtocolFragmentationReceived:
|
||||||
conn.setStackFrag(true)
|
conn.setStackFrag(true)
|
||||||
case ProtocolNonce:
|
|
||||||
if conn.SessionKey == nil {
|
|
||||||
return fmt.Errorf("unexpected nonce on unencrypted connection")
|
|
||||||
}
|
|
||||||
conn.Decryptor.ReceiveNonce(payload)
|
|
||||||
case ProtocolPMTUVerified:
|
case ProtocolPMTUVerified:
|
||||||
conn.pmtuVerified(int(binary.BigEndian.Uint16(payload)))
|
conn.pmtuVerified(int(binary.BigEndian.Uint16(payload)))
|
||||||
case ProtocolGossipUnicast, ProtocolGossipBroadcast, ProtocolGossip:
|
case ProtocolGossipUnicast, ProtocolGossipBroadcast, ProtocolGossip:
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ const (
|
|||||||
DefaultPMTU = 65535
|
DefaultPMTU = 65535
|
||||||
MaxUDPPacketSize = 65536
|
MaxUDPPacketSize = 65536
|
||||||
ChannelSize = 16
|
ChannelSize = 16
|
||||||
UDPNonceSendAt = 8192
|
|
||||||
FragTestSize = 60001
|
FragTestSize = 60001
|
||||||
PMTUDiscoverySize = 60000
|
PMTUDiscoverySize = 60000
|
||||||
TCPHeartbeat = 30 * time.Second
|
TCPHeartbeat = 30 * time.Second
|
||||||
|
|||||||
+138
-273
@@ -1,7 +1,6 @@
|
|||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"code.google.com/p/go-bit/bit"
|
"code.google.com/p/go-bit/bit"
|
||||||
"code.google.com/p/go.crypto/nacl/box"
|
"code.google.com/p/go.crypto/nacl/box"
|
||||||
"code.google.com/p/go.crypto/nacl/secretbox"
|
"code.google.com/p/go.crypto/nacl/secretbox"
|
||||||
@@ -10,7 +9,6 @@ import (
|
|||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -27,71 +25,6 @@ func FormSessionKey(remotePublicKey, localPrivateKey *[32]byte, secretKey []byte
|
|||||||
return &sessionKey
|
return &sessionKey
|
||||||
}
|
}
|
||||||
|
|
||||||
func GenerateRandomNonce() ([24]byte, error) {
|
|
||||||
var nonce [24]byte
|
|
||||||
n, err := rand.Read(nonce[:])
|
|
||||||
if err != nil {
|
|
||||||
return nonce, err
|
|
||||||
}
|
|
||||||
if n != 24 {
|
|
||||||
return nonce, fmt.Errorf("Did not read enough - wanted 24, got %v", n)
|
|
||||||
}
|
|
||||||
return nonce, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func EncryptPrefixNonce(plaintxt []byte, nonce *[24]byte, secret *[32]byte) []byte {
|
|
||||||
buf := make([]byte, 24, 24+len(plaintxt)+secretbox.Overhead)
|
|
||||||
copy(buf, nonce[:])
|
|
||||||
// Seal *appends* to buf
|
|
||||||
return secretbox.Seal(buf, plaintxt, nonce, secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
func DecryptPrefixNonce(ciphertxt []byte, secret *[32]byte) ([]byte, bool) {
|
|
||||||
if len(ciphertxt) < secretbox.Overhead+24 {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
var nonce [24]byte
|
|
||||||
copy(nonce[:], ciphertxt[:24])
|
|
||||||
return secretbox.Open(nil, ciphertxt[24:], &nonce, secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
func SetNonceLow15Bits(nonce *[24]byte, offset uint16) {
|
|
||||||
// ensure top bit of offset is 0
|
|
||||||
offset = offset & ((1 << 15) - 1)
|
|
||||||
// grab top bit of nonce[22:24] (and clear out lower bits)
|
|
||||||
nonceBits := binary.BigEndian.Uint16(nonce[22:24]) & (1 << 15)
|
|
||||||
// Big endian => the MSB is stored at the *lowest* address. So
|
|
||||||
// that top bit in nonce[22] should stay as the top bit in
|
|
||||||
// nonce[22]
|
|
||||||
binary.BigEndian.PutUint16(nonce[22:24], nonceBits+offset)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nonce encoding/decoding
|
|
||||||
|
|
||||||
func EncodeNonce(df bool) (*[24]byte, []byte, error) {
|
|
||||||
nonce, err := GenerateRandomNonce()
|
|
||||||
if err != nil {
|
|
||||||
return nil, []byte{}, err
|
|
||||||
}
|
|
||||||
// wipe out lowest 15 bits, but encode the df right at the bottom
|
|
||||||
flags := uint16(0)
|
|
||||||
if df {
|
|
||||||
flags |= 1
|
|
||||||
}
|
|
||||||
SetNonceLow15Bits(&nonce, flags)
|
|
||||||
// NB: need to make a copy since callers may modify the array
|
|
||||||
return &nonce, Concat(nonce[:]), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func DecodeNonce(msg []byte) (bool, *[24]byte) {
|
|
||||||
flags := uint16(msg[23])
|
|
||||||
df := 0 != (flags & 1)
|
|
||||||
var nonce [24]byte
|
|
||||||
// upper bound is exclusive so this avoids copying the flags
|
|
||||||
copy(nonce[:], msg[:23])
|
|
||||||
return df, &nonce
|
|
||||||
}
|
|
||||||
|
|
||||||
// Frame Encryptors
|
// Frame Encryptors
|
||||||
|
|
||||||
type Encryptor interface {
|
type Encryptor interface {
|
||||||
@@ -113,12 +46,10 @@ type NonEncryptor struct {
|
|||||||
type NaClEncryptor struct {
|
type NaClEncryptor struct {
|
||||||
NonEncryptor
|
NonEncryptor
|
||||||
buf []byte
|
buf []byte
|
||||||
offset uint16
|
|
||||||
nonce *[24]byte
|
|
||||||
nonceChan chan *[24]byte
|
|
||||||
prefixLen int
|
prefixLen int
|
||||||
sessionKey *[32]byte
|
sessionKey *[32]byte
|
||||||
sendNonce func([]byte)
|
nonce [24]byte
|
||||||
|
seqNo uint64
|
||||||
df bool
|
df bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,19 +99,19 @@ func (ne *NonEncryptor) TotalLen() int {
|
|||||||
return ne.buffered
|
return ne.buffered
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewNaClEncryptor(prefix []byte, sessionKey *[32]byte, sendNonce func([]byte), df bool) *NaClEncryptor {
|
func NewNaClEncryptor(prefix []byte, sessionKey *[32]byte, outbound bool, df bool) *NaClEncryptor {
|
||||||
buf := make([]byte, MaxUDPPacketSize)
|
buf := make([]byte, MaxUDPPacketSize)
|
||||||
prefixLen := copy(buf, prefix)
|
prefixLen := copy(buf, prefix)
|
||||||
return &NaClEncryptor{
|
ne := &NaClEncryptor{
|
||||||
NonEncryptor: *NewNonEncryptor([]byte{}),
|
NonEncryptor: *NewNonEncryptor([]byte{}),
|
||||||
buf: buf,
|
buf: buf,
|
||||||
offset: 0,
|
|
||||||
nonce: nil,
|
|
||||||
nonceChan: make(chan *[24]byte, ChannelSize),
|
|
||||||
prefixLen: prefixLen,
|
prefixLen: prefixLen,
|
||||||
sessionKey: sessionKey,
|
sessionKey: sessionKey,
|
||||||
sendNonce: sendNonce,
|
|
||||||
df: df}
|
df: df}
|
||||||
|
if outbound {
|
||||||
|
ne.nonce[0] |= (1 << 7)
|
||||||
|
}
|
||||||
|
return ne
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ne *NaClEncryptor) Bytes() ([]byte, error) {
|
func (ne *NaClEncryptor) Bytes() ([]byte, error) {
|
||||||
@@ -188,52 +119,27 @@ func (ne *NaClEncryptor) Bytes() ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
offsetFlags := ne.offset
|
|
||||||
// We carry the DF flag in the (unencrypted portion of the)
|
// We carry the DF flag in the (unencrypted portion of the)
|
||||||
// payload, rather than just extracting it from the packet headers
|
// payload, rather than just extracting it from the packet headers
|
||||||
// at the receiving end, since we do not trust routers not to mess
|
// at the receiving end, since we do not trust routers not to mess
|
||||||
// with headers. As we have different decryptors for non-DF and
|
// with headers. As we have different decryptors for non-DF and
|
||||||
// DF, that would result in hard to track down packet drops due to
|
// DF, that would result in hard to track down packet drops due to
|
||||||
// crypto errors.
|
// crypto errors.
|
||||||
|
seqNoAndDF := ne.seqNo
|
||||||
if ne.df {
|
if ne.df {
|
||||||
offsetFlags |= (1 << 15)
|
seqNoAndDF |= (1 << 63)
|
||||||
}
|
}
|
||||||
ciphertext := ne.buf
|
ciphertext := ne.buf
|
||||||
binary.BigEndian.PutUint16(ciphertext[ne.prefixLen:], offsetFlags)
|
binary.BigEndian.PutUint64(ciphertext[ne.prefixLen:], seqNoAndDF)
|
||||||
nonce := ne.nonce
|
binary.BigEndian.PutUint64(ne.nonce[16:24], seqNoAndDF)
|
||||||
if nonce == nil {
|
|
||||||
freshNonce, encodedNonce, err := EncodeNonce(ne.df)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ne.sendNonce(encodedNonce)
|
|
||||||
ne.nonce = freshNonce
|
|
||||||
nonce = freshNonce
|
|
||||||
}
|
|
||||||
offset := ne.offset
|
|
||||||
SetNonceLow15Bits(nonce, offset)
|
|
||||||
// Seal *appends* to ciphertext
|
// Seal *appends* to ciphertext
|
||||||
ciphertext = secretbox.Seal(ciphertext[:ne.prefixLen+2], plaintext, nonce, ne.sessionKey)
|
ciphertext = secretbox.Seal(ciphertext[:ne.prefixLen+8], plaintext, &ne.nonce, ne.sessionKey)
|
||||||
|
ne.seqNo++
|
||||||
offset = (offset + 1) & ((1 << 15) - 1)
|
|
||||||
if offset == 0 {
|
|
||||||
// need a new nonce please
|
|
||||||
ne.nonce = <-ne.nonceChan
|
|
||||||
} else if offset == 1<<14 { // half way through range, send new nonce
|
|
||||||
nonce, encodedNonce, err := EncodeNonce(ne.df)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ne.nonceChan <- nonce
|
|
||||||
ne.sendNonce(encodedNonce)
|
|
||||||
}
|
|
||||||
ne.offset = offset
|
|
||||||
|
|
||||||
return ciphertext, nil
|
return ciphertext, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ne *NaClEncryptor) PacketOverhead() int {
|
func (ne *NaClEncryptor) PacketOverhead() int {
|
||||||
return ne.prefixLen + 2 + secretbox.Overhead + ne.NonEncryptor.PacketOverhead()
|
return ne.prefixLen + 8 + secretbox.Overhead + ne.NonEncryptor.PacketOverhead()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ne *NaClEncryptor) TotalLen() int {
|
func (ne *NaClEncryptor) TotalLen() int {
|
||||||
@@ -246,8 +152,6 @@ type FrameConsumer func(src []byte, dst []byte, frame []byte)
|
|||||||
|
|
||||||
type Decryptor interface {
|
type Decryptor interface {
|
||||||
IterateFrames([]byte, FrameConsumer) error
|
IterateFrames([]byte, FrameConsumer) error
|
||||||
ReceiveNonce([]byte)
|
|
||||||
Shutdown()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type NonDecryptor struct {
|
type NonDecryptor struct {
|
||||||
@@ -261,12 +165,18 @@ type NaClDecryptor struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type NaClDecryptorInstance struct {
|
type NaClDecryptorInstance struct {
|
||||||
nonce *[24]byte
|
nonce [24]byte
|
||||||
previousNonce *[24]byte
|
currentWindow uint64
|
||||||
usedOffsets *bit.Set
|
usedOffsets *bit.Set
|
||||||
previousUsedOffsets *bit.Set
|
previousUsedOffsets *bit.Set
|
||||||
highestOffsetSeen uint16
|
}
|
||||||
nonceChan chan *[24]byte
|
|
||||||
|
func NewNaClDecryptorInstance(outbound bool) *NaClDecryptorInstance {
|
||||||
|
di := &NaClDecryptorInstance{usedOffsets: bit.New()}
|
||||||
|
if !outbound {
|
||||||
|
di.nonce[0] |= (1 << 7)
|
||||||
|
}
|
||||||
|
return di
|
||||||
}
|
}
|
||||||
|
|
||||||
type PacketDecodingError struct {
|
type PacketDecodingError struct {
|
||||||
@@ -298,128 +208,125 @@ func (nd *NonDecryptor) IterateFrames(packet []byte, consumer FrameConsumer) err
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nd *NonDecryptor) Shutdown() {
|
func NewNaClDecryptor(sessionKey *[32]byte, outbound bool) *NaClDecryptor {
|
||||||
}
|
|
||||||
|
|
||||||
func (nd *NonDecryptor) ReceiveNonce(msg []byte) {
|
|
||||||
log.Println("Received Nonce on non-encrypted channel. Ignoring.")
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewNaClDecryptor(sessionKey *[32]byte) *NaClDecryptor {
|
|
||||||
return &NaClDecryptor{
|
return &NaClDecryptor{
|
||||||
NonDecryptor: *NewNonDecryptor(),
|
NonDecryptor: *NewNonDecryptor(),
|
||||||
sessionKey: sessionKey,
|
sessionKey: sessionKey,
|
||||||
instance: &NaClDecryptorInstance{
|
instance: NewNaClDecryptorInstance(outbound),
|
||||||
usedOffsets: bit.New(),
|
instanceDF: NewNaClDecryptorInstance(outbound)}
|
||||||
nonceChan: make(chan *[24]byte, ChannelSize)},
|
|
||||||
instanceDF: &NaClDecryptorInstance{
|
|
||||||
usedOffsets: bit.New(),
|
|
||||||
nonceChan: make(chan *[24]byte, ChannelSize)}}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (nd *NaClDecryptor) Shutdown() {
|
|
||||||
close(nd.instance.nonceChan)
|
|
||||||
close(nd.instanceDF.nonceChan)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (nd *NaClDecryptor) ReceiveNonce(msg []byte) {
|
|
||||||
df, nonce := DecodeNonce(msg)
|
|
||||||
if df {
|
|
||||||
nd.instanceDF.nonceChan <- nonce
|
|
||||||
} else {
|
|
||||||
nd.instance.nonceChan <- nonce
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nd *NaClDecryptor) IterateFrames(packet []byte, consumer FrameConsumer) error {
|
func (nd *NaClDecryptor) IterateFrames(packet []byte, consumer FrameConsumer) error {
|
||||||
buf, err := nd.decrypt(packet)
|
if len(packet) < 8 {
|
||||||
if err != nil {
|
return PacketDecodingError{Desc: fmt.Sprintf("encrypted UDP packet too short; expected length >= 8, got %d", len(packet))}
|
||||||
return PacketDecodingError{Desc: fmt.Sprint("decryption failed; ", err)}
|
}
|
||||||
|
buf, success := nd.decrypt(packet)
|
||||||
|
if !success {
|
||||||
|
return PacketDecodingError{Desc: fmt.Sprint("UDP packet decryption failed")}
|
||||||
}
|
}
|
||||||
return nd.NonDecryptor.IterateFrames(buf, consumer)
|
return nd.NonDecryptor.IterateFrames(buf, consumer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (nd *NaClDecryptor) decrypt(buf []byte) ([]byte, error) {
|
func (nd *NaClDecryptor) decrypt(buf []byte) ([]byte, bool) {
|
||||||
offset := binary.BigEndian.Uint16(buf[:2])
|
seqNoAndDF := binary.BigEndian.Uint64(buf[:8])
|
||||||
df := (offset & (1 << 15)) != 0
|
df := (seqNoAndDF & (1 << 63)) != 0
|
||||||
offsetNoFlags := offset & ((1 << 15) - 1)
|
seqNo := seqNoAndDF & ((1 << 63) - 1)
|
||||||
var di *NaClDecryptorInstance
|
var di *NaClDecryptorInstance
|
||||||
if df {
|
if df {
|
||||||
di = nd.instanceDF
|
di = nd.instanceDF
|
||||||
} else {
|
} else {
|
||||||
di = nd.instance
|
di = nd.instance
|
||||||
}
|
}
|
||||||
nonce, usedOffsets, err := di.advanceState(offsetNoFlags)
|
binary.BigEndian.PutUint64(di.nonce[16:24], seqNoAndDF)
|
||||||
if err != nil {
|
result, success := secretbox.Open(nil, buf[8:], &di.nonce, nd.sessionKey)
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
offsetNoFlagsInt := int(offsetNoFlags)
|
|
||||||
if usedOffsets.Contains(offsetNoFlagsInt) {
|
|
||||||
return nil, fmt.Errorf("Suspected replay attack detected when decrypting UDP packet")
|
|
||||||
}
|
|
||||||
SetNonceLow15Bits(nonce, offsetNoFlags)
|
|
||||||
result, success := secretbox.Open(nil, buf[2:], nonce, nd.sessionKey)
|
|
||||||
if !success {
|
if !success {
|
||||||
return nil, fmt.Errorf("Unable to decrypt UDP packet")
|
return nil, false
|
||||||
}
|
}
|
||||||
usedOffsets.Add(offsetNoFlagsInt)
|
// Drop duplicates. We do this *after* decryption since we must
|
||||||
return result, nil
|
// not advance our state unless decryption succeeded. Doing so
|
||||||
|
// would open an easy attack vector where an adversary could
|
||||||
|
// inject a packet with a sequence number of (1 << 63) - 1,
|
||||||
|
// causing all subsequent genuine packets to get dropped.
|
||||||
|
offset, usedOffsets := di.advanceState(seqNo)
|
||||||
|
if usedOffsets == nil || usedOffsets.Contains(offset) {
|
||||||
|
// We have detected a possible replay attack, but it is
|
||||||
|
// possible we may have just received a very old packet, or
|
||||||
|
// duplication may have occurred in the network. So let's just
|
||||||
|
// drop the packet silently.
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
usedOffsets.Add(offset)
|
||||||
|
return result, success
|
||||||
}
|
}
|
||||||
|
|
||||||
func (di *NaClDecryptorInstance) advanceState(offsetNoFlags uint16) (*[24]byte, *bit.Set, error) {
|
// We record seen message sequence numbers in a sliding window of
|
||||||
var ok bool
|
// 2*WindowSize which slides in WindowSize increments. This allows us
|
||||||
if di.nonce == nil {
|
// to process out-of-order delivery within the window, while
|
||||||
if offsetNoFlags > (1 << 13) {
|
// accurately discarding duplicates. By contrast any messages with
|
||||||
// offset is already beyond the first quarter and it's the
|
// sequence numbers below the window are discarded as potential
|
||||||
// first thing we've seen?! I don't think so.
|
// duplicates.
|
||||||
return nil, nil, fmt.Errorf("Unexpected offset when decrypting UDP packet")
|
//
|
||||||
}
|
// There are two sets, corresponding to the lower and upper half of
|
||||||
di.nonce, ok = <-di.nonceChan
|
// the window. We slide the window s.t. that 2nd set always contains
|
||||||
if !ok {
|
// the highest seen sequence number. We do this regardless of how far
|
||||||
return nil, nil, fmt.Errorf("Nonce chan closed")
|
// ahead of the current window that sequence number might be, so we
|
||||||
}
|
// can cope with large gaps resulting from packet loss.
|
||||||
di.highestOffsetSeen = offsetNoFlags
|
|
||||||
} else {
|
const (
|
||||||
highestOffsetSeen := di.highestOffsetSeen
|
WindowSize = 20 // bits
|
||||||
switch {
|
)
|
||||||
case offsetNoFlags < (1<<13) && highestOffsetSeen > ((1<<14)+(1<<13)) &&
|
|
||||||
(highestOffsetSeen-offsetNoFlags) > ((1<<14)+(1<<13)):
|
func (di *NaClDecryptorInstance) advanceState(seqNo uint64) (int, *bit.Set) {
|
||||||
// offset is in the first quarter, highestOffsetSeen is in
|
var (
|
||||||
// the top quarter and under a quarter behind us. We
|
offset = int(seqNo & ((1 << WindowSize) - 1))
|
||||||
// interpret this as we need to move to the next nonce
|
window = seqNo >> WindowSize
|
||||||
di.previousUsedOffsets = di.usedOffsets
|
)
|
||||||
di.usedOffsets = bit.New()
|
switch delta := int64(window - di.currentWindow); {
|
||||||
di.previousNonce = di.nonce
|
case delta < -1:
|
||||||
di.nonce, ok = <-di.nonceChan
|
return offset, nil
|
||||||
if !ok {
|
case delta == -1:
|
||||||
return nil, nil, fmt.Errorf("Nonce chan closed")
|
return offset, di.previousUsedOffsets
|
||||||
}
|
default:
|
||||||
di.highestOffsetSeen = offsetNoFlags
|
return offset, di.usedOffsets
|
||||||
case offsetNoFlags > highestOffsetSeen &&
|
case delta == +1:
|
||||||
(offsetNoFlags-highestOffsetSeen) < (1<<13):
|
di.currentWindow = window
|
||||||
// offset is under a quarter above highestOffsetSeen. This
|
di.previousUsedOffsets = di.usedOffsets
|
||||||
// is ok - maybe some packet loss
|
di.usedOffsets = bit.New()
|
||||||
di.highestOffsetSeen = offsetNoFlags
|
return offset, di.usedOffsets
|
||||||
case offsetNoFlags <= highestOffsetSeen &&
|
case delta > +1:
|
||||||
(highestOffsetSeen-offsetNoFlags) < (1<<13):
|
di.currentWindow = window
|
||||||
// offset is within a quarter of the highest we've
|
di.previousUsedOffsets = bit.New()
|
||||||
// seen. This is ok - just assuming some out-of-order
|
di.usedOffsets = bit.New()
|
||||||
// delivery.
|
return offset, di.usedOffsets
|
||||||
case highestOffsetSeen < (1<<13) && offsetNoFlags > ((1<<14)+(1<<13)) &&
|
|
||||||
(offsetNoFlags-highestOffsetSeen) > ((1<<14)+(1<<13)):
|
|
||||||
// offset is in the last quarter, highestOffsetSeen is in
|
|
||||||
// the first quarter, and offset is under a quarter behind
|
|
||||||
// us. This is ok - as above, just some out of order. But
|
|
||||||
// here it means we're dealing with the previous nonce
|
|
||||||
return di.previousNonce, di.previousUsedOffsets, nil
|
|
||||||
default:
|
|
||||||
return nil, nil, fmt.Errorf("Unexpected offset when decrypting UDP packet")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return di.nonce, di.usedOffsets, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TCP Senders
|
// TCP Senders/Receivers
|
||||||
|
|
||||||
|
// The lowest 64 bits of the nonce contain the message sequence
|
||||||
|
// number. The top most bit indicates the connection polarity at the
|
||||||
|
// sender - '1' for outbound. The remaining 127 bits are zero. The
|
||||||
|
// polarity is needed so that the two ends of a connection do not use
|
||||||
|
// the same nonces. This is a requirement of the NaCl Security Model;
|
||||||
|
// see http://nacl.cr.yp.to/box.html.
|
||||||
|
type TCPCryptoState struct {
|
||||||
|
sessionKey *[32]byte
|
||||||
|
nonce [24]byte
|
||||||
|
seqNo uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTCPCryptoState(sessionKey *[32]byte, outbound bool) *TCPCryptoState {
|
||||||
|
s := &TCPCryptoState{sessionKey: sessionKey}
|
||||||
|
if outbound {
|
||||||
|
s.nonce[0] |= (1 << 7)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TCPCryptoState) advance() {
|
||||||
|
s.seqNo++
|
||||||
|
binary.BigEndian.PutUint64(s.nonce[16:24], s.seqNo)
|
||||||
|
}
|
||||||
|
|
||||||
type TCPSender interface {
|
type TCPSender interface {
|
||||||
Send([]byte) error
|
Send([]byte) error
|
||||||
@@ -430,17 +337,9 @@ type SimpleTCPSender struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type EncryptedTCPSender struct {
|
type EncryptedTCPSender struct {
|
||||||
|
SimpleTCPSender
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
outerEncoder *gob.Encoder
|
state *TCPCryptoState
|
||||||
innerEncoder *gob.Encoder
|
|
||||||
buffer *bytes.Buffer
|
|
||||||
sessionKey *[32]byte
|
|
||||||
msgCount int
|
|
||||||
}
|
|
||||||
|
|
||||||
type EncryptedTCPMessage struct {
|
|
||||||
Number int
|
|
||||||
Body []byte
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSimpleTCPSender(encoder *gob.Encoder) *SimpleTCPSender {
|
func NewSimpleTCPSender(encoder *gob.Encoder) *SimpleTCPSender {
|
||||||
@@ -451,36 +350,20 @@ func (sender *SimpleTCPSender) Send(msg []byte) error {
|
|||||||
return sender.encoder.Encode(msg)
|
return sender.encoder.Encode(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewEncryptedTCPSender(encoder *gob.Encoder, sessionKey *[32]byte) *EncryptedTCPSender {
|
func NewEncryptedTCPSender(encoder *gob.Encoder, sessionKey *[32]byte, outbound bool) *EncryptedTCPSender {
|
||||||
buffer := new(bytes.Buffer)
|
|
||||||
return &EncryptedTCPSender{
|
return &EncryptedTCPSender{
|
||||||
outerEncoder: encoder,
|
SimpleTCPSender: *NewSimpleTCPSender(encoder),
|
||||||
innerEncoder: gob.NewEncoder(buffer),
|
state: NewTCPCryptoState(sessionKey, outbound)}
|
||||||
buffer: buffer,
|
|
||||||
sessionKey: sessionKey,
|
|
||||||
msgCount: 0}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (sender *EncryptedTCPSender) Send(msg []byte) error {
|
func (sender *EncryptedTCPSender) Send(msg []byte) error {
|
||||||
nonce, err := GenerateRandomNonce()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
sender.Lock()
|
sender.Lock()
|
||||||
defer sender.Unlock()
|
defer sender.Unlock()
|
||||||
wrappedMsg := EncryptedTCPMessage{Number: sender.msgCount, Body: msg}
|
encodedMsg := secretbox.Seal(nil, msg, &sender.state.nonce, sender.state.sessionKey)
|
||||||
buffer := sender.buffer
|
sender.state.advance()
|
||||||
buffer.Reset()
|
return sender.SimpleTCPSender.Send(encodedMsg)
|
||||||
err = sender.innerEncoder.Encode(wrappedMsg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
sender.msgCount += 1
|
|
||||||
return sender.outerEncoder.Encode(EncryptPrefixNonce(buffer.Bytes(), &nonce, sender.sessionKey))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TCP Receivers
|
|
||||||
|
|
||||||
type TCPReceiver interface {
|
type TCPReceiver interface {
|
||||||
Decode([]byte) ([]byte, error)
|
Decode([]byte) ([]byte, error)
|
||||||
}
|
}
|
||||||
@@ -489,10 +372,8 @@ type SimpleTCPReceiver struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type EncryptedTCPReceiver struct {
|
type EncryptedTCPReceiver struct {
|
||||||
sessionKey *[32]byte
|
SimpleTCPReceiver
|
||||||
decoder *gob.Decoder
|
state *TCPCryptoState
|
||||||
buffer *bytes.Buffer
|
|
||||||
msgCount int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSimpleTCPReceiver() *SimpleTCPReceiver {
|
func NewSimpleTCPReceiver() *SimpleTCPReceiver {
|
||||||
@@ -503,33 +384,17 @@ func (receiver *SimpleTCPReceiver) Decode(msg []byte) ([]byte, error) {
|
|||||||
return msg, nil
|
return msg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewEncryptedTCPReceiver(sessionKey *[32]byte) *EncryptedTCPReceiver {
|
func NewEncryptedTCPReceiver(sessionKey *[32]byte, outbound bool) *EncryptedTCPReceiver {
|
||||||
buffer := new(bytes.Buffer)
|
|
||||||
return &EncryptedTCPReceiver{
|
return &EncryptedTCPReceiver{
|
||||||
sessionKey: sessionKey,
|
SimpleTCPReceiver: *NewSimpleTCPReceiver(),
|
||||||
decoder: gob.NewDecoder(buffer),
|
state: NewTCPCryptoState(sessionKey, !outbound)}
|
||||||
buffer: buffer,
|
|
||||||
msgCount: 0}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (receiver *EncryptedTCPReceiver) Decode(msg []byte) ([]byte, error) {
|
func (receiver *EncryptedTCPReceiver) Decode(msg []byte) ([]byte, error) {
|
||||||
plaintext, success := DecryptPrefixNonce(msg, receiver.sessionKey)
|
decodedMsg, success := secretbox.Open(nil, msg, &receiver.state.nonce, receiver.state.sessionKey)
|
||||||
if !success {
|
if !success {
|
||||||
return msg, fmt.Errorf("Unable to decrypt TCP msg")
|
return nil, fmt.Errorf("Unable to decrypt TCP msg")
|
||||||
}
|
}
|
||||||
receiver.buffer.Reset()
|
receiver.state.advance()
|
||||||
_, err := receiver.buffer.Write(plaintext)
|
return decodedMsg, nil
|
||||||
if err != nil {
|
|
||||||
return msg, err
|
|
||||||
}
|
|
||||||
wrappedMsg := new(EncryptedTCPMessage)
|
|
||||||
err = receiver.decoder.Decode(wrappedMsg)
|
|
||||||
if err != nil {
|
|
||||||
return msg, err
|
|
||||||
}
|
|
||||||
if wrappedMsg.Number != receiver.msgCount {
|
|
||||||
return msg, fmt.Errorf("Received TCP message with wrong sequence number; possible replay attack")
|
|
||||||
}
|
|
||||||
receiver.msgCount += 1
|
|
||||||
return wrappedMsg.Body, nil
|
|
||||||
}
|
}
|
||||||
+2
-6
@@ -30,8 +30,8 @@ func (conn *LocalConnection) ensureForwarders() error {
|
|||||||
usingPassword := conn.SessionKey != nil
|
usingPassword := conn.SessionKey != nil
|
||||||
var encryptor, encryptorDF Encryptor
|
var encryptor, encryptorDF Encryptor
|
||||||
if usingPassword {
|
if usingPassword {
|
||||||
encryptor = NewNaClEncryptor(conn.local.NameByte, conn.SessionKey, conn.sendNonce, false)
|
encryptor = NewNaClEncryptor(conn.local.NameByte, conn.SessionKey, conn.outbound, false)
|
||||||
encryptorDF = NewNaClEncryptor(conn.local.NameByte, conn.SessionKey, conn.sendNonce, true)
|
encryptorDF = NewNaClEncryptor(conn.local.NameByte, conn.SessionKey, conn.outbound, true)
|
||||||
} else {
|
} else {
|
||||||
encryptor = NewNonEncryptor(conn.local.NameByte)
|
encryptor = NewNonEncryptor(conn.local.NameByte)
|
||||||
encryptorDF = NewNonEncryptor(conn.local.NameByte)
|
encryptorDF = NewNonEncryptor(conn.local.NameByte)
|
||||||
@@ -62,10 +62,6 @@ func (conn *LocalConnection) stopForwarders() {
|
|||||||
conn.forwarderDF.Shutdown()
|
conn.forwarderDF.Shutdown()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *LocalConnection) sendNonce(encodedNonce []byte) {
|
|
||||||
conn.SendProtocolMsg(ProtocolMsg{ProtocolNonce, encodedNonce})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Called from peer.Relay[Broadcast] which is itself invoked from
|
// Called from peer.Relay[Broadcast] which is itself invoked from
|
||||||
// router (both UDP listener process and sniffer process). Also called
|
// router (both UDP listener process and sniffer process). Also called
|
||||||
// from connection's heartbeat process, and from the connection's TCP
|
// from connection's heartbeat process, and from the connection's TCP
|
||||||
|
|||||||
+2
-2
@@ -102,8 +102,8 @@ func (conn *LocalConnection) handshake(enc *gob.Encoder, dec *gob.Decoder, accep
|
|||||||
remotePublic[idx] = elem
|
remotePublic[idx] = elem
|
||||||
}
|
}
|
||||||
conn.SessionKey = FormSessionKey(&remotePublic, private, conn.Router.Password)
|
conn.SessionKey = FormSessionKey(&remotePublic, private, conn.Router.Password)
|
||||||
conn.tcpSender = NewEncryptedTCPSender(enc, conn.SessionKey)
|
conn.tcpSender = NewEncryptedTCPSender(enc, conn.SessionKey, conn.outbound)
|
||||||
conn.Decryptor = NewNaClDecryptor(conn.SessionKey)
|
conn.Decryptor = NewNaClDecryptor(conn.SessionKey, conn.outbound)
|
||||||
} else {
|
} else {
|
||||||
if rpErr == nil {
|
if rpErr == nil {
|
||||||
return fmt.Errorf("Remote network is encrypted. Password required.")
|
return fmt.Errorf("Remote network is encrypted. Password required.")
|
||||||
|
|||||||
+1
-2
@@ -2,7 +2,7 @@ package router
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
Protocol = "weave"
|
Protocol = "weave"
|
||||||
ProtocolVersion = 15
|
ProtocolVersion = 16
|
||||||
)
|
)
|
||||||
|
|
||||||
type ProtocolTag byte
|
type ProtocolTag byte
|
||||||
@@ -12,7 +12,6 @@ const (
|
|||||||
ProtocolConnectionEstablished
|
ProtocolConnectionEstablished
|
||||||
ProtocolFragmentationReceived
|
ProtocolFragmentationReceived
|
||||||
ProtocolStartFragmentationTest
|
ProtocolStartFragmentationTest
|
||||||
ProtocolNonce
|
|
||||||
ProtocolPMTUVerified
|
ProtocolPMTUVerified
|
||||||
ProtocolGossip
|
ProtocolGossip
|
||||||
ProtocolGossipUnicast
|
ProtocolGossipUnicast
|
||||||
|
|||||||
+46
-76
@@ -282,25 +282,23 @@ between two peers.
|
|||||||
#### TCP
|
#### TCP
|
||||||
|
|
||||||
TCP connection are only used to exchange topology information between
|
TCP connection are only used to exchange topology information between
|
||||||
peers, via a message-based protocol. The router generates a fresh
|
peers, via a message-based protocol. Encryption of each message is
|
||||||
192-bit random nonce for every message to be sent, and prepends the
|
carried out by NaCl's `secretbox.Seal` function using the ephemeral
|
||||||
nonce to the encrypted message, as is normal in NaCl, so that the
|
session key and a nonce. The nonce contains the message sequence
|
||||||
receiver knows the nonce. Encryption of each message is carried out
|
number, which is incremented for every message sent, and a bit
|
||||||
using NaCl's `secretbox.Seal` function using the ephemeral session
|
indicating the polarity of the connection at the sender ('1' for
|
||||||
key. Each TCP connection has a monotonically incrementing message
|
outbound). The latter is required by the
|
||||||
counter, the current value of which is included in the encrypted part
|
[NaCl Security Model](http://nacl.cr.yp.to/box.html) in order to
|
||||||
of the message. Given the assumption that TCP is reliable and ordered,
|
ensure that the two ends of the connection do not use the same nonces.
|
||||||
a message received via TCP is only acted upon if the message counter
|
|
||||||
in the received message is the expected message counter. This prevents
|
|
||||||
replay attacks on the TCP connection.
|
|
||||||
|
|
||||||
As TCP connections do not carry captured traffic, minimising message
|
Decryption of a message at the receiver is carried out by NaCl's
|
||||||
size or latency is not a major concern, so the potentially substantial
|
`secretbox.Open` function using the ephemeral session key and a
|
||||||
increase in length of messages by prepending the full nonce, or the
|
nonce. The receiver maintains its own message sequence number, which
|
||||||
cost of generating a fresh random nonce for each message is not
|
it increments for every message it decrypted successfully. The nonce
|
||||||
considered likely to cause problems. The random nonces are created by
|
is constructed from that sequence number and the connection
|
||||||
the go `crypto/rand` package, which implements a cryptographically
|
polarity. As a result the receiver will only be able to decrypt a
|
||||||
secure pseudorandom number generator.
|
message if it has the expected sequence number. This prevents replay
|
||||||
|
attacks.
|
||||||
|
|
||||||
#### UDP
|
#### UDP
|
||||||
|
|
||||||
@@ -311,7 +309,7 @@ follows:
|
|||||||
+-----------------------------------+
|
+-----------------------------------+
|
||||||
| Name of sending peer |
|
| Name of sending peer |
|
||||||
+-----------------------------------+
|
+-----------------------------------+
|
||||||
| Nonce offset and flags |
|
| Message Sequence No and flags |
|
||||||
+-----------------------------------+
|
+-----------------------------------+
|
||||||
| NaCl SecretBox overheads |
|
| NaCl SecretBox overheads |
|
||||||
+-----------------------------------+ -+
|
+-----------------------------------+ -+
|
||||||
@@ -344,65 +342,37 @@ follows:
|
|||||||
|
|
||||||
This is very similar to the [non-crypto encapsulation](#encapsulation).
|
This is very similar to the [non-crypto encapsulation](#encapsulation).
|
||||||
|
|
||||||
All of the frames are encrypted with the same ephemeral session key
|
All of the frames on a connection are encrypted with the same
|
||||||
and all must be decrypted by the receiving peer. Frames which are to
|
ephemeral session key, and a nonce constructed from a message sequence
|
||||||
be forwarded on to some further peer will be re-encrypted with the
|
number, flags and the connection polarity. This is very similar to the
|
||||||
relevant ephemeral session keys for the onward connections. Thus all
|
TCP encryption scheme, and encryption is again done with the NaCl
|
||||||
traffic is fully decrypted on every peer it passes through.
|
`secretbox.Seal` function. The main difference is that the message
|
||||||
Encryption is again done with the NaCl `secretbox.Seal` function.
|
sequence number and flags are transmitted as part of the message,
|
||||||
|
unencrypted.
|
||||||
|
|
||||||
The name of the sending peer enables the receiver to identify the peer
|
The receiver uses the name of the sending peer to determine which
|
||||||
who sent this UDP packet, and in turn to determine which ephemeral
|
ephemeral session key and local cryptographic state to use for
|
||||||
session key was used and which nonce, and perform decryption. To avoid
|
decryption. Frames which are to be forwarded on to some further peer
|
||||||
sending a fresh 192-bit nonce with every UDP packet, which would pose
|
will be re-encrypted with the relevant ephemeral session keys for the
|
||||||
an unacceptable overhead, each UDP packet only carries the lowest 15
|
onward connections. Thus all traffic is fully decrypted on every peer
|
||||||
bits of the nonce, which is treated as an offset from the "established
|
it passes through.
|
||||||
nonce". The lifecycle of a nonce for UDP is:
|
|
||||||
|
|
||||||
1. A fresh nonce is generated and the most significant 177 bits are
|
Decryption is once again carried out by NaCl's `secretbox.Open`
|
||||||
sent to the receiving peer over the TCP connection. These upper
|
function using the ephemeral session key and nonce. The latter is
|
||||||
most 177 bits are used for the next 2^15 (32768) UDP messages. This
|
constructed from the message sequence number and flags that appeared
|
||||||
is the "established nonce".
|
in the unencrypted portion of the received message, and the connection
|
||||||
2. Each UDP message carries the lowest 15 bits as a unique
|
polarity.
|
||||||
counter. Thus the lowest 15 bits are combined with (appended to)
|
|
||||||
the uppermost 177 bits to form the unique nonce for that message.
|
To guard against replay attacks, the receiver maintains some state in
|
||||||
3. Once the sending side has sent the 16384'th message on the current
|
which it remembers the highest message sequence number seen. It could
|
||||||
nonce (50% of the way through the available range), it generates a
|
simply reject messages with lower sequence numbers, but that could
|
||||||
new nonce (upper 177 bits only) and sends that over the TCP
|
result in excessive message loss when messages are re-ordered. The
|
||||||
connection, thus hopefully ensuring it arrives and is ready before
|
receiver therefore additionally maintains a set of received message
|
||||||
it is needed. The sending side will switch to using the new nonce
|
sequence numbers in a window below the highest number seen, and only
|
||||||
once the full 32768 messages of the current nonce have been
|
rejects messages with a sequence number below that window, or
|
||||||
used. At this point, the sending side resets the offset to 0.
|
contained in the set. The window spans at least 2^20 message sequence
|
||||||
4. The receiving side must deal with the fact that UDP is unreliable
|
numbers, and hence any re-ordering between the most recent ~1 million
|
||||||
and unordered. The receiving side keeps track of the highest offset
|
messages is handled without dropping messages.
|
||||||
seen for each established nonce. The condition to switching to the
|
|
||||||
new nonce it has received via the TCP connection is: the highest
|
|
||||||
offset seen for the current nonce must be above 24576 (75% of the
|
|
||||||
available range) _and_ the current message just received must have
|
|
||||||
an offset less than 8192 (25% of the available range) _and_ the new
|
|
||||||
offset must be less than 8192 messages *ahead* of the highest seen
|
|
||||||
offset so far (assuming modulo 32768). If these conditions are met,
|
|
||||||
the highest offset is set to the offset of the current message and
|
|
||||||
the new nonce is used. If those conditions are not met, the
|
|
||||||
receiving side continues with the current nonce (according to the
|
|
||||||
rules below), updating the highest offset seen as appropriate. Thus
|
|
||||||
in order for the nonce to not be updated correctly would require a
|
|
||||||
loss of at least 8192 messages.
|
|
||||||
5. When the receiving side switches to the new nonce, it does not
|
|
||||||
discard the old nonce. If the highest offset seen is below 8192
|
|
||||||
(25% of the range) _and_ the current message offset is above 24576
|
|
||||||
(75% of the range), _and_ the current message offset is less than
|
|
||||||
8192 behind the highest seen nonce (assuming modulo 32768), then
|
|
||||||
the current message is decoded with the old nonce.
|
|
||||||
6. In the remaining cases, the current message is only decoded if its
|
|
||||||
offset is within 8192 either side of the highest seen offset.
|
|
||||||
7. To avoid replay attacks, the receiving side keeps a set of which
|
|
||||||
offsets have been used with the current and previous nonce. If the
|
|
||||||
offset doesn't exist in the set, and the message can be correctly
|
|
||||||
decoded, the offset is added to the relevant set (thus we avoid
|
|
||||||
poisoning attacks). If the offset already exists in the set, or the
|
|
||||||
message cannot be correctly decoded, the message is not processed
|
|
||||||
further.
|
|
||||||
|
|
||||||
### Further reading
|
### Further reading
|
||||||
More details on the inner workings of weave can be found in the
|
More details on the inner workings of weave can be found in the
|
||||||
|
|||||||
Reference in new issue
Block a user