aboutsummaryrefslogtreecommitdiffstats
path: root/src/peer.go
blob: 6a879cb3454bf622d40bd404fac2ed0982df9fcf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main

import (
	"errors"
	"golang.org/x/crypto/blake2s"
	"net"
	"sync"
	"time"
)

const (
	OutboundQueueSize = 64
)

type Peer struct {
	mutex                       sync.RWMutex
	endpoint                    *net.UDPAddr
	persistentKeepaliveInterval time.Duration // 0 = disabled
	keyPairs                    KeyPairs
	handshake                   Handshake
	device                      *Device
	macKey                      [blake2s.Size]byte // Hash(Label-Mac1 || publicKey)
	cookie                      []byte             // cookie
	cookieExpire                time.Time
	queueInbound                chan []byte
	queueOutbound               chan *OutboundWorkQueueElement
	queueOutboundRouting        chan []byte
}

func (device *Device) NewPeer(pk NoisePublicKey) *Peer {
	var peer Peer

	// create peer

	peer.mutex.Lock()
	peer.device = device
	peer.keyPairs.Init()
	peer.queueOutbound = make(chan *OutboundWorkQueueElement, OutboundQueueSize)

	// map public key

	device.mutex.Lock()
	_, ok := device.peers[pk]
	if ok {
		panic(errors.New("bug: adding existing peer"))
	}
	device.peers[pk] = &peer
	device.mutex.Unlock()

	// precompute DH

	handshake := &peer.handshake
	handshake.mutex.Lock()
	handshake.remoteStatic = pk
	handshake.precomputedStaticStatic = device.privateKey.sharedSecret(handshake.remoteStatic)

	// compute mac key

	peer.macKey = blake2s.Sum256(append([]byte(WGLabelMAC1[:]), handshake.remoteStatic[:]...))

	handshake.mutex.Unlock()
	peer.mutex.Unlock()

	return &peer
}