-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathoptions.go
More file actions
668 lines (567 loc) · 20 KB
/
options.go
File metadata and controls
668 lines (567 loc) · 20 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"crypto/tls"
"crypto/x509"
"io"
"net"
"time"
"github.com/pion/dtls/v3/pkg/crypto/elliptic"
"github.com/pion/dtls/v3/pkg/protocol/handshake"
"github.com/pion/logging"
)
// ServerOption configures a DTLS server.
type ServerOption interface {
applyServer(*dtlsConfig) error
}
// ClientOption configures a DTLS client.
type ClientOption interface {
applyClient(*dtlsConfig) error
}
// Option is an option that can be used with both client and server.
// This is used for options that apply to both sides of a connection,
// such as in the Resume function where the side is determined at runtime.
type Option interface {
ServerOption
ClientOption
}
// defensiveCopy copies a slice. This prevents the caller from mutating
// the config after construction. Returns empty slice if input is empty.
func defensiveCopy[T any](t ...T) []T {
return append([]T{}, t...)
}
// dtlsConfig is the internal configuration structure.
// This will eventually replace the exported Config struct.
type dtlsConfig struct { //nolint:dupl
certificates []tls.Certificate
cipherSuites []CipherSuiteID
customCipherSuites func() []CipherSuite
signatureSchemes []tls.SignatureScheme
certificateSignatureSchemes []tls.SignatureScheme
srtpProtectionProfiles []SRTPProtectionProfile
srtpMasterKeyIdentifier []byte
clientAuth ClientAuthType
extendedMasterSecret ExtendedMasterSecretType
flightInterval time.Duration
disableRetransmitBackoff bool
psk PSKCallback
pskIdentityHint []byte
insecureSkipVerify bool
insecureHashes bool
verifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
verifyConnection func(*State) error
rootCAs *x509.CertPool
clientCAs *x509.CertPool
serverName string
loggerFactory logging.LoggerFactory
mtu int
replayProtectionWindow int
keyLogWriter io.Writer
sessionStore SessionStore
supportedProtocols []string
ellipticCurves []elliptic.Curve
getCertificate func(*ClientHelloInfo) (*tls.Certificate, error)
getClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error)
insecureSkipVerifyHello bool
connectionIDGenerator func() []byte
paddingLengthGenerator func(uint) uint
helloRandomBytesGenerator func() [handshake.RandomBytesLength]byte
clientHelloMessageHook func(handshake.MessageClientHello) handshake.Message
serverHelloMessageHook func(handshake.MessageServerHello) handshake.Message
certificateRequestMessageHook func(handshake.MessageCertificateRequest) handshake.Message
onConnectionAttempt func(net.Addr) error
listenConfig net.ListenConfig
}
// applyDefaults applies default values to the config.
func (c *dtlsConfig) applyDefaults() {
c.extendedMasterSecret = RequestExtendedMasterSecret
c.flightInterval = time.Second
c.mtu = defaultMTU
c.replayProtectionWindow = defaultReplayProtectionWindow
}
// toConfig converts internal dtlsConfig to the exported Config struct.
// This is for backward compatibility and will be removed when Config is deprecated.
// All slice fields are copied to ensure immutability.
func (c *dtlsConfig) toConfig() *Config {
config := &Config{
CustomCipherSuites: c.customCipherSuites,
ClientAuth: c.clientAuth,
ExtendedMasterSecret: c.extendedMasterSecret,
FlightInterval: c.flightInterval,
DisableRetransmitBackoff: c.disableRetransmitBackoff,
PSK: c.psk,
InsecureSkipVerify: c.insecureSkipVerify,
InsecureHashes: c.insecureHashes,
VerifyPeerCertificate: c.verifyPeerCertificate,
VerifyConnection: c.verifyConnection,
RootCAs: c.rootCAs,
ClientCAs: c.clientCAs,
ServerName: c.serverName,
LoggerFactory: c.loggerFactory,
MTU: c.mtu,
ReplayProtectionWindow: c.replayProtectionWindow,
KeyLogWriter: c.keyLogWriter,
SessionStore: c.sessionStore,
GetCertificate: c.getCertificate,
GetClientCertificate: c.getClientCertificate,
InsecureSkipVerifyHello: c.insecureSkipVerifyHello,
ConnectionIDGenerator: c.connectionIDGenerator,
PaddingLengthGenerator: c.paddingLengthGenerator,
HelloRandomBytesGenerator: c.helloRandomBytesGenerator,
ClientHelloMessageHook: c.clientHelloMessageHook,
ServerHelloMessageHook: c.serverHelloMessageHook,
CertificateRequestMessageHook: c.certificateRequestMessageHook,
OnConnectionAttempt: c.onConnectionAttempt,
listenConfig: c.listenConfig,
}
if len(c.certificates) > 0 {
config.Certificates = append([]tls.Certificate(nil), c.certificates...)
}
if len(c.cipherSuites) > 0 {
config.CipherSuites = append([]CipherSuiteID(nil), c.cipherSuites...)
}
if len(c.signatureSchemes) > 0 {
config.SignatureSchemes = append([]tls.SignatureScheme(nil), c.signatureSchemes...)
}
if len(c.certificateSignatureSchemes) > 0 {
config.CertificateSignatureSchemes = append([]tls.SignatureScheme(nil), c.certificateSignatureSchemes...)
}
if len(c.srtpProtectionProfiles) > 0 {
config.SRTPProtectionProfiles = append([]SRTPProtectionProfile(nil), c.srtpProtectionProfiles...)
}
if len(c.srtpMasterKeyIdentifier) > 0 {
config.SRTPMasterKeyIdentifier = append([]byte(nil), c.srtpMasterKeyIdentifier...)
}
if len(c.pskIdentityHint) > 0 {
config.PSKIdentityHint = append([]byte(nil), c.pskIdentityHint...)
}
if len(c.supportedProtocols) > 0 {
config.SupportedProtocols = append([]string(nil), c.supportedProtocols...)
}
if len(c.ellipticCurves) > 0 {
config.EllipticCurves = append([]elliptic.Curve(nil), c.ellipticCurves...)
}
return config
}
// buildConfig builds a Config from the provided options, for mixed client/server cases.
func buildConfig(opts ...Option) (*Config, error) {
cfg := &dtlsConfig{}
cfg.applyDefaults()
for _, opt := range opts {
if err := opt.applyServer(cfg); err != nil {
return nil, err
}
}
return cfg.toConfig(), nil
}
// buildServerConfig builds a Config for server from the provided options.
func buildServerConfig(opts ...ServerOption) (*Config, error) {
cfg := &dtlsConfig{}
cfg.applyDefaults()
for _, opt := range opts {
if err := opt.applyServer(cfg); err != nil {
return nil, err
}
}
return cfg.toConfig(), nil
}
// buildClientConfig builds a Config for client from the provided options.
func buildClientConfig(opts ...ClientOption) (*Config, error) {
cfg := &dtlsConfig{}
cfg.applyDefaults()
for _, opt := range opts {
if err := opt.applyClient(cfg); err != nil {
return nil, err
}
}
return cfg.toConfig(), nil
}
// sharedOption wraps an apply function that works for both client and server.
// This eliminates code duplication for options that behave identically on both sides.
type sharedOption func(*dtlsConfig) error
func (o sharedOption) applyServer(c *dtlsConfig) error { return o(c) }
func (o sharedOption) applyClient(c *dtlsConfig) error { return o(c) }
// WithCertificates sets the certificate chain to present to the other side of the connection.
// For functional options, an explicitly empty slice is not allowed.
func WithCertificates(certs ...tls.Certificate) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(certs) == 0 {
return errEmptyCertificates
}
c.certificates = defensiveCopy(certs...)
return nil
})
}
// WithCipherSuites sets the supported cipher suites.
// For functional options, an explicitly empty slice is not allowed.
func WithCipherSuites(suites ...CipherSuiteID) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(suites) == 0 {
return errEmptyCipherSuites
}
c.cipherSuites = defensiveCopy(suites...)
return nil
})
}
// WithCustomCipherSuites sets the custom cipher suites provider.
// Returns an error if the provider is nil.
func WithCustomCipherSuites(fn func() []CipherSuite) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilCustomCipherSuites
}
c.customCipherSuites = fn
return nil
})
}
// WithSignatureSchemes sets the signature schemes.
// For functional options, an explicitly empty slice is not allowed.
func WithSignatureSchemes(schemes ...tls.SignatureScheme) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(schemes) == 0 {
return errEmptySignatureSchemes
}
c.signatureSchemes = defensiveCopy(schemes...)
return nil
})
}
// WithCertificateSignatureSchemes sets the signature and hash schemes that may be used
// in digital signatures for X.509 certificates. If not set, the signature_algorithms_cert
// extension is not sent, and SignatureSchemes is used for both handshake signatures and
// certificate chain validation, as specified in RFC 8446 Section 4.2.3.
// For functional options, an explicitly empty slice is not allowed.
func WithCertificateSignatureSchemes(schemes ...tls.SignatureScheme) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(schemes) == 0 {
return errEmptyCertificateSignatureSchemes
}
c.certificateSignatureSchemes = defensiveCopy(schemes...)
return nil
})
}
// WithSRTPProtectionProfiles sets the SRTP protection profiles.
// For functional options, an explicitly empty slice is not allowed.
func WithSRTPProtectionProfiles(profiles ...SRTPProtectionProfile) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(profiles) == 0 {
return errEmptySRTPProtectionProfiles
}
c.srtpProtectionProfiles = defensiveCopy(profiles...)
return nil
})
}
// WithSRTPMasterKeyIdentifier sets the SRTP master key identifier.
func WithSRTPMasterKeyIdentifier(identifier []byte) Option {
return sharedOption(func(c *dtlsConfig) error {
c.srtpMasterKeyIdentifier = defensiveCopy(identifier...)
return nil
})
}
// WithExtendedMasterSecret sets the extended master secret policy.
// Returns an error if the type is invalid.
func WithExtendedMasterSecret(ems ExtendedMasterSecretType) Option {
return sharedOption(func(c *dtlsConfig) error {
if ems < RequestExtendedMasterSecret || ems > DisableExtendedMasterSecret {
return errInvalidExtendedMasterSecretType
}
c.extendedMasterSecret = ems
return nil
})
}
// WithFlightInterval sets the flight interval for handshake messages.
// Returns an error if the interval is not positive.
func WithFlightInterval(interval time.Duration) Option {
return sharedOption(func(c *dtlsConfig) error {
if interval <= 0 {
return errInvalidFlightInterval
}
c.flightInterval = interval
return nil
})
}
// WithDisableRetransmitBackoff disables retransmit backoff.
func WithDisableRetransmitBackoff(disable bool) Option {
return sharedOption(func(c *dtlsConfig) error {
c.disableRetransmitBackoff = disable
return nil
})
}
// WithPSK sets the pre-shared key callback.
// Returns an error if the callback is nil.
func WithPSK(callback PSKCallback) Option {
return sharedOption(func(c *dtlsConfig) error {
if callback == nil {
return errNilPSKCallback
}
c.psk = callback
return nil
})
}
// WithPSKIdentityHint sets the PSK identity hint.
func WithPSKIdentityHint(hint []byte) Option {
return sharedOption(func(c *dtlsConfig) error {
c.pskIdentityHint = defensiveCopy(hint...)
return nil
})
}
// WithInsecureSkipVerify skips certificate verification.
// This should only be used for testing.
func WithInsecureSkipVerify(skip bool) Option {
return sharedOption(func(c *dtlsConfig) error {
c.insecureSkipVerify = skip
return nil
})
}
// WithInsecureHashes allows the use of insecure hash algorithms.
func WithInsecureHashes(allow bool) Option {
return sharedOption(func(c *dtlsConfig) error {
c.insecureHashes = allow
return nil
})
}
// WithVerifyPeerCertificate sets the peer certificate verification callback.
// Returns an error if the callback is nil.
func WithVerifyPeerCertificate(fn func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilVerifyPeerCertificate
}
c.verifyPeerCertificate = fn
return nil
})
}
// WithVerifyConnection sets the connection verification callback.
// Returns an error if the callback is nil.
func WithVerifyConnection(fn func(*State) error) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilVerifyConnection
}
c.verifyConnection = fn
return nil
})
}
// WithRootCAs sets the root certificate authorities.
func WithRootCAs(pool *x509.CertPool) Option {
return sharedOption(func(c *dtlsConfig) error {
c.rootCAs = pool
return nil
})
}
// WithServerName sets the server name for certificate verification.
func WithServerName(name string) Option {
return sharedOption(func(c *dtlsConfig) error {
c.serverName = name
return nil
})
}
// WithLoggerFactory sets the logger factory for creating loggers.
func WithLoggerFactory(factory logging.LoggerFactory) Option {
return sharedOption(func(c *dtlsConfig) error {
c.loggerFactory = factory
return nil
})
}
// WithMTU sets the maximum transmission unit.
// Returns an error if the MTU is not positive.
func WithMTU(mtu int) Option {
return sharedOption(func(c *dtlsConfig) error {
if mtu <= 0 {
return errInvalidMTU
}
c.mtu = mtu
return nil
})
}
// WithReplayProtectionWindow sets the replay protection window size.
// Returns an error if the window size is negative.
func WithReplayProtectionWindow(window int) Option {
return sharedOption(func(c *dtlsConfig) error {
if window < 0 {
return errInvalidReplayProtectionWindow
}
c.replayProtectionWindow = window
return nil
})
}
// WithKeyLogWriter sets the key log writer for debugging.
// Use of KeyLogWriter compromises security and should only be used for debugging.
func WithKeyLogWriter(writer io.Writer) Option {
return sharedOption(func(c *dtlsConfig) error {
c.keyLogWriter = writer
return nil
})
}
// WithSessionStore sets the session store for resumption.
func WithSessionStore(store SessionStore) Option {
return sharedOption(func(c *dtlsConfig) error {
c.sessionStore = store
return nil
})
}
// WithSupportedProtocols sets the supported application protocols for ALPN.
// For functional options, an explicitly empty slice is not allowed.
func WithSupportedProtocols(protocols ...string) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(protocols) == 0 {
return errEmptySupportedProtocols
}
c.supportedProtocols = defensiveCopy(protocols...)
return nil
})
}
// WithEllipticCurves sets the elliptic curves.
// For functional options, an explicitly empty slice is not allowed.
func WithEllipticCurves(curves ...elliptic.Curve) Option {
return sharedOption(func(c *dtlsConfig) error {
if len(curves) == 0 {
return errEmptyEllipticCurves
}
c.ellipticCurves = defensiveCopy(curves...)
return nil
})
}
// WithGetClientCertificate sets the client certificate getter callback.
// Returns an error if the callback is nil.
func WithGetClientCertificate(fn func(*CertificateRequestInfo) (*tls.Certificate, error)) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilGetClientCertificate
}
c.getClientCertificate = fn
return nil
})
}
// WithConnectionIDGenerator sets the connection ID generator.
// Returns an error if the generator is nil.
func WithConnectionIDGenerator(fn func() []byte) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilConnectionIDGenerator
}
c.connectionIDGenerator = fn
return nil
})
}
// WithPaddingLengthGenerator sets the padding length generator.
// Returns an error if the generator is nil.
func WithPaddingLengthGenerator(fn func(uint) uint) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilPaddingLengthGenerator
}
c.paddingLengthGenerator = fn
return nil
})
}
// WithHelloRandomBytesGenerator sets the hello random bytes generator.
// Returns an error if the generator is nil.
func WithHelloRandomBytesGenerator(fn func() [handshake.RandomBytesLength]byte) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilHelloRandomBytesGenerator
}
c.helloRandomBytesGenerator = fn
return nil
})
}
// WithClientHelloMessageHook sets the client hello message hook.
// Returns an error if the hook is nil.
func WithClientHelloMessageHook(fn func(handshake.MessageClientHello) handshake.Message) Option {
return sharedOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilClientHelloMessageHook
}
c.clientHelloMessageHook = fn
return nil
})
}
// serverOnlyOption wraps an apply function for server-only options.
type serverOnlyOption func(*dtlsConfig) error
func (o serverOnlyOption) applyServer(c *dtlsConfig) error { return o(c) }
// WithClientAuth sets the client authentication policy.
// Returns an error if the type is invalid.
// This option is only applicable to servers.
func WithClientAuth(auth ClientAuthType) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
if auth < NoClientCert || auth > RequireAndVerifyClientCert {
return errInvalidClientAuthType
}
c.clientAuth = auth
return nil
})
}
// WithClientCAs sets the client certificate authorities.
// This option is only applicable to servers.
func WithClientCAs(pool *x509.CertPool) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
c.clientCAs = pool
return nil
})
}
// WithGetCertificate sets the certificate getter callback.
// Returns an error if the callback is nil.
// This option is only applicable to servers.
func WithGetCertificate(fn func(*ClientHelloInfo) (*tls.Certificate, error)) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilGetCertificate
}
c.getCertificate = fn
return nil
})
}
// WithInsecureSkipVerifyHello skips hello verify phase on the server.
// This has implication on DoS attack resistance.
// This option is only applicable to servers.
func WithInsecureSkipVerifyHello(skip bool) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
c.insecureSkipVerifyHello = skip
return nil
})
}
// WithServerHelloMessageHook sets the server hello message hook.
// Returns an error if the hook is nil.
// This option is only applicable to servers.
func WithServerHelloMessageHook(fn func(handshake.MessageServerHello) handshake.Message) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilServerHelloMessageHook
}
c.serverHelloMessageHook = fn
return nil
})
}
// WithCertificateRequestMessageHook sets the certificate request message hook.
// Returns an error if the hook is nil.
// This option is only applicable to servers.
func WithCertificateRequestMessageHook(fn func(handshake.MessageCertificateRequest) handshake.Message) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilCertificateRequestMessageHook
}
c.certificateRequestMessageHook = fn
return nil
})
}
// WithOnConnectionAttempt sets the connection attempt callback.
// Returns an error if the callback is nil.
// This option is only applicable to servers.
func WithOnConnectionAttempt(fn func(net.Addr) error) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
if fn == nil {
return errNilOnConnectionAttempt
}
c.onConnectionAttempt = fn
return nil
})
}
// WithListenConfig sets the underlying listener config.
// This option is only applicable to servers.
func WithListenConfig(listenConfig net.ListenConfig) ServerOption {
return serverOnlyOption(func(c *dtlsConfig) error {
c.listenConfig = listenConfig
return nil
})
}