-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathcbc.go
More file actions
251 lines (210 loc) · 6.33 KB
/
Copy pathcbc.go
File metadata and controls
251 lines (210 loc) · 6.33 KB
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
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"encoding/binary"
"hash"
"github.com/pion/dtls/v3/internal/util"
"github.com/pion/dtls/v3/pkg/crypto/prf"
"github.com/pion/dtls/v3/pkg/protocol"
"github.com/pion/dtls/v3/pkg/protocol/recordlayer"
"golang.org/x/crypto/cryptobyte"
)
// block ciphers using cipher block chaining.
type cbcMode interface {
cipher.BlockMode
SetIV([]byte)
}
// CBC Provides an API to Encrypt/Decrypt DTLS 1.2 Packets.
type CBC struct {
writeCBC, readCBC cbcMode
writeMac, readMac []byte
h prf.HashFunc
}
// NewCBC creates a DTLS CBC Cipher.
func NewCBC(
localKey, localWriteIV, localMac, remoteKey, remoteWriteIV, remoteMac []byte,
hashFunc prf.HashFunc,
) (*CBC, error) {
writeBlock, err := aes.NewCipher(localKey)
if err != nil {
return nil, err
}
readBlock, err := aes.NewCipher(remoteKey)
if err != nil {
return nil, err
}
writeCBC, ok := cipher.NewCBCEncrypter(writeBlock, localWriteIV).(cbcMode)
if !ok {
return nil, errFailedToCast
}
readCBC, ok := cipher.NewCBCDecrypter(readBlock, remoteWriteIV).(cbcMode)
if !ok {
return nil, errFailedToCast
}
return &CBC{
writeCBC: writeCBC,
writeMac: localMac,
readCBC: readCBC,
readMac: remoteMac,
h: hashFunc,
}, nil
}
// Encrypt encrypt a DTLS RecordLayer message.
func (c *CBC) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
payload := raw[pkt.Header.MarshalSize():]
raw = raw[:pkt.Header.MarshalSize()]
blockSize := c.writeCBC.BlockSize()
// Generate + Append MAC
h := pkt.Header
var err error
var mac []byte
if h.ContentType == protocol.ContentTypeConnectionID {
mac, err = c.hmacCID(h.Epoch, h.SequenceNumber, h.Version, payload, c.writeMac, c.h, h.ConnectionID)
} else {
mac, err = c.hmac(h.Epoch, h.SequenceNumber, h.ContentType, h.Version, payload, c.writeMac, c.h)
}
if err != nil {
return nil, err
}
payload = append(payload, mac...)
// Generate + Append padding
padding := make([]byte, blockSize-len(payload)%blockSize)
paddingLen := len(padding)
for i := range paddingLen {
padding[i] = byte(paddingLen - 1) //nolint:gosec //G115
}
payload = append(payload, padding...)
// Generate IV
iv := make([]byte, blockSize)
if _, err := rand.Read(iv); err != nil {
return nil, err
}
// Set IV + Encrypt + Prepend IV
c.writeCBC.SetIV(iv)
c.writeCBC.CryptBlocks(payload, payload)
payload = append(iv, payload...) //nolint:makezero // todo: FIX
// Prepend unencrypted header with encrypted payload
raw = append(raw, payload...)
// Update recordLayer size to include IV+MAC+Padding
binary.BigEndian.PutUint16(raw[pkt.Header.MarshalSize()-2:],
uint16(len(raw)-pkt.Header.MarshalSize())) //nolint:gosec //G115
return raw, nil
}
// Decrypt decrypts a DTLS RecordLayer message.
func (c *CBC) Decrypt(header recordlayer.Header, in []byte) ([]byte, error) {
blockSize := c.readCBC.BlockSize()
mac := c.h()
if err := header.Unmarshal(in); err != nil {
return nil, err
}
body := in[header.MarshalSize():]
switch {
case header.ContentType == protocol.ContentTypeChangeCipherSpec:
// Nothing to encrypt with ChangeCipherSpec
return in, nil
case len(body)%blockSize != 0 || len(body) < blockSize+util.Max(mac.Size()+1, blockSize):
return nil, errNotEnoughRoomForNonce
}
// Set + remove per record IV
c.readCBC.SetIV(body[:blockSize])
body = body[blockSize:]
// Decrypt
c.readCBC.CryptBlocks(body, body)
// Padding+MAC needs to be checked in constant time
// Otherwise we reveal information about the level of correctness
paddingLen, paddingGood := examinePadding(body)
if paddingGood != 255 {
return nil, errInvalidMAC
}
macSize := mac.Size()
if len(body) < macSize {
return nil, errInvalidMAC
}
dataEnd := len(body) - macSize - paddingLen
expectedMAC := body[dataEnd : dataEnd+macSize]
var err error
var actualMAC []byte
if header.ContentType == protocol.ContentTypeConnectionID {
actualMAC, err = c.hmacCID(
header.Epoch, header.SequenceNumber, header.Version, body[:dataEnd], c.readMac, c.h, header.ConnectionID,
)
} else {
actualMAC, err = c.hmac(
header.Epoch, header.SequenceNumber, header.ContentType, header.Version, body[:dataEnd], c.readMac, c.h,
)
}
// Compute Local MAC and compare
if err != nil || !hmac.Equal(actualMAC, expectedMAC) {
return nil, errInvalidMAC
}
return append(in[:header.MarshalSize()], body[:dataEnd]...), nil
}
func (c *CBC) hmac(
epoch uint16,
sequenceNumber uint64,
contentType protocol.ContentType,
protocolVersion protocol.Version,
payload []byte,
key []byte,
hf func() hash.Hash,
) ([]byte, error) {
hmacHash := hmac.New(hf, key)
msg := make([]byte, 13)
binary.BigEndian.PutUint16(msg, epoch)
util.PutBigEndianUint48(msg[2:], sequenceNumber)
msg[8] = byte(contentType)
msg[9] = protocolVersion.Major
msg[10] = protocolVersion.Minor
binary.BigEndian.PutUint16(msg[11:], uint16(len(payload))) //nolint:gosec //G115
if _, err := hmacHash.Write(msg); err != nil {
return nil, err
}
if _, err := hmacHash.Write(payload); err != nil {
return nil, err
}
return hmacHash.Sum(nil), nil
}
// hmacCID calculates a MAC according to
// https://datatracker.ietf.org/doc/html/rfc9146#section-5.1
func (c *CBC) hmacCID(
epoch uint16,
sequenceNumber uint64,
protocolVersion protocol.Version,
payload []byte,
key []byte,
hf func() hash.Hash,
cid []byte,
) ([]byte, error) {
// Must unmarshal inner plaintext in orde to perform MAC.
ip := &recordlayer.InnerPlaintext{}
if err := ip.Unmarshal(payload); err != nil {
return nil, err
}
hmacHash := hmac.New(hf, key)
var msg cryptobyte.Builder
msg.AddUint64(seqNumPlaceholder)
msg.AddUint8(uint8(protocol.ContentTypeConnectionID))
msg.AddUint8(uint8(len(cid))) //nolint:gosec //G115
msg.AddUint8(uint8(protocol.ContentTypeConnectionID))
msg.AddUint8(protocolVersion.Major)
msg.AddUint8(protocolVersion.Minor)
msg.AddUint16(epoch)
msg.AddUint48(sequenceNumber)
msg.AddBytes(cid)
msg.AddUint16(uint16(len(payload))) //nolint:gosec //G115
msg.AddBytes(ip.Content)
msg.AddUint8(uint8(ip.RealType))
msg.AddBytes(make([]byte, ip.Zeros))
if _, err := hmacHash.Write(msg.BytesOrPanic()); err != nil {
return nil, err
}
if _, err := hmacHash.Write(payload); err != nil {
return nil, err
}
return hmacHash.Sum(nil), nil
}