stun, netcheck: move under net

This commit is contained in:
Brad Fitzpatrick
2020-05-25 09:15:50 -07:00
parent 43ded2b581
commit b0c10fa610
9 changed files with 10 additions and 10 deletions

330
net/stun/stun.go Normal file
View File

@@ -0,0 +1,330 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package STUN generates STUN request packets and parses response packets.
package stun
import (
crand "crypto/rand"
"encoding/binary"
"errors"
"hash/crc32"
"net"
)
const (
attrNumSoftware = 0x8022
attrNumFingerprint = 0x8028
attrMappedAddress = 0x0001
attrXorMappedAddress = 0x0020
// This alternative attribute type is not
// mentioned in the RFC, but the shift into
// the "comprehension-optional" range seems
// like an easy mistake for a server to make.
// And servers appear to send it.
attrXorMappedAddressAlt = 0x8020
software = "tailnode" // notably: 8 bytes long, so no padding
bindingRequest = "\x00\x01"
magicCookie = "\x21\x12\xa4\x42"
lenFingerprint = 8 // 2+byte header + 2-byte length + 4-byte crc32
ipv4Len = 4
ipv6Len = 16
headerLen = 20
)
// TxID is a transaction ID.
type TxID [12]byte
// NewTxID returns a new random TxID.
func NewTxID() TxID {
var tx TxID
if _, err := crand.Read(tx[:]); err != nil {
panic(err)
}
return tx
}
// Request generates a binding request STUN packet.
// The transaction ID, tID, should be a random sequence of bytes.
func Request(tID TxID) []byte {
// STUN header, RFC5389 Section 6.
const lenAttrSoftware = 4 + len(software)
b := make([]byte, 0, headerLen+lenAttrSoftware+lenFingerprint)
b = append(b, bindingRequest...)
b = appendU16(b, uint16(lenAttrSoftware+lenFingerprint)) // number of bytes following header
b = append(b, magicCookie...)
b = append(b, tID[:]...)
// Attribute SOFTWARE, RFC5389 Section 15.5.
b = appendU16(b, attrNumSoftware)
b = appendU16(b, uint16(len(software)))
b = append(b, software...)
// Attribute FINGERPRINT, RFC5389 Section 15.5.
fp := fingerPrint(b)
b = appendU16(b, attrNumFingerprint)
b = appendU16(b, 4)
b = appendU32(b, fp)
return b
}
func fingerPrint(b []byte) uint32 { return crc32.ChecksumIEEE(b) ^ 0x5354554e }
func appendU16(b []byte, v uint16) []byte {
return append(b, byte(v>>8), byte(v))
}
func appendU32(b []byte, v uint32) []byte {
return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// ParseBindingRequest parses a STUN binding request.
//
// It returns an error unless it advertises that it came from
// Tailscale.
func ParseBindingRequest(b []byte) (TxID, error) {
if !Is(b) {
return TxID{}, ErrNotSTUN
}
if string(b[:len(bindingRequest)]) != bindingRequest {
return TxID{}, ErrNotBindingRequest
}
var txID TxID
copy(txID[:], b[8:8+len(txID)])
var softwareOK bool
var lastAttr uint16
var gotFP uint32
if err := foreachAttr(b[headerLen:], func(attrType uint16, a []byte) error {
lastAttr = attrType
if attrType == attrNumSoftware && string(a) == software {
softwareOK = true
}
if attrType == attrNumFingerprint && len(a) == 4 {
gotFP = binary.BigEndian.Uint32(a)
}
return nil
}); err != nil {
return TxID{}, err
}
if !softwareOK {
return TxID{}, ErrWrongSoftware
}
if lastAttr != attrNumFingerprint {
return TxID{}, ErrNoFingerprint
}
wantFP := fingerPrint(b[:len(b)-lenFingerprint])
if gotFP != wantFP {
return TxID{}, ErrWrongFingerprint
}
return txID, nil
}
var (
ErrNotSTUN = errors.New("response is not a STUN packet")
ErrNotSuccessResponse = errors.New("STUN packet is not a response")
ErrMalformedAttrs = errors.New("STUN response has malformed attributes")
ErrNotBindingRequest = errors.New("STUN request not a binding request")
ErrWrongSoftware = errors.New("STUN request came from non-Tailscale software")
ErrNoFingerprint = errors.New("STUN request didn't end in fingerprint")
ErrWrongFingerprint = errors.New("STUN request had bogus fingerprint")
)
func foreachAttr(b []byte, fn func(attrType uint16, a []byte) error) error {
for len(b) > 0 {
if len(b) < 4 {
return errors.New("effed-f1")
return ErrMalformedAttrs
}
attrType := binary.BigEndian.Uint16(b[:2])
attrLen := int(binary.BigEndian.Uint16(b[2:4]))
attrLenPad := attrLen % 4
b = b[4:]
if attrLen+attrLenPad > len(b) {
return errors.New("effed-f2")
return ErrMalformedAttrs
}
if err := fn(attrType, b[:attrLen]); err != nil {
return err
}
b = b[attrLen+attrLenPad:]
}
return nil
}
// Response generates a binding response.
func Response(txID TxID, ip net.IP, port uint16) []byte {
if ip4 := ip.To4(); ip4 != nil {
ip = ip4
}
var fam byte
switch len(ip) {
case 4:
fam = 1
case 16:
fam = 2
default:
return nil
}
attrsLen := 8 + len(ip)
b := make([]byte, 0, headerLen+attrsLen)
// Header
b = append(b, 0x01, 0x01) // success
b = appendU16(b, uint16(attrsLen))
b = append(b, magicCookie...)
b = append(b, txID[:]...)
// Attributes (well, one)
b = appendU16(b, attrXorMappedAddress)
b = appendU16(b, uint16(4+len(ip)))
b = append(b,
0, // unused byte
fam)
b = appendU16(b, port^0x2112) // first half of magicCookie
for i, o := range []byte(ip) {
if i < 4 {
b = append(b, o^magicCookie[i])
} else {
b = append(b, o^txID[i-len(magicCookie)])
}
}
return b
}
func beu16(b []byte) uint16 { return binary.BigEndian.Uint16(b) }
// ParseResponse parses a successful binding response STUN packet.
// The IP address is extracted from the XOR-MAPPED-ADDRESS attribute.
// The returned addr slice is owned by the caller and does not alias b.
func ParseResponse(b []byte) (tID TxID, addr []byte, port uint16, err error) {
if !Is(b) {
return tID, nil, 0, ErrNotSTUN
}
copy(tID[:], b[8:8+len(tID)])
if b[0] != 0x01 || b[1] != 0x01 {
return tID, nil, 0, ErrNotSuccessResponse
}
attrsLen := int(beu16(b[2:4]))
b = b[headerLen:] // remove STUN header
if attrsLen > len(b) {
return tID, nil, 0, ErrMalformedAttrs
} else if len(b) > attrsLen {
b = b[:attrsLen] // trim trailing packet bytes
}
var addr6, fallbackAddr, fallbackAddr6 []byte
var port6, fallbackPort, fallbackPort6 uint16
// Read through the attributes.
// The the addr+port reported by XOR-MAPPED-ADDRESS
// as the canonical value. If the attribute is not
// present but the STUN server responds with
// MAPPED-ADDRESS we fall back to it.
if err := foreachAttr(b, func(attrType uint16, attr []byte) error {
switch attrType {
case attrXorMappedAddress, attrXorMappedAddressAlt:
a, p, err := xorMappedAddress(tID, attr)
if err != nil {
return err
}
if len(a) == 16 {
addr6, port6 = a, p
} else {
addr, port = a, p
}
case attrMappedAddress:
a, p, err := mappedAddress(attr)
if err != nil {
return ErrMalformedAttrs
}
if len(a) == 16 {
fallbackAddr6, fallbackPort6 = a, p
} else {
fallbackAddr, fallbackPort = a, p
}
}
return nil
}); err != nil {
return TxID{}, nil, 0, err
}
if addr != nil {
return tID, addr, port, nil
}
if fallbackAddr != nil {
return tID, append([]byte{}, fallbackAddr...), fallbackPort, nil
}
if addr6 != nil {
return tID, addr6, port6, nil
}
if fallbackAddr6 != nil {
return tID, append([]byte{}, fallbackAddr6...), fallbackPort6, nil
}
return tID, nil, 0, ErrMalformedAttrs
}
func xorMappedAddress(tID TxID, b []byte) (addr []byte, port uint16, err error) {
// XOR-MAPPED-ADDRESS attribute, RFC5389 Section 15.2
if len(b) < 4 {
return nil, 0, ErrMalformedAttrs
}
xorPort := beu16(b[2:4])
addrField := b[4:]
port = xorPort ^ 0x2112 // first half of magicCookie
addrLen := familyAddrLen(b[1])
if addrLen == 0 {
return nil, 0, ErrMalformedAttrs
}
if len(addrField) < addrLen {
return nil, 0, ErrMalformedAttrs
}
xorAddr := addrField[:addrLen]
addr = make([]byte, addrLen)
for i := range xorAddr {
if i < len(magicCookie) {
addr[i] = xorAddr[i] ^ magicCookie[i]
} else {
addr[i] = xorAddr[i] ^ tID[i-len(magicCookie)]
}
}
return addr, port, nil
}
func familyAddrLen(fam byte) int {
switch fam {
case 0x01: // IPv4
return ipv4Len
case 0x02: // IPv6
return ipv6Len
default:
return 0
}
}
func mappedAddress(b []byte) (addr []byte, port uint16, err error) {
if len(b) < 4 {
return nil, 0, ErrMalformedAttrs
}
port = uint16(b[2])<<8 | uint16(b[3])
addrField := b[4:]
addrLen := familyAddrLen(b[1])
if addrLen == 0 {
return nil, 0, ErrMalformedAttrs
}
if len(addrField) < addrLen {
return nil, 0, ErrMalformedAttrs
}
return append([]byte(nil), addrField[:addrLen]...), port, nil
}
// Is reports whether b is a STUN message.
func Is(b []byte) bool {
return len(b) >= headerLen &&
b[0]&0b11000000 == 0 && // top two bits must be zero
string(b[4:8]) == magicCookie
}

242
net/stun/stun_test.go Normal file
View File

@@ -0,0 +1,242 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package stun_test
import (
"bytes"
"fmt"
"net"
"testing"
"tailscale.com/net/stun"
)
// TODO(bradfitz): fuzz this.
func ExampleRequest() {
txID := stun.NewTxID()
req := stun.Request(txID)
fmt.Printf("%x\n", req)
}
var responseTests = []struct {
name string
data []byte
wantTID []byte
wantAddr []byte
wantPort uint16
}{
{
name: "google-1",
data: []byte{
0x01, 0x01, 0x00, 0x0c, 0x21, 0x12, 0xa4, 0x42,
0x23, 0x60, 0xb1, 0x1e, 0x3e, 0xc6, 0x8f, 0xfa,
0x93, 0xe0, 0x80, 0x07, 0x00, 0x20, 0x00, 0x08,
0x00, 0x01, 0xc7, 0x86, 0x69, 0x57, 0x85, 0x6f,
},
wantTID: []byte{
0x23, 0x60, 0xb1, 0x1e, 0x3e, 0xc6, 0x8f, 0xfa,
0x93, 0xe0, 0x80, 0x07,
},
wantAddr: []byte{72, 69, 33, 45},
wantPort: 59028,
},
{
name: "google-2",
data: []byte{
0x01, 0x01, 0x00, 0x0c, 0x21, 0x12, 0xa4, 0x42,
0xf9, 0xf1, 0x21, 0xcb, 0xde, 0x7d, 0x7c, 0x75,
0x92, 0x3c, 0xe2, 0x71, 0x00, 0x20, 0x00, 0x08,
0x00, 0x01, 0xc7, 0x87, 0x69, 0x57, 0x85, 0x6f,
},
wantTID: []byte{
0xf9, 0xf1, 0x21, 0xcb, 0xde, 0x7d, 0x7c, 0x75,
0x92, 0x3c, 0xe2, 0x71,
},
wantAddr: []byte{72, 69, 33, 45},
wantPort: 59029,
},
{
name: "stun.sipgate.net:10000",
data: []byte{
0x01, 0x01, 0x00, 0x44, 0x21, 0x12, 0xa4, 0x42,
0x48, 0x2e, 0xb6, 0x47, 0x15, 0xe8, 0xb2, 0x8e,
0xae, 0xad, 0x64, 0x44, 0x00, 0x01, 0x00, 0x08,
0x00, 0x01, 0xe4, 0xab, 0x48, 0x45, 0x21, 0x2d,
0x00, 0x04, 0x00, 0x08, 0x00, 0x01, 0x27, 0x10,
0xd9, 0x0a, 0x44, 0x98, 0x00, 0x05, 0x00, 0x08,
0x00, 0x01, 0x27, 0x11, 0xd9, 0x74, 0x7a, 0x8a,
0x80, 0x20, 0x00, 0x08, 0x00, 0x01, 0xc5, 0xb9,
0x69, 0x57, 0x85, 0x6f, 0x80, 0x22, 0x00, 0x10,
0x56, 0x6f, 0x76, 0x69, 0x64, 0x61, 0x2e, 0x6f,
0x72, 0x67, 0x20, 0x30, 0x2e, 0x39, 0x36, 0x00,
},
wantTID: []byte{
0x48, 0x2e, 0xb6, 0x47, 0x15, 0xe8, 0xb2, 0x8e,
0xae, 0xad, 0x64, 0x44,
},
wantAddr: []byte{72, 69, 33, 45},
wantPort: 58539,
},
{
name: "stun.powervoip.com:3478",
data: []byte{
0x01, 0x01, 0x00, 0x24, 0x21, 0x12, 0xa4, 0x42,
0x7e, 0x57, 0x96, 0x68, 0x29, 0xf4, 0x44, 0x60,
0x9d, 0x1d, 0xea, 0xa6, 0x00, 0x01, 0x00, 0x08,
0x00, 0x01, 0xe9, 0xd3, 0x48, 0x45, 0x21, 0x2d,
0x00, 0x04, 0x00, 0x08, 0x00, 0x01, 0x0d, 0x96,
0x4d, 0x48, 0xa9, 0xd4, 0x00, 0x05, 0x00, 0x08,
0x00, 0x01, 0x0d, 0x97, 0x4d, 0x48, 0xa9, 0xd5,
},
wantTID: []byte{
0x7e, 0x57, 0x96, 0x68, 0x29, 0xf4, 0x44, 0x60,
0x9d, 0x1d, 0xea, 0xa6,
},
wantAddr: []byte{72, 69, 33, 45},
wantPort: 59859,
},
{
name: "in-process pion server",
data: []byte{
0x01, 0x01, 0x00, 0x24, 0x21, 0x12, 0xa4, 0x42,
0xeb, 0xc2, 0xd3, 0x6e, 0xf4, 0x71, 0x21, 0x7c,
0x4f, 0x3e, 0x30, 0x8e, 0x80, 0x22, 0x00, 0x0a,
0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74,
0x65, 0x72, 0x00, 0x00, 0x00, 0x20, 0x00, 0x08,
0x00, 0x01, 0xce, 0x66, 0x5e, 0x12, 0xa4, 0x43,
0x80, 0x28, 0x00, 0x04, 0xb6, 0x99, 0xbb, 0x02,
0x01, 0x01, 0x00, 0x24, 0x21, 0x12, 0xa4, 0x42,
},
wantTID: []byte{
0xeb, 0xc2, 0xd3, 0x6e, 0xf4, 0x71, 0x21, 0x7c,
0x4f, 0x3e, 0x30, 0x8e,
},
wantAddr: []byte{127, 0, 0, 1},
wantPort: 61300,
},
{
name: "stuntman-server ipv6",
data: []byte{
0x01, 0x01, 0x00, 0x48, 0x21, 0x12, 0xa4, 0x42,
0x06, 0xf5, 0x66, 0x85, 0xd2, 0x8a, 0xf3, 0xe6,
0x9c, 0xe3, 0x41, 0xe2, 0x00, 0x01, 0x00, 0x14,
0x00, 0x02, 0x90, 0xce, 0x26, 0x02, 0x00, 0xd1,
0xb4, 0xcf, 0xc1, 0x00, 0x38, 0xb2, 0x31, 0xff,
0xfe, 0xef, 0x96, 0xf6, 0x80, 0x2b, 0x00, 0x14,
0x00, 0x02, 0x0d, 0x96, 0x26, 0x04, 0xa8, 0x80,
0x00, 0x02, 0x00, 0xd1, 0x00, 0x00, 0x00, 0x00,
0x00, 0xc5, 0x70, 0x01, 0x00, 0x20, 0x00, 0x14,
0x00, 0x02, 0xb1, 0xdc, 0x07, 0x10, 0xa4, 0x93,
0xb2, 0x3a, 0xa7, 0x85, 0xea, 0x38, 0xc2, 0x19,
0x62, 0x0c, 0xd7, 0x14,
},
wantTID: []byte{
6, 245, 102, 133, 210, 138, 243, 230, 156, 227,
65, 226,
},
wantAddr: net.ParseIP("2602:d1:b4cf:c100:38b2:31ff:feef:96f6"),
wantPort: 37070,
},
}
func TestParseResponse(t *testing.T) {
subtest := func(t *testing.T, i int) {
test := responseTests[i]
tID, addr, port, err := stun.ParseResponse(test.data)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(tID[:], test.wantTID) {
t.Errorf("tid=%v, want %v", tID[:], test.wantTID)
}
if !bytes.Equal(addr, test.wantAddr) {
t.Errorf("addr=%v (%v), want %v", addr, net.IP(addr), test.wantAddr)
}
if port != test.wantPort {
t.Errorf("port=%d, want %d", port, test.wantPort)
}
}
for i, test := range responseTests {
t.Run(test.name, func(t *testing.T) {
subtest(t, i)
})
}
}
func TestIs(t *testing.T) {
const magicCookie = "\x21\x12\xa4\x42"
tests := []struct {
in string
want bool
}{
{"", false},
{"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", false},
{"\x00\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", false},
{"\x00\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", true},
{"\x00\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00foo", true},
// high bits set:
{"\xf0\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", false},
{"\x40\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", false},
// first byte non-zero, but not high bits:
{"\x20\x00\x00\x00" + magicCookie + "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", true},
}
for i, tt := range tests {
pkt := []byte(tt.in)
got := stun.Is(pkt)
if got != tt.want {
t.Errorf("%d. In(%q (%v)) = %v; want %v", i, pkt, pkt, got, tt.want)
}
}
}
func TestParseBindingRequest(t *testing.T) {
tx := stun.NewTxID()
req := stun.Request(tx)
gotTx, err := stun.ParseBindingRequest(req)
if err != nil {
t.Fatal(err)
}
if gotTx != tx {
t.Errorf("original txID %q != got txID %q", tx, gotTx)
}
}
func TestResponse(t *testing.T) {
txN := func(n int) (x stun.TxID) {
for i := range x {
x[i] = byte(n)
}
return
}
tests := []struct {
tx stun.TxID
ip net.IP
port uint16
}{
{tx: txN(1), ip: net.ParseIP("1.2.3.4").To4(), port: 254},
{tx: txN(2), ip: net.ParseIP("1.2.3.4").To4(), port: 257},
{tx: txN(3), ip: net.ParseIP("1::4"), port: 254},
{tx: txN(4), ip: net.ParseIP("1::4"), port: 257},
}
for _, tt := range tests {
res := stun.Response(tt.tx, tt.ip, tt.port)
tx2, ip2, port2, err := stun.ParseResponse(res)
if err != nil {
t.Errorf("TX %x: error: %v", tt.tx, err)
continue
}
if tt.tx != tx2 {
t.Errorf("TX %x: got TxID = %v", tt.tx, tx2)
}
if !bytes.Equal([]byte(tt.ip), ip2) {
t.Errorf("TX %x: ip = %v (%v); want %v (%v)", tt.tx, ip2, net.IP(ip2), []byte(tt.ip), tt.ip)
}
if tt.port != port2 {
t.Errorf("TX %x: port = %v; want %v", tt.tx, port2, tt.port)
}
}
}

View File

@@ -0,0 +1,129 @@
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package stuntest provides a STUN test server.
package stuntest
import (
"fmt"
"net"
"strconv"
"strings"
"sync"
"testing"
"inet.af/netaddr"
"tailscale.com/net/stun"
"tailscale.com/tailcfg"
)
type stunStats struct {
mu sync.Mutex
readIPv4 int
readIPv6 int
}
func Serve(t *testing.T) (addr *net.UDPAddr, cleanupFn func()) {
t.Helper()
// TODO(crawshaw): use stats to test re-STUN logic
var stats stunStats
pc, err := net.ListenPacket("udp4", ":0")
if err != nil {
t.Fatalf("failed to open STUN listener: %v", err)
}
addr = &net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: pc.LocalAddr().(*net.UDPAddr).Port,
}
doneCh := make(chan struct{})
go runSTUN(t, pc, &stats, doneCh)
return addr, func() {
pc.Close()
<-doneCh
}
}
func runSTUN(t *testing.T, pc net.PacketConn, stats *stunStats, done chan<- struct{}) {
defer close(done)
var buf [64 << 10]byte
for {
n, addr, err := pc.ReadFrom(buf[:])
if err != nil {
if strings.Contains(err.Error(), "closed network connection") {
t.Logf("STUN server shutdown")
return
}
continue
}
ua := addr.(*net.UDPAddr)
pkt := buf[:n]
if !stun.Is(pkt) {
continue
}
txid, err := stun.ParseBindingRequest(pkt)
if err != nil {
continue
}
stats.mu.Lock()
if ua.IP.To4() != nil {
stats.readIPv4++
} else {
stats.readIPv6++
}
stats.mu.Unlock()
res := stun.Response(txid, ua.IP, uint16(ua.Port))
if _, err := pc.WriteTo(res, addr); err != nil {
t.Logf("STUN server write failed: %v", err)
}
}
}
func DERPMapOf(stun ...string) *tailcfg.DERPMap {
m := &tailcfg.DERPMap{
Regions: map[int]*tailcfg.DERPRegion{},
}
for i, hostPortStr := range stun {
regionID := i + 1
host, portStr, err := net.SplitHostPort(hostPortStr)
if err != nil {
panic(fmt.Sprintf("bogus STUN hostport: %q", hostPortStr))
}
port, err := strconv.Atoi(portStr)
if err != nil {
panic(fmt.Sprintf("bogus port %q in %q", portStr, hostPortStr))
}
var ipv4, ipv6 string
ip, err := netaddr.ParseIP(host)
if err != nil {
panic(fmt.Sprintf("bogus non-IP STUN host %q in %q", host, hostPortStr))
}
if ip.Is4() {
ipv4 = host
ipv6 = "none"
}
if ip.Is6() {
ipv6 = host
ipv4 = "none"
}
node := &tailcfg.DERPNode{
Name: fmt.Sprint(regionID) + "a",
RegionID: regionID,
HostName: fmt.Sprintf("d%d.invalid", regionID),
IPv4: ipv4,
IPv6: ipv6,
STUNPort: port,
STUNOnly: true,
}
m.Regions[regionID] = &tailcfg.DERPRegion{
RegionID: regionID,
Nodes: []*tailcfg.DERPNode{node},
}
}
return m
}