-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathcontext.go
More file actions
418 lines (353 loc) · 11.9 KB
/
context.go
File metadata and controls
418 lines (353 loc) · 11.9 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
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
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"bytes"
"fmt"
"github.com/pion/transport/v4/replaydetector"
)
const (
labelSRTPEncryption = 0x00
labelSRTPAuthenticationTag = 0x01
labelSRTPSalt = 0x02
labelSRTCPEncryption = 0x03
labelSRTCPAuthenticationTag = 0x04
labelSRTCPSalt = 0x05
maxSequenceNumber = 65535
maxROC = (1 << 32) - 1
seqNumMedian = 1 << 15
seqNumMax = 1 << 16
)
// Encrypt/Decrypt state for a single SRTP SSRC.
type srtpSSRCState struct {
ssrc uint32
rolloverHasProcessed bool
index uint64
replayDetector replaydetector.ReplayDetector
}
// Encrypt/Decrypt state for a single SRTCP SSRC.
type srtcpSSRCState struct {
srtcpIndex uint32
ssrc uint32
replayDetector replaydetector.ReplayDetector
}
// RCCMode is the mode of Roll-over Counter Carrying Transform from RFC 4771.
type RCCMode int
const (
// RCCModeNone is the default mode.
RCCModeNone RCCMode = iota
// RCCMode1 is RCCm1 mode from RFC 4771. In this mode ROC and truncated auth tag is sent every R-th packet,
// and no auth tag in other ones. This mode is not supported by pion/srtp.
RCCMode1
// RCCMode2 is RCCm2 mode from RFC 4771. In this mode ROC and truncated auth tag is sent every R-th packet,
// and full auth tag in other ones. This mode is supported for AES-CM and NULL profiles only.
RCCMode2
// RCCMode3 is RCCm3 mode from RFC 4771. In this mode ROC is sent every R-th packet (without truncated auth tag),
// and no auth tag in other ones. This mode is supported for AES-GCM profiles only.
RCCMode3
)
// CryptexMode is the mode of Cryptex support for SRTP packets from RFC 9335.
type CryptexMode int
const (
// CryptexModeDisabled (default) disables Cryptex support. Received Cryptex SRTP packets with encrypted
// CSRCs and header extensions will be rejected with an error.
CryptexModeDisabled CryptexMode = 0
// CryptexModeEnabled enables Cryptex support when SRTP packets are encrypted. Received SRTP packets
// with unencrypted CSRCs and header extensions will be accepted and decrypted.
CryptexModeEnabled CryptexMode = 1
// CryptexModeRequired enables Cryptex support when SRTP packets are encrypted. Received SRTP packets
// with unencrypted CSRCs and header extensions will be rejected with an error.
CryptexModeRequired CryptexMode = 2
)
// Context represents a SRTP cryptographic context.
// Context can only be used for one-way operations.
// it must either used ONLY for encryption or ONLY for decryption.
// Note that Context does not provide any concurrency protection:
// access to a Context from multiple goroutines requires external
// synchronization.
type Context struct {
cipher srtpCipher
srtpSSRCStates map[uint32]*srtpSSRCState
srtcpSSRCStates map[uint32]*srtcpSSRCState
newSRTCPReplayDetector func() replaydetector.ReplayDetector
newSRTPReplayDetector func() replaydetector.ReplayDetector
profile ProtectionProfile
// Master Key Identifier used for encrypting RTP/RTCP packets. Set to nil if MKI is not enabled.
sendMKI []byte
// Master Key Identifier to cipher mapping. Used for decrypting packets. Empty if MKI is not enabled.
mkis map[string]srtpCipher
encryptSRTP bool
encryptSRTCP bool
rccMode RCCMode
rocTransmitRate uint16
authTagRTPLen *int
cryptexMode CryptexMode
}
// CreateContext creates a new SRTP Context.
//
// CreateContext receives variable number of ContextOption-s.
// Passing multiple options which set the same parameter let the last one valid.
// Following example create SRTP Context with replay protection with window size of 256.
//
// decCtx, err := srtp.CreateContext(key, salt, profile, srtp.SRTPReplayProtection(256))
func CreateContext(
masterKey, masterSalt []byte,
profile ProtectionProfile,
opts ...ContextOption,
) (c *Context, err error) {
c = &Context{
srtpSSRCStates: map[uint32]*srtpSSRCState{},
srtcpSSRCStates: map[uint32]*srtcpSSRCState{},
profile: profile,
mkis: map[string]srtpCipher{},
}
for _, o := range append(
[]ContextOption{ // Default options
SRTPNoReplayProtection(),
SRTCPNoReplayProtection(),
SRTPEncryption(),
SRTCPEncryption(),
},
opts..., // User specified options
) {
if errOpt := o(c); errOpt != nil {
return nil, errOpt
}
}
if err = c.checkRCCMode(); err != nil {
return nil, err
}
if c.authTagRTPLen != nil {
var authKeyLen int
authKeyLen, err = c.profile.AuthKeyLen()
if err != nil {
return nil, err
}
if *c.authTagRTPLen > authKeyLen {
return nil, errTooLongSRTPAuthTag
}
}
c.cipher, err = c.createCipher(c.sendMKI, masterKey, masterSalt, c.encryptSRTP, c.encryptSRTCP)
if err != nil {
return nil, err
}
if len(c.sendMKI) != 0 {
c.mkis[string(c.sendMKI)] = c.cipher
}
return c, nil
}
// AddCipherForMKI adds new MKI with associated masker key and salt.
// Context must be created with MasterKeyIndicator option
// to enable MKI support. MKI must be unique and have the same length as the one used for creating Context.
// Operation is not thread-safe, you need to provide synchronization with decrypting packets.
func (c *Context) AddCipherForMKI(mki, masterKey, masterSalt []byte) error {
if len(c.mkis) == 0 {
return errMKIIsNotEnabled
}
if len(mki) == 0 || len(mki) != len(c.sendMKI) {
return errInvalidMKILength
}
if _, ok := c.mkis[string(mki)]; ok {
return errMKIAlreadyInUse
}
cipher, err := c.createCipher(mki, masterKey, masterSalt, c.encryptSRTP, c.encryptSRTCP)
if err != nil {
return err
}
c.mkis[string(mki)] = cipher
return nil
}
func (c *Context) createCipher(mki, masterKey, masterSalt []byte, encryptSRTP, encryptSRTCP bool) (srtpCipher, error) {
keyLen, err := c.profile.KeyLen()
if err != nil {
return nil, err
}
saltLen, err := c.profile.SaltLen()
if err != nil {
return nil, err
}
if masterKeyLen := len(masterKey); masterKeyLen != keyLen {
return nil, fmt.Errorf("%w expected(%d) actual(%d)", errShortSrtpMasterKey, keyLen, masterKey)
} else if masterSaltLen := len(masterSalt); masterSaltLen != saltLen {
return nil, fmt.Errorf("%w expected(%d) actual(%d)", errShortSrtpMasterSalt, saltLen, masterSaltLen)
}
profileWithArgs := protectionProfileWithArgs{
ProtectionProfile: c.profile,
authTagRTPLen: c.authTagRTPLen,
}
useCryptex := c.cryptexMode != CryptexModeDisabled && encryptSRTP
switch c.profile {
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return newSrtpCipherAeadAesGcm(profileWithArgs, masterKey, masterSalt, mki, encryptSRTP, encryptSRTCP, useCryptex)
case ProtectionProfileAes128CmHmacSha1_32,
ProtectionProfileAes128CmHmacSha1_80,
ProtectionProfileAes256CmHmacSha1_32,
ProtectionProfileAes256CmHmacSha1_80:
return newSrtpCipherAesCmHmacSha1(profileWithArgs, masterKey, masterSalt, mki, encryptSRTP, encryptSRTCP, useCryptex)
case ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return newSrtpCipherAesCmHmacSha1(profileWithArgs, masterKey, masterSalt, mki, false, false, false)
default:
return nil, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, c.profile)
}
}
// RemoveMKI removes one of MKIs. You cannot remove last MKI and one used for encrypting RTP/RTCP packets.
// Operation is not thread-safe, you need to provide synchronization with decrypting packets.
func (c *Context) RemoveMKI(mki []byte) error {
if _, ok := c.mkis[string(mki)]; !ok {
return ErrMKINotFound
}
if bytes.Equal(mki, c.sendMKI) {
return errMKIAlreadyInUse
}
delete(c.mkis, string(mki))
return nil
}
// SetSendMKI switches MKI and cipher used for encrypting RTP/RTCP packets.
// Operation is not thread-safe, you need to provide synchronization with encrypting packets.
func (c *Context) SetSendMKI(mki []byte) error {
cipher, ok := c.mkis[string(mki)]
if !ok {
return ErrMKINotFound
}
c.sendMKI = mki
c.cipher = cipher
return nil
}
// https://tools.ietf.org/html/rfc3550#appendix-A.1
func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (roc uint32, diff int64, overflow bool) {
seq := int32(sequenceNumber)
localRoc := uint32(s.index >> 16) //nolint:gosec // G115
localSeq := int32(s.index & (seqNumMax - 1)) //nolint:gosec // G115
guessRoc := localRoc
var difference int32
if s.rolloverHasProcessed { //nolint:nestif
// When localROC is equal to 0, and entering seq-localSeq > seqNumMedian
// judgment, it will cause guessRoc calculation error
if s.index > seqNumMedian {
if localSeq < seqNumMedian {
if seq-localSeq > seqNumMedian {
guessRoc = localRoc - 1
difference = seq - localSeq - seqNumMax
} else {
guessRoc = localRoc
difference = seq - localSeq
}
} else {
if localSeq-seqNumMedian > seq {
guessRoc = localRoc + 1
difference = seq - localSeq + seqNumMax
} else {
guessRoc = localRoc
difference = seq - localSeq
}
}
} else {
// localRoc is equal to 0
difference = seq - localSeq
}
}
return guessRoc, int64(difference), (guessRoc == 0 && localRoc == maxROC)
}
func (s *srtpSSRCState) updateRolloverCount(sequenceNumber uint16, difference int64, hasRemoteRoc bool,
remoteRoc uint32,
) {
switch {
case hasRemoteRoc:
s.index = (uint64(remoteRoc) << 16) | uint64(sequenceNumber)
s.rolloverHasProcessed = true
case !s.rolloverHasProcessed:
s.index |= uint64(sequenceNumber)
s.rolloverHasProcessed = true
case difference > 0:
s.index += uint64(difference)
}
}
func (c *Context) getSRTPSSRCState(ssrc uint32) *srtpSSRCState {
s, ok := c.srtpSSRCStates[ssrc]
if ok {
return s
}
s = &srtpSSRCState{
ssrc: ssrc,
replayDetector: c.newSRTPReplayDetector(),
}
c.srtpSSRCStates[ssrc] = s
return s
}
func (c *Context) getSRTCPSSRCState(ssrc uint32) *srtcpSSRCState {
s, ok := c.srtcpSSRCStates[ssrc]
if ok {
return s
}
s = &srtcpSSRCState{
ssrc: ssrc,
replayDetector: c.newSRTCPReplayDetector(),
}
c.srtcpSSRCStates[ssrc] = s
return s
}
// ROC returns SRTP rollover counter value of specified SSRC.
func (c *Context) ROC(ssrc uint32) (uint32, bool) {
s, ok := c.srtpSSRCStates[ssrc]
if !ok {
return 0, false
}
return uint32(s.index >> 16), true //nolint:gosec // G115
}
// SetROC sets SRTP rollover counter value of specified SSRC.
func (c *Context) SetROC(ssrc uint32, roc uint32) {
s := c.getSRTPSSRCState(ssrc)
s.index = uint64(roc) << 16
s.rolloverHasProcessed = false
}
// Index returns SRTCP index value of specified SSRC.
func (c *Context) Index(ssrc uint32) (uint32, bool) {
s, ok := c.srtcpSSRCStates[ssrc]
if !ok {
return 0, false
}
return s.srtcpIndex, true
}
// SetIndex sets SRTCP index value of specified SSRC.
func (c *Context) SetIndex(ssrc uint32, index uint32) {
s := c.getSRTCPSSRCState(ssrc)
s.srtcpIndex = index % (maxSRTCPIndex + 1)
}
//nolint:cyclop
func (c *Context) checkRCCMode() error {
if c.rccMode == RCCModeNone {
return nil
}
if c.rocTransmitRate == 0 {
return errZeroRocTransmitRate
}
switch c.profile {
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
// AEAD profiles support RCCMode3 only
if c.rccMode != RCCMode3 {
return errUnsupportedRccMode
}
case ProtectionProfileAes128CmHmacSha1_32,
ProtectionProfileAes256CmHmacSha1_32,
ProtectionProfileNullHmacSha1_32:
if c.authTagRTPLen == nil {
// ROC completely replaces auth tag for _32 profiles. If you really want to use 4-byte
// SRTP auth tag with RCC, use SRTPAuthenticationTagLength(4) option.
return errTooShortSRTPAuthTag
}
fallthrough // Checks below are common for _32 and _80 profiles.
case ProtectionProfileAes128CmHmacSha1_80,
ProtectionProfileAes256CmHmacSha1_80,
ProtectionProfileNullHmacSha1_80:
// AES-CM and NULL profiles support RCCMode2 only
if c.rccMode != RCCMode2 {
return errUnsupportedRccMode
}
if c.authTagRTPLen != nil && *c.authTagRTPLen < 4 {
return errTooShortSRTPAuthTag
}
default:
return errUnsupportedRccMode
}
return nil
}