-
Notifications
You must be signed in to change notification settings - Fork 3
/
ike.go
294 lines (257 loc) · 7.79 KB
/
ike.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
package ike
import (
"crypto/hmac"
"github.com/pkg/errors"
"github.com/free5gc/ike/message"
"github.com/free5gc/ike/security"
)
func EncodeEncrypt(
ikeMsg *message.IKEMessage,
ikesaKey *security.IKESAKey,
role message.Role,
) ([]byte, error) {
if ikesaKey != nil {
err := encryptMsg(ikeMsg, ikesaKey, role)
if err != nil {
return nil, errors.Wrapf(err, "IKE encode encrypt")
}
}
msg, err := ikeMsg.Encode()
return msg, errors.Wrapf(err, "IKE encode")
}
// Before use this function, need to use IKEMessage.Encode first
// and get IKESA
func DecodeDecrypt(
msg []byte,
ikeHeader *message.IKEHeader,
ikesaKey *security.IKESAKey,
role message.Role,
) (*message.IKEMessage, error) {
ikeMsg := new(message.IKEMessage)
var err error
if ikeHeader == nil {
err = ikeMsg.Decode(msg)
if err != nil {
return nil, errors.Wrapf(err, "DecodeDecrypt()")
}
} else {
ikeMsg.IKEHeader = ikeHeader
err = ikeMsg.DecodePayload(msg[message.IKE_HEADER_LEN:])
if err != nil {
return nil, errors.Wrapf(err, "DecodeDecrypt()")
}
}
if ikeMsg.Payloads[0].Type() == message.TypeSK {
if ikesaKey == nil {
return nil, errors.Errorf("IKE decode decrypt: need ikesaKey to decrypt")
}
ikeMsg, err = decryptMsg(msg, ikeMsg, ikesaKey, role)
if err != nil {
return nil, errors.Wrapf(err, "IKE decode decrypt")
}
}
return ikeMsg, nil
}
func verifyIntegrity(
originData []byte,
checksum []byte,
ikesaKey *security.IKESAKey,
role message.Role,
) error {
expectChecksum, err := calculateIntegrity(ikesaKey, role, originData)
if err != nil {
return errors.Wrapf(err, "verifyIntegrity[%d]", ikesaKey.IntegInfo.TransformID())
}
// fmt.Printf("Calculated checksum:\n%s\nReceived checksum:\n%s",
// hex.Dump(expectChecksum), hex.Dump(checksum))
if !hmac.Equal(checksum, expectChecksum) {
return errors.Errorf("invalid checksum")
}
return nil
}
func calculateIntegrity(
ikesaKey *security.IKESAKey,
role message.Role,
originData []byte,
) ([]byte, error) {
outputLen := ikesaKey.IntegInfo.GetOutputLength()
var calculatedChecksum []byte
if role == message.Role_Initiator {
if ikesaKey.Integ_i == nil {
return nil, errors.Errorf("CalcIKEChecksum() : IKE SA have nil Integ_r")
}
ikesaKey.Integ_i.Reset()
if _, err := ikesaKey.Integ_i.Write(originData); err != nil {
return nil, errors.Wrapf(err, "CalcIKEChecksum()")
}
calculatedChecksum = ikesaKey.Integ_i.Sum(nil)
} else {
if ikesaKey.Integ_r == nil {
return nil, errors.Errorf("CalcIKEChecksum() : IKE SA have nil Integ_i")
}
ikesaKey.Integ_r.Reset()
if _, err := ikesaKey.Integ_r.Write(originData); err != nil {
return nil, errors.Wrapf(err, "CalcIKEChecksum()")
}
calculatedChecksum = ikesaKey.Integ_r.Sum(nil)
}
return calculatedChecksum[:outputLen], nil
}
func encryptPayload(
plainText []byte,
ikesaKey *security.IKESAKey,
role message.Role,
) ([]byte, error) {
var cipherText []byte
if role == message.Role_Initiator {
var err error
if cipherText, err = ikesaKey.Encr_i.Encrypt(plainText); err != nil {
return nil, errors.Wrapf(err, "encryptPayload()")
}
} else {
var err error
if cipherText, err = ikesaKey.Encr_r.Encrypt(plainText); err != nil {
return nil, errors.Wrapf(err, "encryptPayload()")
}
}
return cipherText, nil
}
func decryptPayload(
cipherText []byte,
ikesaKey *security.IKESAKey,
role message.Role,
) ([]byte, error) {
var plainText []byte
if role == message.Role_Initiator {
var err error
if plainText, err = ikesaKey.Encr_r.Decrypt(cipherText); err != nil {
return nil, errors.Wrapf(err, "decryptPayload()")
}
} else {
var err error
if plainText, err = ikesaKey.Encr_i.Decrypt(cipherText); err != nil {
return nil, errors.Wrapf(err, "decryptPayload()")
}
}
return plainText, nil
}
func decryptMsg(
msg []byte,
ikeMsg *message.IKEMessage,
ikesaKey *security.IKESAKey,
role message.Role,
) (*message.IKEMessage, error) {
// Check parameters
if ikesaKey == nil {
return nil, errors.Errorf("decryptMsg(): IKE SA is nil")
}
if msg == nil {
return nil, errors.Errorf("decryptMsg(): msg is nil")
}
if ikeMsg == nil {
return nil, errors.Errorf("decryptMsg(): IKE encrypted payload is nil")
}
// Check if the context contain needed data
if ikesaKey.IntegInfo == nil {
return nil, errors.Errorf("decryptMsg(): No integrity algorithm specified")
}
if ikesaKey.EncrInfo == nil {
return nil, errors.Errorf("decryptMsg(): No encryption algorithm specified")
}
if ikesaKey.Integ_i == nil {
return nil, errors.Errorf("decryptMsg(): No initiator's integrity key")
}
if ikesaKey.Encr_i == nil {
return nil, errors.Errorf("decryptMsg(): No initiator's encryption key")
}
var encryptedPayload *message.Encrypted
for _, ikePayload := range ikeMsg.Payloads {
switch ikePayload.Type() {
case message.TypeSK:
encryptedPayload = ikePayload.(*message.Encrypted)
default:
return nil, errors.Errorf(
"Get IKE payload (type %d), this payload will not be decode",
ikePayload.Type())
}
}
checksumLength := ikesaKey.IntegInfo.GetOutputLength()
// Checksum
checksum := encryptedPayload.EncryptedData[len(encryptedPayload.EncryptedData)-checksumLength:]
err := verifyIntegrity(msg[:len(msg)-checksumLength], checksum, ikesaKey, !role)
if err != nil {
return nil, errors.Wrapf(err, "decryptMsg(): verify integrity")
}
// Decrypt
encryptedData := encryptedPayload.EncryptedData[:len(encryptedPayload.EncryptedData)-checksumLength]
plainText, err := decryptPayload(encryptedData, ikesaKey, role)
if err != nil {
return nil, errors.Wrapf(err, "decryptMsg(): Error decrypting message")
}
var decryptedPayloads message.IKEPayloadContainer
err = decryptedPayloads.Decode(encryptedPayload.NextPayload, plainText)
if err != nil {
return nil, errors.Wrapf(err, "decryptMsg(): Decoding decrypted payload failed")
}
ikeMsg.Payloads.Reset()
ikeMsg.Payloads = append(ikeMsg.Payloads, decryptedPayloads...)
return ikeMsg, nil
}
func encryptMsg(
ikeMsg *message.IKEMessage,
ikesaKey *security.IKESAKey,
role message.Role,
) error {
if ikeMsg == nil {
return errors.Errorf("encryptMsg(): Response IKE message is nil")
}
if ikesaKey == nil {
return errors.Errorf("encryptMsg(): IKE SA is nil")
}
ikePayloads := ikeMsg.Payloads
// Check if the context contain needed data
if ikesaKey.IntegInfo == nil {
return errors.Errorf("encryptMsg(): No integrity algorithm specified")
}
if ikesaKey.EncrInfo == nil {
return errors.Errorf("encryptMsg(): No encryption algorithm specified")
}
if ikesaKey.Integ_r == nil {
return errors.Errorf("encryptMsg(): No responder's integrity key")
}
if ikesaKey.Encr_r == nil {
return errors.Errorf("encryptMsg(): No responder's encryption key")
}
checksumLength := ikesaKey.IntegInfo.GetOutputLength()
plainTextPayload, err := ikePayloads.Encode()
if err != nil {
return errors.Wrapf(err, "encryptMsg(): Encoding IKE payload failed.")
}
// Encrypting
encryptedData, err := encryptPayload(plainTextPayload, ikesaKey, role)
if err != nil {
return errors.Wrapf(err, "encryptMsg(): Error encrypting message")
}
encryptedData = append(encryptedData, make([]byte, checksumLength)...)
ikeMsg.Payloads.Reset()
var encrNextPayloadType message.IkePayloadType
if len(ikePayloads) == 0 {
encrNextPayloadType = message.NoNext
} else {
encrNextPayloadType = ikePayloads[0].Type()
}
sk := ikeMsg.Payloads.BuildEncrypted(encrNextPayloadType, encryptedData)
// Calculate checksum
ikeMsgData, err := ikeMsg.Encode()
if err != nil {
return errors.Wrapf(err, "encryptMsg(): Encoding IKE message error")
}
checksumOfMessage, err := calculateIntegrity(ikesaKey, role,
ikeMsgData[:len(ikeMsgData)-checksumLength])
if err != nil {
return errors.Wrapf(err, "encryptMsg(): Error calculating checksum")
}
checksumField := sk.EncryptedData[len(sk.EncryptedData)-checksumLength:]
copy(checksumField, checksumOfMessage)
return nil
}