aboutsummaryrefslogtreecommitdiffstats
path: root/timers.go
blob: 38c9b460731ddf5a763895d5561753866c988cab (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
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
/* SPDX-License-Identifier: GPL-2.0
 *
 * Copyright (C) 2017-2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 */

package main

import (
	"bytes"
	"encoding/binary"
	"math/rand"
	"sync/atomic"
	"time"
)

/* NOTE:
 * Notion of validity
 */

/* Called when a new authenticated message has been send
 *
 */
func (peer *Peer) KeepKeyFreshSending() {
	kp := peer.keyPairs.Current()
	if kp == nil {
		return
	}
	nonce := atomic.LoadUint64(&kp.sendNonce)
	if nonce > RekeyAfterMessages {
		peer.event.handshakeBegin.Fire()
	}
	if kp.isInitiator && time.Now().Sub(kp.created) > RekeyAfterTime {
		peer.event.handshakeBegin.Fire()
	}
}

/* Called when a new authenticated message has been received
 *
 * NOTE: Not thread safe, but called by sequential receiver!
 */
func (peer *Peer) KeepKeyFreshReceiving() {
	if peer.timer.sendLastMinuteHandshake.Get() {
		return
	}
	kp := peer.keyPairs.Current()
	if kp == nil {
		return
	}
	if !kp.isInitiator {
		return
	}
	nonce := atomic.LoadUint64(&kp.sendNonce)
	send := nonce > RekeyAfterMessages || time.Now().Sub(kp.created) > RekeyAfterTimeReceiving
	if send {
		// do a last minute attempt at initiating a new handshake
		peer.timer.sendLastMinuteHandshake.Set(true)
		peer.event.handshakeBegin.Fire()
	}
}

/* Queues a keep-alive if no packets are queued for peer
 */
func (peer *Peer) SendKeepAlive() bool {
	if len(peer.queue.nonce) != 0 {
		return false
	}
	elem := peer.device.NewOutboundElement()
	elem.packet = nil
	select {
	case peer.queue.nonce <- elem:
		return true
	default:
		return false
	}
}

/* Called after successfully completing a handshake.
 * i.e. after:
 *
 * - Valid handshake response
 * - First transport message under the "next" key
 */
// peer.device.log.Info.Println(peer, ": New handshake completed")

/* Event:
 * An ephemeral key is generated
 *
 * i.e. after:
 *
 * CreateMessageInitiation
 * CreateMessageResponse
 *
 * Action:
 * Schedule the deletion of all key material
 * upon failure to complete a handshake
 */
func (peer *Peer) TimerEphemeralKeyCreated() {
	peer.event.ephemeralKeyCreated.Fire()
	// peer.timer.zeroAllKeys.Reset(RejectAfterTime * 3)
}

/* Sends a new handshake initiation message to the peer (endpoint)
 */
func (peer *Peer) sendNewHandshake() error {

	// create initiation message

	msg, err := peer.device.CreateMessageInitiation(peer)
	if err != nil {
		return err
	}

	// marshal handshake message

	var buff [MessageInitiationSize]byte
	writer := bytes.NewBuffer(buff[:0])
	binary.Write(writer, binary.LittleEndian, msg)
	packet := writer.Bytes()
	peer.mac.AddMacs(packet)

	// send to endpoint

	peer.event.anyAuthenticatedPacketTraversal.Fire()

	return peer.SendBuffer(packet)
}

func newTimer() *time.Timer {
	timer := time.NewTimer(time.Hour)
	timer.Stop()
	return timer
}

func (peer *Peer) RoutineTimerHandler() {

	device := peer.device

	logInfo := device.log.Info
	logDebug := device.log.Debug

	defer func() {
		logDebug.Println(peer, ": Routine: timer handler - stopped")
		peer.routines.stopping.Done()
	}()

	logDebug.Println(peer, ": Routine: timer handler - started")

	// reset all timers

	enableHandshake := true
	pendingHandshakeNew := false
	pendingKeepalivePassive := false
	needAnotherKeepalive := false

	timerKeepalivePassive := newTimer()
	timerHandshakeDeadline := newTimer()
	timerHandshakeTimeout := newTimer()
	timerHandshakeNew := newTimer()
	timerZeroAllKeys := newTimer()
	timerKeepalivePersistent := newTimer()

	interval := peer.persistentKeepaliveInterval
	if interval > 0 {
		duration := time.Duration(interval) * time.Second
		timerKeepalivePersistent.Reset(duration)
	}

	// signal synchronised setup complete

	peer.routines.starting.Done()

	// handle timer events

	for {
		select {

		/* stopping */

		case <-peer.routines.stop:
			return

		/* events */

		case <-peer.event.dataSent.C:
			timerKeepalivePassive.Stop()
			if !pendingHandshakeNew {
				timerHandshakeNew.Reset(NewHandshakeTime)
			}

		case <-peer.event.dataReceived.C:
			if pendingKeepalivePassive {
				needAnotherKeepalive = true
			} else {
				timerKeepalivePassive.Reset(KeepaliveTimeout)
			}

		case <-peer.event.anyAuthenticatedPacketTraversal.C:
			interval := peer.persistentKeepaliveInterval
			if interval > 0 {
				duration := time.Duration(interval) * time.Second
				timerKeepalivePersistent.Reset(duration)
			}

		case <-peer.event.handshakeBegin.C:

			if !enableHandshake {
				continue
			}

			logDebug.Println(peer, ": Event, Handshake Begin")

			err := peer.sendNewHandshake()

			// set timeout

			jitter := time.Millisecond * time.Duration(rand.Int31n(334))
			timerKeepalivePassive.Stop()
			timerHandshakeTimeout.Reset(RekeyTimeout + jitter)

			if err != nil {
				logInfo.Println(peer, ": Failed to send handshake initiation", err)
			} else {
				logDebug.Println(peer, ": Send handshake initiation (initial)")
			}

			timerHandshakeDeadline.Reset(RekeyAttemptTime)

			// disable further handshakes

			peer.event.handshakeBegin.Clear()
			enableHandshake = false

		case <-peer.event.handshakeCompleted.C:

			logInfo.Println(peer, ": Handshake completed")

			atomic.StoreInt64(
				&peer.stats.lastHandshakeNano,
				time.Now().UnixNano(),
			)

			timerHandshakeTimeout.Stop()
			timerHandshakeDeadline.Stop()
			peer.timer.sendLastMinuteHandshake.Set(false)

			// allow further handshakes

			peer.event.handshakeBegin.Clear()
			enableHandshake = true

		/* timers */

		case <-timerKeepalivePersistent.C:

			interval := peer.persistentKeepaliveInterval
			if interval > 0 {
				logDebug.Println(peer, ": Send keep-alive (persistent)")
				timerKeepalivePassive.Stop()
				peer.SendKeepAlive()
			}

		case <-timerKeepalivePassive.C:

			logDebug.Println(peer, ": Send keep-alive (passive)")

			peer.SendKeepAlive()

			if needAnotherKeepalive {
				timerKeepalivePassive.Reset(KeepaliveTimeout)
				needAnotherKeepalive = false
			}

		case <-timerZeroAllKeys.C:

			logDebug.Println(peer, ": Clear all key-material (timer event)")

			hs := &peer.handshake
			hs.mutex.Lock()

			kp := &peer.keyPairs
			kp.mutex.Lock()

			// remove key-pairs

			if kp.previous != nil {
				device.DeleteKeyPair(kp.previous)
				kp.previous = nil
			}
			if kp.current != nil {
				device.DeleteKeyPair(kp.current)
				kp.current = nil
			}
			if kp.next != nil {
				device.DeleteKeyPair(kp.next)
				kp.next = nil
			}
			kp.mutex.Unlock()

			// zero out handshake

			device.indices.Delete(hs.localIndex)
			hs.Clear()
			hs.mutex.Unlock()

		case <-timerHandshakeTimeout.C:

			// allow new handshake to be send

			enableHandshake = true

			// clear source (in case this is causing problems)

			peer.mutex.Lock()
			if peer.endpoint != nil {
				peer.endpoint.ClearSrc()
			}
			peer.mutex.Unlock()

			// send new handshake

			err := peer.sendNewHandshake()

			// set timeout

			jitter := time.Millisecond * time.Duration(rand.Int31n(334))
			timerKeepalivePassive.Stop()
			timerHandshakeTimeout.Reset(RekeyTimeout + jitter)

			if err != nil {
				logInfo.Println(peer, ": Failed to send handshake initiation", err)
			} else {
				logDebug.Println(peer, ": Send handshake initiation (subsequent)")
			}

			// disable further handshakes

			peer.event.handshakeBegin.Clear()
			enableHandshake = false

		case <-timerHandshakeDeadline.C:

			// clear all queued packets and stop keep-alive

			logInfo.Println(peer, ": Handshake negotiation timed-out")

			peer.flushNonceQueue()
			peer.event.flushNonceQueue.Fire()

			// renable further handshakes

			peer.event.handshakeBegin.Clear()
			enableHandshake = true
		}
	}
}