-
Notifications
You must be signed in to change notification settings - Fork 6
/
controller.go
239 lines (203 loc) · 7.59 KB
/
controller.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
package datachannel
import (
"bytes"
"crypto/hmac"
"fmt"
"strings"
"github.com/apex/log"
"github.com/ooni/minivpn/internal/bytesx"
"github.com/ooni/minivpn/internal/model"
"github.com/ooni/minivpn/internal/runtimex"
"github.com/ooni/minivpn/internal/session"
"github.com/ooni/minivpn/pkg/config"
)
// dataChannelHandler manages the data "channel".
type dataChannelHandler interface {
setupKeys(*session.DataChannelKey) error
writePacket([]byte) (*model.Packet, error)
readPacket(*model.Packet) ([]byte, error)
decodeEncryptedPayload([]byte, *dataChannelState) (*encryptedData, error)
encryptAndEncodePayload([]byte, *dataChannelState) ([]byte, error)
}
// DataChannel represents the data "channel", that will encrypt and decrypt the tunnel payloads.
// data implements the dataHandler interface.
type DataChannel struct {
options *config.OpenVPNOptions
sessionManager *session.Manager
state *dataChannelState
decodeFn func(model.Logger, []byte, *session.Manager, *dataChannelState) (*encryptedData, error)
encryptEncodeFn func(model.Logger, []byte, *session.Manager, *dataChannelState) ([]byte, error)
decryptFn func([]byte, *encryptedData) ([]byte, error)
log model.Logger
}
var _ dataChannelHandler = &DataChannel{} // Ensure that we implement dataChannelHandler
// NewDataChannelFromOptions returns a new data object, initialized with the
// options given. it also returns any error raised.
func NewDataChannelFromOptions(logger model.Logger,
opt *config.OpenVPNOptions,
sessionManager *session.Manager) (*DataChannel, error) {
runtimex.Assert(opt != nil, "openvpn datachannel: opts cannot be nil")
runtimex.Assert(opt != nil, "openvpn datachannel: opts cannot be nil")
runtimex.Assert(len(opt.Cipher) != 0, "need a configured cipher option")
runtimex.Assert(len(opt.Auth) != 0, "need a configured auth option")
state := &dataChannelState{}
data := &DataChannel{
options: opt,
sessionManager: sessionManager,
state: state,
}
dataCipher, err := newDataCipherFromCipherSuite(opt.Cipher)
if err != nil {
return data, err
}
data.state.dataCipher = dataCipher
switch dataCipher.isAEAD() {
case true:
data.decodeFn = decodeEncryptedPayloadAEAD
data.encryptEncodeFn = encryptAndEncodePayloadAEAD
case false:
data.decodeFn = decodeEncryptedPayloadNonAEAD
data.encryptEncodeFn = encryptAndEncodePayloadNonAEAD
}
hmacHash, ok := newHMACFactory(strings.ToLower(opt.Auth))
if !ok {
return data, fmt.Errorf("%w: %s", ErrInitError, fmt.Sprintf("no such mac: %v", opt.Auth))
}
data.state.hash = hmacHash
data.decryptFn = state.dataCipher.decrypt
logger.Info(fmt.Sprintf("Cipher: %s", opt.Cipher))
logger.Info(fmt.Sprintf("Auth: %s", opt.Auth))
return data, nil
}
// DecodeEncryptedPayload calls the corresponding function for AEAD or Non-AEAD decryption.
func (d *DataChannel) decodeEncryptedPayload(b []byte, dcs *dataChannelState) (*encryptedData, error) {
return d.decodeFn(d.log, b, d.sessionManager, dcs)
}
// setSetupKeys performs the key expansion from the local and remote
// keySources, initializing the data channel state.
func (d *DataChannel) setupKeys(dck *session.DataChannelKey) error {
runtimex.Assert(dck != nil, "data channel key cannot be nil")
if !dck.Ready() {
return fmt.Errorf("%w: %s", errDataChannelKey, "key not ready")
}
master := prf(
dck.Local().PreMaster[:],
[]byte("OpenVPN master secret"),
dck.Local().R1[:],
dck.Remote().R1[:],
[]byte{}, []byte{},
48)
keys := prf(
master,
[]byte("OpenVPN key expansion"),
dck.Local().R2[:],
dck.Remote().R2[:],
d.sessionManager.LocalSessionID(),
d.sessionManager.RemoteSessionID(),
256)
var keyLocal, hmacLocal, keyRemote, hmacRemote keySlot
copy(keyLocal[:], keys[0:64])
copy(hmacLocal[:], keys[64:128])
copy(keyRemote[:], keys[128:192])
copy(hmacRemote[:], keys[192:256])
d.state.cipherKeyLocal = keyLocal
d.state.hmacKeyLocal = hmacLocal
d.state.cipherKeyRemote = keyRemote
d.state.hmacKeyRemote = hmacRemote
log.Debugf("Cipher key local: %x", keyLocal)
log.Debugf("Cipher key remote: %x", keyRemote)
log.Debugf("Hmac key local: %x", hmacLocal)
log.Debugf("Hmac key remote: %x", hmacRemote)
hashSize := d.state.hash().Size()
d.state.hmacLocal = hmac.New(d.state.hash, hmacLocal[:hashSize])
d.state.hmacRemote = hmac.New(d.state.hash, hmacRemote[:hashSize])
log.Info("Key derivation OK")
return nil
}
//
// write + encrypt
//
func (d *DataChannel) writePacket(payload []byte) (*model.Packet, error) {
runtimex.Assert(d.state != nil, "data: nil state")
runtimex.Assert(d.state.dataCipher != nil, "data.state: nil dataCipher")
var err error
switch d.state.dataCipher.isAEAD() {
case false: // non-aead
localPacketID, _ := d.sessionManager.LocalDataPacketID()
payload = prependPacketID(localPacketID, payload)
case true:
}
payload, err = doCompress(payload, d.options.Compress)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCannotEncrypt, err)
}
// encryptAndEncodePayload adds padding, if needed, and it also includes the
// opcode/keyid and peer-id headers and, if used, any authenticated
// parts in the packet.
encrypted, err := d.encryptAndEncodePayload(payload, d.state)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCannotEncrypt, err)
}
// TODO(ainghazal): increment counter for used bytes
// and trigger renegotiation if we're near the end of the key useful lifetime.
packet := model.NewPacket(model.P_DATA_V2, d.sessionManager.CurrentKeyID(), encrypted)
peerid := &bytes.Buffer{}
bytesx.WriteUint24(peerid, uint32(d.sessionManager.TunnelInfo().PeerID))
packet.PeerID = model.PeerID(peerid.Bytes())
return packet, nil
}
// encrypt calls the corresponding function for AEAD or Non-AEAD decryption.
// Due to the particularities of the iv generation on each of the modes, encryption and encoding are
// done together in the same function.
func (d *DataChannel) encryptAndEncodePayload(plaintext []byte, dcs *dataChannelState) ([]byte, error) {
runtimex.Assert(dcs != nil, "datachanelState is nil")
runtimex.Assert(dcs.dataCipher != nil, "dcs.dataCipher is nil")
if len(plaintext) == 0 {
return []byte{}, fmt.Errorf("%w: nothing to encrypt", ErrCannotEncrypt)
}
padded, err := doPadding(plaintext, d.options.Compress, dcs.dataCipher.blockSize())
if err != nil {
return []byte{}, fmt.Errorf("%w: %s", ErrCannotEncrypt, err)
}
encrypted, err := d.encryptEncodeFn(d.log, padded, d.sessionManager, d.state)
if err != nil {
return []byte{}, fmt.Errorf("%w: %s", ErrCannotEncrypt, err)
}
return encrypted, nil
}
//
// read + decrypt
//
func (d *DataChannel) readPacket(p *model.Packet) ([]byte, error) {
if len(p.Payload) == 0 {
return nil, fmt.Errorf("%w: %s", ErrCannotDecrypt, "empty payload")
}
runtimex.Assert(p.IsData(), "ReadPacket expects data packet")
plaintext, err := d.decrypt(p.Payload)
if err != nil {
return nil, err
}
// get plaintext payload from the decrypted plaintext
return maybeDecompress(plaintext, d.state, d.options)
}
func (d *DataChannel) decrypt(encrypted []byte) ([]byte, error) {
if d.decryptFn == nil {
return []byte{}, ErrInitError
}
if len(d.state.hmacKeyRemote) == 0 {
d.log.Warn("decrypt: not ready yet")
return nil, ErrCannotDecrypt
}
encryptedData, err := d.decodeEncryptedPayload(encrypted, d.state)
if err != nil {
return []byte{}, fmt.Errorf("%w: %s", ErrCannotDecrypt, err)
}
if len(encryptedData.ciphertext) == 0 {
return []byte{}, fmt.Errorf("%w: nothing to decrypt", ErrCannotDecrypt)
}
plainText, err := d.decryptFn(d.state.cipherKeyRemote[:], encryptedData)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCannotDecrypt, err)
}
return plainText, nil
}