-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsession.go
473 lines (423 loc) · 12.7 KB
/
session.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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package ike
import (
"bytes"
"context"
stderror "errors"
"fmt"
"net"
"sync/atomic"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/msgboxio/ike/platform"
"github.com/msgboxio/ike/protocol"
"github.com/pkg/errors"
)
var (
errorReplyTimedout = stderror.New("Timed Out")
errorSessionClosed = stderror.New("Session Closed")
errorRekeyDeadlineExceeded = stderror.New("Rekey Deadline Exceeded")
errPeerRemovedIkeSa = stderror.New("Delete IKE SA")
errPeerRemovedEspSa = stderror.New("Delete ESP SA")
)
var sessionCount int32
// SessionCallback holds the callbacks used by the session to notify the user
type SessionCallback struct {
InstallPolicy func(*Session, *protocol.PolicyParams) error
RemovePolicy func(*Session, *protocol.PolicyParams) error
InstallChildSa func(*Session, *platform.SaParams) error
RemoveChildSa func(*Session, *platform.SaParams) error
}
// Session stores IKE session's local state
type Session struct {
cxt context.Context
cancel context.CancelFunc
isClosing bool
cfg Config // copy of Config given to us
tkm *Tkm
authPeer, authLocal Authenticator
isInitiator bool
rfc7427Signatures bool
SessionID int32
IkeSpiI, IkeSpiR protocol.Spi
EspSpiI, EspSpiR protocol.Spi
msgIDReq, msgIDResp msgID
incoming chan *Message
// cached data
initIb, initRb []byte
responderCookie []byte
// data from client
Conn Conn
Local, Remote net.Addr
Cb SessionCallback
Logger log.Logger
}
// Constructors
// NewInitiator creates an initiator session
func NewInitiator(cfg *Config, localAddr, remoteAddr net.Addr, conn Conn, cb *SessionCallback, logger log.Logger) (*Session, error) {
tkm, err := NewTkm(cfg, nil)
if err != nil {
return nil, err
}
cxt, cancel := context.WithCancel(context.Background())
sess := &Session{
cxt: cxt,
cancel: cancel,
SessionID: atomic.AddInt32(&sessionCount, 1),
isInitiator: true,
rfc7427Signatures: true,
tkm: tkm,
cfg: *cfg,
IkeSpiI: MakeSpi(),
IkeSpiR: make([]byte, 8),
incoming: make(chan *Message, 10),
Conn: conn,
Cb: *cb,
msgIDReq: msgID{id: 0},
msgIDResp: msgID{id: -1},
}
err = sess.setAddresses(localAddr, remoteAddr)
if err != nil {
return nil, err
}
sess.Logger = log.With(logger, "session", sess.tag())
return sess, nil
}
// NewResponder creates a Responder session
func NewResponder(cfg *Config, conn Conn, cb *SessionCallback, initI *Message, logger log.Logger) (*Session, error) {
// get spi
ikeSpiI := initI.IkeHeader.SpiI
// cast is safe since we already checked for presence of payloads
// assert ?
noI := initI.Payloads.Get(protocol.PayloadTypeNonce).(*protocol.NoncePayload)
// creating tkm is expensive, should come after checks are positive
tkm, err := NewTkm(cfg, noI.Nonce)
if err != nil {
return nil, err
}
cxt, cancel := context.WithCancel(context.Background())
// create and run session
sess := &Session{
cxt: cxt,
cancel: cancel,
SessionID: atomic.AddInt32(&sessionCount, 1),
tkm: tkm,
cfg: *cfg,
IkeSpiI: ikeSpiI,
IkeSpiR: MakeSpi(),
incoming: make(chan *Message, 10),
Conn: conn,
Cb: *cb,
msgIDReq: msgID{id: 0},
msgIDResp: msgID{id: -1},
}
err = sess.setAddresses(initI.LocalAddr, initI.RemoteAddr)
if err != nil {
return nil, err
}
sess.Logger = log.With(logger, "session", sess.tag())
return sess, nil
}
// Destructors
// Shutdown is called to initiate a session shutdown
// 1: peer shut us down, or 2: we are shutting down all sessions
func (sess *Session) Shutdown(err error) {
sess.Logger.Log("Shutdown", err)
if sess.isClosing {
return
}
sess.isClosing = true
// dont send Delete for
switch errors.Cause(err) {
case errPeerRemovedIkeSa,
protocol.ERR_UNSUPPORTED_CRITICAL_PAYLOAD,
protocol.ERR_INVALID_SYNTAX,
protocol.ERR_AUTHENTICATION_FAILED:
break
default:
sess.sendIkeSaDelete()
}
sess.RemoveSa()
sess.removePolicy()
// NOTE : it is possible that RunSession has exited already
close(sess.incoming) // closing channel will cause RunSession to continue
<-sess.cxt.Done() // wait till it returns
}
// Housekeeping
func (sess *Session) IsInitiator() bool {
return sess.isInitiator
}
type OutgoingMessage struct {
Data []byte
}
func (sess *Session) tag() string {
ini := "[I]"
if !sess.isInitiator {
ini = "[R]"
}
return ini + sess.IkeSpiI.String()
}
func (sess *Session) String() string {
return fmt.Sprintf("%s<=>%s %s", sess.IkeSpiI, sess.IkeSpiR, sess.tkm)
}
func (sess *Session) CreateIkeSa(init *initParams) error {
if sess.isInitiator {
// peer responders nonce
sess.tkm.Nr = init.nonce
// peer responders spi
sess.IkeSpiR = append([]byte{}, init.spiR...)
} else {
// peer initiators nonce
sess.tkm.Ni = init.nonce
// peer initiators spi
sess.IkeSpiI = append([]byte{}, init.spiI...)
}
//
// we know what IKE ciphersuite peer selected
// generate keys necessary for IKE SA protection and encryption.
// initialize dh shared with their public key
err := sess.tkm.DhGenerateKey(init.dhPublic)
if err != nil {
return err
}
// peer will/not use secure signatures
sess.rfc7427Signatures = init.rfc7427Signatures
// create rest of ike sa
sess.tkm.IkeSaKeys(sess.IkeSpiI, sess.IkeSpiR, nil)
// create authenticators
sess.authLocal = NewAuthenticator(sess.cfg.LocalID, sess.tkm, sess.isInitiator, sess.rfc7427Signatures)
sess.authPeer = NewAuthenticator(sess.cfg.PeerID, sess.tkm, sess.isInitiator, sess.rfc7427Signatures)
sess.Logger.Log("IKE_SA", "initialised", "session", sess, "securesig", init.rfc7427Signatures)
return nil
}
func (sess *Session) SetCookie(cn *protocol.NotifyPayload) {
sess.responderCookie = cn.NotificationMessage.([]byte)
}
func (sess *Session) PostMessage(msg *Message) {
check := func() (err error) {
if err = sess.isMessageValid(msg); err != nil {
return
}
if err = DecryptMessage(msg, sess.tkm, sess.isInitiator, sess.Logger); err != nil {
return
}
if sess.isClosing {
err = errors.New("closing")
}
return
}
if err := check(); err != nil {
level.Warn(sess.Logger).Log("DROP", err)
return
}
sess.incoming <- msg
}
func (sess *Session) encode(msg *Message) (*OutgoingMessage, error) {
buf, err := msg.Encode(sess.tkm, sess.isInitiator, sess.Logger)
return &OutgoingMessage{buf}, err
}
func (sess *Session) sendMsg(msg *OutgoingMessage, err error) error {
if err != nil {
return err
}
return WriteData(sess.Conn, msg.Data, sess.Remote, sess.Logger)
}
// this can be used in genreal case, but not for INFO requests from responders -- TODO
func (sess *Session) nextID() (id uint32) {
if sess.isInitiator {
id = sess.msgIDReq.next()
} else {
id = sess.msgIDResp.next()
}
return
}
// InitMsg generates IKE_INIT
func (sess *Session) InitMsg() (*OutgoingMessage, error) {
init := InitFromSession(sess)
init.IkeHeader.MsgID = sess.nextID()
// encode
initB, err := sess.encode(init)
if err != nil {
return nil, err
}
if sess.isInitiator {
sess.initIb = initB.Data
} else {
sess.initRb = initB.Data
}
return initB, nil
}
// AuthMsg generates IKE_AUTH
func (sess *Session) AuthMsg() (*OutgoingMessage, error) {
sess.Logger.Log("TX_SELECTORS", fmt.Sprintf("[INI]%s<=>%s[RES]", sess.cfg.TsI, sess.cfg.TsR))
// make sure selectors are present
if sess.cfg.TsI == nil || sess.cfg.TsR == nil {
return nil, errors.WithStack(protocol.ERR_NO_PROPOSAL_CHOSEN)
}
auth, err := authFromSession(sess)
if err != nil {
sess.Logger.Log("ERROR", err)
return nil, err
}
auth.IkeHeader.MsgID = sess.nextID()
return sess.encode(auth)
}
func (sess *Session) RekeyMsg(child *Message) (*OutgoingMessage, error) {
child.IkeHeader.MsgID = sess.nextID()
// encode & send
return sess.encode(child)
}
// SendMsgGetReply sends a request and waits for valid reply
func (sess *Session) SendMsgGetReply(genMsg func() (*OutgoingMessage, error)) (*Message, error) {
for {
// send initiator INIT after jittered wait
if err := sess.sendMsg(genMsg()); err != nil {
return nil, err
}
// wait for reply, or timeout
msg, err := packetOrTimeOut(sess.incoming)
if err != nil {
// on timeout, send INIT again, and loop
if err == errorReplyTimedout {
continue
}
return nil, err
}
return msg, err
}
}
// utilities
// CheckError checks error for error & sends notification within INFORMATIONAL
func (sess *Session) CheckError(err error, isResponse bool) error {
if iErr, ok := errors.Cause(err).(protocol.IkeErrorCode); ok {
sess.Notify(iErr, isResponse)
}
return err
}
func (sess *Session) AuthReply(ie error) {
// send AUTH reply to peer & end IKE SA
if iErr, ok := errors.Cause(ie).(protocol.IkeErrorCode); ok {
reply := NotifyFromSession(sess, iErr, true)
reply.IkeHeader.ExchangeType = protocol.IKE_AUTH
reply.IkeHeader.MsgID = sess.nextID()
// encode & send
sess.sendMsg(sess.encode(reply))
}
}
func (sess *Session) Notify(ie protocol.IkeErrorCode, isResponse bool) {
info := NotifyFromSession(sess, ie, isResponse)
info.IkeHeader.MsgID = sess.nextID()
// encode & send
sess.sendMsg(sess.encode(info))
}
func (sess *Session) sendIkeSaDelete() {
info := DeleteFromSession(sess)
info.IkeHeader.MsgID = sess.msgIDReq.next()
// encode & send
sess.sendMsg(sess.encode(info))
}
// SendEmptyInformational can be used for periodic keepalive
func (sess *Session) SendEmptyInformational(isResponse bool) error {
info := EmptyFromSession(sess, isResponse)
if isResponse {
info.IkeHeader.MsgID = sess.msgIDResp.next()
} else {
info.IkeHeader.MsgID = sess.msgIDReq.next()
}
// encode & send
return sess.sendMsg(sess.encode(info))
}
func (sess *Session) isMessageValid(msg *Message) error {
if spi := msg.IkeHeader.SpiI; !bytes.Equal(spi, sess.IkeSpiI) {
return errors.Errorf("different initiator Spi %s", spi)
}
// Dont check Responder SPI. initiator IKE_SA_INIT does not have it
// for un-encrypted payloads, make sure that the state is correct
if msg.IkeHeader.NextPayload != protocol.PayloadTypeSK {
// TODO -
}
// check sequence numbers
seq := msg.IkeHeader.MsgID
if msg.IkeHeader.Flags.IsResponse() {
// response id ought to be same as our request id
if seq != uint32(sess.msgIDReq.get()) {
return errors.Wrap(protocol.ERR_INVALID_MESSAGE_ID,
fmt.Sprintf("unexpected response id %d, expected %+v", seq, sess.msgIDReq))
}
sess.msgIDReq.confirm()
} else {
// request id ought to be one larger than the prev response
if seq != uint32(sess.msgIDResp.get()+1) {
return errors.Wrap(protocol.ERR_INVALID_MESSAGE_ID,
fmt.Sprintf("unexpected request id %d, expected %+v", seq, sess.msgIDResp))
}
sess.msgIDResp.confirm()
}
return nil
}
// setAddresses sets tunnel endpoint addresses
func (sess *Session) setAddresses(local, remote net.Addr) error {
sess.Local = local
sess.Remote = remote
if sess.cfg.TsI != nil && sess.cfg.TsR != nil {
// selectors already configured
return nil
}
return sess.cfg.AddHostSelectors(AddrToIp(local), AddrToIp(remote), sess.isInitiator)
}
func (sess *Session) saAddr() (net.IP, net.IP) {
remoteIP := AddrToIp(sess.Remote)
localIP := AddrToIp(sess.Local)
if sess.isInitiator {
return localIP, remoteIP
}
return remoteIP, localIP
}
// AddSa adds Child SA
func (sess *Session) AddSa(sa *platform.SaParams) (err error) {
sa.Ini, sa.Res = sess.saAddr()
sess.Logger.Log("INSTALL_SA",
fmt.Sprintf("%#x<=>%#x; [%s]%s<=>%s[%s]", sa.SpiI, sa.SpiR, sa.Ini, sa.IniNet, sa.ResNet, sa.Res))
if sess.Cb.InstallChildSa != nil {
err = sess.Cb.InstallChildSa(sess, sa)
}
return
}
// RemoveSa removes Child SA
func (sess *Session) RemoveSa() (err error) {
if sess.EspSpiI == nil || sess.EspSpiR == nil {
sess.Logger.Log("REMOVE_SA", "sa was not started")
return
}
sa := removeSaParams(sess.EspSpiI, sess.EspSpiR, &sess.cfg)
sa.Ini, sa.Res = sess.saAddr()
sess.Logger.Log("REMOVE_SA",
fmt.Sprintf("%#x<=>%#x; [%s]%s<=>%s[%s]", sa.SpiI, sa.SpiR, sa.Ini, sa.IniNet, sa.ResNet, sa.Res))
if sess.Cb.RemoveChildSa != nil {
err = sess.Cb.RemoveChildSa(sess, sa)
}
return
}
func (sess *Session) installPolicy() (err error) {
pol := sess.cfg.Policy()
pol.Ini, pol.Res = sess.saAddr()
sess.Logger.Log("INSTALL_POLICY",
fmt.Sprintf("[%s]%s<=>%s[%s]", pol.Ini, pol.IniNet, pol.ResNet, pol.Res))
if sess.Cb.InstallPolicy != nil {
err = sess.Cb.InstallPolicy(sess, pol)
}
return
}
func (sess *Session) removePolicy() (err error) {
if sess.EspSpiI == nil || sess.EspSpiR == nil {
sess.Logger.Log("REMOVE_POLICY", "sa was not started")
return
}
pol := sess.cfg.Policy()
pol.Ini, pol.Res = sess.saAddr()
sess.Logger.Log("REMOVE_POLICY",
fmt.Sprintf("[%s]%s<=>%s[%s]", pol.Ini, pol.IniNet, pol.ResNet, pol.Res))
if sess.Cb.RemovePolicy != nil {
err = sess.Cb.RemovePolicy(sess, pol)
}
return
}