-
Notifications
You must be signed in to change notification settings - Fork 6
/
lease.go
223 lines (201 loc) · 5.42 KB
/
lease.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Heavily borrows from:
// https://github.com/coredhcp/coredhcp/blob/master/plugins/range/plugin.go
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"inet.af/netaddr"
)
// WGRecord describes a lease entry for a peer.
type WGRecord struct {
PubKey string
IP netaddr.IP
expires time.Time
}
func (wgr WGRecord) String() string {
return wgr.PubKey + " " + wgr.IP.String() + " " + wgr.expires.Format(time.RFC3339)
}
// fileLeaseManager implements functionality for managing address leases for
// peers, using a file as a state backend.
type fileLeaseManager struct {
deviceName string
filename string
ipPrefix netaddr.IPPrefix
wgRecords map[string]WGRecord
wgRecordsMutex sync.Mutex
}
func newFileLeaseManager(cfg *serverConfig) (*fileLeaseManager, error) {
if cfg.LeasesFilename == "" {
return nil, fmt.Errorf("file name cannot be empty")
}
logger.Verbosef("leases filename: %s\n", cfg.LeasesFilename)
leaseDir := filepath.Dir(cfg.LeasesFilename)
err := os.MkdirAll(leaseDir, 0755)
if err != nil {
logger.Errorf("Unable to create directory=%s", leaseDir)
return nil, err
}
lm := &fileLeaseManager{
ipPrefix: cfg.WireguardIPPrefix,
deviceName: cfg.DeviceName,
filename: cfg.LeasesFilename,
}
if err := lm.loadWgRecords(); err != nil {
return nil, err
}
if err := lm.updateWgPeers(); err != nil {
return nil, err
}
logger.Verbosef("Init complete")
return lm, nil
}
func (lm *fileLeaseManager) loadWgRecords() error {
lm.wgRecordsMutex.Lock()
defer lm.wgRecordsMutex.Unlock()
lm.wgRecords = make(map[string]WGRecord)
r, err := os.Open(lm.filename)
if err != nil {
logger.Errorf("unable to open leases file: %v", err)
return nil
}
defer r.Close()
sc := bufio.NewScanner(r)
for sc.Scan() {
line := sc.Text()
if len(line) == 0 {
continue
}
tokens := strings.Fields(line)
if len(tokens) != 4 {
return fmt.Errorf("malformed line, want 3 fields, got %d: %s", len(tokens), line)
}
username := tokens[0]
pubKey := tokens[1]
ipaddr, err := netaddr.ParseIP(tokens[2])
if err != nil {
return err
}
expires, err := time.Parse(time.RFC3339, tokens[3])
if err != nil {
return fmt.Errorf("expected time of exipry in RFC3339 format, got: %v", tokens[2])
}
if expires.After(time.Now()) {
lm.wgRecords[username] = WGRecord{
PubKey: pubKey,
IP: ipaddr,
expires: expires,
}
}
}
logger.Verbosef("records loaded")
return nil
}
func (lm *fileLeaseManager) saveWgRecords() error {
lm.wgRecordsMutex.Lock()
defer lm.wgRecordsMutex.Unlock()
f, err := os.OpenFile(lm.filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer f.Close()
for username, record := range lm.wgRecords {
if _, err := fmt.Fprintf(f, "%s %s\n", username, record); err != nil {
return err
}
}
return nil
}
func (lm *fileLeaseManager) syncWgRecords() error {
lm.wgRecordsMutex.Lock()
changed := false
for k, r := range lm.wgRecords {
if r.expires.Before(time.Now()) {
delete(lm.wgRecords, k)
changed = true
}
}
lm.wgRecordsMutex.Unlock()
if changed {
if err := lm.updateWgPeers(); err != nil {
return err
}
if err := lm.saveWgRecords(); err != nil {
return err
}
}
return nil
}
func (lm *fileLeaseManager) updateWgPeers() error {
lm.wgRecordsMutex.Lock()
defer lm.wgRecordsMutex.Unlock()
peers := []wgtypes.PeerConfig{}
for _, r := range lm.wgRecords {
peerConfig, err := newPeerConfig(r.PubKey, "", "", []string{fmt.Sprintf("%s/32", r.IP.String())})
if err != nil {
logger.Errorf("error calculating peer config %v", err)
continue
}
peers = append(peers, *peerConfig)
}
return setPeers(lm.deviceName, peers)
}
func (lm *fileLeaseManager) createOrUpdatePeer(username, pubKey string, expiry time.Time) (WGRecord, error) {
if username == "" {
return WGRecord{}, fmt.Errorf("Cannot add peer for empty username")
}
if pubKey == "" {
return WGRecord{}, fmt.Errorf("Cannot add peer for empty public key")
}
lm.wgRecordsMutex.Lock()
defer lm.wgRecordsMutex.Unlock()
if record, ok := lm.wgRecords[username]; ok {
record.PubKey = pubKey
record.expires = expiry
lm.wgRecords[username] = record
return lm.wgRecords[username], nil
}
lm.wgRecords[username] = WGRecord{
PubKey: pubKey,
IP: lm.nextAvailableAddress(),
expires: expiry,
}
return lm.wgRecords[username], nil
}
func (lm *fileLeaseManager) addNewPeer(username, pubKey string, expiry time.Time) (WGRecord, error) {
record, err := lm.createOrUpdatePeer(username, pubKey, expiry)
if err != nil {
return WGRecord{}, err
}
if err := lm.updateWgPeers(); err != nil {
return WGRecord{}, err
}
if err := lm.saveWgRecords(); err != nil {
return WGRecord{}, err
}
return record, nil
}
// nextAvailableAddress returns an available IP address within subnet
// - Add the whole subnet
// - remove the gateway address
// - remove the *first* and *last* address (reserved)
// https://en.wikipedia.org/wiki/IPv4#First_and_last_subnet_addresses
// - remove all already leased addresses
// Remaining IPs are "available", get the first one
func (lm *fileLeaseManager) nextAvailableAddress() netaddr.IP {
var b netaddr.IPSetBuilder
b.AddPrefix(lm.ipPrefix)
b.Remove(lm.ipPrefix.IP())
b.Remove(lm.ipPrefix.Range().From())
b.Remove(lm.ipPrefix.Range().To())
for _, r := range lm.wgRecords {
b.Remove(r.IP)
}
a, _ := b.IPSet()
return a.Prefixes()[0].IP()
}