flight1handler.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. // At least one ECC cipher suite needs to be retained for compatibilty
  137. // with the server's ECC certificate. Select from the ECC cipher suites
  138. // currently returned by defaultCipherSuites.
  139. eccCipherSuites := []uint16{
  140. uint16(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
  141. uint16(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
  142. uint16(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
  143. }
  144. hasECC := false
  145. checkECCLoop:
  146. for _, cipherSuite := range cipherSuites {
  147. for _, eccCipherSuite := range eccCipherSuites {
  148. if cipherSuite == eccCipherSuite {
  149. hasECC = true
  150. break checkECCLoop
  151. }
  152. }
  153. }
  154. if !hasECC {
  155. eccCipherSuite := eccCipherSuites[PRNG.Intn(len(eccCipherSuites))]
  156. cipherSuites = append(cipherSuites, eccCipherSuite)
  157. PRNG.Shuffle(len(cipherSuites), func(i, j int) {
  158. cipherSuites[i], cipherSuites[j] = cipherSuites[j], cipherSuites[i]
  159. })
  160. }
  161. for _, ext := range extensions {
  162. switch e := ext.(type) {
  163. case *extension.SupportedSignatureAlgorithms:
  164. // Limitation: to ensure compatibility with the ECDSA P-256 certificates generated by pion/webrtc,
  165. // https://github.com/pion/webrtc/blob/1df634e1188e06c08fe87753c7bdd576a29e0c92/dtlstransport.go#L84-L92,
  166. // the corresponding signature/hash algorithm needs to remain in the first position.
  167. e.SignatureHashAlgorithms = append([]signaturehash.Algorithm(nil), e.SignatureHashAlgorithms...)
  168. PRNG.Shuffle(len(e.SignatureHashAlgorithms)-1, func(i, j int) {
  169. e.SignatureHashAlgorithms[i+1], e.SignatureHashAlgorithms[j+1] =
  170. e.SignatureHashAlgorithms[j+1], e.SignatureHashAlgorithms[i+1]
  171. })
  172. e.SignatureHashAlgorithms = e.SignatureHashAlgorithms[:cut(len(e.SignatureHashAlgorithms))]
  173. case *extension.SupportedEllipticCurves:
  174. e.EllipticCurves = append([]elliptic.Curve(nil), e.EllipticCurves...)
  175. PRNG.Shuffle(len(e.EllipticCurves), func(i, j int) {
  176. e.EllipticCurves[i], e.EllipticCurves[j] =
  177. e.EllipticCurves[j], e.EllipticCurves[i]
  178. })
  179. e.EllipticCurves = e.EllipticCurves[:cut(len(e.EllipticCurves))]
  180. case *extension.SupportedPointFormats:
  181. e.PointFormats = append([]elliptic.CurvePointFormat(nil), e.PointFormats...)
  182. PRNG.Shuffle(len(e.PointFormats), func(i, j int) {
  183. e.PointFormats[i], e.PointFormats[j] =
  184. e.PointFormats[j], e.PointFormats[i]
  185. })
  186. e.PointFormats = e.PointFormats[:cut(len(e.PointFormats))]
  187. case *extension.UseSRTP:
  188. e.ProtectionProfiles = append([]SRTPProtectionProfile(nil), e.ProtectionProfiles...)
  189. PRNG.Shuffle(len(e.ProtectionProfiles), func(i, j int) {
  190. e.ProtectionProfiles[i], e.ProtectionProfiles[j] =
  191. e.ProtectionProfiles[j], e.ProtectionProfiles[i]
  192. })
  193. e.ProtectionProfiles = e.ProtectionProfiles[:cut(len(e.ProtectionProfiles))]
  194. }
  195. }
  196. PRNG.Shuffle(len(extensions), func(i, j int) {
  197. extensions[i], extensions[j] = extensions[j], extensions[i]
  198. })
  199. }
  200. return []*packet{
  201. {
  202. record: &recordlayer.RecordLayer{
  203. Header: recordlayer.Header{
  204. Version: protocol.Version1_2,
  205. },
  206. Content: &handshake.Handshake{
  207. Message: &handshake.MessageClientHello{
  208. Version: protocol.Version1_2,
  209. SessionID: state.SessionID,
  210. Cookie: state.cookie,
  211. Random: state.localRandom,
  212. CipherSuiteIDs: cipherSuites,
  213. CompressionMethods: defaultCompressionMethods(),
  214. Extensions: extensions,
  215. },
  216. },
  217. },
  218. },
  219. }, nil, nil
  220. }