-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
336 lines (258 loc) · 6.66 KB
/
server.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
// SPDX-FileCopyrightText: 2023 Steffen Vogel <[email protected]>
// SPDX-License-Identifier: Apache-2.0
package rosenpass
import (
"errors"
"fmt"
"net"
"sync"
"time"
"golang.org/x/exp/slog"
)
type Server struct {
spkm spk
sskm ssk
handlers []Handler
biscuitKeys [2]key
biscuitCtr biscuitNo
biscuitTicker *time.Ticker
biscuitLock sync.RWMutex // Protects biscuitCtr and biscuitKeys
peers map[pid]*peer // A lookup table mapping the peer ID to the internal peer structure
handshakes map[sid]*initiatorHandshake // A lookup table mapping the session ID to the ongoing initiator handshake or live session
handshakesLock sync.RWMutex // Protects handshakes
conn conn
logger *slog.Logger
}
func NewUDPServer(cfg Config) (*Server, error) {
if len(cfg.ListenAddrs) == 0 {
// Listen on random port on all interfaces by default
cfg.ListenAddrs = append(cfg.ListenAddrs, &net.UDPAddr{})
}
var err error
if cfg.Conn, err = newUDPConn(cfg.ListenAddrs); err != nil {
return nil, err
}
return NewServer(cfg)
}
func NewServer(cfg Config) (*Server, error) {
biscuitKey, err := generateKey(keySize)
if err != nil {
return nil, fmt.Errorf("failed to generate biscuit key: %w", err)
}
s := &Server{
spkm: cfg.PublicKey,
sskm: cfg.SecretKey,
handlers: cfg.Handlers,
biscuitKeys: [2]key{
key(biscuitKey),
},
biscuitTicker: time.NewTicker(BiscuitEpoch),
peers: map[pid]*peer{},
handshakes: map[sid]*initiatorHandshake{},
conn: cfg.Conn,
logger: cfg.Logger,
}
if s.logger == nil {
s.logger = slog.Default()
}
recvFncs, err := s.conn.Open()
if err != nil {
return nil, fmt.Errorf("failed to open listeners: %w", err)
}
for _, pCfg := range cfg.Peers {
p, err := s.newPeer(&pCfg)
if err != nil {
return nil, err
}
s.logger.Debug("Added peer", "pid", p.PID())
s.peers[p.PID()] = p
}
for _, recvFnc := range recvFncs {
go s.receiveLoop(recvFnc)
}
go s.biscuitLoop()
return s, nil
}
func (s *Server) PID() pid {
return pid(khPeerID.hash(s.spkm[:]))
}
func (s *Server) Close() error {
s.biscuitTicker.Stop()
if err := s.conn.Close(); err != nil {
return err
}
// s.handshakesLock.Lock()
// for _, hs := range s.handshakes {
// if err := hs.Close(); err != nil {
// return err
// }
// }
return nil
}
func (s *Server) Run() error {
for _, p := range s.peers {
s.initiateHandshake(p)
}
return nil
}
func (s *Server) receiveLoop(recvFnc receiveFunc) {
for {
pl, from, err := recvFnc(s.spkm)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
s.logger.Error("Failed to receive message", "error", err)
continue
}
if err := s.handle(pl, from); err != nil {
s.logger.Error("Failed to handle message", "error", err)
continue
}
}
}
func (s *Server) biscuitLoop() {
for range s.biscuitTicker.C {
if err := s.rotateBiscuitKey(); err != nil {
s.logger.Error("Failed to generate biscuit key", slog.Any("error", err))
}
}
}
func (s *Server) rotateBiscuitKey() error {
s.logger.Debug("Renewing biscuit key")
newBiscuitKey, err := generateBiscuitKey()
if err != nil {
return err
}
s.biscuitLock.Lock()
defer s.biscuitLock.Unlock()
oldBiscuitKey := s.biscuitKeys[0]
s.biscuitKeys = [2]key{
newBiscuitKey,
oldBiscuitKey,
}
return nil
}
func (s *Server) handle(pl payload, from *net.UDPAddr) error {
var err error
mTyp := msgTypeFromPayload(pl)
s.logger.Debug("Handling message", "type", mTyp)
// Get or create handshake state
switch req := pl.(type) {
case *initHello:
hs := &responderHandshake{
handshake: handshake{
server: s,
},
}
if err = hs.handleInitHello(req); err != nil {
return err
}
// Update peers endpoint of the init hello message
// has been received from an unknown address.
if hs.peer.endpoint == nil || !compareAddr(hs.peer.endpoint, from) {
hs.peer.endpoint = from
hs.peer.logger.Debug("Learned new endpoint", slog.Any("endpoint", from))
}
if err = hs.sendRespHello(); err != nil {
return err
}
case *respHello:
s.handshakesLock.RLock()
hs, ok := s.handshakes[req.sidi]
s.handshakesLock.RUnlock()
if !ok {
return fmt.Errorf("%s: %s", ErrSessionNotFound, req.sidi)
}
if hs.nextMsg != msgTypeRespHello {
return fmt.Errorf("%w: %s", ErrUnexpectedMsgType, mTyp)
}
if err = hs.handleRespHello(req); err != nil {
return err
}
hs.txTimer.Stop()
if err = hs.sendInitConf(); err != nil {
return err
}
hs.nextMsg = msgTypeEmptyData
case *initConf:
hs := &responderHandshake{
handshake: handshake{
server: s,
},
}
if err = hs.handleInitConf(req); err != nil {
return err
}
if err = hs.sendEmptyData(); err != nil {
return err
}
s.completeHandshake(&hs.handshake, RekeyAfterTimeResponder)
case *emptyData:
s.handshakesLock.RLock()
hs, ok := s.handshakes[req.sid]
s.handshakesLock.RUnlock()
if !ok {
return fmt.Errorf("%s: %s", ErrSessionNotFound, req.sid)
}
if hs.nextMsg != msgTypeEmptyData {
return fmt.Errorf("%w: %s", ErrUnexpectedMsgType, mTyp)
}
if err = hs.handleEmptyData(req); err != nil {
return err
}
hs.nextMsg = msgTypeData
hs.txTimer.Stop()
hs.expiryTimer.Stop()
s.handshakesLock.Lock()
delete(s.handshakes, hs.sidi)
s.handshakesLock.Unlock()
s.completeHandshake(&hs.handshake, RekeyAfterTimeInitiator)
default:
return ErrInvalidMsgType
}
return nil
}
func (s *Server) initiateHandshake(p *peer) {
if hs, err := p.initiateHandshake(); err != nil {
if errors.Is(err, ErrMissingEndpoint) {
p.logger.Debug("Skipping handshake due to missing endpoint")
} else {
p.logger.Error("Failed to initiate handshake for peer", slog.Any("error", err))
}
} else {
hs.expiryTimer = time.AfterFunc(RejectAfterTime, func() {
s.expireHandshake(&hs.handshake)
})
s.handshakesLock.Lock()
s.handshakes[hs.sidi] = hs
s.handshakesLock.Unlock()
}
}
func (s *Server) completeHandshake(hs *handshake, rekeyAfter time.Duration) {
hs.peer.logger.Debug("Exchanged key with peer")
for _, h := range s.handlers {
if h, ok := h.(HandshakeCompletedHandler); ok {
h.HandshakeCompleted(hs.peer.PID(), hs.osk)
}
}
hs.peer.logger.Debug("Rekey", slog.Duration("after", rekeyAfter))
p := hs.peer
if p.rekeyTimer != nil {
p.rekeyTimer.Stop()
}
p.rekeyTimer = time.AfterFunc(rekeyAfter, func() {
s.initiateHandshake(p)
})
}
func (s *Server) expireHandshake(hs *handshake) {
hs.peer.logger.Debug("Erasing outdated key from peer")
s.handshakesLock.Lock()
delete(s.handshakes, hs.sidi)
s.handshakesLock.Unlock()
for _, h := range s.handlers {
if h, ok := h.(HandshakeExpiredHandler); ok {
h.HandshakeExpired(hs.peer.PID())
}
}
}