-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathsrtp_cipher_aead_aes_gcm.go
More file actions
391 lines (335 loc) · 11 KB
/
srtp_cipher_aead_aes_gcm.go
File metadata and controls
391 lines (335 loc) · 11 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
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
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"fmt"
"github.com/pion/rtp"
)
type srtpCipherAeadAesGcm struct {
protectionProfileWithArgs
srtpCipher, srtcpCipher cipher.AEAD
srtpSessionSalt, srtcpSessionSalt []byte
mki []byte
srtpEncrypted, srtcpEncrypted bool
useCryptex bool
// Pre-allocated buffers for IV to avoid heap allocation in hot path
rtpIV [12]byte
rtcpIV [12]byte
}
func newSrtpCipherAeadAesGcm(
profile protectionProfileWithArgs,
masterKey, masterSalt, mki []byte,
encryptSRTP, encryptSRTCP, useCryptex bool,
) (*srtpCipherAeadAesGcm, error) {
srtpCipher := &srtpCipherAeadAesGcm{
protectionProfileWithArgs: profile,
srtpEncrypted: encryptSRTP,
srtcpEncrypted: encryptSRTCP,
useCryptex: useCryptex,
}
srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
}
srtpBlock, err := aes.NewCipher(srtpSessionKey)
if err != nil {
return nil, err
}
srtpCipher.srtpCipher, err = cipher.NewGCM(srtpBlock)
if err != nil {
return nil, err
}
srtcpSessionKey, err := aesCmKeyDerivation(labelSRTCPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
}
srtcpBlock, err := aes.NewCipher(srtcpSessionKey)
if err != nil {
return nil, err
}
srtpCipher.srtcpCipher, err = cipher.NewGCM(srtcpBlock)
if err != nil {
return nil, err
}
if srtpCipher.srtpSessionSalt, err = aesCmKeyDerivation(
labelSRTPSalt, masterKey, masterSalt, 0, len(masterSalt),
); err != nil {
return nil, err
} else if srtpCipher.srtcpSessionSalt, err = aesCmKeyDerivation(
labelSRTCPSalt, masterKey, masterSalt, 0, len(masterSalt),
); err != nil {
return nil, err
}
mkiLen := len(mki)
if mkiLen > 0 {
srtpCipher.mki = make([]byte, mkiLen)
copy(srtpCipher.mki, mki)
}
return srtpCipher, nil
}
func (s *srtpCipherAeadAesGcm) encryptRTP(
dst []byte,
header *rtp.Header,
headerLen int,
plaintext []byte,
roc uint32,
rocInAuthTag bool,
) (ciphertext []byte, err error) {
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
payloadLen := len(plaintext) - headerLen
authPartLen := headerLen + payloadLen + authTagLen
dstLen := authPartLen + len(s.mki)
if rocInAuthTag {
dstLen += 4
}
insertEmptyExtHdr := needsEmptyExtensionHeader(s.useCryptex, header)
if insertEmptyExtHdr {
dstLen += extensionHeaderSize
}
dst = growBufferSize(dst, dstLen)
sameBuffer := isSameBuffer(dst, plaintext)
if insertEmptyExtHdr {
plaintext = insertEmptyExtensionHeader(dst, plaintext, sameBuffer, header)
sameBuffer = true
headerLen += extensionHeaderSize
}
err = s.doEncryptRTP(dst, header, headerLen, plaintext, roc, rocInAuthTag, sameBuffer, payloadLen, authPartLen)
if err != nil {
return nil, err
}
return dst, nil
}
func (s *srtpCipherAeadAesGcm) doEncryptRTP(dst []byte, header *rtp.Header, headerLen int, plaintext []byte, roc uint32,
rocInAuthTag bool, sameBuffer bool, payloadLen int, authPartLen int,
) error {
s.rtpInitializationVector(header, roc)
encrypt := func(dst, plaintext []byte, headerLen int) error {
s.srtpCipher.Seal(dst[headerLen:headerLen], s.rtpIV[:], plaintext[headerLen:], plaintext[:headerLen])
return nil
}
switch {
case s.useCryptex && header.Extension:
err := encryptCryptexRTP(dst, plaintext, sameBuffer, header, encrypt)
if err != nil {
return err
}
case s.srtpEncrypted:
// Copy the header unencrypted.
if !sameBuffer {
copy(dst, plaintext[:headerLen])
}
s.srtpCipher.Seal(dst[headerLen:headerLen], s.rtpIV[:], plaintext[headerLen:], dst[:headerLen])
default:
clearLen := headerLen + payloadLen
if !sameBuffer {
copy(dst, plaintext)
}
s.srtpCipher.Seal(dst[clearLen:clearLen], s.rtpIV[:], nil, dst[:clearLen])
}
// Add MKI after the encrypted payload
if len(s.mki) > 0 {
copy(dst[authPartLen:], s.mki)
}
if rocInAuthTag {
binary.BigEndian.PutUint32(dst[len(dst)-4:], roc)
}
return nil
}
func (s *srtpCipherAeadAesGcm) decryptRTP(
dst, ciphertext []byte,
header *rtp.Header,
headerLen int,
roc uint32,
rocInAuthTag bool,
) ([]byte, error) {
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
rocLen := 0
if rocInAuthTag {
rocLen = 4
}
nDst := len(ciphertext) - authTagLen - len(s.mki) - rocLen
if nDst < headerLen {
// Size of ciphertext is shorter than AEAD auth tag len.
return nil, ErrFailedToVerifyAuthTag
}
dst = growBufferSize(dst, nDst)
sameBuffer := isSameBuffer(dst, ciphertext)
nEnd := len(ciphertext) - len(s.mki) - rocLen
err = s.doDecryptRTP(dst, ciphertext, header, headerLen, roc, sameBuffer, nEnd, authTagLen)
if err != nil {
return nil, err
}
return dst, nil
}
func (s *srtpCipherAeadAesGcm) doDecryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int, roc uint32,
sameBuffer bool, nEnd int, authTagLen int,
) error {
s.rtpInitializationVector(header, roc)
decrypt := func(dst, ciphertext []byte, headerLen int) error {
_, err := s.srtpCipher.Open(dst[headerLen:headerLen], s.rtpIV[:], ciphertext[headerLen:nEnd], ciphertext[:headerLen])
return err
}
switch {
case isCryptexPacket(header):
err := decryptCryptexRTP(dst, ciphertext, sameBuffer, header, headerLen, decrypt)
if err != nil {
return fmt.Errorf("%w: %w", ErrFailedToVerifyAuthTag, err)
}
case s.srtpEncrypted:
if err := decrypt(dst, ciphertext[:nEnd], headerLen); err != nil {
return fmt.Errorf("%w: %w", ErrFailedToVerifyAuthTag, err)
}
// Copy the header unencrypted.
if !sameBuffer {
copy(dst[:headerLen], ciphertext[:headerLen])
}
default:
nDataEnd := nEnd - authTagLen
if _, err := s.srtpCipher.Open(
nil, s.rtpIV[:], ciphertext[nDataEnd:nEnd], ciphertext[:nDataEnd],
); err != nil {
return fmt.Errorf("%w: %w", ErrFailedToVerifyAuthTag, err)
}
// Copy the header and payload unencrypted.
if !sameBuffer {
copy(dst, ciphertext[:nDataEnd])
}
}
return nil
}
func (s *srtpCipherAeadAesGcm) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) {
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
aadPos := len(decrypted) + authTagLen
// Grow the given buffer to fit the output.
dst = growBufferSize(dst, aadPos+srtcpIndexSize+len(s.mki))
sameBuffer := isSameBuffer(dst, decrypted)
s.rtcpInitializationVector(srtcpIndex, ssrc)
if s.srtcpEncrypted {
aad := s.rtcpAdditionalAuthenticatedData(decrypted, srtcpIndex)
if !sameBuffer {
// Copy the header unencrypted.
copy(dst[:srtcpHeaderSize], decrypted[:srtcpHeaderSize])
}
// Copy index to the proper place.
copy(dst[aadPos:aadPos+srtcpIndexSize], aad[8:12])
s.srtcpCipher.Seal(dst[srtcpHeaderSize:srtcpHeaderSize], s.rtcpIV[:], decrypted[srtcpHeaderSize:], aad[:])
} else {
// Copy the packet unencrypted.
if !sameBuffer {
copy(dst, decrypted)
}
// Append the SRTCP index to the end of the packet - this will form the AAD.
binary.BigEndian.PutUint32(dst[len(decrypted):], srtcpIndex)
// Generate the authentication tag.
tag := make([]byte, authTagLen)
s.srtcpCipher.Seal(tag[0:0], s.rtcpIV[:], nil, dst[:len(decrypted)+srtcpIndexSize])
// Copy index to the proper place.
copy(dst[aadPos:], dst[len(decrypted):len(decrypted)+srtcpIndexSize])
// Copy the auth tag after RTCP payload.
copy(dst[len(decrypted):], tag)
}
copy(dst[aadPos+srtcpIndexSize:], s.mki)
return dst, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ssrc uint32) ([]byte, error) {
aadPos := len(encrypted) - srtcpIndexSize - len(s.mki)
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
nDst := aadPos - authTagLen
if nDst < 0 {
// Size of ciphertext is shorter than AEAD auth tag len.
return nil, ErrFailedToVerifyAuthTag
}
dst = growBufferSize(dst, nDst)
sameBuffer := isSameBuffer(dst, encrypted)
isEncrypted := encrypted[aadPos]&srtcpEncryptionFlag != 0
s.rtcpInitializationVector(srtcpIndex, ssrc)
if isEncrypted {
aad := s.rtcpAdditionalAuthenticatedData(encrypted, srtcpIndex)
if _, err := s.srtcpCipher.Open(dst[srtcpHeaderSize:srtcpHeaderSize], s.rtcpIV[:], encrypted[srtcpHeaderSize:aadPos],
aad[:]); err != nil {
return nil, fmt.Errorf("%w: %w", ErrFailedToVerifyAuthTag, err)
}
} else {
// Prepare AAD for received packet.
dataEnd := aadPos - authTagLen
aad := make([]byte, dataEnd+4)
copy(aad, encrypted[:dataEnd])
copy(aad[dataEnd:], encrypted[aadPos:aadPos+4])
// Verify the auth tag.
if _, err := s.srtcpCipher.Open(nil, s.rtcpIV[:], encrypted[dataEnd:aadPos], aad); err != nil {
return nil, fmt.Errorf("%w: %w", ErrFailedToVerifyAuthTag, err)
}
// Copy the unencrypted payload.
if !sameBuffer {
copy(dst[srtcpHeaderSize:], encrypted[srtcpHeaderSize:dataEnd])
}
}
// Copy the header unencrypted.
if !sameBuffer {
copy(dst[:srtcpHeaderSize], encrypted[:srtcpHeaderSize])
}
return dst, nil
}
// The 12-octet IV used by AES-GCM SRTP is formed by first concatenating
// 2 octets of zeroes, the 4-octet SSRC, the 4-octet rollover counter
// (ROC), and the 2-octet sequence number (SEQ). The resulting 12-octet
// value is then XORed to the 12-octet salt to form the 12-octet IV.
//
// https://tools.ietf.org/html/rfc7714#section-8.1
func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc uint32) {
s.rtpIV = [12]byte{}
binary.BigEndian.PutUint32(s.rtpIV[2:], header.SSRC)
binary.BigEndian.PutUint32(s.rtpIV[6:], roc)
binary.BigEndian.PutUint16(s.rtpIV[10:], header.SequenceNumber)
for i := range s.rtpIV {
s.rtpIV[i] ^= s.srtpSessionSalt[i]
}
}
// The 12-octet IV used by AES-GCM SRTCP is formed by first
// concatenating 2 octets of zeroes, the 4-octet SSRC identifier,
// 2 octets of zeroes, a single "0" bit, and the 31-bit SRTCP index.
// The resulting 12-octet value is then XORed to the 12-octet salt to
// form the 12-octet IV.
//
// https://tools.ietf.org/html/rfc7714#section-9.1
func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc uint32) {
s.rtcpIV = [12]byte{}
binary.BigEndian.PutUint32(s.rtcpIV[2:], ssrc)
binary.BigEndian.PutUint32(s.rtcpIV[8:], srtcpIndex)
for i := range s.rtcpIV {
s.rtcpIV[i] ^= s.srtcpSessionSalt[i]
}
}
// In an SRTCP packet, a 1-bit Encryption flag is prepended to the
// 31-bit SRTCP index to form a 32-bit value we shall call the
// "ESRTCP word"
//
// https://tools.ietf.org/html/rfc7714#section-17
func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) [12]byte {
var aad [12]byte
copy(aad[:], rtcpPacket[:8])
binary.BigEndian.PutUint32(aad[8:], srtcpIndex)
aad[8] |= srtcpEncryptionFlag
return aad
}
func (s *srtpCipherAeadAesGcm) getRTCPIndex(in []byte) uint32 {
return binary.BigEndian.Uint32(in[len(in)-len(s.mki)-srtcpIndexSize:]) &^ (srtcpEncryptionFlag << 24)
}