Fix HID transfers, harden the tunnel, add E2E crypto and direct peers
The HID failure came down to the endpoint type map being indexed by endpoint number without the direction bit. A composite device can have endpoint 1 as both interrupt IN (0x81) and bulk OUT (0x01); the last one read won, so interrupt URBs were submitted as bulk and the kernel rejected them. The device attached and stayed silent. Endpoint data now comes from the raw descriptors read from /dev/bus/usb rather than sysfs, which only ever exposes the active alternate setting — a webcam's isochronous endpoints are invisible there because they only exist after SET_INTERFACE. Two sysfs parsing bugs fell out of that too: the numeric endpoint attributes are hex without a prefix (wMaxPacketSize "0040" was read as 40, not 64), and bInterval was never read at all. Reliability: three places could freeze the whole process. The share path fed io.Pipe from the WebSocket read loop, so one slow USB transfer stalled every tunnel and the keepalives with them. The relay wrote to client sockets while holding the hub lock, so one peer that stopped reading blocked routing and registration for everyone. Control transfers ran inline in the protocol loop behind a 5s timeout. Also fixed: a use-after- free where a discarded URB's memory could be collected while the kernel still owned it, a reap loop that spun at 100% CPU on ioctl errors, a missing attach timeout, a double close(done) panic, and Hash[:8] in the relay's log line, which let a client with a short hash take the server down. Adds mode "both", so one client can offer and consume devices at once. The tunnel and client-left callbacks became multicast for it: as plain fields the second manager to register silently unhooked the first. Tunnel traffic is now AES-256-GCM end to end, on the relay path as well as directly. The key is derived from the three tokens, not from the group hash — the relay is told the hash, so a key derived from it would protect nothing from the one party in the middle. Group IDs are unchanged, so existing setups keep working; only clients configured without the tokens drop to unencrypted, relay-only operation. Peers now try to connect directly, with the relay supplying the public address neither side can determine for itself. Candidates are raced because an unreachable address hangs until timeout rather than refusing. Falling back to the relay is not an error. Platform reach: cross-compiled targets for ARM, MIPS and RISC-V (the Linux client needed no code changes — usbdevfs is not architecture specific), multi-arch Docker images, an Android bridge that accepts devices over SCM_RIGHTS because apps cannot open /dev/bus/usb, and macOS builds via system_profiler enumeration. Adds a Windows KMDF filter driver under driver/windows with its Go side. UNTESTED: it has never been compiled or run, needs the WDK to build and an EV certificate to distribute. Treat it as a starting point. Adds "usb-client diag": says per machine whether sharing and using are possible, what stands in the way, and what fixes it. Reports can be uploaded to a relay to get them off machines that are awkward to copy from. 96 tests, all green under -race. Builds for linux, windows and darwin on amd64 and arm64. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
tok1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa="
|
||||
tok2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb="
|
||||
tok3 = "ccccccccccccccccccccccccccccccccccccccccccc="
|
||||
)
|
||||
|
||||
func mustSecret(t *testing.T) *TunnelSecret {
|
||||
t.Helper()
|
||||
s, err := DeriveTunnelSecret(tok1, tok2, tok3)
|
||||
if err != nil {
|
||||
t.Fatalf("DeriveTunnelSecret: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestDeriveTunnelSecretIsDeterministic(t *testing.T) {
|
||||
a := mustSecret(t)
|
||||
b := mustSecret(t)
|
||||
|
||||
if !bytes.Equal(a.master, b.master) {
|
||||
t.Error("same tokens produced different secrets")
|
||||
}
|
||||
|
||||
other, err := DeriveTunnelSecret(tok1, tok2, "different")
|
||||
if err != nil {
|
||||
t.Fatalf("DeriveTunnelSecret: %v", err)
|
||||
}
|
||||
if bytes.Equal(a.master, other.master) {
|
||||
t.Error("different tokens produced the same secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeriveTunnelSecretRequiresAllTokens(t *testing.T) {
|
||||
for _, tc := range [][3]string{
|
||||
{"", tok2, tok3},
|
||||
{tok1, "", tok3},
|
||||
{tok1, tok2, ""},
|
||||
} {
|
||||
if _, err := DeriveTunnelSecret(tc[0], tc[1], tc[2]); err == nil {
|
||||
t.Errorf("DeriveTunnelSecret(%q, %q, %q) succeeded, want an error", tc[0], tc[1], tc[2])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The whole point of the design: the relay knows the group hash, so the
|
||||
// tunnel secret must not be derivable from it.
|
||||
func TestTunnelSecretDiffersFromGroupHash(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
|
||||
combined := strings.Join([]string{tok1, tok2, tok3}, ":")
|
||||
sum := sha256.Sum256([]byte(combined))
|
||||
groupHash := hex.EncodeToString(sum[:])
|
||||
|
||||
if hex.EncodeToString(s.master) == groupHash {
|
||||
t.Fatal("tunnel secret equals the group hash — the relay could decrypt everything")
|
||||
}
|
||||
|
||||
key, err := s.TunnelKey("tunnel-1")
|
||||
if err != nil {
|
||||
t.Fatalf("TunnelKey: %v", err)
|
||||
}
|
||||
if hex.EncodeToString(key) == groupHash {
|
||||
t.Fatal("tunnel key equals the group hash")
|
||||
}
|
||||
if bytes.Equal(key, s.master) {
|
||||
t.Error("tunnel key equals the master secret; it should be derived per tunnel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelKeyIsPerTunnel(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
|
||||
a, _ := s.TunnelKey("tunnel-a")
|
||||
b, _ := s.TunnelKey("tunnel-b")
|
||||
aAgain, _ := s.TunnelKey("tunnel-a")
|
||||
|
||||
if bytes.Equal(a, b) {
|
||||
t.Error("different tunnel IDs produced the same key")
|
||||
}
|
||||
if !bytes.Equal(a, aAgain) {
|
||||
t.Error("same tunnel ID produced different keys")
|
||||
}
|
||||
if len(a) != keySize {
|
||||
t.Errorf("key is %d bytes, want %d", len(a), keySize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSealOpenRoundTrip(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
|
||||
sealer, err := NewSealer(key, DirShareToUse)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSealer: %v", err)
|
||||
}
|
||||
opener, err := NewOpener(key, DirShareToUse)
|
||||
if err != nil {
|
||||
t.Fatalf("NewOpener: %v", err)
|
||||
}
|
||||
|
||||
messages := [][]byte{
|
||||
[]byte("first"),
|
||||
[]byte(""),
|
||||
bytes.Repeat([]byte{0xAB}, 65536),
|
||||
[]byte("last"),
|
||||
}
|
||||
|
||||
for i, want := range messages {
|
||||
frame, err := sealer.Seal(want)
|
||||
if err != nil {
|
||||
t.Fatalf("Seal %d: %v", i, err)
|
||||
}
|
||||
if len(frame) != len(want)+FrameOverhead {
|
||||
t.Errorf("frame %d is %d bytes, want %d", i, len(frame), len(want)+FrameOverhead)
|
||||
}
|
||||
// The plaintext must not be visible on the wire.
|
||||
if len(want) > 8 && bytes.Contains(frame, want) {
|
||||
t.Errorf("frame %d contains its plaintext", i)
|
||||
}
|
||||
|
||||
got, err := opener.Open(frame)
|
||||
if err != nil {
|
||||
t.Fatalf("Open %d: %v", i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Errorf("frame %d round-tripped to %q, want %q", i, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Both ends derive the same tunnel key, so the direction byte is the only
|
||||
// thing keeping their nonce spaces apart.
|
||||
func TestDirectionsUseSeparateNonceSpaces(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
|
||||
shareToUse, _ := NewSealer(key, DirShareToUse)
|
||||
useToShare, _ := NewSealer(key, DirUseToShare)
|
||||
|
||||
plaintext := []byte("identical plaintext")
|
||||
a, _ := shareToUse.Seal(plaintext)
|
||||
b, _ := useToShare.Seal(plaintext)
|
||||
|
||||
if bytes.Equal(a, b) {
|
||||
t.Fatal("both directions produced identical ciphertext — nonce reuse")
|
||||
}
|
||||
// Same counter, so any difference must come from the direction byte.
|
||||
if !bytes.Equal(a[:counterSize], b[:counterSize]) {
|
||||
t.Fatal("test assumption broken: counters differ")
|
||||
}
|
||||
|
||||
// A frame from one direction must not open with the other direction's opener.
|
||||
wrongWay, _ := NewOpener(key, DirUseToShare)
|
||||
if _, err := wrongWay.Open(a); err == nil {
|
||||
t.Error("a frame opened under the wrong direction")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsTampering(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
sealer, _ := NewSealer(key, DirShareToUse)
|
||||
|
||||
original, _ := sealer.Seal([]byte("sensitive usb traffic"))
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func([]byte) []byte
|
||||
}{
|
||||
{"flipped ciphertext bit", func(f []byte) []byte {
|
||||
f[counterSize+2] ^= 0x01
|
||||
return f
|
||||
}},
|
||||
{"flipped counter bit", func(f []byte) []byte {
|
||||
f[0] ^= 0x80
|
||||
return f
|
||||
}},
|
||||
{"truncated tag", func(f []byte) []byte { return f[:len(f)-1] }},
|
||||
{"appended byte", func(f []byte) []byte { return append(f, 0x00) }},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
frame := append([]byte(nil), original...)
|
||||
opener, _ := NewOpener(key, DirShareToUse)
|
||||
if _, err := opener.Open(tt.mutate(frame)); err == nil {
|
||||
t.Error("tampered frame was accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsWrongKey(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
good, _ := s.TunnelKey("t1")
|
||||
bad, _ := s.TunnelKey("t2")
|
||||
|
||||
sealer, _ := NewSealer(good, DirShareToUse)
|
||||
frame, _ := sealer.Seal([]byte("secret"))
|
||||
|
||||
opener, _ := NewOpener(bad, DirShareToUse)
|
||||
if _, err := opener.Open(frame); err == nil {
|
||||
t.Error("frame opened under a key from a different tunnel")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsReplay(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
|
||||
sealer, _ := NewSealer(key, DirShareToUse)
|
||||
opener, _ := NewOpener(key, DirShareToUse)
|
||||
|
||||
frame, _ := sealer.Seal([]byte("do this once"))
|
||||
|
||||
if _, err := opener.Open(append([]byte(nil), frame...)); err != nil {
|
||||
t.Fatalf("first delivery: %v", err)
|
||||
}
|
||||
if _, err := opener.Open(append([]byte(nil), frame...)); !errors.Is(err, ErrReplay) {
|
||||
t.Errorf("replayed frame gave %v, want ErrReplay", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A forged frame carrying a huge counter must not poison the replay window
|
||||
// and lock out the genuine frames that follow.
|
||||
func TestForgedFrameDoesNotAdvanceCounter(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
|
||||
sealer, _ := NewSealer(key, DirShareToUse)
|
||||
opener, _ := NewOpener(key, DirShareToUse)
|
||||
|
||||
forged := make([]byte, FrameOverhead+4)
|
||||
for i := range forged[:counterSize] {
|
||||
forged[i] = 0xFF
|
||||
}
|
||||
if _, err := opener.Open(forged); err == nil {
|
||||
t.Fatal("forged frame was accepted")
|
||||
}
|
||||
|
||||
genuine, _ := sealer.Seal([]byte("real traffic"))
|
||||
got, err := opener.Open(genuine)
|
||||
if err != nil {
|
||||
t.Fatalf("genuine frame rejected after a forgery: %v", err)
|
||||
}
|
||||
if string(got) != "real traffic" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenRejectsUndersizedFrame(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
key, _ := s.TunnelKey("t1")
|
||||
opener, _ := NewOpener(key, DirShareToUse)
|
||||
|
||||
for _, size := range []int{0, 1, counterSize, FrameOverhead - 1} {
|
||||
if _, err := opener.Open(make([]byte, size)); err == nil {
|
||||
t.Errorf("frame of %d bytes was accepted", size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerTokenBindsToContext(t *testing.T) {
|
||||
s := mustSecret(t)
|
||||
|
||||
a := s.PeerToken("tunnel-1")
|
||||
b := s.PeerToken("tunnel-2")
|
||||
aAgain := s.PeerToken("tunnel-1")
|
||||
|
||||
if a == b {
|
||||
t.Error("different contexts produced the same token")
|
||||
}
|
||||
if a != aAgain {
|
||||
t.Error("same context produced different tokens")
|
||||
}
|
||||
if len(a) != 64 {
|
||||
t.Errorf("token is %d hex chars, want 64", len(a))
|
||||
}
|
||||
|
||||
// A different group must not be able to produce a matching token.
|
||||
other, _ := DeriveTunnelSecret(tok1, tok2, "different")
|
||||
if other.PeerToken("tunnel-1") == a {
|
||||
t.Error("a different group secret produced the same peer token")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Frame layout on the wire:
|
||||
//
|
||||
// [8 bytes counter (big endian)][ciphertext + 16 byte auth tag]
|
||||
//
|
||||
// The counter travels in the clear because the receiver needs it to rebuild
|
||||
// the nonce; it carries no secret, and the authentication tag covers it.
|
||||
const (
|
||||
counterSize = 8
|
||||
nonceSize = 12 // AES-GCM standard nonce
|
||||
tagSize = 16
|
||||
// FrameOverhead is how much a frame grows over its plaintext.
|
||||
FrameOverhead = counterSize + tagSize
|
||||
)
|
||||
|
||||
// Direction distinguishes the two halves of a tunnel.
|
||||
//
|
||||
// Both ends derive the same tunnel key, so without this they would encrypt
|
||||
// different plaintexts under the same (key, nonce) pair — the one failure that
|
||||
// breaks AES-GCM completely, revealing the XOR of both messages and allowing
|
||||
// forgery.
|
||||
type Direction uint8
|
||||
|
||||
const (
|
||||
// DirShareToUse marks traffic from the sharing side to the using side.
|
||||
DirShareToUse Direction = 1
|
||||
// DirUseToShare marks traffic in the opposite direction.
|
||||
DirUseToShare Direction = 2
|
||||
)
|
||||
|
||||
// ErrCounterExhausted is returned once a sealer has used every counter value.
|
||||
var ErrCounterExhausted = errors.New("tunnel counter exhausted, reconnect required")
|
||||
|
||||
// ErrReplay is returned for a frame whose counter was already seen.
|
||||
var ErrReplay = errors.New("replayed or out-of-order tunnel frame")
|
||||
|
||||
// Sealer encrypts outgoing tunnel frames.
|
||||
type Sealer struct {
|
||||
mu sync.Mutex
|
||||
aead cipher.AEAD
|
||||
dir Direction
|
||||
counter uint64
|
||||
}
|
||||
|
||||
// Opener decrypts incoming tunnel frames.
|
||||
type Opener struct {
|
||||
mu sync.Mutex
|
||||
aead cipher.AEAD
|
||||
dir Direction
|
||||
lastSeen uint64
|
||||
started bool
|
||||
}
|
||||
|
||||
// NewSealer creates a sealer for one direction of a tunnel.
|
||||
func NewSealer(key []byte, dir Direction) (*Sealer, error) {
|
||||
aead, err := newAEAD(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Sealer{aead: aead, dir: dir}, nil
|
||||
}
|
||||
|
||||
// NewOpener creates an opener for one direction of a tunnel.
|
||||
// The direction must be the one the *sender* used.
|
||||
func NewOpener(key []byte, dir Direction) (*Opener, error) {
|
||||
aead, err := newAEAD(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Opener{aead: aead, dir: dir}, nil
|
||||
}
|
||||
|
||||
func newAEAD(key []byte) (cipher.AEAD, error) {
|
||||
if len(key) != keySize {
|
||||
return nil, fmt.Errorf("key is %d bytes, want %d", len(key), keySize)
|
||||
}
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating cipher: %w", err)
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("creating GCM: %w", err)
|
||||
}
|
||||
return aead, nil
|
||||
}
|
||||
|
||||
// nonceFor builds the 12-byte nonce: direction, four zero bytes, counter.
|
||||
// Distinct directions therefore never share a nonce under the same key.
|
||||
func nonceFor(dir Direction, counter uint64) [nonceSize]byte {
|
||||
var nonce [nonceSize]byte
|
||||
nonce[0] = byte(dir)
|
||||
binary.BigEndian.PutUint64(nonce[4:], counter)
|
||||
return nonce
|
||||
}
|
||||
|
||||
// Seal encrypts one frame and returns it ready for transmission.
|
||||
func (s *Sealer) Seal(plaintext []byte) ([]byte, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.counter == ^uint64(0) {
|
||||
return nil, ErrCounterExhausted
|
||||
}
|
||||
counter := s.counter
|
||||
s.counter++
|
||||
|
||||
nonce := nonceFor(s.dir, counter)
|
||||
|
||||
out := make([]byte, counterSize, counterSize+len(plaintext)+tagSize)
|
||||
binary.BigEndian.PutUint64(out, counter)
|
||||
|
||||
// The counter prefix is authenticated as additional data, so it cannot be
|
||||
// altered to make a frame decrypt under a different nonce.
|
||||
return s.aead.Seal(out, nonce[:], plaintext, out[:counterSize]), nil
|
||||
}
|
||||
|
||||
// Open decrypts one frame.
|
||||
//
|
||||
// Frames must arrive in order, which holds for both transports in use: a
|
||||
// direct TCP connection and a relayed WebSocket both preserve ordering. A
|
||||
// counter that does not advance means duplication or tampering.
|
||||
func (o *Opener) Open(frame []byte) ([]byte, error) {
|
||||
if len(frame) < FrameOverhead {
|
||||
return nil, fmt.Errorf("frame is %d bytes, minimum is %d", len(frame), FrameOverhead)
|
||||
}
|
||||
|
||||
counter := binary.BigEndian.Uint64(frame[:counterSize])
|
||||
|
||||
o.mu.Lock()
|
||||
if o.started && counter <= o.lastSeen {
|
||||
o.mu.Unlock()
|
||||
return nil, ErrReplay
|
||||
}
|
||||
o.mu.Unlock()
|
||||
|
||||
nonce := nonceFor(o.dir, counter)
|
||||
plaintext, err := o.aead.Open(nil, nonce[:], frame[counterSize:], frame[:counterSize])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authentication failed: %w", err)
|
||||
}
|
||||
|
||||
// Only advance after the frame proves authentic, so a forged frame with a
|
||||
// high counter cannot make us reject the genuine ones that follow.
|
||||
o.mu.Lock()
|
||||
if counter > o.lastSeen || !o.started {
|
||||
o.lastSeen = counter
|
||||
o.started = true
|
||||
}
|
||||
o.mu.Unlock()
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// Package crypto derives the keys that protect tunnel traffic and provides
|
||||
// the authenticated framing used on direct peer-to-peer connections.
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/hkdf"
|
||||
)
|
||||
|
||||
// keySize is the AES-256 key length.
|
||||
const keySize = 32
|
||||
|
||||
// hkdfSalt separates this key schedule from any other use of the same tokens.
|
||||
const hkdfSalt = "usb-server/tunnel/v1"
|
||||
|
||||
// TunnelSecret is the long-lived group secret derived from the three tokens.
|
||||
//
|
||||
// It deliberately is NOT the group hash. The relay is told the hash so it can
|
||||
// group clients, which means anyone running the relay knows it — using it to
|
||||
// encrypt would protect nothing from the party best positioned to look. The
|
||||
// tokens themselves never leave the client, and the hash is a SHA-256 of them,
|
||||
// so knowing the hash does not yield this secret.
|
||||
type TunnelSecret struct {
|
||||
master []byte
|
||||
}
|
||||
|
||||
// DeriveTunnelSecret builds the group secret from the three tokens.
|
||||
// All three must be non-empty; a client configured with only the group hash
|
||||
// cannot participate in encrypted tunnels.
|
||||
func DeriveTunnelSecret(token1, token2, token3 string) (*TunnelSecret, error) {
|
||||
if token1 == "" || token2 == "" || token3 == "" {
|
||||
return nil, fmt.Errorf("all three tokens are required to derive the tunnel key")
|
||||
}
|
||||
|
||||
// Same joining as the group hash, so both are bound to the same input.
|
||||
combined := strings.Join([]string{token1, token2, token3}, ":")
|
||||
|
||||
master := make([]byte, keySize)
|
||||
r := hkdf.New(sha256.New, []byte(combined), []byte(hkdfSalt), []byte("master"))
|
||||
if _, err := io.ReadFull(r, master); err != nil {
|
||||
return nil, fmt.Errorf("deriving master key: %w", err)
|
||||
}
|
||||
|
||||
return &TunnelSecret{master: master}, nil
|
||||
}
|
||||
|
||||
// TunnelKey derives the key for one tunnel from its ID.
|
||||
//
|
||||
// Every tunnel gets a fresh random ID, so each connection gets a distinct key
|
||||
// and nonces can restart from zero without ever repeating a (key, nonce) pair.
|
||||
func (s *TunnelSecret) TunnelKey(tunnelID string) ([]byte, error) {
|
||||
key := make([]byte, keySize)
|
||||
r := hkdf.New(sha256.New, s.master, []byte(hkdfSalt), []byte("tunnel:"+tunnelID))
|
||||
if _, err := io.ReadFull(r, key); err != nil {
|
||||
return nil, fmt.Errorf("deriving tunnel key: %w", err)
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// PeerToken produces a short value a peer can present to prove it knows the
|
||||
// group secret, bound to the given context string.
|
||||
//
|
||||
// This authenticates direct connections: the relay can tell two clients how to
|
||||
// reach each other, but it cannot forge this, so a peer that presents a valid
|
||||
// token really is a group member rather than whoever happens to reach the port.
|
||||
func (s *TunnelSecret) PeerToken(context string) string {
|
||||
r := hkdf.New(sha256.New, s.master, []byte(hkdfSalt), []byte("peer-token:"+context))
|
||||
token := make([]byte, 32)
|
||||
io.ReadFull(r, token)
|
||||
return hex.EncodeToString(token)
|
||||
}
|
||||
Reference in New Issue
Block a user