-
Notifications
You must be signed in to change notification settings - Fork 4
/
entities.go
399 lines (337 loc) · 8.21 KB
/
entities.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package dwgd
import (
"crypto/sha256"
"database/sql"
"embed"
"errors"
"fmt"
"io/fs"
"net"
"sort"
"time"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
)
type Network struct {
id string
endpoint *net.UDPAddr
seed []byte
pubkey wgtypes.Key
route string
ifname string
}
func (n *Network) PeerConfig() wgtypes.PeerConfig {
keepalive := 25 * time.Second
_, ipnet, _ := net.ParseCIDR("0.0.0.0/0")
allowedIPs := []net.IPNet{*ipnet}
return wgtypes.PeerConfig{
Endpoint: n.endpoint,
PublicKey: n.pubkey,
PersistentKeepaliveInterval: &keepalive,
AllowedIPs: allowedIPs,
ReplaceAllowedIPs: true,
}
}
type Client struct {
id string
ip net.IP
ifname string
network *Network
}
func (c *Client) Config() wgtypes.Config {
privkey := GeneratePrivateKey(c.network.seed, c.ip)
peers := make([]wgtypes.PeerConfig, 1)
peers[0] = c.network.PeerConfig()
return wgtypes.Config{
PrivateKey: privkey,
Peers: peers,
}
}
func (c *Client) PeerConfig() wgtypes.PeerConfig {
keepalive := 25 * time.Second
ipnet := net.IPNet{
IP: c.ip,
Mask: []byte{255, 255, 255, 255},
}
allowedIPs := []net.IPNet{ipnet}
privkey := GeneratePrivateKey(c.network.seed, c.ip)
return wgtypes.PeerConfig{
PublicKey: privkey.PublicKey(),
Remove: false,
UpdateOnly: false,
PresharedKey: nil,
Endpoint: nil,
PersistentKeepaliveInterval: &keepalive,
ReplaceAllowedIPs: true,
AllowedIPs: allowedIPs,
}
}
func GeneratePrivateKey(seed []byte, ip net.IP) *wgtypes.Key {
h := sha256.New()
h.Write(seed)
h.Write(ip)
// since the size of a SHA256 checksum is 32 bytes by default,
// wgtypes.NewKey cannot return error
priv, _ := wgtypes.NewKey(h.Sum(nil))
// Modify random bytes using algorithm described at:
// https://cr.yp.to/ecdh.html.
priv[0] &= 248
priv[31] &= 127
priv[31] |= 64
return &priv
}
type Storage struct {
db *sql.DB
}
func (s *Storage) Open(path string) error {
db, err := sql.Open("sqlite3", path)
if err != nil {
return err
}
s.db = db
// Enable foreign key checks.
if _, err := db.Exec(`PRAGMA foreign_keys = ON;`); err != nil {
return fmt.Errorf("foreign keys pragma: %w", err)
}
if err := s.migrate(); err != nil {
return fmt.Errorf("migrate: %w", err)
}
return err
}
func (s *Storage) Close() error {
return s.db.Close()
}
//go:embed migrations/*.sql
var migrationFS embed.FS
// migrate sets up migration tracking and executes pending migration files.
//
// Migration files are embedded in the sqlite/migration folder and are executed
// in lexigraphical order.
//
// Once a migration is run, its name is stored in the 'migrations' table so it
// is not re-executed. Migrations run in a transaction to prevent partial
// migrations.
func (s *Storage) migrate() error {
// Ensure the 'migrations' table exists so we don't duplicate migrations.
if _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY);`); err != nil {
return fmt.Errorf("cannot create migrations table: %w", err)
}
// Read migration files from our embedded file system.
// This uses Go 1.16's 'embed' package.
names, err := fs.Glob(migrationFS, "migrations/*.sql")
if err != nil {
return err
}
sort.Strings(names)
// Loop over all migration files and execute them in order.
for _, name := range names {
if err := s.migrateFile(name); err != nil {
return fmt.Errorf("migration error: name=%q err=%w", name, err)
}
}
return nil
}
// migrate runs a single migration file within a transaction. On success, the
// migration file name is saved to the "migrations" table to prevent re-running.
func (s *Storage) migrateFile(name string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Ensure migration has not already been run.
var n int
if err := tx.QueryRow(`SELECT COUNT(*) FROM migrations WHERE name = ?`, name).Scan(&n); err != nil {
return err
} else if n != 0 {
return nil // already run migration, skip
}
// Read and execute migration file.
if buf, err := fs.ReadFile(migrationFS, name); err != nil {
return err
} else if _, err := tx.Exec(string(buf)); err != nil {
return err
}
// Insert record into migrations to prevent re-running migration.
if _, err := tx.Exec(`INSERT INTO migrations (name) VALUES (?)`, name); err != nil {
return err
}
return tx.Commit()
}
func (s *Storage) AddNetwork(n *Network) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stm, err := s.db.Prepare("INSERT INTO network(id, endpoint, seed, pubkey, route, ifname) VALUES(?, ?, ?, ?, ?, ?)")
if err != nil {
return err
}
defer stm.Close()
r, err := stm.Exec(n.id, n.endpoint.String(), n.seed, n.pubkey[:], n.route, n.ifname)
if err != nil {
return err
}
num, err := r.RowsAffected()
if err != nil {
return err
}
if num != 1 {
return fmt.Errorf("number of inserted rows: %d is not 1", num)
}
return tx.Commit()
}
func (s *Storage) RemoveNetwork(id string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stm, err := tx.Prepare("DELETE FROM network WHERE id = ?")
if err != nil {
return err
}
defer stm.Close()
r, err := stm.Exec(id)
if err != nil {
return err
}
num, err := r.RowsAffected()
if err != nil {
return err
}
if num != 1 {
return fmt.Errorf("number of deleted rows: %d is not 1", num)
}
return tx.Commit()
}
func (s *Storage) GetNetwork(id string) (*Network, error) {
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
stmt, err := tx.Prepare("SELECT id, endpoint, seed, pubkey, route, ifname FROM network WHERE id = ?")
if err != nil {
return nil, err
}
defer stmt.Close()
n := &Network{}
var endpoint string
var pubkey []byte
err = stmt.QueryRow(id).Scan(&n.id, &endpoint, &n.seed, &pubkey, &n.route, &n.ifname)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
n.endpoint, err = net.ResolveUDPAddr("udp", endpoint)
if err != nil {
return nil, err
}
n.pubkey, err = wgtypes.NewKey(pubkey)
if err != nil {
return nil, err
}
return n, nil
}
func (s *Storage) AddClient(c *Client) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stm, err := tx.Prepare("INSERT INTO client(id, network_id, ip, ifname) VALUES(?, ?, ?, ?)")
if err != nil {
return err
}
defer stm.Close()
r, err := stm.Exec(c.id, c.network.id, c.ip.String(), c.ifname)
if err != nil {
return err
}
num, err := r.RowsAffected()
if err != nil {
return err
}
if num != 1 {
return fmt.Errorf("number of inserted rows: %d is not 1", num)
}
return tx.Commit()
}
func (s *Storage) RemoveClient(id string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
stm, err := tx.Prepare("DELETE FROM client WHERE id = ?")
if err != nil {
return err
}
defer stm.Close()
r, err := stm.Exec(id)
if err != nil {
return err
}
num, err := r.RowsAffected()
if err != nil {
return err
}
if num != 1 {
return fmt.Errorf("number of deleted rows: %d is not 1", num)
}
return tx.Commit()
}
func (s *Storage) GetClient(id string) (*Client, error) {
q := `
SELECT
client.id,
client.network_id,
client.ip,
client.ifname,
network.endpoint,
network.seed,
network.pubkey,
network.route,
network.ifname
FROM
client
INNER JOIN network
ON client.network_id = network.id
WHERE client.id = ?
`
tx, err := s.db.Begin()
if err != nil {
return nil, err
}
defer tx.Rollback()
stmt, err := tx.Prepare(q)
if err != nil {
return nil, err
}
defer stmt.Close()
c := &Client{}
c.network = &Network{}
var endpoint string
var ip string
var pubkey []byte
err = stmt.QueryRow(id).Scan(&c.id, &c.network.id, &ip, &c.ifname, &endpoint, &c.network.seed, &pubkey, &c.network.route, &c.network.ifname)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
c.ip = net.ParseIP(ip)
c.network.endpoint, err = net.ResolveUDPAddr("udp", endpoint)
if err != nil {
return nil, err
}
c.network.pubkey, err = wgtypes.NewKey(pubkey)
if err != nil {
return nil, err
}
return c, nil
}