1
0
Fork 0
mirror of https://github.com/ossrs/srs.git synced 2025-03-09 15:49:59 +00:00

TEST: Upgrade pion to v3.2.9. (#3567)

------

Co-authored-by: chundonglinlin <chundonglinlin@163.com>
This commit is contained in:
Winlin 2023-06-05 11:25:04 +08:00 committed by GitHub
parent 104cf14d68
commit df854339ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1383 changed files with 118469 additions and 41421 deletions

View file

@ -1,2 +1,25 @@
# vim temporary files
### JetBrains IDE ###
#####################
.idea/
### Emacs Temporary Files ###
#############################
*~
### Folders ###
###############
bin/
vendor/
node_modules/
### Files ###
#############
*.ivf
*.ogg
tags
cover.out
*.sw[poe]
*.wasm
examples/sfu-ws/cert.pem
examples/sfu-ws/key.pem
wasm_exec.js

View file

@ -3,6 +3,117 @@ linters-settings:
check-shadowing: true
misspell:
locale: US
exhaustive:
default-signifies-exhaustive: true
gomodguard:
blocked:
modules:
- github.com/pkg/errors:
recommendations:
- errors
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- deadcode # Finds unused code
- decorder # check declaration order and count of types, constants, variables and functions
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- exhaustivestruct # Checks if all struct's fields are initialized
- forbidigo # Forbids identifiers
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!
issues:
exclude-use-default: false
exclude-rules:
# Allow complex tests, better to be self contained
- path: _test\.go
linters:
- gocognit
# Allow complex main function in examples
- path: examples
text: "of func `main` is high"
linters:
- gocognit
run:
skip-dirs-use-default: false

View file

@ -0,0 +1,17 @@
# Thank you to everyone that made Pion possible. If you are interested in contributing
# we would love to have you https://github.com/pion/webrtc/wiki/Contributing
#
# This file is auto generated, using git to list all individuals contributors.
# see `.github/generate-authors.sh` for the scripting
Atsushi Watanabe <atsushi.w@ieee.org>
backkem <mail@backkem.me>
Benny Daon <benny@tuzig.com>
Chinmay Kousik <chinmaykousik1@gmail.com>
Eric Daniels <eric@erdaniels.com>
Hugo Arregui <hugo.arregui@gmail.com>
Hugo Arregui <hugo@decentraland.org>
John Bradley <jrb@turrettech.com>
Norman Rasmussen <norman@rasmussen.co.za>
Sean DuBois <seaduboi@amazon.com>
Sean DuBois <sean@siobud.com>
Yutaka Takeda <yt0916@gmail.com>

View file

@ -33,13 +33,5 @@ If you need commercial support or don't want to use public methods you can conta
### Contributing
Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible:
* [John Bradley](https://github.com/kc5nra) - *Original Author*
* [Sean DuBois](https://github.com/Sean-Der) - *Original Author*
* [Michiel De Backker](https://github.com/backkem) - *Public API*
* [Yutaka Takeda](https://github.com/enobufs) - *PR-SCTP*
* [Hugo Arregui](https://github.com/hugoArregui)
* [Atsushi Watanabe](https://github.com/at-wat)
* [Norman Rasmussen](https://github.com/normanr) - *Fix Empty DataChannel messages*
### License
MIT License - see [LICENSE](LICENSE) for full text

View file

@ -2,13 +2,15 @@
package datachannel
import (
"errors"
"fmt"
"io"
"sync"
"sync/atomic"
"time"
"github.com/pion/logging"
"github.com/pion/sctp"
"github.com/pkg/errors"
)
const receiveMTU = 8192
@ -19,6 +21,11 @@ type Reader interface {
ReadDataChannel([]byte) (int, bool, error)
}
// ReadDeadliner extends an io.Reader to expose setting a read deadline.
type ReadDeadliner interface {
SetReadDeadline(time.Time) error
}
// Writer is an extended io.Writer
// that also allows indicating if a message is text.
type Writer interface {
@ -45,6 +52,10 @@ type DataChannel struct {
bytesSent uint64
bytesReceived uint64
mu sync.Mutex
onOpenCompleteHandler func()
openCompleteHandlerOnce sync.Once
stream *sctp.Stream
log logging.LeveledLogger
}
@ -97,22 +108,28 @@ func Client(stream *sctp.Stream, config *Config) (*DataChannel, error) {
if !config.Negotiated {
rawMsg, err := msg.Marshal()
if err != nil {
return nil, fmt.Errorf("failed to marshal ChannelOpen %v", err)
return nil, fmt.Errorf("failed to marshal ChannelOpen %w", err)
}
if _, err = stream.WriteSCTP(rawMsg, sctp.PayloadTypeWebRTCDCEP); err != nil {
return nil, fmt.Errorf("failed to send ChannelOpen %v", err)
return nil, fmt.Errorf("failed to send ChannelOpen %w", err)
}
}
return newDataChannel(stream, config)
}
// Accept is used to accept incoming data channels over SCTP
func Accept(a *sctp.Association, config *Config) (*DataChannel, error) {
func Accept(a *sctp.Association, config *Config, existingChannels ...*DataChannel) (*DataChannel, error) {
stream, err := a.AcceptStream()
if err != nil {
return nil, err
}
for _, ch := range existingChannels {
if ch.StreamIdentifier() == stream.StreamIdentifier() {
ch.stream.SetDefaultPayloadType(sctp.PayloadTypeWebRTCBinary)
return ch, nil
}
}
stream.SetDefaultPayloadType(sctp.PayloadTypeWebRTCBinary)
@ -126,19 +143,19 @@ func Accept(a *sctp.Association, config *Config) (*DataChannel, error) {
// Server accepts a data channel over an SCTP stream
func Server(stream *sctp.Stream, config *Config) (*DataChannel, error) {
buffer := make([]byte, receiveMTU) // TODO: Can probably be smaller
buffer := make([]byte, receiveMTU)
n, ppi, err := stream.ReadSCTP(buffer)
if err != nil {
return nil, err
}
if ppi != sctp.PayloadTypeWebRTCDCEP {
return nil, fmt.Errorf("unexpected packet type: %s", ppi)
return nil, fmt.Errorf("%w %s", ErrInvalidPayloadProtocolIdentifier, ppi)
}
openMsg, err := parseExpectDataChannelOpen(buffer[:n])
if err != nil {
return nil, errors.Wrap(err, "failed to parse DataChannelOpen packet")
return nil, fmt.Errorf("failed to parse DataChannelOpen packet %w", err)
}
config.ChannelType = openMsg.ChannelType
@ -174,11 +191,10 @@ func (c *DataChannel) Read(p []byte) (int, error) {
func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) {
for {
n, ppi, err := c.stream.ReadSCTP(p)
if err == io.EOF {
if errors.Is(err, io.EOF) {
// When the peer sees that an incoming stream was
// reset, it also resets its corresponding outgoing stream.
closeErr := c.stream.Close()
if closeErr != nil {
if closeErr := c.stream.Close(); closeErr != nil {
return 0, false, closeErr
}
}
@ -186,30 +202,28 @@ func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) {
return 0, false, err
}
var isString bool
switch ppi {
case sctp.PayloadTypeWebRTCDCEP:
err = c.handleDCEP(p[:n])
if err != nil {
if ppi == sctp.PayloadTypeWebRTCDCEP {
if err = c.handleDCEP(p[:n]); err != nil {
c.log.Errorf("Failed to handle DCEP: %s", err.Error())
continue
}
continue
case sctp.PayloadTypeWebRTCString, sctp.PayloadTypeWebRTCStringEmpty:
isString = true
}
switch ppi {
case sctp.PayloadTypeWebRTCBinaryEmpty, sctp.PayloadTypeWebRTCStringEmpty:
} else if ppi == sctp.PayloadTypeWebRTCBinaryEmpty || ppi == sctp.PayloadTypeWebRTCStringEmpty {
n = 0
}
atomic.AddUint32(&c.messagesReceived, 1)
atomic.AddUint64(&c.bytesReceived, uint64(n))
isString := ppi == sctp.PayloadTypeWebRTCString || ppi == sctp.PayloadTypeWebRTCStringEmpty
return n, isString, err
}
}
// SetReadDeadline sets a deadline for reads to return
func (c *DataChannel) SetReadDeadline(t time.Time) error {
return c.stream.SetReadDeadline(t)
}
// MessagesSent returns the number of messages sent
func (c *DataChannel) MessagesSent() uint32 {
return atomic.LoadUint32(&c.messagesSent)
@ -220,6 +234,29 @@ func (c *DataChannel) MessagesReceived() uint32 {
return atomic.LoadUint32(&c.messagesReceived)
}
// OnOpen sets an event handler which is invoked when
// a DATA_CHANNEL_ACK message is received.
// The handler is called only on thefor the channel opened
// https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-data-protocol-09#section-5.2
func (c *DataChannel) OnOpen(f func()) {
c.mu.Lock()
c.openCompleteHandlerOnce = sync.Once{}
c.onOpenCompleteHandler = f
c.mu.Unlock()
}
func (c *DataChannel) onOpenComplete() {
c.mu.Lock()
hdlr := c.onOpenCompleteHandler
c.mu.Unlock()
if hdlr != nil {
go c.openCompleteHandlerOnce.Do(func() {
hdlr()
})
}
}
// BytesSent returns the number of bytes sent
func (c *DataChannel) BytesSent() uint64 {
return atomic.LoadUint64(&c.bytesSent)
@ -238,29 +275,18 @@ func (c *DataChannel) StreamIdentifier() uint16 {
func (c *DataChannel) handleDCEP(data []byte) error {
msg, err := parse(data)
if err != nil {
return errors.Wrap(err, "Failed to parse DataChannel packet")
return fmt.Errorf("failed to parse DataChannel packet %w", err)
}
switch msg := msg.(type) {
case *channelOpen:
c.log.Debug("Received DATA_CHANNEL_OPEN")
err = c.writeDataChannelAck()
if err != nil {
return fmt.Errorf("failed to ACK channel open: %v", err)
}
// Note: DATA_CHANNEL_OPEN message is handled inside Server() method.
// Therefore, the message will not reach here.
case *channelAck:
c.log.Debug("Received DATA_CHANNEL_ACK")
err = c.commitReliabilityParams()
if err != nil {
if err = c.commitReliabilityParams(); err != nil {
return err
}
// TODO: handle ChannelAck (https://tools.ietf.org/html/draft-ietf-rtcweb-data-protocol-09#section-5.2)
c.onOpenComplete()
default:
return fmt.Errorf("unhandled DataChannel message %v", msg)
return fmt.Errorf("%w %v", ErrInvalidMessageType, msg)
}
return nil
@ -306,12 +332,11 @@ func (c *DataChannel) writeDataChannelAck() error {
ack := channelAck{}
ackMsg, err := ack.Marshal()
if err != nil {
return fmt.Errorf("failed to marshal ChannelOpen ACK: %v", err)
return fmt.Errorf("failed to marshal ChannelOpen ACK: %w", err)
}
_, err = c.stream.WriteSCTP(ackMsg, sctp.PayloadTypeWebRTCDCEP)
if err != nil {
return fmt.Errorf("failed to send ChannelOpen ACK: %v", err)
if _, err = c.stream.WriteSCTP(ackMsg, sctp.PayloadTypeWebRTCDCEP); err != nil {
return fmt.Errorf("failed to send ChannelOpen ACK: %w", err)
}
return err
@ -372,7 +397,7 @@ func (c *DataChannel) commitReliabilityParams() error {
case ChannelTypePartialReliableTimedUnordered:
c.stream.SetReliabilityParams(true, sctp.ReliabilityTypeTimed, c.Config.ReliabilityParameter)
default:
return fmt.Errorf("invalid ChannelType: %v ", c.Config.ChannelType)
return fmt.Errorf("%w %v", ErrInvalidChannelType, c.Config.ChannelType)
}
return nil
}

View file

@ -0,0 +1,24 @@
package datachannel
import "errors"
var (
// ErrDataChannelMessageTooShort means that the data isn't long enough to be a valid DataChannel message
ErrDataChannelMessageTooShort = errors.New("DataChannel message is not long enough to determine type")
// ErrInvalidPayloadProtocolIdentifier means that we got a DataChannel messages with a Payload Protocol Identifier
// we don't know how to handle
ErrInvalidPayloadProtocolIdentifier = errors.New("DataChannel message Payload Protocol Identifier is value we can't handle")
// ErrInvalidChannelType means that the remote requested a channel type that we don't support
ErrInvalidChannelType = errors.New("invalid Channel Type")
// ErrInvalidMessageType is returned when a DataChannel Message has a type we don't support
ErrInvalidMessageType = errors.New("invalid Message Type")
// ErrExpectedAndActualLengthMismatch is when the declared length and actual length don't match
ErrExpectedAndActualLengthMismatch = errors.New("expected and actual length do not match")
// ErrUnexpectedDataChannelType is when a message type does not match the expected type
ErrUnexpectedDataChannelType = errors.New("expected and actual message type does not match")
)

View file

@ -1,11 +0,0 @@
module github.com/pion/datachannel
require (
github.com/pion/logging v0.2.2
github.com/pion/sctp v1.7.10
github.com/pion/transport v0.10.1
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.6.1
)
go 1.13

View file

@ -1,38 +0,0 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/sctp v1.7.10 h1:o3p3/hZB5Cx12RMGyWmItevJtZ6o2cpuxaw6GOS4x+8=
github.com/pion/sctp v1.7.10/go.mod h1:EhpTUQu1/lcK3xI+eriS6/96fWetHGCvBi9MSsnaBN0=
github.com/pion/transport v0.10.1 h1:2W+yJT+0mOQ160ThZYUx5Zp2skzshiNgxrNE9GUfhJM=
github.com/pion/transport v0.10.1/go.mod h1:PBis1stIILMiis0PewDw91WJeLJkyIMcEk+DwKOzf4A=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200625001655-4c5254603344 h1:vGXIOMxbNfDTk/aXCmfdLgkrSV+Z2tcbze+pEc3v5W4=
golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -2,8 +2,6 @@ package datachannel
import (
"fmt"
"github.com/pkg/errors"
)
// message is a parsed DataChannel message
@ -35,7 +33,7 @@ func (t messageType) String() string {
// parse accepts raw input and returns a DataChannel message
func parse(raw []byte) (message, error) {
if len(raw) == 0 {
return nil, errors.Errorf("DataChannel message is not long enough to determine type ")
return nil, ErrDataChannelMessageTooShort
}
var msg message
@ -45,7 +43,7 @@ func parse(raw []byte) (message, error) {
case dataChannelAck:
msg = &channelAck{}
default:
return nil, errors.Errorf("Unknown MessageType %v", messageType(raw[0]))
return nil, fmt.Errorf("%w %v", ErrInvalidMessageType, messageType(raw[0]))
}
if err := msg.Unmarshal(raw); err != nil {
@ -59,11 +57,11 @@ func parse(raw []byte) (message, error) {
// or throws an error
func parseExpectDataChannelOpen(raw []byte) (*channelOpen, error) {
if len(raw) == 0 {
return nil, errors.Errorf("the DataChannel message is not long enough to determine type")
return nil, ErrDataChannelMessageTooShort
}
if actualTyp := messageType(raw[0]); actualTyp != dataChannelOpen {
return nil, errors.Errorf("expected DataChannelOpen but got %s", actualTyp)
return nil, fmt.Errorf("%w expected(%s) actual(%s)", ErrUnexpectedDataChannelType, actualTyp, dataChannelOpen)
}
msg := &channelOpen{}
@ -73,22 +71,3 @@ func parseExpectDataChannelOpen(raw []byte) (*channelOpen, error) {
return msg, nil
}
// parseExpectDataChannelAck parses a DataChannelAck message
// or throws an error
// func parseExpectDataChannelAck(raw []byte) (*channelAck, error) {
// if len(raw) == 0 {
// return nil, errors.Errorf("the DataChannel message is not long enough to determine type")
// }
//
// if actualTyp := messageType(raw[0]); actualTyp != dataChannelAck {
// return nil, errors.Errorf("expected DataChannelAck but got %s", actualTyp)
// }
//
// msg := &channelAck{}
// if err := msg.Unmarshal(raw); err != nil {
// return nil, err
// }
//
// return msg, nil
// }

View file

@ -2,15 +2,15 @@ package datachannel
import (
"encoding/binary"
"github.com/pkg/errors"
"fmt"
)
/*
channelOpen represents a DATA_CHANNEL_OPEN Message
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Message Type | Channel Type | Priority |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
@ -104,7 +104,7 @@ func (c *channelOpen) Marshal() ([]byte, error) {
// Unmarshal populates the struct with the given raw data
func (c *channelOpen) Unmarshal(raw []byte) error {
if len(raw) < channelOpenHeaderLength {
return errors.Errorf("Length of input is not long enough to satisfy header %d", len(raw))
return fmt.Errorf("%w expected(%d) actual(%d)", ErrExpectedAndActualLengthMismatch, channelOpenHeaderLength, len(raw))
}
c.ChannelType = ChannelType(raw[1])
c.Priority = binary.BigEndian.Uint16(raw[2:])
@ -113,8 +113,8 @@ func (c *channelOpen) Unmarshal(raw []byte) error {
labelLength := binary.BigEndian.Uint16(raw[8:])
protocolLength := binary.BigEndian.Uint16(raw[10:])
if len(raw) != int(channelOpenHeaderLength+labelLength+protocolLength) {
return errors.Errorf("Label + Protocol length don't match full packet length")
if expectedLen := int(channelOpenHeaderLength + labelLength + protocolLength); len(raw) != expectedLen {
return fmt.Errorf("%w expected(%d) actual(%d)", ErrExpectedAndActualLengthMismatch, expectedLen, len(raw))
}
c.Label = raw[channelOpenHeaderLength : channelOpenHeaderLength+labelLength]

View file

@ -1,15 +1,27 @@
{
"extends": [
"config:base"
"config:base",
":disableDependencyDashboard"
],
"postUpdateOptions": [
"gomodTidy"
],
"commitBody": "Generated by renovateBot",
"packageRules": [
{
"matchUpdateTypes": ["minor", "patch", "pin", "digest"],
"automerge": true
},
{
"packagePatterns": ["^golang.org/x/"],
"schedule": ["on the first day of the month"]
}
],
"ignorePaths": [
".github/workflows/generate-authors.yml",
".github/workflows/lint.yaml",
".github/workflows/renovate-go-mod-fix.yaml",
".github/workflows/test.yaml",
".github/workflows/tidy-check.yaml"
]
}

View file

@ -1,4 +1,6 @@
# http://editorconfig.org/
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
root = true

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
### JetBrains IDE ###
#####################
.idea/
@ -22,3 +25,4 @@ cover.out
*.wasm
examples/sfu-ws/cert.pem
examples/sfu-ws/key.pem
wasm_exec.js

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
linters-settings:
govet:
check-shadowing: true
@ -10,19 +13,34 @@ linters-settings:
modules:
- github.com/pkg/errors:
recommendations:
- errors
- errors
forbidigo:
forbid:
- ^fmt.Print(f|ln)?$
- ^log.(Panic|Fatal|Print)(f|ln)?$
- ^os.Exit$
- ^panic$
- ^print(ln)?$
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- deadcode # Finds unused code
- contextcheck # check the function whether use a non-inherited context
- decorder # check declaration order and count of types, constants, variables and functions
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
@ -35,40 +53,59 @@ linters:
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- scopelint # Scopelint checks for unpinned variables in go programs
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- exhaustivestruct # Checks if all struct's fields are initialized
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!
issues:
@ -78,12 +115,23 @@ issues:
- path: _test\.go
linters:
- gocognit
- forbidigo
# Allow complex main function in examples
- path: examples
text: "of func `main` is high"
linters:
- gocognit
# Allow forbidden identifiers in examples
- path: examples
linters:
- forbidigo
# Allow forbidden identifiers in CLI commands
- path: cmd
linters:
- forbidigo
run:
skip-dirs-use-default: false

View file

@ -0,0 +1,5 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
builds:
- skip: true

View file

@ -0,0 +1,57 @@
# Thank you to everyone that made Pion possible. If you are interested in contributing
# we would love to have you https://github.com/pion/webrtc/wiki/Contributing
#
# This file is auto generated, using git to list all individuals contributors.
# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting
Aleksandr Razumov <ar@gortc.io>
alvarowolfx <alvarowolfx@gmail.com>
Arlo Breault <arlolra@gmail.com>
Atsushi Watanabe <atsushi.w@ieee.org>
backkem <mail@backkem.me>
bjdgyc <bjdgyc@163.com>
boks1971 <raja.gobi@tutanota.com>
Bragadeesh <bragboy@gmail.com>
Carson Hoffman <c@rsonhoffman.com>
Cecylia Bocovich <cohosh@torproject.org>
Chris Hiszpanski <thinkski@users.noreply.github.com>
cnderrauber <zengjie9004@gmail.com>
Daniele Sluijters <daenney@users.noreply.github.com>
folbrich <frank.olbricht@gmail.com>
Hayden James <hayden.james@gmail.com>
Hugo Arregui <hugo.arregui@gmail.com>
Hugo Arregui <hugo@decentraland.org>
igolaizola <11333576+igolaizola@users.noreply.github.com>
Jeffrey Stoke <me@arhat.dev>
Jeroen de Bruijn <vidavidorra+jdbruijn@gmail.com>
Jeroen de Bruijn <vidavidorra@gmail.com>
Jim Wert <jimwert@gmail.com>
jinleileiking <jinleileiking@gmail.com>
Jozef Kralik <jojo.lwin@gmail.com>
Julien Salleyron <julien.salleyron@gmail.com>
Juliusz Chroboczek <jch@irif.fr>
Kegan Dougal <kegan@matrix.org>
Kevin Wang <kevmo314@gmail.com>
Lander Noterman <lander.noterman@basalte.be>
Len <len@hpcnt.com>
Lukas Lihotzki <lukas@lihotzki.de>
ManuelBk <26275612+ManuelBk@users.noreply.github.com>
Michael Zabka <zabka.michael@gmail.com>
Michiel De Backker <mail@backkem.me>
Rachel Chen <rachel@chens.email>
Robert Eperjesi <eperjesi@uber.com>
Ryan Gordon <ryan.gordon@getcruise.com>
Sam Lancia <sam.lancia@motorolasolutions.com>
Sean DuBois <duboisea@justin.tv>
Sean DuBois <seaduboi@amazon.com>
Sean DuBois <sean@siobud.com>
Shelikhoo <xiaokangwang@outlook.com>
Stefan Tatschner <stefan@rumpelsepp.org>
Steffen Vogel <post@steffenvogel.de>
Vadim <fffilimonov@yandex.ru>
Vadim Filimonov <fffilimonov@yandex.ru>
wmiao <wu.miao@viasat.com>
ZHENK <chengzhenyang@gmail.com>
吕海涛 <hi@taoshu.in>
# List of contributors not appearing in Git history

View file

@ -1,21 +1,9 @@
MIT License
Copyright (c) 2018
Copyright (c) 2023 The Pion community <https://pion.ly>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,6 +0,0 @@
fuzz-build-record-layer: fuzz-prepare
go-fuzz-build -tags gofuzz -func FuzzRecordLayer
fuzz-run-record-layer:
go-fuzz -bin dtls-fuzz.zip -workdir fuzz
fuzz-prepare:
@GO111MODULE=on go mod vendor

View file

@ -9,24 +9,38 @@
<a href="https://sourcegraph.com/github.com/pion/dtls"><img src="https://sourcegraph.com/github.com/pion/dtls/-/badge.svg" alt="Sourcegraph Widget"></a>
<a href="https://pion.ly/slack"><img src="https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen" alt="Slack Widget"></a>
<br>
<a href="https://travis-ci.org/pion/dtls"><img src="https://travis-ci.org/pion/dtls.svg?branch=master" alt="Build Status"></a>
<a href="https://pkg.go.dev/github.com/pion/dtls"><img src="https://godoc.org/github.com/pion/dtls?status.svg" alt="GoDoc"></a>
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pion/dtls/test.yaml">
<a href="https://pkg.go.dev/github.com/pion/dtls/v2"><img src="https://pkg.go.dev/badge/github.com/pion/dtls/v2.svg" alt="Go Reference"></a>
<a href="https://codecov.io/gh/pion/dtls"><img src="https://codecov.io/gh/pion/dtls/branch/master/graph/badge.svg" alt="Coverage Status"></a>
<a href="https://goreportcard.com/report/github.com/pion/dtls"><img src="https://goreportcard.com/badge/github.com/pion/dtls" alt="Go Report Card"></a>
<a href="https://www.codacy.com/app/Sean-Der/dtls"><img src="https://api.codacy.com/project/badge/Grade/18f4aec384894e6aac0b94effe51961d" alt="Codacy Badge"></a>
<a href="https://goreportcard.com/report/github.com/pion/dtls/v2"><img src="https://goreportcard.com/badge/github.com/pion/dtls/v2" alt="Go Report Card"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
</p>
<br>
Native [DTLS 1.2][rfc6347] implementation in the Go programming language.
A long term goal is a professional security review, and maye inclusion in stdlib.
A long term goal is a professional security review, and maybe an inclusion in stdlib.
### RFCs
#### Implemented
- **RFC 6347**: [Datagram Transport Layer Security Version 1.2][rfc6347]
- **RFC 5705**: [Keying Material Exporters for Transport Layer Security (TLS)][rfc5705]
- **RFC 7627**: [Transport Layer Security (TLS) - Session Hash and Extended Master Secret Extension][rfc7627]
- **RFC 7301**: [Transport Layer Security (TLS) - Application-Layer Protocol Negotiation Extension][rfc7301]
[rfc5289]: https://tools.ietf.org/html/rfc5289
[rfc5487]: https://tools.ietf.org/html/rfc5487
[rfc5489]: https://tools.ietf.org/html/rfc5489
[rfc5705]: https://tools.ietf.org/html/rfc5705
[rfc6347]: https://tools.ietf.org/html/rfc6347
[rfc6655]: https://tools.ietf.org/html/rfc6655
[rfc7301]: https://tools.ietf.org/html/rfc7301
[rfc7627]: https://tools.ietf.org/html/rfc7627
[rfc8422]: https://tools.ietf.org/html/rfc8422
### Goals/Progress
This will only be targeting DTLS 1.2, and the most modern/common cipher suites.
We would love contributes that fall under the 'Planned Features' and fixing any bugs!
We would love contributions that fall under the 'Planned Features' and any bug fixes!
#### Current features
* DTLS 1.2 Client/Server
@ -35,30 +49,32 @@ We would love contributes that fall under the 'Planned Features' and fixing any
* Key export ([RFC 5705][rfc5705])
* Serialization and Resumption of sessions
* Extended Master Secret extension ([RFC 7627][rfc7627])
[rfc5705]: https://tools.ietf.org/html/rfc5705
[rfc7627]: https://tools.ietf.org/html/rfc7627
* ALPN extension ([RFC 7301][rfc7301])
#### Supported ciphers
##### ECDHE
* TLS_ECDHE_ECDSA_WITH_AES_128_CCM ([RFC 6655][rfc6655])
* TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ([RFC 6655][rfc6655])
* TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ([RFC 5289][rfc5289])
* TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ([RFC 5289][rfc5289])
* TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 ([RFC 5289][rfc5289])
* TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ([RFC 5289][rfc5289])
* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ([RFC 8422][rfc8422])
* TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ([RFC 8422][rfc8422])
##### PSK
* TLS_PSK_WITH_AES_128_CCM ([RFC 6655][rfc6655])
* TLS_PSK_WITH_AES_128_CCM_8 ([RFC 6655][rfc6655])
* TLS_PSK_WITH_AES_256_CCM_8 ([RFC 6655][rfc6655])
* TLS_PSK_WITH_AES_128_GCM_SHA256 ([RFC 5487][rfc5487])
* TLS_PSK_WITH_AES_128_CBC_SHA256 ([RFC 5487][rfc5487])
[rfc5289]: https://tools.ietf.org/html/rfc5289
[rfc8422]: https://tools.ietf.org/html/rfc8422
[rfc6655]: https://tools.ietf.org/html/rfc6655
[rfc5487]: https://tools.ietf.org/html/rfc5487
##### ECDHE & PSK
* TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 ([RFC 5489][rfc5489])
#### Planned Features
* Chacha20Poly1305
@ -102,7 +118,6 @@ Pion DTLS can connect to itself and OpenSSL.
### Using with PSK
Pion DTLS also comes with examples that do key exchange via PSK
#### Pion DTLS
```sh
go run examples/listen/psk/main.go
@ -121,35 +136,16 @@ go run examples/dial/psk/main.go
openssl s_client -dtls1_2 -connect 127.0.0.1:4444 -psk abc123 -cipher PSK-AES128-CCM8
```
### Contributing
Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible:
### Community
Pion has an active community on the [Slack](https://pion.ly/slack).
* [Sean DuBois](https://github.com/Sean-Der) - *Original Author*
* [Michiel De Backker](https://github.com/backkem) - *Public API*
* [Chris Hiszpanski](https://github.com/thinkski) - *Support Signature Algorithms Extension*
* [Iñigo Garcia Olaizola](https://github.com/igolaizola) - *Serialization & resumption, cert verification, E2E*
* [Daniele Sluijters](https://github.com/daenney) - *AES-CCM support*
* [Jin Lei](https://github.com/jinleileiking) - *Logging*
* [Hugo Arregui](https://github.com/hugoArregui)
* [Lander Noterman](https://github.com/LanderN)
* [Aleksandr Razumov](https://github.com/ernado) - *Fuzzing*
* [Ryan Gordon](https://github.com/ryangordon)
* [Stefan Tatschner](https://rumpelsepp.org/contact.html)
* [Hayden James](https://github.com/hjames9)
* [Jozef Kralik](https://github.com/jkralik)
* [Robert Eperjesi](https://github.com/epes)
* [Atsushi Watanabe](https://github.com/at-wat)
* [Julien Salleyron](https://github.com/juliens) - *Server Name Indication*
* [Jeroen de Bruijn](https://github.com/vidavidorra)
* [bjdgyc](https://github.com/bjdgyc)
* [Jeffrey Stoke (Jeff Ctor)](https://github.com/jeffreystoke) - *Fragmentbuffer Fix*
* [Frank Olbricht](https://github.com/folbricht)
* [ZHENK](https://github.com/scorpionknifes)
* [Carson Hoffman](https://github.com/CarsonHoffman)
* [Vadim Filimonov](https://github.com/fffilimonov)
* [Jim Wert](https://github.com/bocajim)
* [Alvaro Viebrantz](https://github.com/alvarowolfx)
* [Kegan Dougal](https://github.com/Kegsay)
Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news.
We are always looking to support **your projects**. Please reach out if you have something to build!
If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly)
### Contributing
Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt)
### License
MIT License - see [LICENSE](LICENSE) for full text

View file

@ -1,35 +1,105 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"strings"
)
func (c *handshakeConfig) getCertificate(serverName string) (*tls.Certificate, error) {
// ClientHelloInfo contains information from a ClientHello message in order to
// guide application logic in the GetCertificate.
type ClientHelloInfo struct {
// ServerName indicates the name of the server requested by the client
// in order to support virtual hosting. ServerName is only set if the
// client is using SNI (see RFC 4366, Section 3.1).
ServerName string
// CipherSuites lists the CipherSuites supported by the client (e.g.
// TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256).
CipherSuites []CipherSuiteID
}
// CertificateRequestInfo contains information from a server's
// CertificateRequest message, which is used to demand a certificate and proof
// of control from a client.
type CertificateRequestInfo struct {
// AcceptableCAs contains zero or more, DER-encoded, X.501
// Distinguished Names. These are the names of root or intermediate CAs
// that the server wishes the returned certificate to be signed by. An
// empty slice indicates that the server has no preference.
AcceptableCAs [][]byte
}
// SupportsCertificate returns nil if the provided certificate is supported by
// the server that sent the CertificateRequest. Otherwise, it returns an error
// describing the reason for the incompatibility.
// NOTE: original src: https://github.com/golang/go/blob/29b9a328d268d53833d2cc063d1d8b4bf6852675/src/crypto/tls/common.go#L1273
func (cri *CertificateRequestInfo) SupportsCertificate(c *tls.Certificate) error {
if len(cri.AcceptableCAs) == 0 {
return nil
}
for j, cert := range c.Certificate {
x509Cert := c.Leaf
// Parse the certificate if this isn't the leaf node, or if
// chain.Leaf was nil.
if j != 0 || x509Cert == nil {
var err error
if x509Cert, err = x509.ParseCertificate(cert); err != nil {
return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err)
}
}
for _, ca := range cri.AcceptableCAs {
if bytes.Equal(x509Cert.RawIssuer, ca) {
return nil
}
}
}
return errNotAcceptableCertificateChain
}
func (c *handshakeConfig) setNameToCertificateLocked() {
nameToCertificate := make(map[string]*tls.Certificate)
for i := range c.localCertificates {
cert := &c.localCertificates[i]
x509Cert := cert.Leaf
if x509Cert == nil {
var parseErr error
x509Cert, parseErr = x509.ParseCertificate(cert.Certificate[0])
if parseErr != nil {
continue
}
}
if len(x509Cert.Subject.CommonName) > 0 {
nameToCertificate[strings.ToLower(x509Cert.Subject.CommonName)] = cert
}
for _, san := range x509Cert.DNSNames {
nameToCertificate[strings.ToLower(san)] = cert
}
}
c.nameToCertificate = nameToCertificate
}
func (c *handshakeConfig) getCertificate(clientHelloInfo *ClientHelloInfo) (*tls.Certificate, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.nameToCertificate == nil {
nameToCertificate := make(map[string]*tls.Certificate)
for i := range c.localCertificates {
cert := &c.localCertificates[i]
x509Cert := cert.Leaf
if x509Cert == nil {
var parseErr error
x509Cert, parseErr = x509.ParseCertificate(cert.Certificate[0])
if parseErr != nil {
continue
}
}
if len(x509Cert.Subject.CommonName) > 0 {
nameToCertificate[strings.ToLower(x509Cert.Subject.CommonName)] = cert
}
for _, san := range x509Cert.DNSNames {
nameToCertificate[strings.ToLower(san)] = cert
}
if c.localGetCertificate != nil &&
(len(c.localCertificates) == 0 || len(clientHelloInfo.ServerName) > 0) {
cert, err := c.localGetCertificate(clientHelloInfo)
if cert != nil || err != nil {
return cert, err
}
c.nameToCertificate = nameToCertificate
}
if c.nameToCertificate == nil {
c.setNameToCertificateLocked()
}
if len(c.localCertificates) == 0 {
@ -41,11 +111,11 @@ func (c *handshakeConfig) getCertificate(serverName string) (*tls.Certificate, e
return &c.localCertificates[0], nil
}
if len(serverName) == 0 {
if len(clientHelloInfo.ServerName) == 0 {
return &c.localCertificates[0], nil
}
name := strings.TrimRight(strings.ToLower(serverName), ".")
name := strings.TrimRight(strings.ToLower(clientHelloInfo.ServerName), ".")
if cert, ok := c.nameToCertificate[name]; ok {
return cert, nil
@ -65,3 +135,23 @@ func (c *handshakeConfig) getCertificate(serverName string) (*tls.Certificate, e
// If nothing matches, return the first certificate.
return &c.localCertificates[0], nil
}
// NOTE: original src: https://github.com/golang/go/blob/29b9a328d268d53833d2cc063d1d8b4bf6852675/src/crypto/tls/handshake_client.go#L974
func (c *handshakeConfig) getClientCertificate(cri *CertificateRequestInfo) (*tls.Certificate, error) {
c.mu.Lock()
defer c.mu.Unlock()
if c.localGetClientCertificate != nil {
return c.localGetClientCertificate(cri)
}
for i := range c.localCertificates {
chain := c.localCertificates[i]
if err := cri.SupportsCertificate(&chain); err != nil {
continue
}
return &chain, nil
}
// No acceptable certificate found. Don't send a certificate.
return new(tls.Certificate), nil
}

View file

@ -1,6 +1,13 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"fmt"
"hash"
@ -15,21 +22,27 @@ type CipherSuiteID = ciphersuite.ID
// Supported Cipher Suites
const (
// AES-128-CCM
TLS_ECDHE_ECDSA_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM //nolint:revive,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 //nolint:revive,stylecheck
// AES-128-GCM-SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 //nolint:revive,stylecheck
// AES-256-CBC-SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA //nolint:golint,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM_8 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CBC_SHA256 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM_8 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_256_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_256_CCM_8 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CBC_SHA256 //nolint:revive,stylecheck
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 //nolint:revive,stylecheck
)
// CipherSuiteAuthenticationType controls what authentication method is using during the handshake for a CipherSuite
@ -42,6 +55,16 @@ const (
CipherSuiteAuthenticationTypeAnonymous CipherSuiteAuthenticationType = ciphersuite.AuthenticationTypeAnonymous
)
// CipherSuiteKeyExchangeAlgorithm controls what exchange algorithm is using during the handshake for a CipherSuite
type CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithm
// CipherSuiteKeyExchangeAlgorithm Bitmask
const (
CipherSuiteKeyExchangeAlgorithmNone CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmNone
CipherSuiteKeyExchangeAlgorithmPsk CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmPsk
CipherSuiteKeyExchangeAlgorithmEcdhe CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmEcdhe
)
var _ = allCipherSuites() // Necessary until this function isn't only used by Go 1.14
// CipherSuite is an interface that all DTLS CipherSuites must satisfy
@ -61,10 +84,16 @@ type CipherSuite interface {
// AuthenticationType controls what authentication method is using during the handshake
AuthenticationType() CipherSuiteAuthenticationType
// KeyExchangeAlgorithm controls what exchange algorithm is using during the handshake
KeyExchangeAlgorithm() CipherSuiteKeyExchangeAlgorithm
// ECC (Elliptic Curve Cryptography) determines whether ECC extesions will be send during handshake.
// https://datatracker.ietf.org/doc/html/rfc4492#page-10
ECC() bool
// Called when keying material has been generated, should initialize the internal cipher
Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error
IsInitialized() bool
Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error)
Decrypt(in []byte) ([]byte, error)
}
@ -103,10 +132,18 @@ func cipherSuiteForID(id CipherSuiteID, customCiphers func() []CipherSuite) Ciph
return ciphersuite.NewTLSPskWithAes128Ccm()
case TLS_PSK_WITH_AES_128_CCM_8:
return ciphersuite.NewTLSPskWithAes128Ccm8()
case TLS_PSK_WITH_AES_256_CCM_8:
return ciphersuite.NewTLSPskWithAes256Ccm8()
case TLS_PSK_WITH_AES_128_GCM_SHA256:
return &ciphersuite.TLSPskWithAes128GcmSha256{}
case TLS_PSK_WITH_AES_128_CBC_SHA256:
return &ciphersuite.TLSPskWithAes128CbcSha256{}
case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
return &ciphersuite.TLSEcdheEcdsaWithAes256GcmSha384{}
case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
return &ciphersuite.TLSEcdheRsaWithAes256GcmSha384{}
case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
return ciphersuite.NewTLSEcdhePskWithAes128CbcSha256()
}
if customCiphers != nil {
@ -127,6 +164,8 @@ func defaultCipherSuites() []CipherSuite {
&ciphersuite.TLSEcdheRsaWithAes128GcmSha256{},
&ciphersuite.TLSEcdheEcdsaWithAes256CbcSha{},
&ciphersuite.TLSEcdheRsaWithAes256CbcSha{},
&ciphersuite.TLSEcdheEcdsaWithAes256GcmSha384{},
&ciphersuite.TLSEcdheRsaWithAes256GcmSha384{},
}
}
@ -140,7 +179,10 @@ func allCipherSuites() []CipherSuite {
&ciphersuite.TLSEcdheRsaWithAes256CbcSha{},
ciphersuite.NewTLSPskWithAes128Ccm(),
ciphersuite.NewTLSPskWithAes128Ccm8(),
ciphersuite.NewTLSPskWithAes256Ccm8(),
&ciphersuite.TLSPskWithAes128GcmSha256{},
&ciphersuite.TLSEcdheEcdsaWithAes256GcmSha384{},
&ciphersuite.TLSEcdheRsaWithAes256GcmSha384{},
}
}
@ -158,7 +200,7 @@ func parseCipherSuites(userSelectedSuites []CipherSuiteID, customCipherSuites fu
for _, id := range ids {
c := cipherSuiteForID(id, nil)
if c == nil {
return nil, &invalidCipherSuite{id}
return nil, &invalidCipherSuiteError{id}
}
cipherSuites = append(cipherSuites, c)
}
@ -211,3 +253,24 @@ func parseCipherSuites(userSelectedSuites []CipherSuiteID, customCipherSuites fu
return cipherSuites[:i], nil
}
func filterCipherSuitesForCertificate(cert *tls.Certificate, cipherSuites []CipherSuite) []CipherSuite {
if cert == nil || cert.PrivateKey == nil {
return cipherSuites
}
var certType clientcertificate.Type
switch cert.PrivateKey.(type) {
case ed25519.PrivateKey, *ecdsa.PrivateKey:
certType = clientcertificate.ECDSASign
case *rsa.PrivateKey:
certType = clientcertificate.RSASign
}
filtered := []CipherSuite{}
for _, c := range cipherSuites {
if c.AuthenticationType() != CipherSuiteAuthenticationTypeCertificate || certType == c.CertificateType() {
filtered = append(filtered, c)
}
}
return filtered
}

View file

@ -1,3 +1,7 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build go1.14
// +build go1.14
package dtls

View file

@ -3,6 +3,8 @@
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
coverage:
status:

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import "github.com/pion/dtls/v2/pkg/protocol"

View file

@ -1,14 +1,19 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"context"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"io"
"time"
"github.com/pion/dtls/v2/pkg/crypto/elliptic"
"github.com/pion/logging"
)
@ -81,6 +86,16 @@ type Config struct {
// be considered but the verifiedChains will always be nil.
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
// VerifyConnection, if not nil, is called after normal certificate
// verification/PSK and after VerifyPeerCertificate by either a TLS client
// or server. If it returns a non-nil error, the handshake is aborted
// and that error results.
//
// If normal verification fails then the handshake will abort before
// considering this callback. This callback will run for all connections
// regardless of InsecureSkipVerify or ClientAuth settings.
VerifyConnection func(*State) error
// RootCAs defines the set of root certificate authorities
// that one peer uses when verifying the other peer's certificates.
// If RootCAs is nil, TLS uses the host's root CA set.
@ -123,6 +138,44 @@ type Config struct {
// Use of KeyLogWriter compromises security and should only be
// used for debugging.
KeyLogWriter io.Writer
// SessionStore is the container to store session for resumption.
SessionStore SessionStore
// List of application protocols the peer supports, for ALPN
SupportedProtocols []string
// List of Elliptic Curves to use
//
// If an ECC ciphersuite is configured and EllipticCurves is empty
// it will default to X25519, P-256, P-384 in this specific order.
EllipticCurves []elliptic.Curve
// GetCertificate returns a Certificate based on the given
// ClientHelloInfo. It will only be called if the client supplies SNI
// information or if Certificates is empty.
//
// If GetCertificate is nil or returns nil, then the certificate is
// retrieved from NameToCertificate. If NameToCertificate is nil, the
// best element of Certificates will be used.
GetCertificate func(*ClientHelloInfo) (*tls.Certificate, error)
// GetClientCertificate, if not nil, is called when a server requests a
// certificate from a client. If set, the contents of Certificates will
// be ignored.
//
// If GetClientCertificate returns an error, the handshake will be
// aborted and that error will be returned. Otherwise
// GetClientCertificate must return a non-nil Certificate. If
// Certificate.Certificate is empty then no certificate will be sent to
// the server. If this is unacceptable to the server then it may abort
// the handshake.
GetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error)
// InsecureSkipVerifyHello, if true and when acting as server, allow client to
// skip hello verify phase and receive ServerHello after initial ClientHello.
// This have implication on DoS attack resistance.
InsecureSkipVerifyHello bool
}
func defaultConnectContextMaker() (context.Context, func()) {
@ -136,8 +189,14 @@ func (c *Config) connectContextMaker() (context.Context, func()) {
return c.ConnectContextMaker()
}
func (c *Config) includeCertificateSuites() bool {
return c.PSK == nil || len(c.Certificates) > 0 || c.GetCertificate != nil || c.GetClientCertificate != nil
}
const defaultMTU = 1200 // bytes
var defaultCurves = []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384} //nolint:gochecknoglobals
// PSKCallback is called once we have the remote's PSKIdentityHint.
// If the remote provided none it will be nil
type PSKCallback func([]byte) ([]byte, error)
@ -182,12 +241,13 @@ func validateConfig(config *Config) error {
switch cert.PrivateKey.(type) {
case ed25519.PrivateKey:
case *ecdsa.PrivateKey:
case *rsa.PrivateKey:
default:
return errInvalidPrivateKey
}
}
}
_, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.PSK == nil || len(config.Certificates) > 0, config.PSK != nil)
_, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil)
return err
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -18,14 +21,15 @@ import (
"github.com/pion/dtls/v2/pkg/protocol/handshake"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
"github.com/pion/logging"
"github.com/pion/transport/connctx"
"github.com/pion/transport/deadline"
"github.com/pion/transport/replaydetector"
"github.com/pion/transport/v2/connctx"
"github.com/pion/transport/v2/deadline"
"github.com/pion/transport/v2/replaydetector"
)
const (
initialTickerInterval = time.Second
cookieLength = 20
sessionLength = 32
defaultNamedCurve = elliptic.X25519
inboundBufferSize = 8192
// Default replay protection window is specified by RFC 6347 Section 4.1.2.6
@ -87,7 +91,7 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient
return nil, errNilNextConn
}
cipherSuites, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.PSK == nil || len(config.Certificates) > 0, config.PSK != nil)
cipherSuites, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil)
if err != nil {
return nil, err
}
@ -147,16 +151,15 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient
c.setLocalEpoch(0)
serverName := config.ServerName
// Use host from conn address when serverName is not provided
if isClient && serverName == "" && nextConn.RemoteAddr() != nil {
remoteAddr := nextConn.RemoteAddr().String()
var host string
host, _, err = net.SplitHostPort(remoteAddr)
if err != nil {
serverName = remoteAddr
} else {
serverName = host
}
// Do not allow the use of an IP address literal as an SNI value.
// See RFC 6066, Section 3.
if net.ParseIP(serverName) != nil {
serverName = ""
}
curves := config.EllipticCurves
if len(curves) == 0 {
curves = defaultCurves
}
hsCfg := &handshakeConfig{
@ -167,10 +170,12 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient
extendedMasterSecret: config.ExtendedMasterSecret,
localSRTPProtectionProfiles: config.SRTPProtectionProfiles,
serverName: serverName,
supportedProtocols: config.SupportedProtocols,
clientAuth: config.ClientAuth,
localCertificates: config.Certificates,
insecureSkipVerify: config.InsecureSkipVerify,
verifyPeerCertificate: config.VerifyPeerCertificate,
verifyConnection: config.VerifyConnection,
rootCAs: config.RootCAs,
clientCAs: config.ClientCAs,
customCipherSuites: config.CustomCipherSuites,
@ -178,6 +183,22 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient
log: logger,
initialEpoch: 0,
keyLogWriter: config.KeyLogWriter,
sessionStore: config.SessionStore,
ellipticCurves: curves,
localGetCertificate: config.GetCertificate,
localGetClientCertificate: config.GetClientCertificate,
insecureSkipHelloVerify: config.InsecureSkipVerifyHello,
}
// rfc5246#section-7.4.3
// In addition, the hash and signature algorithms MUST be compatible
// with the key in the server's end-entity certificate.
if !isClient {
cert, err := hsCfg.getCertificate(&ClientHelloInfo{})
if err != nil && !errors.Is(err, errNoCertificates) {
return nil, err
}
hsCfg.localCipherSuites = filterCipherSuitesForCertificate(cert, cipherSuites)
}
var initialFlight flightVal
@ -324,7 +345,7 @@ func (c *Conn) Write(p []byte) (int, error) {
{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Epoch: c.getLocalEpoch(),
Epoch: c.state.getLocalEpoch(),
Version: protocol.Version1_2,
},
Content: &protocol.ApplicationData{
@ -338,7 +359,7 @@ func (c *Conn) Write(p []byte) (int, error) {
// Close closes the connection.
func (c *Conn) Close() error {
err := c.close(true)
err := c.close(true) //nolint:contextcheck
c.handshakeLoopsFinished.Wait()
return err
}
@ -409,6 +430,11 @@ func (c *Conn) writePackets(ctx context.Context, pkts []*packet) error {
}
func (c *Conn) compactRawPackets(rawPackets [][]byte) [][]byte {
// avoid a useless copy in the common case
if len(rawPackets) == 1 {
return rawPackets
}
combinedRawPackets := make([][]byte, 0)
currentCombinedRawPacket := make([]byte, 0)
@ -481,14 +507,14 @@ func (c *Conn) processHandshakePacket(p *packet, h *handshake.Handshake) ([][]by
SequenceNumber: seq,
}
recordlayerHeaderBytes, err := recordlayerHeader.Marshal()
rawPacket, err := recordlayerHeader.Marshal()
if err != nil {
return nil, err
}
p.record.Header = *recordlayerHeader
rawPacket := append(recordlayerHeaderBytes, handshakeFragment...)
rawPacket = append(rawPacket, handshakeFragment...)
if p.shouldEncrypt {
var err error
rawPacket, err = c.state.cipherSuite.Encrypt(p.record, rawPacket)
@ -532,12 +558,12 @@ func (c *Conn) fragmentHandshake(h *handshake.Handshake) ([][]byte, error) {
offset += contentFragmentLen
headerFragmentRaw, err := headerFragment.Marshal()
fragmentedHandshake, err := headerFragment.Marshal()
if err != nil {
return nil, err
}
fragmentedHandshake := append(headerFragmentRaw, contentFragment...)
fragmentedHandshake = append(fragmentedHandshake, contentFragment...)
fragmentedHandshakes = append(fragmentedHandshakes, fragmentedHandshake)
}
@ -552,7 +578,10 @@ var poolReadBuffer = sync.Pool{ //nolint:gochecknoglobals
}
func (c *Conn) readAndBuffer(ctx context.Context) error {
bufptr := poolReadBuffer.Get().(*[]byte)
bufptr, ok := poolReadBuffer.Get().(*[]byte)
if !ok {
return errFailedToAccessPoolReadBuffer
}
defer poolReadBuffer.Put(bufptr)
b := *bufptr
@ -568,7 +597,7 @@ func (c *Conn) readAndBuffer(ctx context.Context) error {
var hasHandshake bool
for _, p := range pkts {
hs, alert, err := c.handleIncomingPacket(p, true)
hs, alert, err := c.handleIncomingPacket(ctx, p, true)
if alert != nil {
if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
if err == nil {
@ -579,13 +608,13 @@ func (c *Conn) readAndBuffer(ctx context.Context) error {
if hs {
hasHandshake = true
}
switch e := err.(type) {
case nil:
case *errAlert:
var e *alertError
if errors.As(err, &e) {
if e.IsFatalOrCloseNotify() {
return e
}
default:
} else if err != nil {
return e
}
}
@ -607,7 +636,7 @@ func (c *Conn) handleQueuedPackets(ctx context.Context) error {
c.encryptedPackets = nil
for _, p := range pkts {
_, alert, err := c.handleIncomingPacket(p, false) // don't re-enqueue
_, alert, err := c.handleIncomingPacket(ctx, p, false) // don't re-enqueue
if alert != nil {
if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
if err == nil {
@ -615,20 +644,19 @@ func (c *Conn) handleQueuedPackets(ctx context.Context) error {
}
}
}
switch e := err.(type) {
case nil:
case *errAlert:
var e *alertError
if errors.As(err, &e) {
if e.IsFatalOrCloseNotify() {
return e
}
default:
} else if err != nil {
return e
}
}
return nil
}
func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Alert, error) { //nolint:gocognit
func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, enqueue bool) (bool, *alert.Alert, error) { //nolint:gocognit
h := &recordlayer.Header{}
if err := h.Unmarshal(buf); err != nil {
// Decode error must be silently discarded
@ -638,7 +666,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Aler
}
// Validate epoch
remoteEpoch := c.getRemoteEpoch()
remoteEpoch := c.state.getRemoteEpoch()
if h.Epoch > remoteEpoch {
if h.Epoch > remoteEpoch+1 {
c.log.Debugf("discarded future packet (epoch: %d, seq: %d)",
@ -694,13 +722,12 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Aler
} else if isHandshake {
markPacketAsValid()
for out, epoch := c.fragmentBuffer.pop(); out != nil; out, epoch = c.fragmentBuffer.pop() {
rawHandshake := &handshake.Handshake{}
if err := rawHandshake.Unmarshal(out); err != nil {
header := &handshake.Header{}
if err := header.Unmarshal(out); err != nil {
c.log.Debugf("%s: handshake parse failed: %s", srvCliStr(c.state.isClient), err)
continue
}
_ = c.handshakeCache.push(out, epoch, rawHandshake.Header.MessageSequence, rawHandshake.Header.Type, !c.state.isClient)
c.handshakeCache.push(out, epoch, header.MessageSequence, header.Type, !c.state.isClient)
}
return true, nil, nil
@ -720,7 +747,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Aler
a = &alert.Alert{Level: alert.Warning, Description: alert.CloseNotify}
}
markPacketAsValid()
return false, a, &errAlert{content}
return false, a, &alertError{content}
case *protocol.ChangeCipherSpec:
if c.state.cipherSuite == nil || !c.state.cipherSuite.IsInitialized() {
if enqueue {
@ -733,7 +760,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Aler
newRemoteEpoch := h.Epoch + 1
c.log.Tracef("%s: <- ChangeCipherSpec (epoch: %d)", srvCliStr(c.state.isClient), newRemoteEpoch)
if c.getRemoteEpoch()+1 == newRemoteEpoch {
if c.state.getRemoteEpoch()+1 == newRemoteEpoch {
c.setRemoteEpoch(newRemoteEpoch)
markPacketAsValid()
}
@ -747,6 +774,7 @@ func (c *Conn) handleIncomingPacket(buf []byte, enqueue bool) (bool, *alert.Aler
select {
case c.decrypted <- content.Data:
case <-c.closed.Done():
case <-ctx.Done():
}
default:
@ -760,11 +788,21 @@ func (c *Conn) recvHandshake() <-chan chan struct{} {
}
func (c *Conn) notify(ctx context.Context, level alert.Level, desc alert.Description) error {
if level == alert.Fatal && len(c.state.SessionID) > 0 {
// According to the RFC, we need to delete the stored session.
// https://datatracker.ietf.org/doc/html/rfc5246#section-7.2
if ss := c.fsm.cfg.sessionStore; ss != nil {
c.log.Tracef("clean invalid session: %s", c.state.SessionID)
if err := ss.Del(c.sessionKey()); err != nil {
return err
}
}
}
return c.writePackets(ctx, []*packet{
{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Epoch: c.getLocalEpoch(),
Epoch: c.state.getLocalEpoch(),
Version: protocol.Version1_2,
},
Content: &alert.Alert{
@ -830,42 +868,49 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh
defer c.handshakeLoopsFinished.Done()
for {
if err := c.readAndBuffer(ctxRead); err != nil {
switch e := err.(type) {
case *errAlert:
var e *alertError
if errors.As(err, &e) {
if !e.IsFatalOrCloseNotify() {
if c.isHandshakeCompletedSuccessfully() {
// Pass the error to Read()
select {
case c.decrypted <- err:
case <-c.closed.Done():
case <-ctxRead.Done():
}
}
continue // non-fatal alert must not stop read loop
}
case error:
switch err {
case context.DeadlineExceeded, context.Canceled, io.EOF:
} else {
switch {
case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled), errors.Is(err, io.EOF):
default:
if c.isHandshakeCompletedSuccessfully() {
// Keep read loop and pass the read error to Read()
select {
case c.decrypted <- err:
case <-c.closed.Done():
case <-ctxRead.Done():
}
continue // non-fatal alert must not stop read loop
}
}
}
select {
case firstErr <- err:
default:
}
if e, ok := err.(*errAlert); ok {
if e != nil {
if e.IsFatalOrCloseNotify() {
_ = c.close(false)
_ = c.close(false) //nolint:contextcheck
}
}
if !c.isConnectionClosed() && errors.Is(err, context.Canceled) {
c.log.Trace("handshake timeouts - closing underline connection")
_ = c.close(false) //nolint:contextcheck
}
return
}
}
@ -875,10 +920,12 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh
case err := <-firstErr:
cancelRead()
cancel()
c.handshakeLoopsFinished.Wait()
return c.translateHandshakeCtxError(err)
case <-ctx.Done():
cancelRead()
cancel()
c.handshakeLoopsFinished.Wait()
return c.translateHandshakeCtxError(ctx.Err())
case <-done:
return nil
@ -911,6 +958,7 @@ func (c *Conn) close(byUser bool) error {
if byUser {
c.connectionClosedByUser = true
}
isClosed := c.isConnectionClosed()
c.closed.Close()
c.closeLock.Unlock()
@ -918,6 +966,10 @@ func (c *Conn) close(byUser bool) error {
return ErrConnClosed
}
if isClosed {
return nil
}
return c.nextConn.Close()
}
@ -934,18 +986,10 @@ func (c *Conn) setLocalEpoch(epoch uint16) {
c.state.localEpoch.Store(epoch)
}
func (c *Conn) getLocalEpoch() uint16 {
return c.state.localEpoch.Load().(uint16)
}
func (c *Conn) setRemoteEpoch(epoch uint16) {
c.state.remoteEpoch.Store(epoch)
}
func (c *Conn) getRemoteEpoch() uint16 {
return c.state.remoteEpoch.Load().(uint16)
}
// LocalAddr implements net.Conn.LocalAddr
func (c *Conn) LocalAddr() net.Addr {
return c.nextConn.LocalAddr()
@ -956,6 +1000,16 @@ func (c *Conn) RemoteAddr() net.Addr {
return c.nextConn.RemoteAddr()
}
func (c *Conn) sessionKey() []byte {
if c.state.isClient {
// As ServerName can be like 0.example.com, it's better to add
// delimiter character which is not allowed to be in
// neither address or domain name.
return []byte(c.nextConn.RemoteAddr().String() + "_" + c.fsm.cfg.serverName)
}
return c.state.SessionID
}
// SetDeadline implements net.Conn.SetDeadline
func (c *Conn) SetDeadline(t time.Time) error {
c.readDeadline.Set(t)

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -108,6 +111,13 @@ func verifyKeySignature(message, remoteKeySignature []byte, hashAlgorithm hash.A
// the private key in the certificate.
// https://tools.ietf.org/html/rfc5246#section-7.3
func generateCertificateVerify(handshakeBodies []byte, privateKey crypto.PrivateKey, hashAlgorithm hash.Algorithm) ([]byte, error) {
if p, ok := privateKey.(ed25519.PrivateKey); ok {
// https://pkg.go.dev/crypto/ed25519#PrivateKey.Sign
// Sign signs the given message with priv. Ed25519 performs two passes over
// messages to be signed and therefore cannot handle pre-hashed messages.
return p.Sign(rand.Reader, handshakeBodies, crypto.Hash(0))
}
h := sha256.New()
if _, err := h.Write(handshakeBodies); err != nil {
return nil, err
@ -115,9 +125,6 @@ func generateCertificateVerify(handshakeBodies []byte, privateKey crypto.Private
hashed := h.Sum(nil)
switch p := privateKey.(type) {
case ed25519.PrivateKey:
// https://crypto.stackexchange.com/a/55483
return p.Sign(rand.Reader, hashed, crypto.Hash(0))
case *ecdsa.PrivateKey:
return p.Sign(rand.Reader, hashed, hashAlgorithm.CryptoHash())
case *rsa.PrivateKey:

View file

@ -1,2 +1,5 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package dtls implements Datagram Transport Layer Security (DTLS) 1.2
package dtls

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -10,14 +13,13 @@ import (
"github.com/pion/dtls/v2/pkg/protocol"
"github.com/pion/dtls/v2/pkg/protocol/alert"
"golang.org/x/xerrors"
)
// Typed errors
var (
ErrConnClosed = &FatalError{Err: errors.New("conn is closed")} //nolint:goerr113
errDeadlineExceeded = &TimeoutError{Err: xerrors.Errorf("read/write timeout: %w", context.DeadlineExceeded)}
errDeadlineExceeded = &TimeoutError{Err: fmt.Errorf("read/write timeout: %w", context.DeadlineExceeded)}
errInvalidContentType = &TemporaryError{Err: errors.New("invalid content type")} //nolint:goerr113
errBufferTooSmall = &TemporaryError{Err: errors.New("buffer is too small")} //nolint:goerr113
@ -55,6 +57,7 @@ var (
errServerNoMatchingSRTPProfile = &FatalError{Err: errors.New("client requested SRTP but we have no matching profiles")} //nolint:goerr113
errServerRequiredButNoClientEMS = &FatalError{Err: errors.New("server requires the Extended Master Secret extension, but the client does not support it")} //nolint:goerr113
errVerifyDataMismatch = &FatalError{Err: errors.New("expected and actual verify data does not match")} //nolint:goerr113
errNotAcceptableCertificateChain = &FatalError{Err: errors.New("certificate chain is not signed by an acceptable CA")} //nolint:goerr113
errInvalidFlight = &InternalError{Err: errors.New("invalid flight number")} //nolint:goerr113
errKeySignatureGenerateUnimplemented = &InternalError{Err: errors.New("unable to generate key signature, unimplemented")} //nolint:goerr113
@ -62,6 +65,8 @@ var (
errLengthMismatch = &InternalError{Err: errors.New("data length and declared length do not match")} //nolint:goerr113
errSequenceNumberOverflow = &InternalError{Err: errors.New("sequence number overflow")} //nolint:goerr113
errInvalidFSMTransition = &InternalError{Err: errors.New("invalid state machine transition")} //nolint:goerr113
errFailedToAccessPoolReadBuffer = &InternalError{Err: errors.New("failed to access pool read buffer")} //nolint:goerr113
errFragmentBufferOverflow = &InternalError{Err: errors.New("fragment buffer overflow")} //nolint:goerr113
)
// FatalError indicates that the DTLS connection is no longer available.
@ -81,37 +86,39 @@ type TimeoutError = protocol.TimeoutError
// HandshakeError indicates that the handshake failed.
type HandshakeError = protocol.HandshakeError
// invalidCipherSuite indicates an attempt at using an unsupported cipher suite.
type invalidCipherSuite struct {
// errInvalidCipherSuite indicates an attempt at using an unsupported cipher suite.
type invalidCipherSuiteError struct {
id CipherSuiteID
}
func (e *invalidCipherSuite) Error() string {
func (e *invalidCipherSuiteError) Error() string {
return fmt.Sprintf("CipherSuite with id(%d) is not valid", e.id)
}
func (e *invalidCipherSuite) Is(err error) bool {
if other, ok := err.(*invalidCipherSuite); ok {
func (e *invalidCipherSuiteError) Is(err error) bool {
var other *invalidCipherSuiteError
if errors.As(err, &other) {
return e.id == other.id
}
return false
}
// errAlert wraps DTLS alert notification as an error
type errAlert struct {
type alertError struct {
*alert.Alert
}
func (e *errAlert) Error() string {
func (e *alertError) Error() string {
return fmt.Sprintf("alert: %s", e.Alert.String())
}
func (e *errAlert) IsFatalOrCloseNotify() bool {
func (e *alertError) IsFatalOrCloseNotify() bool {
return e.Level == alert.Fatal || e.Description == alert.CloseNotify
}
func (e *errAlert) Is(err error) bool {
if other, ok := err.(*errAlert); ok {
func (e *alertError) Is(err error) bool {
var other *alertError
if errors.As(err, &other) {
return e.Level == other.Level && e.Description == other.Description
}
return false
@ -119,14 +126,20 @@ func (e *errAlert) Is(err error) bool {
// netError translates an error from underlying Conn to corresponding net.Error.
func netError(err error) error {
switch err {
case io.EOF, context.Canceled, context.DeadlineExceeded:
switch {
case errors.Is(err, io.EOF), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
// Return io.EOF and context errors as is.
return err
}
switch e := err.(type) {
case (*net.OpError):
if se, ok := e.Err.(*os.SyscallError); ok {
var (
ne net.Error
opError *net.OpError
se *os.SyscallError
)
if errors.As(err, &opError) {
if errors.As(opError, &se) {
if se.Timeout() {
return &TimeoutError{Err: err}
}
@ -134,8 +147,11 @@ func netError(err error) error {
return &TemporaryError{Err: err}
}
}
case (net.Error):
}
if errors.As(err, &ne) {
return err
}
return &FatalError{Err: err}
}

View file

@ -1,3 +1,7 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build aix || darwin || dragonfly || freebsd || linux || nacl || nacljs || netbsd || openbsd || solaris || windows
// +build aix darwin dragonfly freebsd linux nacl nacljs netbsd openbsd solaris windows
// For systems having syscall.Errno.
@ -8,18 +12,11 @@
package dtls
import (
"errors"
"os"
"syscall"
)
func isOpErrorTemporary(err *os.SyscallError) bool {
if ne, ok := err.Err.(syscall.Errno); ok {
switch ne {
case syscall.ECONNREFUSED:
return true
default:
return false
}
}
return false
return errors.Is(err.Err, syscall.ECONNREFUSED)
}

View file

@ -1,3 +1,7 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
//go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !nacl && !nacljs && !netbsd && !openbsd && !solaris && !windows
// +build !aix,!darwin,!dragonfly,!freebsd,!linux,!nacl,!nacljs,!netbsd,!openbsd,!solaris,!windows
// For systems without syscall.Errno.

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
/*
@ -6,6 +9,9 @@ package dtls
of a number of messages, they should be viewed as monolithic for the
purpose of timeout and retransmission.
https://tools.ietf.org/html/rfc4347#section-4.2.4
Message flights for full handshake:
Client Server
------ ------
Waiting Flight 0
@ -31,6 +37,23 @@ package dtls
[ChangeCipherSpec] \ Flight 6
<-------- Finished /
Message flights for session-resuming handshake (no cookie exchange):
Client Server
------ ------
Waiting Flight 0
ClientHello --------> Flight 1
ServerHello \
[ChangeCipherSpec] Flight 4b
<-------- Finished /
[ChangeCipherSpec] \ Flight 5b
Finished --------> /
[ChangeCipherSpec] \ Flight 6
<-------- Finished /
*/
type flightVal uint8
@ -41,7 +64,9 @@ const (
flight2
flight3
flight4
flight4b
flight5
flight5b
flight6
)
@ -57,8 +82,12 @@ func (f flightVal) String() string {
return "Flight 3"
case flight4:
return "Flight 4"
case flight4b:
return "Flight 4b"
case flight5:
return "Flight 5"
case flight5b:
return "Flight 5b"
case flight6:
return "Flight 6"
default:
@ -67,9 +96,9 @@ func (f flightVal) String() string {
}
func (f flightVal) isLastSendFlight() bool {
return f == flight6
return f == flight6 || f == flight5b
}
func (f flightVal) isLastRecvFlight() bool {
return f == flight5
return f == flight5 || f == flight4b
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -11,8 +14,8 @@ import (
"github.com/pion/dtls/v2/pkg/protocol/handshake"
)
func flight0Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
seq, msgs, ok := cache.fullPullMap(0,
func flight0Parse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
seq, msgs, ok := cache.fullPullMap(0, state.cipherSuite,
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
)
if !ok {
@ -64,6 +67,8 @@ func flight0Parse(ctx context.Context, c flightConn, state *State, cache *handsh
}
case *extension.ServerName:
state.serverName = e.ServerName // remote server name
case *extension.ALPN:
state.peerSupportedProtocols = e.ProtocolNameList
}
}
@ -79,14 +84,45 @@ func flight0Parse(ctx context.Context, c flightConn, state *State, cache *handsh
}
}
return flight2, nil, nil
nextFlight := flight2
if cfg.insecureSkipHelloVerify {
nextFlight = flight4
}
return handleHelloResume(clientHello.SessionID, state, cfg, nextFlight)
}
func flight0Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func handleHelloResume(sessionID []byte, state *State, cfg *handshakeConfig, next flightVal) (flightVal, *alert.Alert, error) {
if len(sessionID) > 0 && cfg.sessionStore != nil {
if s, err := cfg.sessionStore.Get(sessionID); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
} else if s.ID != nil {
cfg.log.Tracef("[handshake] resume session: %x", sessionID)
state.SessionID = sessionID
state.masterSecret = s.Secret
if err := state.initCipherSuite(); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
clientRandom := state.localRandom.MarshalFixed()
cfg.writeKeyLog(keyLogLabelTLS12, clientRandom[:], state.masterSecret)
return flight4b, nil, nil
}
}
return next, nil, nil
}
func flight0Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
// Initialize
state.cookie = make([]byte, cookieLength)
if _, err := rand.Read(state.cookie); err != nil {
return nil, nil, err
if !cfg.insecureSkipHelloVerify {
state.cookie = make([]byte, cookieLength)
if _, err := rand.Read(state.cookie); err != nil {
return nil, nil, err
}
}
var zeroEpoch uint16

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -14,7 +17,7 @@ import (
func flight1Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
// HelloVerifyRequest can be skipped by the server,
// so allow ServerHello during flight1 also
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeHelloVerifyRequest, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, true},
)
@ -43,7 +46,7 @@ func flight1Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
}
func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func flight1Generate(c flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
var zeroEpoch uint16
state.localEpoch.Store(zeroEpoch)
state.remoteEpoch.Store(zeroEpoch)
@ -62,10 +65,19 @@ func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
RenegotiatedConnection: 0,
},
}
if cfg.localPSKCallback == nil {
var setEllipticCurveCryptographyClientHelloExtensions bool
for _, c := range cfg.localCipherSuites {
if c.ECC() {
setEllipticCurveCryptographyClientHelloExtensions = true
break
}
}
if setEllipticCurveCryptographyClientHelloExtensions {
extensions = append(extensions, []extension.Extension{
&extension.SupportedEllipticCurves{
EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
EllipticCurves: cfg.ellipticCurves,
},
&extension.SupportedPointFormats{
PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
@ -90,6 +102,22 @@ func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
extensions = append(extensions, &extension.ServerName{ServerName: cfg.serverName})
}
if len(cfg.supportedProtocols) > 0 {
extensions = append(extensions, &extension.ALPN{ProtocolNameList: cfg.supportedProtocols})
}
if cfg.sessionStore != nil {
cfg.log.Tracef("[handshake] try to resume session")
if s, err := cfg.sessionStore.Get(c.sessionKey()); err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
} else if s.ID != nil {
cfg.log.Tracef("[handshake] get saved session: %x", s.ID)
state.SessionID = s.ID
state.masterSecret = s.Secret
}
}
return []*packet{
{
record: &recordlayer.RecordLayer{
@ -99,6 +127,7 @@ func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
Content: &handshake.Handshake{
Message: &handshake.MessageClientHello{
Version: protocol.Version1_2,
SessionID: state.SessionID,
Cookie: state.cookie,
Random: state.localRandom,
CipherSuiteIDs: cipherSuiteIDs(cfg.localCipherSuites),

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -11,7 +14,7 @@ import (
)
func flight2Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
)
if !ok {
@ -41,7 +44,7 @@ func flight2Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return flight4, nil, nil
}
func flight2Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func flight2Generate(_ flightConn, state *State, _ *handshakeCache, _ *handshakeConfig) ([]*packet, *alert.Alert, error) {
state.handshakeSendSequence = 0
return []*packet{
{

View file

@ -1,8 +1,13 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"context"
"github.com/pion/dtls/v2/internal/ciphersuite/types"
"github.com/pion/dtls/v2/pkg/crypto/elliptic"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol"
@ -16,7 +21,7 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh
// Clients may receive multiple HelloVerifyRequest messages with different cookies.
// Clients SHOULD handle this by sending a new ClientHello with a cookie in response
// to the new HelloVerifyRequest. RFC 6347 Section 4.2.1
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeHelloVerifyRequest, cfg.initialEpoch, false, true},
)
if ok {
@ -32,36 +37,23 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh
}
}
if cfg.localPSKCallback != nil {
seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence,
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerHelloDone, cfg.initialEpoch, false, false},
)
} else {
seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence,
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeCertificate, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeCertificateRequest, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerHelloDone, cfg.initialEpoch, false, false},
)
}
_, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
)
if !ok {
// Don't have enough messages. Keep reading
return 0, nil, nil
}
state.handshakeRecvSequence = seq
if h, ok := msgs[handshake.TypeServerHello].(*handshake.MessageServerHello); ok {
if h, msgOk := msgs[handshake.TypeServerHello].(*handshake.MessageServerHello); msgOk {
if !h.Version.Equal(protocol.Version1_2) {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.ProtocolVersion}, errUnsupportedProtocolVersion
}
for _, v := range h.Extensions {
switch e := v.(type) {
case *extension.UseSRTP:
profile, ok := findMatchingSRTPProfile(e.ProtectionProfiles, cfg.localSRTPProtectionProfiles)
if !ok {
profile, found := findMatchingSRTPProfile(e.ProtectionProfiles, cfg.localSRTPProtectionProfiles)
if !found {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.IllegalParameter}, errClientNoMatchingSRTPProfile
}
state.srtpProtectionProfile = profile
@ -69,6 +61,11 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh
if cfg.extendedMasterSecret != DisableExtendedMasterSecret {
state.extendedMasterSecret = true
}
case *extension.ALPN:
if len(e.ProtocolNameList) > 1 { // This should be exactly 1, the zero case is handle when unmarshalling
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, extension.ErrALPNInvalidFormat // Meh, internal error?
}
state.NegotiatedProtocol = e.ProtocolNameList[0]
}
}
if cfg.extendedMasterSecret == RequireExtendedMasterSecret && !state.extendedMasterSecret {
@ -83,16 +80,54 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errCipherSuiteNoIntersection
}
selectedCipherSuite, ok := findMatchingCipherSuite([]CipherSuite{remoteCipherSuite}, cfg.localCipherSuites)
if !ok {
selectedCipherSuite, found := findMatchingCipherSuite([]CipherSuite{remoteCipherSuite}, cfg.localCipherSuites)
if !found {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errInvalidCipherSuite
}
state.cipherSuite = selectedCipherSuite
state.remoteRandom = h.Random
cfg.log.Tracef("[handshake] use cipher suite: %s", selectedCipherSuite.String())
if len(h.SessionID) > 0 && bytes.Equal(state.SessionID, h.SessionID) {
return handleResumption(ctx, c, state, cache, cfg)
}
if len(state.SessionID) > 0 {
cfg.log.Tracef("[handshake] clean old session : %s", state.SessionID)
if err := cfg.sessionStore.Del(state.SessionID); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
if cfg.sessionStore == nil {
state.SessionID = []byte{}
} else {
state.SessionID = h.SessionID
}
state.masterSecret = []byte{}
}
if cfg.localPSKCallback != nil {
seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite,
handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerHelloDone, cfg.initialEpoch, false, false},
)
} else {
seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite,
handshakeCachePullRule{handshake.TypeCertificate, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeCertificateRequest, cfg.initialEpoch, false, true},
handshakeCachePullRule{handshake.TypeServerHelloDone, cfg.initialEpoch, false, false},
)
}
if !ok {
// Don't have enough messages. Keep reading
return 0, nil, nil
}
state.handshakeRecvSequence = seq
if h, ok := msgs[handshake.TypeCertificate].(*handshake.MessageCertificate); ok {
state.PeerCertificates = h.Certificate
} else if state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeCertificate {
@ -113,15 +148,72 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return flight5, nil, nil
}
func handleResumption(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
if err := state.initCipherSuite(); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
// Now, encrypted packets can be handled
if err := c.handleQueuedPackets(ctx); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false},
)
if !ok {
// No valid message received. Keep reading
return 0, nil, nil
}
var finished *handshake.MessageFinished
if finished, ok = msgs[handshake.TypeFinished].(*handshake.MessageFinished); !ok {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
}
plainText := cache.pullAndMerge(
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
)
expectedVerifyData, err := prf.VerifyDataServer(state.masterSecret, plainText, state.cipherSuite.HashFunc())
if err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
if !bytes.Equal(expectedVerifyData, finished.VerifyData) {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errVerifyDataMismatch
}
clientRandom := state.localRandom.MarshalFixed()
cfg.writeKeyLog(keyLogLabelTLS12, clientRandom[:], state.masterSecret)
return flight5b, nil, nil
}
func handleServerKeyExchange(_ flightConn, state *State, cfg *handshakeConfig, h *handshake.MessageServerKeyExchange) (*alert.Alert, error) {
var err error
if state.cipherSuite == nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errInvalidCipherSuite
}
if cfg.localPSKCallback != nil {
var psk []byte
if psk, err = cfg.localPSKCallback(h.IdentityHint); err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
state.IdentityHint = h.IdentityHint
state.preMasterSecret = prf.PSKPreMasterSecret(psk)
switch state.cipherSuite.KeyExchangeAlgorithm() {
case types.KeyExchangeAlgorithmPsk:
state.preMasterSecret = prf.PSKPreMasterSecret(psk)
case (types.KeyExchangeAlgorithmEcdhe | types.KeyExchangeAlgorithmPsk):
if state.localKeypair, err = elliptic.GenerateKeypair(h.NamedCurve); err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
state.preMasterSecret, err = prf.EcdhePSKPreMasterSecret(psk, h.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve)
if err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
default:
return &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errInvalidCipherSuite
}
} else {
if state.localKeypair, err = elliptic.GenerateKeypair(h.NamedCurve); err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
@ -132,10 +224,10 @@ func handleServerKeyExchange(_ flightConn, state *State, cfg *handshakeConfig, h
}
}
return nil, nil
return nil, nil //nolint:nilnil
}
func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func flight3Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
extensions := []extension.Extension{
&extension.SupportedSignatureAlgorithms{
SignatureHashAlgorithms: cfg.localSignatureSchemes,
@ -144,7 +236,7 @@ func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
RenegotiatedConnection: 0,
},
}
if cfg.localPSKCallback == nil {
if state.namedCurve != 0 {
extensions = append(extensions, []extension.Extension{
&extension.SupportedEllipticCurves{
EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
@ -172,6 +264,10 @@ func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
extensions = append(extensions, &extension.ServerName{ServerName: cfg.serverName})
}
if len(cfg.supportedProtocols) > 0 {
extensions = append(extensions, &extension.ALPN{ProtocolNameList: cfg.supportedProtocols})
}
return []*packet{
{
record: &recordlayer.RecordLayer{
@ -181,6 +277,7 @@ func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
Content: &handshake.Handshake{
Message: &handshake.MessageClientHello{
Version: protocol.Version1_2,
SessionID: state.SessionID,
Cookie: state.cookie,
Random: state.localRandom,
CipherSuiteIDs: cipherSuiteIDs(cfg.localCipherSuites),

View file

@ -0,0 +1,144 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"context"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol"
"github.com/pion/dtls/v2/pkg/protocol/alert"
"github.com/pion/dtls/v2/pkg/protocol/extension"
"github.com/pion/dtls/v2/pkg/protocol/handshake"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
func flight4bParse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false},
)
if !ok {
// No valid message received. Keep reading
return 0, nil, nil
}
var finished *handshake.MessageFinished
if finished, ok = msgs[handshake.TypeFinished].(*handshake.MessageFinished); !ok {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
}
plainText := cache.pullAndMerge(
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false},
)
expectedVerifyData, err := prf.VerifyDataClient(state.masterSecret, plainText, state.cipherSuite.HashFunc())
if err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
if !bytes.Equal(expectedVerifyData, finished.VerifyData) {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errVerifyDataMismatch
}
// Other party may re-transmit the last flight. Keep state to be flight4b.
return flight4b, nil, nil
}
func flight4bGenerate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
var pkts []*packet
extensions := []extension.Extension{&extension.RenegotiationInfo{
RenegotiatedConnection: 0,
}}
if (cfg.extendedMasterSecret == RequestExtendedMasterSecret ||
cfg.extendedMasterSecret == RequireExtendedMasterSecret) && state.extendedMasterSecret {
extensions = append(extensions, &extension.UseExtendedMasterSecret{
Supported: true,
})
}
if state.srtpProtectionProfile != 0 {
extensions = append(extensions, &extension.UseSRTP{
ProtectionProfiles: []SRTPProtectionProfile{state.srtpProtectionProfile},
})
}
selectedProto, err := extension.ALPNProtocolSelection(cfg.supportedProtocols, state.peerSupportedProtocols)
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.NoApplicationProtocol}, err
}
if selectedProto != "" {
extensions = append(extensions, &extension.ALPN{
ProtocolNameList: []string{selectedProto},
})
state.NegotiatedProtocol = selectedProto
}
cipherSuiteID := uint16(state.cipherSuite.ID())
serverHello := &handshake.Handshake{
Message: &handshake.MessageServerHello{
Version: protocol.Version1_2,
Random: state.localRandom,
SessionID: state.SessionID,
CipherSuiteID: &cipherSuiteID,
CompressionMethod: defaultCompressionMethods()[0],
Extensions: extensions,
},
}
serverHello.Header.MessageSequence = uint16(state.handshakeSendSequence)
if len(state.localVerifyData) == 0 {
plainText := cache.pullAndMerge(
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
)
raw, err := serverHello.Marshal()
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
plainText = append(plainText, raw...)
state.localVerifyData, err = prf.VerifyDataServer(state.masterSecret, plainText, state.cipherSuite.HashFunc())
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
pkts = append(pkts,
&packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: serverHello,
},
},
&packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: &protocol.ChangeCipherSpec{},
},
},
&packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
Epoch: 1,
},
Content: &handshake.Handshake{
Message: &handshake.MessageFinished{
VerifyData: state.localVerifyData,
},
},
},
shouldEncrypt: true,
resetLocalSequenceNumber: true,
},
)
return pkts, nil, nil
}

View file

@ -1,9 +1,14 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"context"
"crypto/rand"
"crypto/x509"
"github.com/pion/dtls/v2/internal/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
"github.com/pion/dtls/v2/pkg/crypto/elliptic"
"github.com/pion/dtls/v2/pkg/crypto/prf"
@ -16,7 +21,7 @@ import (
)
func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { //nolint:gocognit
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeCertificate, cfg.initialEpoch, true, true},
handshakeCachePullRule{handshake.TypeClientKeyExchange, cfg.initialEpoch, true, false},
handshakeCachePullRule{handshake.TypeCertificateVerify, cfg.initialEpoch, true, true},
@ -34,6 +39,12 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
if h, hasCert := msgs[handshake.TypeCertificate].(*handshake.MessageCertificate); hasCert {
state.PeerCertificates = h.Certificate
// If the client offer its certificate, just disable session resumption.
// Otherwise, we have to store the certificate identitfication and expire time.
// And we have to check whether this certificate expired, revoked or changed.
//
// https://curl.se/docs/CVE-2016-5419.html
state.SessionID = nil
}
if h, hasCertVerify := msgs[handshake.TypeCertificateVerify].(*handshake.MessageCertificateVerify); hasCertVerify {
@ -82,6 +93,10 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
}
}
state.peerCertificatesVerified = verified
} else if state.PeerCertificates != nil {
// A certificate was received, but we haven't seen a CertificateVerify
// keep reading until we receive one
return 0, nil, nil
}
if !state.cipherSuite.IsInitialized() {
@ -96,7 +111,16 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
state.IdentityHint = clientKeyExchange.IdentityHint
preMasterSecret = prf.PSKPreMasterSecret(psk)
switch state.cipherSuite.KeyExchangeAlgorithm() {
case CipherSuiteKeyExchangeAlgorithmPsk:
preMasterSecret = prf.PSKPreMasterSecret(psk)
case (CipherSuiteKeyExchangeAlgorithmPsk | CipherSuiteKeyExchangeAlgorithmEcdhe):
if preMasterSecret, err = prf.EcdhePSKPreMasterSecret(psk, clientKeyExchange.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
default:
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, errInvalidCipherSuite
}
} else {
preMasterSecret, err = prf.PreMasterSecret(clientKeyExchange.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve)
if err != nil {
@ -128,12 +152,23 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
cfg.writeKeyLog(keyLogLabelTLS12, clientRandom[:], state.masterSecret)
}
if len(state.SessionID) > 0 {
s := Session{
ID: state.SessionID,
Secret: state.masterSecret,
}
cfg.log.Tracef("[handshake] save new session: %x", s.ID)
if err := cfg.sessionStore.Set(state.SessionID, s); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
// Now, encrypted packets can be handled
if err := c.handleQueuedPackets(ctx); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
seq, msgs, ok = cache.fullPullMap(seq,
seq, msgs, ok = cache.fullPullMap(seq, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false},
)
if !ok {
@ -147,6 +182,11 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
}
if state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeAnonymous {
if cfg.verifyConnection != nil {
if err := cfg.verifyConnection(state.clone()); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err
}
}
return flight6, nil, nil
}
@ -167,13 +207,18 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, errClientCertificateNotVerified
}
case NoClientCert, RequestClientCert:
return flight6, nil, nil
// go to flight6
}
if cfg.verifyConnection != nil {
if err := cfg.verifyConnection(state.clone()); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err
}
}
return flight6, nil, nil
}
func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func flight4Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
extensions := []extension.Extension{&extension.RenegotiationInfo{
RenegotiatedConnection: 0,
}}
@ -189,19 +234,32 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
})
}
if state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeCertificate {
extensions = append(extensions, []extension.Extension{
&extension.SupportedEllipticCurves{
EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384},
},
&extension.SupportedPointFormats{
PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
},
}...)
extensions = append(extensions, &extension.SupportedPointFormats{
PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
})
}
selectedProto, err := extension.ALPNProtocolSelection(cfg.supportedProtocols, state.peerSupportedProtocols)
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.NoApplicationProtocol}, err
}
if selectedProto != "" {
extensions = append(extensions, &extension.ALPN{
ProtocolNameList: []string{selectedProto},
})
state.NegotiatedProtocol = selectedProto
}
var pkts []*packet
cipherSuiteID := uint16(state.cipherSuite.ID())
if cfg.sessionStore != nil {
state.SessionID = make([]byte, sessionLength)
if _, err := rand.Read(state.SessionID); err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
pkts = append(pkts, &packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
@ -211,6 +269,7 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
Message: &handshake.MessageServerHello{
Version: protocol.Version1_2,
Random: state.localRandom,
SessionID: state.SessionID,
CipherSuiteID: &cipherSuiteID,
CompressionMethod: defaultCompressionMethods()[0],
Extensions: extensions,
@ -221,7 +280,10 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
switch {
case state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeCertificate:
certificate, err := cfg.getCertificate(cfg.serverName)
certificate, err := cfg.getCertificate(&ClientHelloInfo{
ServerName: state.serverName,
CipherSuites: []ciphersuite.ID{state.cipherSuite.ID()},
})
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, err
}
@ -273,6 +335,16 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
})
if cfg.clientAuth > NoClientCert {
// An empty list of certificateAuthorities signals to
// the client that it may send any certificate in response
// to our request. When we know the CAs we trust, then
// we can send them down, so that the client can choose
// an appropriate certificate to give to us.
var certificateAuthorities [][]byte
if cfg.clientCAs != nil {
// nolint:staticcheck // ignoring tlsCert.RootCAs.Subjects is deprecated ERR because cert does not come from SystemCertPool and it's ok if certificate authorities is empty.
certificateAuthorities = cfg.clientCAs.Subjects()
}
pkts = append(pkts, &packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
@ -280,43 +352,36 @@ func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
},
Content: &handshake.Handshake{
Message: &handshake.MessageCertificateRequest{
CertificateTypes: []clientcertificate.Type{clientcertificate.RSASign, clientcertificate.ECDSASign},
SignatureHashAlgorithms: cfg.localSignatureSchemes,
CertificateTypes: []clientcertificate.Type{clientcertificate.RSASign, clientcertificate.ECDSASign},
SignatureHashAlgorithms: cfg.localSignatureSchemes,
CertificateAuthoritiesNames: certificateAuthorities,
},
},
},
})
}
case cfg.localPSKIdentityHint != nil:
case cfg.localPSKIdentityHint != nil || state.cipherSuite.KeyExchangeAlgorithm().Has(CipherSuiteKeyExchangeAlgorithmEcdhe):
// To help the client in selecting which identity to use, the server
// can provide a "PSK identity hint" in the ServerKeyExchange message.
// If no hint is provided, the ServerKeyExchange message is omitted.
// If no hint is provided and cipher suite doesn't use elliptic curve,
// the ServerKeyExchange message is omitted.
//
// https://tools.ietf.org/html/rfc4279#section-2
srvExchange := &handshake.MessageServerKeyExchange{
IdentityHint: cfg.localPSKIdentityHint,
}
if state.cipherSuite.KeyExchangeAlgorithm().Has(CipherSuiteKeyExchangeAlgorithmEcdhe) {
srvExchange.EllipticCurveType = elliptic.CurveTypeNamedCurve
srvExchange.NamedCurve = state.namedCurve
srvExchange.PublicKey = state.localKeypair.PublicKey
}
pkts = append(pkts, &packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: &handshake.Handshake{
Message: &handshake.MessageServerKeyExchange{
IdentityHint: cfg.localPSKIdentityHint,
},
},
},
})
case state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeAnonymous:
pkts = append(pkts, &packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: &handshake.Handshake{
Message: &handshake.MessageServerKeyExchange{
EllipticCurveType: elliptic.CurveTypeNamedCurve,
NamedCurve: state.namedCurve,
PublicKey: state.localKeypair.PublicKey,
},
Message: srvExchange,
},
},
})

View file

@ -0,0 +1,78 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"context"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol"
"github.com/pion/dtls/v2/pkg/protocol/alert"
"github.com/pion/dtls/v2/pkg/protocol/handshake"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
func flight5bParse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false},
)
if !ok {
// No valid message received. Keep reading
return 0, nil, nil
}
if _, ok = msgs[handshake.TypeFinished].(*handshake.MessageFinished); !ok {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
}
// Other party may re-transmit the last flight. Keep state to be flight5b.
return flight5b, nil, nil
}
func flight5bGenerate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { //nolint:gocognit
var pkts []*packet
pkts = append(pkts,
&packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
},
Content: &protocol.ChangeCipherSpec{},
},
})
if len(state.localVerifyData) == 0 {
plainText := cache.pullAndMerge(
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false},
)
var err error
state.localVerifyData, err = prf.VerifyDataClient(state.masterSecret, plainText, state.cipherSuite.HashFunc())
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
pkts = append(pkts,
&packet{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Version: protocol.Version1_2,
Epoch: 1,
},
Content: &handshake.Handshake{
Message: &handshake.MessageFinished{
VerifyData: state.localVerifyData,
},
},
},
shouldEncrypt: true,
resetLocalSequenceNumber: true,
})
return pkts, nil, nil
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -14,8 +17,8 @@ import (
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
func flight5Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence,
func flight5Parse(_ context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false},
)
if !ok {
@ -48,24 +51,45 @@ func flight5Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errVerifyDataMismatch
}
if len(state.SessionID) > 0 {
s := Session{
ID: state.SessionID,
Secret: state.masterSecret,
}
cfg.log.Tracef("[handshake] save new session: %x", s.ID)
if err := cfg.sessionStore.Set(c.sessionKey(), s); err != nil {
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
}
}
return flight5, nil, nil
}
func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { //nolint:gocognit
var certBytes [][]byte
var privateKey crypto.PrivateKey
if len(cfg.localCertificates) > 0 {
certificate, err := cfg.getCertificate(cfg.serverName)
var pkts []*packet
if state.remoteRequestedCertificate {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-2, state.cipherSuite,
handshakeCachePullRule{handshake.TypeCertificateRequest, cfg.initialEpoch, false, false})
if !ok {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errClientCertificateRequired
}
reqInfo := CertificateRequestInfo{}
if r, ok := msgs[handshake.TypeCertificateRequest].(*handshake.MessageCertificateRequest); ok {
reqInfo.AcceptableCAs = r.CertificateAuthoritiesNames
} else {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errClientCertificateRequired
}
certificate, err := cfg.getClientCertificate(&reqInfo)
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, err
}
certBytes = certificate.Certificate
privateKey = certificate.PrivateKey
}
var pkts []*packet
if state.remoteRequestedCertificate {
if certificate == nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errNotAcceptableCertificateChain
}
if certificate.Certificate != nil {
privateKey = certificate.PrivateKey
}
pkts = append(pkts,
&packet{
record: &recordlayer.RecordLayer{
@ -74,7 +98,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
},
Content: &handshake.Handshake{
Message: &handshake.MessageCertificate{
Certificate: certBytes,
Certificate: certificate.Certificate,
},
},
},
@ -87,6 +111,9 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
} else {
clientKeyExchange.IdentityHint = cfg.localPSKIdentityHint
}
if state != nil && state.localKeypair != nil && len(state.localKeypair.PublicKey) > 0 {
clientKeyExchange.PublicKey = state.localKeypair.PublicKey
}
pkts = append(pkts,
&packet{
@ -113,7 +140,9 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
return nil, alertPtr, err
}
} else {
rawHandshake := &handshake.Handshake{}
rawHandshake := &handshake.Handshake{
KeyExchangeAlgorithm: state.cipherSuite.KeyExchangeAlgorithm(),
}
err := rawHandshake.Unmarshal(serverKeyExchangeData)
if err != nil {
return nil, &alert.Alert{Level: alert.Fatal, Description: alert.UnexpectedMessage}, err
@ -151,7 +180,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
// If the client has sent a certificate with signing ability, a digitally-signed
// CertificateVerify message is sent to explicitly verify possession of the
// private key in the certificate.
if state.remoteRequestedCertificate && len(cfg.localCertificates) > 0 {
if state.remoteRequestedCertificate && privateKey != nil {
plainText := append(cache.pullAndMerge(
handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false},
handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false},
@ -257,7 +286,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han
func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeConfig, h *handshake.MessageServerKeyExchange, sendingPlainText []byte) (*alert.Alert, error) { //nolint:gocognit
if state.cipherSuite.IsInitialized() {
return nil, nil
return nil, nil //nolint
}
clientRandom := state.localRandom.MarshalFixed()
@ -312,6 +341,11 @@ func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeCon
}
}
}
if cfg.verifyConnection != nil {
if err = cfg.verifyConnection(state.clone()); err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err
}
}
if err = state.cipherSuite.Init(state.masterSecret, clientRandom[:], serverRandom[:], true); err != nil {
return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
@ -319,5 +353,5 @@ func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeCon
cfg.writeKeyLog(keyLogLabelTLS12, clientRandom[:], state.masterSecret)
return nil, nil
return nil, nil //nolint
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -10,8 +13,8 @@ import (
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
func flight6Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1,
func flight6Parse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
_, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, state.cipherSuite,
handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false},
)
if !ok {
@ -23,11 +26,11 @@ func flight6Parse(ctx context.Context, c flightConn, state *State, cache *handsh
return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
}
// Other party retransmitted the last flight.
// Other party may re-transmit the last flight. Keep state to be flight6.
return flight6, nil, nil
}
func flight6Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
func flight6Generate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
var pkts []*packet
pkts = append(pkts,

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -24,8 +27,12 @@ func (f flightVal) getFlightParser() (flightParser, error) {
return flight3Parse, nil
case flight4:
return flight4Parse, nil
case flight4b:
return flight4bParse, nil
case flight5:
return flight5Parse, nil
case flight5b:
return flight5bParse, nil
case flight6:
return flight6Parse, nil
default:
@ -47,8 +54,12 @@ func (f flightVal) getFlightGenerator() (gen flightGenerator, retransmit bool, e
return flight3Generate, true, nil
case flight4:
return flight4Generate, true, nil
case flight4b:
return flight4bGenerate, true, nil
case flight5:
return flight5Generate, true, nil
case flight5b:
return flight5bGenerate, true, nil
case flight6:
return flight6Generate, true, nil
default:

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -6,6 +9,9 @@ import (
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
// 2 megabytes
const fragmentBufferMaxSize = 2000000
type fragment struct {
recordLayerHeader recordlayer.Header
handshakeHeader handshake.Header
@ -23,10 +29,25 @@ func newFragmentBuffer() *fragmentBuffer {
return &fragmentBuffer{cache: map[uint16][]*fragment{}}
}
// current total size of buffer
func (f *fragmentBuffer) size() int {
size := 0
for i := range f.cache {
for j := range f.cache[i] {
size += len(f.cache[i][j].data)
}
}
return size
}
// Attempts to push a DTLS packet to the fragmentBuffer
// when it returns true it means the fragmentBuffer has inserted and the buffer shouldn't be handled
// when an error returns it is fatal, and the DTLS connection should be stopped
func (f *fragmentBuffer) push(buf []byte) (bool, error) {
if f.size()+len(buf) >= fragmentBufferMaxSize {
return false, errFragmentBufferOverflow
}
frag := new(fragment)
if err := frag.recordLayerHeader.Unmarshal(buf); err != nil {
return false, err
@ -76,7 +97,7 @@ func (f *fragmentBuffer) pop() (content []byte, epoch uint16) {
for _, f := range frags {
if f.handshakeHeader.FragmentOffset == targetOffset {
fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength)
if fragmentEnd != f.handshakeHeader.Length {
if fragmentEnd != f.handshakeHeader.Length && f.handshakeHeader.FragmentLength != 0 {
if !appendMessage(fragmentEnd) {
return false
}

View file

@ -1,38 +0,0 @@
// +build gofuzz
package dtls
import "fmt"
func partialHeaderMismatch(a, b recordlayer.Header) bool {
// Ignoring content length for now.
a.contentLen = b.contentLen
return a != b
}
func FuzzRecordLayer(data []byte) int {
var r recordLayer
if err := r.Unmarshal(data); err != nil {
return 0
}
buf, err := r.Marshal()
if err != nil {
return 1
}
if len(buf) == 0 {
panic("zero buff") // nolint
}
var nr recordLayer
if err = nr.Unmarshal(data); err != nil {
panic(err) // nolint
}
if partialHeaderMismatch(nr.recordlayer.Header, r.recordlayer.Header) {
panic( // nolint
fmt.Sprintf("header mismatch: %+v != %+v",
nr.recordlayer.Header, r.recordlayer.Header,
),
)
}
return 1
}

View file

@ -1,12 +0,0 @@
module github.com/pion/dtls/v2
require (
github.com/pion/logging v0.2.2
github.com/pion/transport v0.12.2
github.com/pion/udp v0.1.0
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
golang.org/x/net v0.0.0-20210119194325-5f4716e94777
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1
)
go 1.13

View file

@ -1,48 +0,0 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/transport v0.10.0 h1:9M12BSneJm6ggGhJyWpDveFOstJsTiQjkLf4M44rm80=
github.com/pion/transport v0.10.0/go.mod h1:BnHnUipd0rZQyTVB2SBGojFHT9CBt5C5TcsJSQGkvSE=
github.com/pion/transport v0.12.2 h1:WYEjhloRHt1R86LhUKjC5y+P52Y11/QqEUalvtzVoys=
github.com/pion/transport v0.12.2/go.mod h1:N3+vZQD9HlDP5GWkZ85LohxNsDcNgofQmyL6ojX5d8Q=
github.com/pion/udp v0.1.0 h1:uGxQsNyrqG3GLINv36Ff60covYmfrLoxzwnCsIYspXI=
github.com/pion/udp v0.1.0/go.mod h1:BPELIjbwE9PRbd/zxI/KYBnbo7B6+oA6YuEaNE8lths=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201201195509-5d6afe98e0b7 h1:3uJsdck53FDIpWwLeAXlia9p4C8j0BO2xZrqzKpL0D8=
golang.org/x/net v0.0.0-20201201195509-5d6afe98e0b7/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew=
golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -31,17 +34,10 @@ func newHandshakeCache() *handshakeCache {
return &handshakeCache{}
}
func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshake.Type, isClient bool) bool { //nolint
func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshake.Type, isClient bool) {
h.mu.Lock()
defer h.mu.Unlock()
for _, i := range h.cache {
if i.messageSequence == messageSequence &&
i.isClient == isClient {
return false
}
}
h.cache = append(h.cache, &handshakeCacheItem{
data: append([]byte{}, data...),
epoch: epoch,
@ -49,7 +45,6 @@ func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ ha
typ: typ,
isClient: isClient,
})
return true
}
// returns a list handshakes that match the requested rules
@ -77,7 +72,7 @@ func (h *handshakeCache) pull(rules ...handshakeCachePullRule) []*handshakeCache
}
// fullPullMap pulls all handshakes between rules[0] to rules[len(rules)-1] as map.
func (h *handshakeCache) fullPullMap(startSeq int, rules ...handshakeCachePullRule) (int, map[handshake.Type]handshake.Message, bool) {
func (h *handshakeCache) fullPullMap(startSeq int, cipherSuite CipherSuite, rules ...handshakeCachePullRule) (int, map[handshake.Type]handshake.Message, bool) {
h.mu.Lock()
defer h.mu.Unlock()
@ -108,7 +103,13 @@ func (h *handshakeCache) fullPullMap(startSeq int, rules ...handshakeCachePullRu
if i == nil {
continue
}
rawHandshake := &handshake.Handshake{}
var keyExchangeAlgorithm CipherSuiteKeyExchangeAlgorithm
if cipherSuite != nil {
keyExchangeAlgorithm = cipherSuite.KeyExchangeAlgorithm()
}
rawHandshake := &handshake.Handshake{
KeyExchangeAlgorithm: keyExchangeAlgorithm,
}
if err := rawHandshake.Unmarshal(i.data); err != nil {
return startSeq, nil, false
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -9,6 +12,7 @@ import (
"sync"
"time"
"github.com/pion/dtls/v2/pkg/crypto/elliptic"
"github.com/pion/dtls/v2/pkg/crypto/signaturehash"
"github.com/pion/dtls/v2/pkg/protocol/alert"
"github.com/pion/dtls/v2/pkg/protocol/handshake"
@ -95,20 +99,28 @@ type handshakeConfig struct {
extendedMasterSecret ExtendedMasterSecretType // Policy for the Extended Master Support extension
localSRTPProtectionProfiles []SRTPProtectionProfile // Available SRTPProtectionProfiles, if empty no SRTP support
serverName string
supportedProtocols []string
clientAuth ClientAuthType // If we are a client should we request a client certificate
localCertificates []tls.Certificate
nameToCertificate map[string]*tls.Certificate
insecureSkipVerify bool
verifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
verifyConnection func(*State) error
sessionStore SessionStore
rootCAs *x509.CertPool
clientCAs *x509.CertPool
retransmitInterval time.Duration
customCipherSuites func() []CipherSuite
ellipticCurves []elliptic.Curve
insecureSkipHelloVerify bool
onFlightState func(flightVal, handshakeState)
log logging.LeveledLogger
keyLogWriter io.Writer
localGetCertificate func(*ClientHelloInfo) (*tls.Certificate, error)
localGetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error)
initialEpoch uint16
mu sync.Mutex
@ -120,6 +132,7 @@ type flightConn interface {
recvHandshake() <-chan chan struct{}
setLocalEpoch(epoch uint16)
handleQueuedPackets(context.Context) error
sessionKey() []byte
}
func (c *handshakeConfig) writeKeyLog(label string, clientRandom, secret []byte) {
@ -323,6 +336,9 @@ func (s *handshakeFSM) finish(ctx context.Context, c flightConn) (handshakeState
if nextFlight == 0 {
break
}
if nextFlight.isLastRecvFlight() && s.currentFlight == nextFlight {
return handshakeFinished, nil
}
<-retransmitTimer.C
// Retransmit last flight
return handshakeSending, nil

View file

@ -1,108 +1,33 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"crypto/sha256"
"fmt"
"hash"
"sync/atomic"
"github.com/pion/dtls/v2/pkg/crypto/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
// Aes128Ccm is a base class used by multiple AES-CCM Ciphers
type Aes128Ccm struct {
ccm atomic.Value // *cryptoCCM
clientCertificateType clientcertificate.Type
id ID
psk bool
cryptoCCMTagLen ciphersuite.CCMTagLen
AesCcm
}
func newAes128Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen) *Aes128Ccm {
func newAes128Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen, keyExchangeAlgorithm KeyExchangeAlgorithm, ecc bool) *Aes128Ccm {
return &Aes128Ccm{
clientCertificateType: clientCertificateType,
id: id,
psk: psk,
cryptoCCMTagLen: cryptoCCMTagLen,
AesCcm: AesCcm{
clientCertificateType: clientCertificateType,
id: id,
psk: psk,
cryptoCCMTagLen: cryptoCCMTagLen,
keyExchangeAlgorithm: keyExchangeAlgorithm,
ecc: ecc,
},
}
}
// CertificateType returns what type of certificate this CipherSuite exchanges
func (c *Aes128Ccm) CertificateType() clientcertificate.Type {
return c.clientCertificateType
}
// ID returns the ID of the CipherSuite
func (c *Aes128Ccm) ID() ID {
return c.id
}
func (c *Aes128Ccm) String() string {
return c.id.String()
}
// HashFunc returns the hashing func for this CipherSuite
func (c *Aes128Ccm) HashFunc() func() hash.Hash {
return sha256.New
}
// AuthenticationType controls what authentication method is using during the handshake
func (c *Aes128Ccm) AuthenticationType() AuthenticationType {
if c.psk {
return AuthenticationTypePreSharedKey
}
return AuthenticationTypeCertificate
}
// IsInitialized returns if the CipherSuite has keying material and can
// encrypt/decrypt packets
func (c *Aes128Ccm) IsInitialized() bool {
return c.ccm.Load() != nil
}
// Init initializes the internal Cipher with keying material
func (c *Aes128Ccm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const (
prfMacLen = 0
prfKeyLen = 16
prfIvLen = 4
)
keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
if err != nil {
return err
}
var ccm *ciphersuite.CCM
if isClient {
ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ClientWriteKey, keys.ClientWriteIV, keys.ServerWriteKey, keys.ServerWriteIV)
} else {
ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ServerWriteKey, keys.ServerWriteIV, keys.ClientWriteKey, keys.ClientWriteIV)
}
c.ccm.Store(ccm)
return err
}
// Encrypt encrypts a single TLS RecordLayer
func (c *Aes128Ccm) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
ccm := c.ccm.Load()
if ccm == nil {
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return ccm.(*ciphersuite.CCM).Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *Aes128Ccm) Decrypt(raw []byte) ([]byte, error) {
ccm := c.ccm.Load()
if ccm == nil {
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return ccm.(*ciphersuite.CCM).Decrypt(raw)
const prfKeyLen = 16
return c.AesCcm.Init(masterSecret, clientRandom, serverRandom, isClient, prfKeyLen)
}

View file

@ -0,0 +1,33 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"github.com/pion/dtls/v2/pkg/crypto/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
)
// Aes256Ccm is a base class used by multiple AES-CCM Ciphers
type Aes256Ccm struct {
AesCcm
}
func newAes256Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen, keyExchangeAlgorithm KeyExchangeAlgorithm, ecc bool) *Aes256Ccm {
return &Aes256Ccm{
AesCcm: AesCcm{
clientCertificateType: clientCertificateType,
id: id,
psk: psk,
cryptoCCMTagLen: cryptoCCMTagLen,
keyExchangeAlgorithm: keyExchangeAlgorithm,
ecc: ecc,
},
}
}
// Init initializes the internal Cipher with keying material
func (c *Aes256Ccm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const prfKeyLen = 32
return c.AesCcm.Init(masterSecret, clientRandom, serverRandom, isClient, prfKeyLen)
}

View file

@ -0,0 +1,113 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"crypto/sha256"
"fmt"
"hash"
"sync/atomic"
"github.com/pion/dtls/v2/pkg/crypto/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
// AesCcm is a base class used by multiple AES-CCM Ciphers
type AesCcm struct {
ccm atomic.Value // *cryptoCCM
clientCertificateType clientcertificate.Type
id ID
psk bool
keyExchangeAlgorithm KeyExchangeAlgorithm
cryptoCCMTagLen ciphersuite.CCMTagLen
ecc bool
}
// CertificateType returns what type of certificate this CipherSuite exchanges
func (c *AesCcm) CertificateType() clientcertificate.Type {
return c.clientCertificateType
}
// ID returns the ID of the CipherSuite
func (c *AesCcm) ID() ID {
return c.id
}
func (c *AesCcm) String() string {
return c.id.String()
}
// ECC uses Elliptic Curve Cryptography
func (c *AesCcm) ECC() bool {
return c.ecc
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *AesCcm) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return c.keyExchangeAlgorithm
}
// HashFunc returns the hashing func for this CipherSuite
func (c *AesCcm) HashFunc() func() hash.Hash {
return sha256.New
}
// AuthenticationType controls what authentication method is using during the handshake
func (c *AesCcm) AuthenticationType() AuthenticationType {
if c.psk {
return AuthenticationTypePreSharedKey
}
return AuthenticationTypeCertificate
}
// IsInitialized returns if the CipherSuite has keying material and can
// encrypt/decrypt packets
func (c *AesCcm) IsInitialized() bool {
return c.ccm.Load() != nil
}
// Init initializes the internal Cipher with keying material
func (c *AesCcm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool, prfKeyLen int) error {
const (
prfMacLen = 0
prfIvLen = 4
)
keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
if err != nil {
return err
}
var ccm *ciphersuite.CCM
if isClient {
ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ClientWriteKey, keys.ClientWriteIV, keys.ServerWriteKey, keys.ServerWriteIV)
} else {
ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ServerWriteKey, keys.ServerWriteIV, keys.ClientWriteKey, keys.ClientWriteIV)
}
c.ccm.Store(ccm)
return err
}
// Encrypt encrypts a single TLS RecordLayer
func (c *AesCcm) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
cipherSuite, ok := c.ccm.Load().(*ciphersuite.CCM)
if !ok {
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return cipherSuite.Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *AesCcm) Decrypt(raw []byte) ([]byte, error) {
cipherSuite, ok := c.ccm.Load().(*ciphersuite.CCM)
if !ok {
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return cipherSuite.Decrypt(raw)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package ciphersuite provides TLS Ciphers as registered with the IANA https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4
package ciphersuite
@ -5,6 +8,7 @@ import (
"errors"
"fmt"
"github.com/pion/dtls/v2/internal/ciphersuite/types"
"github.com/pion/dtls/v2/pkg/protocol"
)
@ -31,10 +35,18 @@ func (i ID) String() string {
return "TLS_PSK_WITH_AES_128_CCM"
case TLS_PSK_WITH_AES_128_CCM_8:
return "TLS_PSK_WITH_AES_128_CCM_8"
case TLS_PSK_WITH_AES_256_CCM_8:
return "TLS_PSK_WITH_AES_256_CCM_8"
case TLS_PSK_WITH_AES_128_GCM_SHA256:
return "TLS_PSK_WITH_AES_128_GCM_SHA256"
case TLS_PSK_WITH_AES_128_CBC_SHA256:
return "TLS_PSK_WITH_AES_128_CBC_SHA256"
case TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384:
return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256:
return "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"
default:
return fmt.Sprintf("unknown(%v)", uint16(i))
}
@ -43,29 +55,44 @@ func (i ID) String() string {
// Supported Cipher Suites
const (
// AES-128-CCM
TLS_ECDHE_ECDSA_WITH_AES_128_CCM ID = 0xc0ac //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ID = 0xc0ae //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM ID = 0xc0ac //nolint:revive,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ID = 0xc0ae //nolint:revive,stylecheck
// AES-128-GCM-SHA256
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ID = 0xc02b //nolint:golint,stylecheck
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ID = 0xc02f //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ID = 0xc02b //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ID = 0xc02f //nolint:revive,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 ID = 0xc02c //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ID = 0xc030 //nolint:revive,stylecheck
// AES-256-CBC-SHA
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ID = 0xc00a //nolint:golint,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ID = 0xc014 //nolint:golint,stylecheck
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ID = 0xc00a //nolint:revive,stylecheck
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ID = 0xc014 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CCM ID = 0xc0a4 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CCM_8 ID = 0xc0a8 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_GCM_SHA256 ID = 0x00a8 //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CBC_SHA256 ID = 0x00ae //nolint:golint,stylecheck
TLS_PSK_WITH_AES_128_CCM ID = 0xc0a4 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CCM_8 ID = 0xc0a8 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_256_CCM_8 ID = 0xc0a9 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_GCM_SHA256 ID = 0x00a8 //nolint:revive,stylecheck
TLS_PSK_WITH_AES_128_CBC_SHA256 ID = 0x00ae //nolint:revive,stylecheck
TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 ID = 0xC037 //nolint:revive,stylecheck
)
// AuthenticationType controls what authentication method is using during the handshake
type AuthenticationType int
type AuthenticationType = types.AuthenticationType
// AuthenticationType Enums
const (
AuthenticationTypeCertificate AuthenticationType = iota + 1
AuthenticationTypePreSharedKey
AuthenticationTypeAnonymous
AuthenticationTypeCertificate AuthenticationType = types.AuthenticationTypeCertificate
AuthenticationTypePreSharedKey AuthenticationType = types.AuthenticationTypePreSharedKey
AuthenticationTypeAnonymous AuthenticationType = types.AuthenticationTypeAnonymous
)
// KeyExchangeAlgorithm controls what exchange algorithm was chosen.
type KeyExchangeAlgorithm = types.KeyExchangeAlgorithm
// KeyExchangeAlgorithm Bitmask
const (
KeyExchangeAlgorithmNone KeyExchangeAlgorithm = types.KeyExchangeAlgorithmNone
KeyExchangeAlgorithmPsk KeyExchangeAlgorithm = types.KeyExchangeAlgorithmPsk
KeyExchangeAlgorithmEcdhe KeyExchangeAlgorithm = types.KeyExchangeAlgorithmEcdhe
)

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -7,5 +10,5 @@ import (
// NewTLSEcdheEcdsaWithAes128Ccm constructs a TLS_ECDHE_ECDSA_WITH_AES_128_CCM Cipher
func NewTLSEcdheEcdsaWithAes128Ccm() *Aes128Ccm {
return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM, false, ciphersuite.CCMTagLength)
return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM, false, ciphersuite.CCMTagLength, KeyExchangeAlgorithmEcdhe, true)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -7,5 +10,5 @@ import (
// NewTLSEcdheEcdsaWithAes128Ccm8 creates a new TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuite
func NewTLSEcdheEcdsaWithAes128Ccm8() *Aes128Ccm {
return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, false, ciphersuite.CCMTagLength8)
return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, false, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmEcdhe, true)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -22,6 +25,16 @@ func (c *TLSEcdheEcdsaWithAes128GcmSha256) CertificateType() clientcertificate.T
return clientcertificate.ECDSASign
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *TLSEcdheEcdsaWithAes128GcmSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return KeyExchangeAlgorithmEcdhe
}
// ECC uses Elliptic Curve Cryptography
func (c *TLSEcdheEcdsaWithAes128GcmSha256) ECC() bool {
return true
}
// ID returns the ID of the CipherSuite
func (c *TLSEcdheEcdsaWithAes128GcmSha256) ID() ID {
return TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
@ -47,15 +60,8 @@ func (c *TLSEcdheEcdsaWithAes128GcmSha256) IsInitialized() bool {
return c.gcm.Load() != nil
}
// Init initializes the internal Cipher with keying material
func (c *TLSEcdheEcdsaWithAes128GcmSha256) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const (
prfMacLen = 0
prfKeyLen = 16
prfIvLen = 4
)
keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
func (c *TLSEcdheEcdsaWithAes128GcmSha256) init(masterSecret, clientRandom, serverRandom []byte, isClient bool, prfMacLen, prfKeyLen, prfIvLen int, hashFunc func() hash.Hash) error {
keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, hashFunc)
if err != nil {
return err
}
@ -67,26 +73,36 @@ func (c *TLSEcdheEcdsaWithAes128GcmSha256) Init(masterSecret, clientRandom, serv
gcm, err = ciphersuite.NewGCM(keys.ServerWriteKey, keys.ServerWriteIV, keys.ClientWriteKey, keys.ClientWriteIV)
}
c.gcm.Store(gcm)
return err
}
// Init initializes the internal Cipher with keying material
func (c *TLSEcdheEcdsaWithAes128GcmSha256) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const (
prfMacLen = 0
prfKeyLen = 16
prfIvLen = 4
)
return c.init(masterSecret, clientRandom, serverRandom, isClient, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
}
// Encrypt encrypts a single TLS RecordLayer
func (c *TLSEcdheEcdsaWithAes128GcmSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
gcm := c.gcm.Load()
if gcm == nil {
cipherSuite, ok := c.gcm.Load().(*ciphersuite.GCM)
if !ok {
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return gcm.(*ciphersuite.GCM).Encrypt(pkt, raw)
return cipherSuite.Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *TLSEcdheEcdsaWithAes128GcmSha256) Decrypt(raw []byte) ([]byte, error) {
gcm := c.gcm.Load()
if gcm == nil {
cipherSuite, ok := c.gcm.Load().(*ciphersuite.GCM)
if !ok {
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return gcm.(*ciphersuite.GCM).Decrypt(raw)
return cipherSuite.Decrypt(raw)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -23,6 +26,16 @@ func (c *TLSEcdheEcdsaWithAes256CbcSha) CertificateType() clientcertificate.Type
return clientcertificate.ECDSASign
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *TLSEcdheEcdsaWithAes256CbcSha) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return KeyExchangeAlgorithmEcdhe
}
// ECC uses Elliptic Curve Cryptography
func (c *TLSEcdheEcdsaWithAes256CbcSha) ECC() bool {
return true
}
// ID returns the ID of the CipherSuite
func (c *TLSEcdheEcdsaWithAes256CbcSha) ID() ID {
return TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
@ -82,20 +95,20 @@ func (c *TLSEcdheEcdsaWithAes256CbcSha) Init(masterSecret, clientRandom, serverR
// Encrypt encrypts a single TLS RecordLayer
func (c *TLSEcdheEcdsaWithAes256CbcSha) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
cbc := c.cbc.Load()
if cbc == nil { // !c.isInitialized()
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok {
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return cbc.(*ciphersuite.CBC).Encrypt(pkt, raw)
return cipherSuite.Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *TLSEcdheEcdsaWithAes256CbcSha) Decrypt(raw []byte) ([]byte, error) {
cbc := c.cbc.Load()
if cbc == nil { // !c.isInitialized()
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok {
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return cbc.(*ciphersuite.CBC).Decrypt(raw)
return cipherSuite.Decrypt(raw)
}

View file

@ -0,0 +1,39 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"crypto/sha512"
"hash"
)
// TLSEcdheEcdsaWithAes256GcmSha384 represents a TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuite
type TLSEcdheEcdsaWithAes256GcmSha384 struct {
TLSEcdheEcdsaWithAes128GcmSha256
}
// ID returns the ID of the CipherSuite
func (c *TLSEcdheEcdsaWithAes256GcmSha384) ID() ID {
return TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
}
func (c *TLSEcdheEcdsaWithAes256GcmSha384) String() string {
return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
}
// HashFunc returns the hashing func for this CipherSuite
func (c *TLSEcdheEcdsaWithAes256GcmSha384) HashFunc() func() hash.Hash {
return sha512.New384
}
// Init initializes the internal Cipher with keying material
func (c *TLSEcdheEcdsaWithAes256GcmSha384) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const (
prfMacLen = 0
prfKeyLen = 32
prfIvLen = 4
)
return c.init(masterSecret, clientRandom, serverRandom, isClient, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
}

View file

@ -0,0 +1,118 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"crypto/sha256"
"fmt"
"hash"
"sync/atomic"
"github.com/pion/dtls/v2/pkg/crypto/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
"github.com/pion/dtls/v2/pkg/crypto/prf"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
)
// TLSEcdhePskWithAes128CbcSha256 implements the TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 CipherSuite
type TLSEcdhePskWithAes128CbcSha256 struct {
cbc atomic.Value // *cryptoCBC
}
// NewTLSEcdhePskWithAes128CbcSha256 creates TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 cipher.
func NewTLSEcdhePskWithAes128CbcSha256() *TLSEcdhePskWithAes128CbcSha256 {
return &TLSEcdhePskWithAes128CbcSha256{}
}
// CertificateType returns what type of certificate this CipherSuite exchanges
func (c *TLSEcdhePskWithAes128CbcSha256) CertificateType() clientcertificate.Type {
return clientcertificate.Type(0)
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *TLSEcdhePskWithAes128CbcSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return (KeyExchangeAlgorithmPsk | KeyExchangeAlgorithmEcdhe)
}
// ECC uses Elliptic Curve Cryptography
func (c *TLSEcdhePskWithAes128CbcSha256) ECC() bool {
return true
}
// ID returns the ID of the CipherSuite
func (c *TLSEcdhePskWithAes128CbcSha256) ID() ID {
return TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
}
func (c *TLSEcdhePskWithAes128CbcSha256) String() string {
return "TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256"
}
// HashFunc returns the hashing func for this CipherSuite
func (c *TLSEcdhePskWithAes128CbcSha256) HashFunc() func() hash.Hash {
return sha256.New
}
// AuthenticationType controls what authentication method is using during the handshake
func (c *TLSEcdhePskWithAes128CbcSha256) AuthenticationType() AuthenticationType {
return AuthenticationTypePreSharedKey
}
// IsInitialized returns if the CipherSuite has keying material and can
// encrypt/decrypt packets
func (c *TLSEcdhePskWithAes128CbcSha256) IsInitialized() bool {
return c.cbc.Load() != nil
}
// Init initializes the internal Cipher with keying material
func (c *TLSEcdhePskWithAes128CbcSha256) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error {
const (
prfMacLen = 32
prfKeyLen = 16
prfIvLen = 16
)
keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc())
if err != nil {
return err
}
var cbc *ciphersuite.CBC
if isClient {
cbc, err = ciphersuite.NewCBC(
keys.ClientWriteKey, keys.ClientWriteIV, keys.ClientMACKey,
keys.ServerWriteKey, keys.ServerWriteIV, keys.ServerMACKey,
c.HashFunc(),
)
} else {
cbc, err = ciphersuite.NewCBC(
keys.ServerWriteKey, keys.ServerWriteIV, keys.ServerMACKey,
keys.ClientWriteKey, keys.ClientWriteIV, keys.ClientMACKey,
c.HashFunc(),
)
}
c.cbc.Store(cbc)
return err
}
// Encrypt encrypts a single TLS RecordLayer
func (c *TLSEcdhePskWithAes128CbcSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok { // !c.isInitialized()
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return cipherSuite.Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *TLSEcdhePskWithAes128CbcSha256) Decrypt(raw []byte) ([]byte, error) {
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok { // !c.isInitialized()
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return cipherSuite.Decrypt(raw)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate"

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate"

View file

@ -0,0 +1,25 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
// TLSEcdheRsaWithAes256GcmSha384 implements the TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 CipherSuite
type TLSEcdheRsaWithAes256GcmSha384 struct {
TLSEcdheEcdsaWithAes256GcmSha384
}
// CertificateType returns what type of certificate this CipherSuite exchanges
func (c *TLSEcdheRsaWithAes256GcmSha384) CertificateType() clientcertificate.Type {
return clientcertificate.RSASign
}
// ID returns the ID of the CipherSuite
func (c *TLSEcdheRsaWithAes256GcmSha384) ID() ID {
return TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
}
func (c *TLSEcdheRsaWithAes256GcmSha384) String() string {
return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -22,6 +25,16 @@ func (c *TLSPskWithAes128CbcSha256) CertificateType() clientcertificate.Type {
return clientcertificate.Type(0)
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *TLSPskWithAes128CbcSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return KeyExchangeAlgorithmPsk
}
// ECC uses Elliptic Curve Cryptography
func (c *TLSPskWithAes128CbcSha256) ECC() bool {
return false
}
// ID returns the ID of the CipherSuite
func (c *TLSPskWithAes128CbcSha256) ID() ID {
return TLS_PSK_WITH_AES_128_CBC_SHA256
@ -81,20 +94,20 @@ func (c *TLSPskWithAes128CbcSha256) Init(masterSecret, clientRandom, serverRando
// Encrypt encrypts a single TLS RecordLayer
func (c *TLSPskWithAes128CbcSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) {
cbc := c.cbc.Load()
if cbc == nil { // !c.isInitialized()
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok {
return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit)
}
return cbc.(*ciphersuite.CBC).Encrypt(pkt, raw)
return cipherSuite.Encrypt(pkt, raw)
}
// Decrypt decrypts a single TLS RecordLayer
func (c *TLSPskWithAes128CbcSha256) Decrypt(raw []byte) ([]byte, error) {
cbc := c.cbc.Load()
if cbc == nil { // !c.isInitialized()
cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC)
if !ok {
return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit)
}
return cbc.(*ciphersuite.CBC).Decrypt(raw)
return cipherSuite.Decrypt(raw)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -7,5 +10,5 @@ import (
// NewTLSPskWithAes128Ccm returns the TLS_PSK_WITH_AES_128_CCM CipherSuite
func NewTLSPskWithAes128Ccm() *Aes128Ccm {
return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM, true, ciphersuite.CCMTagLength)
return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM, true, ciphersuite.CCMTagLength, KeyExchangeAlgorithmPsk, false)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -7,5 +10,5 @@ import (
// NewTLSPskWithAes128Ccm8 returns the TLS_PSK_WITH_AES_128_CCM_8 CipherSuite
func NewTLSPskWithAes128Ccm8() *Aes128Ccm {
return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM_8, true, ciphersuite.CCMTagLength8)
return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM_8, true, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmPsk, false)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
@ -12,6 +15,11 @@ func (c *TLSPskWithAes128GcmSha256) CertificateType() clientcertificate.Type {
return clientcertificate.Type(0)
}
// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake
func (c *TLSPskWithAes128GcmSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm {
return KeyExchangeAlgorithmPsk
}
// ID returns the ID of the CipherSuite
func (c *TLSPskWithAes128GcmSha256) ID() ID {
return TLS_PSK_WITH_AES_128_GCM_SHA256

View file

@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
"github.com/pion/dtls/v2/pkg/crypto/ciphersuite"
"github.com/pion/dtls/v2/pkg/crypto/clientcertificate"
)
// NewTLSPskWithAes256Ccm8 returns the TLS_PSK_WITH_AES_256_CCM_8 CipherSuite
func NewTLSPskWithAes256Ccm8() *Aes256Ccm {
return newAes256Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_256_CCM_8, true, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmPsk, false)
}

View file

@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package types
// AuthenticationType controls what authentication method is using during the handshake
type AuthenticationType int
// AuthenticationType Enums
const (
AuthenticationTypeCertificate AuthenticationType = iota + 1
AuthenticationTypePreSharedKey
AuthenticationTypeAnonymous
)

View file

@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package types provides types for TLS Ciphers
package types
// KeyExchangeAlgorithm controls what exchange algorithm was chosen.
type KeyExchangeAlgorithm int
// KeyExchangeAlgorithm Bitmask
const (
KeyExchangeAlgorithmNone KeyExchangeAlgorithm = 0
KeyExchangeAlgorithmPsk KeyExchangeAlgorithm = iota << 1
KeyExchangeAlgorithmEcdhe
)
// Has check if keyExchangeAlgorithm is supported.
func (a KeyExchangeAlgorithm) Has(v KeyExchangeAlgorithm) bool {
return (a & v) == v
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package closer provides signaling channel for shutdown
package closer

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package util contains small helpers used across the repo
package util

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
@ -5,7 +8,7 @@ import (
"github.com/pion/dtls/v2/pkg/protocol"
"github.com/pion/dtls/v2/pkg/protocol/recordlayer"
"github.com/pion/udp"
"github.com/pion/transport/v2/udp"
)
// Listen creates a DTLS listener

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import "github.com/pion/dtls/v2/pkg/protocol/recordlayer"

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package ccm implements a CCM, Counter with CBC-MAC
// as per RFC 3610.
//

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import ( //nolint:gci
@ -39,11 +42,21 @@ func NewCBC(localKey, localWriteIV, localMac, remoteKey, remoteWriteIV, remoteMa
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: cipher.NewCBCEncrypter(writeBlock, localWriteIV).(cbcMode),
writeCBC: writeCBC,
writeMac: localMac,
readCBC: cipher.NewCBCDecrypter(readBlock, remoteWriteIV).(cbcMode),
readCBC: readCBC,
readMac: remoteMac,
h: h,
}, nil

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -98,7 +101,7 @@ func (c *CCM) Decrypt(in []byte) ([]byte, error) {
additionalData := generateAEADAdditionalData(&h, len(out)-int(c.tagLen))
out, err = c.remoteCCM.Open(out[:0], nonce, out, additionalData)
if err != nil {
return nil, fmt.Errorf("%w: %v", errDecryptPacket, err)
return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) //nolint:errorlint
}
return append(in[:recordlayer.HeaderSize], out...), nil
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package ciphersuite provides the crypto operations needed for a DTLS CipherSuite
package ciphersuite
@ -13,6 +16,7 @@ var (
errNotEnoughRoomForNonce = &protocol.InternalError{Err: errors.New("buffer not long enough to contain nonce")} //nolint:goerr113
errDecryptPacket = &protocol.TemporaryError{Err: errors.New("failed to decrypt packet")} //nolint:goerr113
errInvalidMAC = &protocol.TemporaryError{Err: errors.New("invalid mac")} //nolint:goerr113
errFailedToCast = &protocol.FatalError{Err: errors.New("failed to cast")} //nolint:goerr113
)
func generateAEADAdditionalData(h *recordlayer.Header, payloadLen int) []byte {

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package ciphersuite
import (
@ -94,7 +97,7 @@ func (g *GCM) Decrypt(in []byte) ([]byte, error) {
additionalData := generateAEADAdditionalData(&h, len(out)-gcmTagLength)
out, err = g.remoteGCM.Open(out[:0], nonce, out, additionalData)
if err != nil {
return nil, fmt.Errorf("%w: %v", errDecryptPacket, err)
return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) //nolint:errorlint
}
return append(in[:recordlayer.HeaderSize], out...), nil
}

View file

@ -1,10 +1,13 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package clientcertificate provides all the support Client Certificate types
package clientcertificate
// Type is used to communicate what
// type of certificate is being transported
//
//https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-2
// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-2
type Type byte
// ClientCertificateType enums

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package elliptic provides elliptic curve cryptography for DTLS
package elliptic
@ -5,6 +8,7 @@ import (
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"golang.org/x/crypto/curve25519"
)
@ -57,6 +61,18 @@ const (
X25519 Curve = 0x001d
)
func (c Curve) String() string {
switch c {
case P256:
return "P-256"
case P384:
return "P-384"
case X25519:
return "X25519"
}
return fmt.Sprintf("%#x", uint16(c))
}
// Curves returns all curves we implement
func Curves() map[Curve]bool {
return map[Curve]bool{
@ -68,7 +84,7 @@ func Curves() map[Curve]bool {
// GenerateKeypair generates a keypair for the given Curve
func GenerateKeypair(c Curve) (*Keypair, error) {
switch c { //nolint:golint
switch c { //nolint:revive
case X25519:
tmp := make([]byte, 32)
if _, err := rand.Read(tmp); err != nil {

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package fingerprint provides a helper to create fingerprint string from certificate
package fingerprint

View file

@ -1,8 +1,12 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package fingerprint
import (
"crypto"
"errors"
"strings"
)
var errInvalidHashAlgorithm = errors.New("fingerprint: invalid hash algorithm")
@ -20,7 +24,7 @@ func nameToHash() map[string]crypto.Hash {
// HashFromString allows looking up a hash algorithm by it's string representation
func HashFromString(s string) (crypto.Hash, error) {
if h, ok := nameToHash()[s]; ok {
if h, ok := nameToHash()[strings.ToLower(s)]; ok {
return h, nil
}
return 0, errInvalidHashAlgorithm

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package hash provides TLS HashAlgorithm as defined in TLS 1.2
package hash

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package prf implements TLS 1.2 Pseudorandom functions
package prf
@ -74,6 +77,34 @@ func PSKPreMasterSecret(psk []byte) []byte {
return out
}
// EcdhePSKPreMasterSecret implements TLS 1.2 Premaster Secret generation given a psk, a keypair and a curve
//
// https://datatracker.ietf.org/doc/html/rfc5489#section-2
func EcdhePSKPreMasterSecret(psk, publicKey, privateKey []byte, curve elliptic.Curve) ([]byte, error) {
preMasterSecret, err := PreMasterSecret(publicKey, privateKey, curve)
if err != nil {
return nil, err
}
out := make([]byte, 2+len(preMasterSecret)+2+len(psk))
// write preMasterSecret length
offset := 0
binary.BigEndian.PutUint16(out[offset:], uint16(len(preMasterSecret)))
offset += 2
// write preMasterSecret
copy(out[offset:], preMasterSecret)
offset += len(preMasterSecret)
// write psk length
binary.BigEndian.PutUint16(out[offset:], uint16(len(psk)))
offset += 2
// write psk
copy(out[offset:], psk)
return out, nil
}
// PreMasterSecret implements TLS 1.2 Premaster Secret generation given a keypair and a curve
func PreMasterSecret(publicKey, privateKey []byte, curve elliptic.Curve) ([]byte, error) {
switch curve {
@ -107,14 +138,14 @@ func ellipticCurvePreMasterSecret(publicKey, privateKey []byte, c1, c2 ellipticS
// specify a PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a
// stronger standard hash function.
//
// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
// HMAC_hash(secret, A(2) + seed) +
// HMAC_hash(secret, A(3) + seed) + ...
// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
// HMAC_hash(secret, A(2) + seed) +
// HMAC_hash(secret, A(3) + seed) + ...
//
// A() is defined as:
//
// A(0) = seed
// A(i) = HMAC_hash(secret, A(i-1))
// A(0) = seed
// A(i) = HMAC_hash(secret, A(i-1))
//
// P_hash can be iterated as many times as necessary to produce the
// required quantity of data. For example, if P_SHA256 is being used to

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package signature provides our implemented Signature Algorithms
package signature

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package signaturehash
import "errors"

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package signaturehash provides the SignatureHashAlgorithm as defined in TLS 1.2
package signaturehash
@ -7,10 +10,10 @@ import (
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"fmt"
"github.com/pion/dtls/v2/pkg/crypto/hash"
"github.com/pion/dtls/v2/pkg/crypto/signature"
"golang.org/x/xerrors"
)
// Algorithm is a signature/hash algorithm pairs which may be used in
@ -70,11 +73,11 @@ func ParseSignatureSchemes(sigs []tls.SignatureScheme, insecureHashes bool) ([]A
sig := signature.Algorithm(ss & 0xFF)
if _, ok := signature.Algorithms()[sig]; !ok {
return nil,
xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidSignatureAlgorithm)
fmt.Errorf("SignatureScheme %04x: %w", ss, errInvalidSignatureAlgorithm)
}
h := hash.Algorithm(ss >> 8)
if _, ok := hash.Algorithms()[h]; !ok || (ok && h == hash.None) {
return nil, xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidHashAlgorithm)
return nil, fmt.Errorf("SignatureScheme %04x: %w", ss, errInvalidHashAlgorithm)
}
if h.Insecure() && !insecureHashes {
continue

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package alert implements TLS alert protocol https://tools.ietf.org/html/rfc5246#section-7.2
package alert
@ -60,6 +63,7 @@ const (
UserCanceled Description = 90
NoRenegotiation Description = 100
UnsupportedExtension Description = 110
NoApplicationProtocol Description = 120
)
func (d Description) String() string {
@ -114,6 +118,8 @@ func (d Description) String() string {
return "NoRenegotiation"
case UnsupportedExtension:
return "UnsupportedExtension"
case NoApplicationProtocol:
return "NoApplicationProtocol"
default:
return "Invalid alert description"
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package protocol
// ApplicationData messages are carried by the record layer and are

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package protocol
// ChangeCipherSpec protocol exists to signal transitions in
@ -5,8 +8,7 @@ package protocol
// which is encrypted and compressed under the current (not the pending)
// connection state. The message consists of a single byte of value 1.
// https://tools.ietf.org/html/rfc5246#section-7.1
type ChangeCipherSpec struct {
}
type ChangeCipherSpec struct{}
// ContentType returns the ContentType of this content
func (c ChangeCipherSpec) ContentType() ContentType {

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package protocol
// CompressionMethodID is the ID for a CompressionMethod

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package protocol
// ContentType represents the IANA Registered ContentTypes

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package protocol
import (
@ -84,7 +87,8 @@ func (e *TimeoutError) Error() string { return fmt.Sprintf("dtls timeout: %v", e
// Timeout implements net.Error.Timeout()
func (e *HandshakeError) Timeout() bool {
if netErr, ok := e.Err.(net.Error); ok {
var netErr net.Error
if errors.As(e.Err, &netErr) {
return netErr.Timeout()
}
return false
@ -92,8 +96,9 @@ func (e *HandshakeError) Timeout() bool {
// Temporary implements net.Error.Temporary()
func (e *HandshakeError) Temporary() bool {
if netErr, ok := e.Err.(net.Error); ok {
return netErr.Temporary()
var netErr net.Error
if errors.As(e.Err, &netErr) {
return netErr.Temporary() //nolint
}
return false
}

View file

@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import (
"golang.org/x/crypto/cryptobyte"
)
// ALPN is a TLS extension for application-layer protocol negotiation within
// the TLS handshake.
//
// https://tools.ietf.org/html/rfc7301
type ALPN struct {
ProtocolNameList []string
}
// TypeValue returns the extension TypeValue
func (a ALPN) TypeValue() TypeValue {
return ALPNTypeValue
}
// Marshal encodes the extension
func (a *ALPN) Marshal() ([]byte, error) {
var b cryptobyte.Builder
b.AddUint16(uint16(a.TypeValue()))
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) {
for _, proto := range a.ProtocolNameList {
p := proto // Satisfy range scope lint
b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
b.AddBytes([]byte(p))
})
}
})
})
return b.Bytes()
}
// Unmarshal populates the extension from encoded data
func (a *ALPN) Unmarshal(data []byte) error {
val := cryptobyte.String(data)
var extension uint16
val.ReadUint16(&extension)
if TypeValue(extension) != a.TypeValue() {
return errInvalidExtensionType
}
var extData cryptobyte.String
val.ReadUint16LengthPrefixed(&extData)
var protoList cryptobyte.String
if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() {
return ErrALPNInvalidFormat
}
for !protoList.Empty() {
var proto cryptobyte.String
if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() {
return ErrALPNInvalidFormat
}
a.ProtocolNameList = append(a.ProtocolNameList, string(proto))
}
return nil
}
// ALPNProtocolSelection negotiates a shared protocol according to #3.2 of rfc7301
func ALPNProtocolSelection(supportedProtocols, peerSupportedProtocols []string) (string, error) {
if len(supportedProtocols) == 0 || len(peerSupportedProtocols) == 0 {
return "", nil
}
for _, s := range supportedProtocols {
for _, c := range peerSupportedProtocols {
if s == c {
return s, nil
}
}
}
return "", errALPNNoAppProto
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import (
@ -7,6 +10,9 @@ import (
)
var (
// ErrALPNInvalidFormat is raised when the ALPN format is invalid
ErrALPNInvalidFormat = &protocol.FatalError{Err: errors.New("invalid alpn format")} //nolint:goerr113
errALPNNoAppProto = &protocol.FatalError{Err: errors.New("no application protocol")} //nolint:goerr113
errBufferTooSmall = &protocol.TemporaryError{Err: errors.New("buffer is too small")} //nolint:goerr113
errInvalidExtensionType = &protocol.FatalError{Err: errors.New("invalid extension type")} //nolint:goerr113
errInvalidSNIFormat = &protocol.FatalError{Err: errors.New("invalid server name format")} //nolint:goerr113

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package extension implements the extension values in the ClientHello/ServerHello
package extension
@ -15,6 +18,7 @@ const (
SupportedPointFormatsTypeValue TypeValue = 11
SupportedSignatureAlgorithmsTypeValue TypeValue = 13
UseSRTPTypeValue TypeValue = 14
ALPNTypeValue TypeValue = 16
UseExtendedMasterSecretTypeValue TypeValue = 23
RenegotiationInfoTypeValue TypeValue = 65281
)
@ -62,6 +66,8 @@ func Unmarshal(buf []byte) ([]Extension, error) {
err = unmarshalAndAppend(buf[offset:], &SupportedEllipticCurves{})
case UseSRTPTypeValue:
err = unmarshalAndAppend(buf[offset:], &UseSRTP{})
case ALPNTypeValue:
err = unmarshalAndAppend(buf[offset:], &ALPN{})
case UseExtendedMasterSecretTypeValue:
err = unmarshalAndAppend(buf[offset:], &UseExtendedMasterSecret{})
case RenegotiationInfoTypeValue:

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import "encoding/binary"

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import (
@ -9,7 +12,7 @@ import (
const serverNameTypeDNSHostName = 0
// ServerName allows the client to inform the server the specific
// name it wishs to contact. Useful if multiple DNS names resolve
// name it wishes to contact. Useful if multiple DNS names resolve
// to one IP
//
// https://tools.ietf.org/html/rfc6066#section-3

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
// SRTPProtectionProfile defines the parameters and options that are in effect for the SRTP processing

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import (

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package extension
import (

Some files were not shown because too many files have changed in this diff Show more