client.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. // client.go - Transport client implementation.
  2. // Copyright (C) 2016 Yawning Angel.
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as
  6. // published by the Free Software Foundation, either version 3 of the
  7. // License, or (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. package basket2
  17. import (
  18. "net"
  19. "git.schwanenlied.me/yawning/basket2.git/crypto/ecdh"
  20. "git.schwanenlied.me/yawning/basket2.git/crypto/rand"
  21. "git.schwanenlied.me/yawning/basket2.git/framing"
  22. "git.schwanenlied.me/yawning/basket2.git/handshake"
  23. )
  24. // ClientConfig is the client configuration parameters to use when
  25. // constructing a ClientConn.
  26. type ClientConfig struct {
  27. KEXMethod handshake.KEXMethod
  28. PaddingMethods []PaddingMethod
  29. ServerPublicKey ecdh.PublicKey
  30. // AuthFn is the function called at handshake time to authenticate with
  31. // the remote peer. It is expected to return the authentication request
  32. // message, the amount of padding to add, or an error if it is not
  33. // possible to authenticate.
  34. AuthFn func(conn *ClientConn, transcriptDigest []byte) (reqMsg []byte, padLen int, err error)
  35. }
  36. // ClientConn is a client connection instance, that implements the net.Conn
  37. // interface.
  38. type ClientConn struct {
  39. commonConn
  40. config *ClientConfig
  41. handshakeState *handshake.ClientHandshake
  42. }
  43. // Handshake associates a ClientConn with an established net.Conn, and executes
  44. // the authenticated/encrypted/obfuscated key exchange, and optionally
  45. // authenticates the client with the server.
  46. func (c *ClientConn) Handshake(conn net.Conn) (err error) {
  47. // Pass or fail, obliterate the handshake state.
  48. defer c.handshakeState.Reset()
  49. defer func() {
  50. if err != nil {
  51. c.setState(stateError)
  52. }
  53. }()
  54. // Initalize the underlying conn structure, and transition to the
  55. // handshaking state.
  56. if err = c.initConn(conn); err != nil {
  57. return
  58. }
  59. // Build the request extData to negotiate padding algorithms.
  60. reqExtData := make([]byte, 0, 1+1+len(c.config.PaddingMethods))
  61. reqExtData = append(reqExtData, ProtocolVersion)
  62. reqExtData = append(reqExtData, byte(len(c.config.PaddingMethods)))
  63. for _, v := range c.config.PaddingMethods {
  64. reqExtData = append(reqExtData, byte(v))
  65. }
  66. // Determine the request padding length by adding padding required to
  67. // bring the request size up to the minimum target length, and then
  68. // adding a random amount of padding.
  69. //
  70. // All requests on the wire will be of length [min, max).
  71. padLen := handshake.MinHandshakeSize - (handshake.MessageSize + len(reqExtData))
  72. if padLen < 0 { // Should never happen.
  73. panic("basket2: handshake request exceeds payload capacity")
  74. }
  75. padLen += c.mRNG.Intn(handshake.MaxHandshakeSize - handshake.MinHandshakeSize)
  76. // Send the request, receive the response, and derive the session keys.
  77. var keys *handshake.SessionKeys
  78. var respExtData []byte
  79. if keys, respExtData, err = c.handshakeState.Handshake(c.rawConn, reqExtData, padLen); err != nil {
  80. return
  81. }
  82. defer keys.Reset()
  83. // Parse the response extData to see which padding algorithm to use,
  84. // and if authentication is possible/required.
  85. if len(respExtData) < minRespExtDataSize {
  86. return ErrInvalidExtData
  87. }
  88. if respExtData[0] != ProtocolVersion {
  89. return ErrInvalidExtData
  90. }
  91. authPolicy := AuthPolicy(respExtData[1])
  92. paddingMethod := PaddingMethod(respExtData[2])
  93. paddingParams := respExtData[minRespExtDataSize:]
  94. // Validate that the negotiated padding method is contained in our request.
  95. if !paddingOk(paddingMethod, c.config.PaddingMethods) {
  96. return ErrInvalidPadding
  97. }
  98. // Initialize the frame encoder/decoder with the session key material.
  99. if err = c.initFraming(keys.KDF); err != nil {
  100. return
  101. }
  102. // Bring the chosen padding algorithm online.
  103. if err = c.setPadding(paddingMethod, paddingParams); err != nil {
  104. return
  105. }
  106. // Authenticate if needed.
  107. if authPolicy == AuthMust {
  108. if err = c.authenticate(keys.TranscriptDigest); err != nil {
  109. return
  110. }
  111. }
  112. // The connection is now fully established.
  113. if err = c.setState(stateEstablished); err != nil {
  114. return
  115. }
  116. return nil
  117. }
  118. func (c *ClientConn) authenticate(transcriptDigest []byte) error {
  119. if err := c.setState(stateAuthenticate); err != nil {
  120. return err
  121. }
  122. // Caller didn't provide an authentication callback.
  123. if c.config.AuthFn == nil {
  124. return ErrInvalidAuth
  125. }
  126. // Caller does something with transcriptDigest and returns the auth
  127. // packet payload and pad length.
  128. reqMsg, padLen, err := c.config.AuthFn(c, transcriptDigest)
  129. if err != nil {
  130. return err
  131. }
  132. // Send the Authenticate packet.
  133. if err = c.SendRawRecord(framing.CmdAuthenticate, reqMsg, padLen); err != nil {
  134. return err
  135. }
  136. // Receive the authentication response.
  137. respCmd, respMsg, err := c.RecvRawRecord()
  138. if err != nil {
  139. return err
  140. }
  141. if respCmd != framing.CmdAuthenticate || len(respMsg) != 0 {
  142. // On success, expect an Authenticate packet with no payload.
  143. return ErrInvalidAuth
  144. }
  145. // Authentication successful.
  146. return nil
  147. }
  148. // NewClientConn initializes a ClientConn. This step should be done offline,
  149. // as timing variation due to the Elligator 2 rejection sampling may leak
  150. // information regarding the obfuscation method.
  151. func NewClientConn(config *ClientConfig) (*ClientConn, error) {
  152. var err error
  153. if len(config.PaddingMethods) == 0 {
  154. panic("basket2: no requested padding methods")
  155. }
  156. if len(config.PaddingMethods) > 255 {
  157. panic("basket2: too many padding methods")
  158. }
  159. if config.ServerPublicKey == nil {
  160. panic("basket2: no server public key")
  161. }
  162. if config.ServerPublicKey.Curve() != handshake.IdentityCurve {
  163. panic("basket2: invalid server public key curve")
  164. }
  165. c := new(ClientConn)
  166. c.config = config
  167. c.isClient = true
  168. if c.handshakeState, err = handshake.NewClientHandshake(rand.Reader, config.KEXMethod, config.ServerPublicKey); err != nil {
  169. return nil, err
  170. }
  171. return c, nil
  172. }
  173. var _ net.Conn = (*ClientConn)(nil)