flight1handler.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package dtls
  4. import (
  5. "context"
  6. "github.com/pion/dtls/v2/pkg/crypto/elliptic"
  7. "github.com/pion/dtls/v2/pkg/crypto/signaturehash"
  8. "github.com/pion/dtls/v2/pkg/protocol"
  9. "github.com/pion/dtls/v2/pkg/protocol/alert"
  10. "github.com/pion/dtls/v2/pkg/protocol/extension"
  11. "github.com/pion/dtls/v2/pkg/protocol/handshake"
  12. "github.com/pion/dtls/v2/pkg/protocol/recordlayer"
  13. inproxy_dtls "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy/dtls"
  14. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  15. )
  16. func flight1Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) {
  17. // HelloVerifyRequest can be skipped by the server,
  18. // so allow ServerHello during flight1 also
  19. seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite,
  20. handshakeCachePullRule{handshake.TypeHelloVerifyRequest, cfg.initialEpoch, false, true},
  21. handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, true},
  22. )
  23. if !ok {
  24. // No valid message received. Keep reading
  25. return 0, nil, nil
  26. }
  27. if _, ok := msgs[handshake.TypeServerHello]; ok {
  28. // Flight1 and flight2 were skipped.
  29. // Parse as flight3.
  30. return flight3Parse(ctx, c, state, cache, cfg)
  31. }
  32. if h, ok := msgs[handshake.TypeHelloVerifyRequest].(*handshake.MessageHelloVerifyRequest); ok {
  33. // DTLS 1.2 clients must not assume that the server will use the protocol version
  34. // specified in HelloVerifyRequest message. RFC 6347 Section 4.2.1
  35. if !h.Version.Equal(protocol.Version1_0) && !h.Version.Equal(protocol.Version1_2) {
  36. return 0, &alert.Alert{Level: alert.Fatal, Description: alert.ProtocolVersion}, errUnsupportedProtocolVersion
  37. }
  38. state.cookie = append([]byte{}, h.Cookie...)
  39. state.handshakeRecvSequence = seq
  40. return flight3, nil, nil
  41. }
  42. return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil
  43. }
  44. // [Psiphon]
  45. // The API for this Psiphon fork is identical to upstream, apart from this
  46. // symbol, which may be used to verify that the fork is used when compiling.
  47. const IsPsiphon = true
  48. func flight1Generate(ctx context.Context, c flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) {
  49. var zeroEpoch uint16
  50. state.localEpoch.Store(zeroEpoch)
  51. state.remoteEpoch.Store(zeroEpoch)
  52. state.namedCurve = defaultNamedCurve
  53. state.cookie = nil
  54. if err := state.localRandom.Populate(); err != nil {
  55. return nil, nil, err
  56. }
  57. // [Psiphon]
  58. // Conjure DTLS support, from: https://github.com/mingyech/dtls/commit/a56eccc1
  59. if state.isClient && cfg.customClientHelloRandom != nil {
  60. state.localRandom.RandomBytes = cfg.customClientHelloRandom()
  61. }
  62. extensions := []extension.Extension{
  63. &extension.SupportedSignatureAlgorithms{
  64. SignatureHashAlgorithms: cfg.localSignatureSchemes,
  65. },
  66. &extension.RenegotiationInfo{
  67. RenegotiatedConnection: 0,
  68. },
  69. }
  70. var setEllipticCurveCryptographyClientHelloExtensions bool
  71. for _, c := range cfg.localCipherSuites {
  72. if c.ECC() {
  73. setEllipticCurveCryptographyClientHelloExtensions = true
  74. break
  75. }
  76. }
  77. if setEllipticCurveCryptographyClientHelloExtensions {
  78. extensions = append(extensions, []extension.Extension{
  79. &extension.SupportedEllipticCurves{
  80. EllipticCurves: cfg.ellipticCurves,
  81. },
  82. &extension.SupportedPointFormats{
  83. PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed},
  84. },
  85. }...)
  86. }
  87. if len(cfg.localSRTPProtectionProfiles) > 0 {
  88. extensions = append(extensions, &extension.UseSRTP{
  89. ProtectionProfiles: cfg.localSRTPProtectionProfiles,
  90. })
  91. }
  92. if cfg.extendedMasterSecret == RequestExtendedMasterSecret ||
  93. cfg.extendedMasterSecret == RequireExtendedMasterSecret {
  94. extensions = append(extensions, &extension.UseExtendedMasterSecret{
  95. Supported: true,
  96. })
  97. }
  98. if len(cfg.serverName) > 0 {
  99. extensions = append(extensions, &extension.ServerName{ServerName: cfg.serverName})
  100. }
  101. if len(cfg.supportedProtocols) > 0 {
  102. extensions = append(extensions, &extension.ALPN{ProtocolNameList: cfg.supportedProtocols})
  103. }
  104. if cfg.sessionStore != nil {
  105. cfg.log.Tracef("[handshake] try to resume session")
  106. if s, err := cfg.sessionStore.Get(c.sessionKey()); err != nil {
  107. return nil, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err
  108. } else if s.ID != nil {
  109. cfg.log.Tracef("[handshake] get saved session: %x", s.ID)
  110. state.SessionID = s.ID
  111. state.masterSecret = s.Secret
  112. }
  113. }
  114. cipherSuites := cipherSuiteIDs(cfg.localCipherSuites)
  115. // [Psiphon]
  116. // Randomize ClientHello
  117. seed, err := inproxy_dtls.GetDTLSSeed(ctx)
  118. if err != nil {
  119. return nil, nil, err
  120. }
  121. if seed != nil {
  122. PRNG := prng.NewPRNGWithSeed(seed)
  123. cut := func(length int) int {
  124. n := length
  125. for ; n > 1; n-- {
  126. if !PRNG.FlipCoin() {
  127. break
  128. }
  129. }
  130. return n
  131. }
  132. PRNG.Shuffle(len(cipherSuites), func(i, j int) {
  133. cipherSuites[i], cipherSuites[j] = cipherSuites[j], cipherSuites[i]
  134. })
  135. cipherSuites = cipherSuites[:cut(len(cipherSuites))]
  136. for _, ext := range extensions {
  137. switch e := ext.(type) {
  138. case *extension.SupportedSignatureAlgorithms:
  139. // Limitation: to ensure compatibility with the ECDSA P-256 certificates generated by pion/webrtc,
  140. // https://github.com/pion/webrtc/blob/1df634e1188e06c08fe87753c7bdd576a29e0c92/dtlstransport.go#L84-L92,
  141. // the corresponding signature/hash algorithm needs to remain in the first position.
  142. e.SignatureHashAlgorithms = append([]signaturehash.Algorithm(nil), e.SignatureHashAlgorithms...)
  143. PRNG.Shuffle(len(e.SignatureHashAlgorithms)-1, func(i, j int) {
  144. e.SignatureHashAlgorithms[i+1], e.SignatureHashAlgorithms[j+1] =
  145. e.SignatureHashAlgorithms[j+1], e.SignatureHashAlgorithms[i+1]
  146. })
  147. e.SignatureHashAlgorithms = e.SignatureHashAlgorithms[:cut(len(e.SignatureHashAlgorithms))]
  148. case *extension.SupportedEllipticCurves:
  149. e.EllipticCurves = append([]elliptic.Curve(nil), e.EllipticCurves...)
  150. PRNG.Shuffle(len(e.EllipticCurves), func(i, j int) {
  151. e.EllipticCurves[i], e.EllipticCurves[j] =
  152. e.EllipticCurves[j], e.EllipticCurves[i]
  153. })
  154. e.EllipticCurves = e.EllipticCurves[:cut(len(e.EllipticCurves))]
  155. case *extension.SupportedPointFormats:
  156. e.PointFormats = append([]elliptic.CurvePointFormat(nil), e.PointFormats...)
  157. PRNG.Shuffle(len(e.PointFormats), func(i, j int) {
  158. e.PointFormats[i], e.PointFormats[j] =
  159. e.PointFormats[j], e.PointFormats[i]
  160. })
  161. e.PointFormats = e.PointFormats[:cut(len(e.PointFormats))]
  162. case *extension.UseSRTP:
  163. e.ProtectionProfiles = append([]SRTPProtectionProfile(nil), e.ProtectionProfiles...)
  164. PRNG.Shuffle(len(e.ProtectionProfiles), func(i, j int) {
  165. e.ProtectionProfiles[i], e.ProtectionProfiles[j] =
  166. e.ProtectionProfiles[j], e.ProtectionProfiles[i]
  167. })
  168. e.ProtectionProfiles = e.ProtectionProfiles[:cut(len(e.ProtectionProfiles))]
  169. }
  170. }
  171. PRNG.Shuffle(len(extensions), func(i, j int) {
  172. extensions[i], extensions[j] = extensions[j], extensions[i]
  173. })
  174. }
  175. return []*packet{
  176. {
  177. record: &recordlayer.RecordLayer{
  178. Header: recordlayer.Header{
  179. Version: protocol.Version1_2,
  180. },
  181. Content: &handshake.Handshake{
  182. Message: &handshake.MessageClientHello{
  183. Version: protocol.Version1_2,
  184. SessionID: state.SessionID,
  185. Cookie: state.cookie,
  186. Random: state.localRandom,
  187. CipherSuiteIDs: cipherSuites,
  188. CompressionMethods: defaultCompressionMethods(),
  189. Extensions: extensions,
  190. },
  191. },
  192. },
  193. },
  194. }, nil, nil
  195. }