handshaker.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package dtls
  4. import (
  5. "context"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "fmt"
  9. "io"
  10. "net"
  11. "sync"
  12. "time"
  13. "github.com/pion/dtls/v2/pkg/crypto/elliptic"
  14. "github.com/pion/dtls/v2/pkg/crypto/signaturehash"
  15. "github.com/pion/dtls/v2/pkg/protocol/alert"
  16. "github.com/pion/dtls/v2/pkg/protocol/handshake"
  17. "github.com/pion/logging"
  18. )
  19. // [RFC6347 Section-4.2.4]
  20. // +-----------+
  21. // +---> | PREPARING | <--------------------+
  22. // | +-----------+ |
  23. // | | |
  24. // | | Buffer next flight |
  25. // | | |
  26. // | \|/ |
  27. // | +-----------+ |
  28. // | | SENDING |<------------------+ | Send
  29. // | +-----------+ | | HelloRequest
  30. // Receive | | | |
  31. // next | | Send flight | | or
  32. // flight | +--------+ | |
  33. // | | | Set retransmit timer | | Receive
  34. // | | \|/ | | HelloRequest
  35. // | | +-----------+ | | Send
  36. // +--)--| WAITING |-------------------+ | ClientHello
  37. // | | +-----------+ Timer expires | |
  38. // | | | | |
  39. // | | +------------------------+ |
  40. // Receive | | Send Read retransmit |
  41. // last | | last |
  42. // flight | | flight |
  43. // | | |
  44. // \|/\|/ |
  45. // +-----------+ |
  46. // | FINISHED | -------------------------------+
  47. // +-----------+
  48. // | /|\
  49. // | |
  50. // +---+
  51. // Read retransmit
  52. // Retransmit last flight
  53. type handshakeState uint8
  54. const (
  55. handshakeErrored handshakeState = iota
  56. handshakePreparing
  57. handshakeSending
  58. handshakeWaiting
  59. handshakeFinished
  60. )
  61. func (s handshakeState) String() string {
  62. switch s {
  63. case handshakeErrored:
  64. return "Errored"
  65. case handshakePreparing:
  66. return "Preparing"
  67. case handshakeSending:
  68. return "Sending"
  69. case handshakeWaiting:
  70. return "Waiting"
  71. case handshakeFinished:
  72. return "Finished"
  73. default:
  74. return "Unknown"
  75. }
  76. }
  77. type handshakeFSM struct {
  78. currentFlight flightVal
  79. flights []*packet
  80. retransmit bool
  81. state *State
  82. cache *handshakeCache
  83. cfg *handshakeConfig
  84. closed chan struct{}
  85. }
  86. type handshakeConfig struct {
  87. localPSKCallback PSKCallback
  88. localPSKIdentityHint []byte
  89. localCipherSuites []CipherSuite // Available CipherSuites
  90. localSignatureSchemes []signaturehash.Algorithm // Available signature schemes
  91. extendedMasterSecret ExtendedMasterSecretType // Policy for the Extended Master Support extension
  92. localSRTPProtectionProfiles []SRTPProtectionProfile // Available SRTPProtectionProfiles, if empty no SRTP support
  93. serverName string
  94. supportedProtocols []string
  95. clientAuth ClientAuthType // If we are a client should we request a client certificate
  96. localCertificates []tls.Certificate
  97. nameToCertificate map[string]*tls.Certificate
  98. insecureSkipVerify bool
  99. verifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
  100. verifyConnection func(*State) error
  101. sessionStore SessionStore
  102. rootCAs *x509.CertPool
  103. clientCAs *x509.CertPool
  104. retransmitInterval time.Duration
  105. customCipherSuites func() []CipherSuite
  106. ellipticCurves []elliptic.Curve
  107. insecureSkipHelloVerify bool
  108. // [Psiphon]
  109. // Conjure DTLS support, from: https://github.com/mingyech/dtls/commit/a56eccc1
  110. customClientHelloRandom func() [handshake.RandomBytesLength]byte
  111. onFlightState func(flightVal, handshakeState)
  112. log logging.LeveledLogger
  113. keyLogWriter io.Writer
  114. localGetCertificate func(*ClientHelloInfo) (*tls.Certificate, error)
  115. localGetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error)
  116. initialEpoch uint16
  117. mu sync.Mutex
  118. }
  119. type flightConn interface {
  120. notify(ctx context.Context, level alert.Level, desc alert.Description) error
  121. writePackets(context.Context, []*packet) error
  122. recvHandshake() <-chan chan struct{}
  123. setLocalEpoch(epoch uint16)
  124. handleQueuedPackets(context.Context) error
  125. sessionKey() []byte
  126. // [Psiphon]
  127. LocalAddr() net.Addr
  128. }
  129. func (c *handshakeConfig) writeKeyLog(label string, clientRandom, secret []byte) {
  130. if c.keyLogWriter == nil {
  131. return
  132. }
  133. c.mu.Lock()
  134. defer c.mu.Unlock()
  135. _, err := c.keyLogWriter.Write([]byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret)))
  136. if err != nil {
  137. c.log.Debugf("failed to write key log file: %s", err)
  138. }
  139. }
  140. func srvCliStr(isClient bool) string {
  141. if isClient {
  142. return "client"
  143. }
  144. return "server"
  145. }
  146. func newHandshakeFSM(
  147. s *State, cache *handshakeCache, cfg *handshakeConfig,
  148. initialFlight flightVal,
  149. ) *handshakeFSM {
  150. return &handshakeFSM{
  151. currentFlight: initialFlight,
  152. state: s,
  153. cache: cache,
  154. cfg: cfg,
  155. closed: make(chan struct{}),
  156. }
  157. }
  158. func (s *handshakeFSM) Run(ctx context.Context, c flightConn, initialState handshakeState) error {
  159. state := initialState
  160. defer func() {
  161. close(s.closed)
  162. }()
  163. for {
  164. s.cfg.log.Tracef("[handshake:%s] %s: %s", srvCliStr(s.state.isClient), s.currentFlight.String(), state.String())
  165. if s.cfg.onFlightState != nil {
  166. s.cfg.onFlightState(s.currentFlight, state)
  167. }
  168. var err error
  169. switch state {
  170. case handshakePreparing:
  171. state, err = s.prepare(ctx, c)
  172. case handshakeSending:
  173. state, err = s.send(ctx, c)
  174. case handshakeWaiting:
  175. state, err = s.wait(ctx, c)
  176. case handshakeFinished:
  177. state, err = s.finish(ctx, c)
  178. default:
  179. return errInvalidFSMTransition
  180. }
  181. if err != nil {
  182. return err
  183. }
  184. }
  185. }
  186. func (s *handshakeFSM) Done() <-chan struct{} {
  187. return s.closed
  188. }
  189. func (s *handshakeFSM) prepare(ctx context.Context, c flightConn) (handshakeState, error) {
  190. s.flights = nil
  191. // Prepare flights
  192. var (
  193. a *alert.Alert
  194. err error
  195. pkts []*packet
  196. )
  197. gen, retransmit, errFlight := s.currentFlight.getFlightGenerator()
  198. if errFlight != nil {
  199. err = errFlight
  200. a = &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}
  201. } else {
  202. // [Psiphon]
  203. // Pass in dial context for GetDTLSSeed.
  204. pkts, a, err = gen(ctx, c, s.state, s.cache, s.cfg)
  205. s.retransmit = retransmit
  206. }
  207. if a != nil {
  208. if alertErr := c.notify(ctx, a.Level, a.Description); alertErr != nil {
  209. if err != nil {
  210. err = alertErr
  211. }
  212. }
  213. }
  214. if err != nil {
  215. return handshakeErrored, err
  216. }
  217. s.flights = pkts
  218. epoch := s.cfg.initialEpoch
  219. nextEpoch := epoch
  220. for _, p := range s.flights {
  221. p.record.Header.Epoch += epoch
  222. if p.record.Header.Epoch > nextEpoch {
  223. nextEpoch = p.record.Header.Epoch
  224. }
  225. if h, ok := p.record.Content.(*handshake.Handshake); ok {
  226. h.Header.MessageSequence = uint16(s.state.handshakeSendSequence)
  227. s.state.handshakeSendSequence++
  228. }
  229. }
  230. if epoch != nextEpoch {
  231. s.cfg.log.Tracef("[handshake:%s] -> changeCipherSpec (epoch: %d)", srvCliStr(s.state.isClient), nextEpoch)
  232. c.setLocalEpoch(nextEpoch)
  233. }
  234. return handshakeSending, nil
  235. }
  236. func (s *handshakeFSM) send(ctx context.Context, c flightConn) (handshakeState, error) {
  237. // Send flights
  238. if err := c.writePackets(ctx, s.flights); err != nil {
  239. return handshakeErrored, err
  240. }
  241. if s.currentFlight.isLastSendFlight() {
  242. return handshakeFinished, nil
  243. }
  244. return handshakeWaiting, nil
  245. }
  246. func (s *handshakeFSM) wait(ctx context.Context, c flightConn) (handshakeState, error) { //nolint:gocognit
  247. parse, errFlight := s.currentFlight.getFlightParser()
  248. if errFlight != nil {
  249. if alertErr := c.notify(ctx, alert.Fatal, alert.InternalError); alertErr != nil {
  250. if errFlight != nil {
  251. return handshakeErrored, alertErr
  252. }
  253. }
  254. return handshakeErrored, errFlight
  255. }
  256. retransmitTimer := time.NewTimer(s.cfg.retransmitInterval)
  257. for {
  258. select {
  259. case done := <-c.recvHandshake():
  260. nextFlight, alert, err := parse(ctx, c, s.state, s.cache, s.cfg)
  261. close(done)
  262. if alert != nil {
  263. if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
  264. if err != nil {
  265. err = alertErr
  266. }
  267. }
  268. }
  269. if err != nil {
  270. return handshakeErrored, err
  271. }
  272. if nextFlight == 0 {
  273. break
  274. }
  275. s.cfg.log.Tracef("[handshake:%s] %s -> %s", srvCliStr(s.state.isClient), s.currentFlight.String(), nextFlight.String())
  276. if nextFlight.isLastRecvFlight() && s.currentFlight == nextFlight {
  277. return handshakeFinished, nil
  278. }
  279. s.currentFlight = nextFlight
  280. return handshakePreparing, nil
  281. case <-retransmitTimer.C:
  282. if !s.retransmit {
  283. return handshakeWaiting, nil
  284. }
  285. return handshakeSending, nil
  286. case <-ctx.Done():
  287. return handshakeErrored, ctx.Err()
  288. }
  289. }
  290. }
  291. func (s *handshakeFSM) finish(ctx context.Context, c flightConn) (handshakeState, error) {
  292. parse, errFlight := s.currentFlight.getFlightParser()
  293. if errFlight != nil {
  294. if alertErr := c.notify(ctx, alert.Fatal, alert.InternalError); alertErr != nil {
  295. if errFlight != nil {
  296. return handshakeErrored, alertErr
  297. }
  298. }
  299. return handshakeErrored, errFlight
  300. }
  301. retransmitTimer := time.NewTimer(s.cfg.retransmitInterval)
  302. select {
  303. case done := <-c.recvHandshake():
  304. nextFlight, alert, err := parse(ctx, c, s.state, s.cache, s.cfg)
  305. close(done)
  306. if alert != nil {
  307. if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
  308. if err != nil {
  309. err = alertErr
  310. }
  311. }
  312. }
  313. if err != nil {
  314. return handshakeErrored, err
  315. }
  316. if nextFlight == 0 {
  317. break
  318. }
  319. if nextFlight.isLastRecvFlight() && s.currentFlight == nextFlight {
  320. return handshakeFinished, nil
  321. }
  322. <-retransmitTimer.C
  323. // Retransmit last flight
  324. return handshakeSending, nil
  325. case <-ctx.Done():
  326. return handshakeErrored, ctx.Err()
  327. }
  328. return handshakeFinished, nil
  329. }