implement source address token generation and validation

ref #121
This commit is contained in:
Lucas Clemente
2016-05-23 18:13:39 +02:00
parent c3f8837dfe
commit 9539169fa4
3 changed files with 234 additions and 0 deletions

View File

@@ -0,0 +1,119 @@
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"time"
"github.com/lucas-clemente/quic-go/protocol"
"golang.org/x/crypto/hkdf"
)
type sourceAddressToken struct {
ip net.IP
// unix timestamp in seconds
timestamp uint64
}
func (t *sourceAddressToken) serialize() []byte {
res := make([]byte, 8+len(t.ip))
binary.LittleEndian.PutUint64(res, t.timestamp)
copy(res[8:], t.ip)
return res
}
func parseToken(data []byte) (*sourceAddressToken, error) {
if len(data) != 8+4 && len(data) != 8+16 {
return nil, fmt.Errorf("invalid STK length %d", len(data))
}
return &sourceAddressToken{
ip: data[8:],
timestamp: binary.LittleEndian.Uint64(data),
}, nil
}
type stkSource struct {
aead cipher.AEAD
}
const stkKeySize = 16
// Chrome currently sets this to 12, but discusses changing it to 16. We start
// at 16 :)
const stkNonceSize = 16
func newStkSource(secret []byte) (*stkSource, error) {
key, err := deriveKey(secret)
if err != nil {
return nil, err
}
c, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCMWithNonceSize(c, stkNonceSize)
if err != nil {
return nil, err
}
return &stkSource{aead: aead}, nil
}
func (s *stkSource) NewToken(ip net.IP) ([]byte, error) {
return encryptToken(s.aead, &sourceAddressToken{
ip: ip,
timestamp: uint64(time.Now().Unix()),
})
}
func (s *stkSource) VerifyToken(ip net.IP, data []byte) error {
if len(data) < stkNonceSize {
return errors.New("STK too short")
}
nonce := data[:stkNonceSize]
res, err := s.aead.Open(nil, nonce, data[stkNonceSize:], nil)
if err != nil {
return err
}
token, err := parseToken(res)
if err != nil {
return err
}
if subtle.ConstantTimeCompare(token.ip, ip) != 1 {
return errors.New("invalid ip in STK")
}
if time.Now().Unix() > int64(token.timestamp)+protocol.STKExpiryTimeSec {
return errors.New("STK expired")
}
return nil
}
func deriveKey(secret []byte) ([]byte, error) {
r := hkdf.New(sha256.New, secret, nil, []byte("QUIC source address token key"))
key := make([]byte, stkKeySize)
if _, err := io.ReadFull(r, key); err != nil {
return nil, err
}
return key, nil
}
func encryptToken(aead cipher.AEAD, token *sourceAddressToken) ([]byte, error) {
nonce := make([]byte, stkNonceSize)
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return nil, err
}
return aead.Seal(nonce, nonce, token.serialize(), nil), nil
}