server.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // server.go - Transport server 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. // ServerConfig is the server configuration parameters to use when
  25. // constructing a ServerConn.
  26. type ServerConfig struct {
  27. ServerPrivateKey ecdh.PrivateKey
  28. KEXMethods []handshake.KEXMethod
  29. PaddingMethods []PaddingMethod
  30. AuthPolicy AuthPolicy
  31. ReplayFilter handshake.ReplayFilter
  32. // PaddingParamFn is the function called at handshake time to obtain the
  33. // per-connection padding parameters used to instantiate the server side
  34. // padding algorithm (that will also be propagated back to the client).
  35. PaddingParamFn func(PaddingMethod) ([]byte, error)
  36. // AuthFn is the function called at handshake time to validate the
  37. // authentication received from the client. It is expected to return if
  38. // the authentication was valid, and the amoung of padding to apply to
  39. // the response message.
  40. AuthFn func(conn *ServerConn, transcriptDigest []byte, reqMsg []byte) (ok bool, padLen int)
  41. }
  42. // ServerConn is a server side client connection instance, that implements the
  43. // net.Conn interface.
  44. type ServerConn struct {
  45. commonConn
  46. config *ServerConfig
  47. handshakeState *handshake.ServerHandshake
  48. }
  49. // Handshake associates a ServerConn with an established net.Conn, and executes
  50. // the authenticated/encrypted/obfuscated key exchange, and optionally
  51. // authenticates the client.
  52. func (s *ServerConn) Handshake(conn net.Conn) (err error) {
  53. // Pass or fail, obliterate the handshake state.
  54. defer s.handshakeState.Reset()
  55. defer func() {
  56. if err != nil {
  57. s.setState(stateError)
  58. }
  59. }()
  60. // Initalize the underlying conn structure, and transition to the
  61. // handshaking state.
  62. if err = s.initConn(conn); err != nil {
  63. return
  64. }
  65. // Receive the client's handshake request.
  66. var reqExtData []byte
  67. if reqExtData, err = s.handshakeState.RecvHandshakeReq(s.rawConn); err != nil {
  68. return
  69. }
  70. // Parse the request extData to see which padding algorithm(s) the
  71. // peer wants us to select from.
  72. if len(reqExtData) < minReqExtDataSize {
  73. return ErrInvalidExtData
  74. }
  75. if reqExtData[0] != ProtocolVersion {
  76. return ErrInvalidExtData
  77. }
  78. if int(reqExtData[1]) != len(reqExtData)-2 {
  79. return ErrInvalidExtData
  80. }
  81. paddingMethod := PaddingInvalid
  82. for _, v := range reqExtData[2:] {
  83. if paddingOk(PaddingMethod(v), s.config.PaddingMethods) {
  84. paddingMethod = PaddingMethod(v)
  85. break
  86. }
  87. }
  88. if paddingMethod == PaddingInvalid {
  89. return ErrInvalidPadding
  90. }
  91. var paddingParams []byte
  92. if paddingParams, err = s.config.PaddingParamFn(paddingMethod); err != nil {
  93. return
  94. }
  95. // Build the response extData.
  96. respExtData := make([]byte, 0, minRespExtDataSize+len(paddingParams))
  97. respExtData = append(respExtData, ProtocolVersion)
  98. respExtData = append(respExtData, byte(s.config.AuthPolicy))
  99. respExtData = append(respExtData, byte(paddingMethod))
  100. respExtData = append(respExtData, paddingParams...)
  101. // Determine the response padding length by adding padding required to
  102. // bring the response size up to the minimum target length, and then
  103. // adding a random amount of padding.
  104. padLen := handshake.MinHandshakeSize - (handshake.MessageSize + len(respExtData))
  105. if padLen < 0 { // Should never happen.
  106. panic("basket2: handshake response exceeds payload capacity")
  107. }
  108. padLen += s.mRNG.Intn(handshake.MaxHandshakeSize - handshake.MinHandshakeSize)
  109. // Send the handshake response and derive the session keys.
  110. var keys *handshake.SessionKeys
  111. if keys, err = s.handshakeState.SendHandshakeResp(s.rawConn, respExtData, padLen); err != nil {
  112. return
  113. }
  114. defer keys.Reset()
  115. // Initialize the frame decoder/encoder with the session key material.
  116. if err = s.initFraming(keys.KDF); err != nil {
  117. return
  118. }
  119. // Bring the chosen padding algorithm online.
  120. if err = s.setPadding(paddingMethod, paddingParams); err != nil {
  121. return
  122. }
  123. // Authenticate the client if needed.
  124. if s.config.AuthPolicy == AuthMust {
  125. if err = s.authenticate(keys.TranscriptDigest); err != nil {
  126. return
  127. }
  128. }
  129. // The connection is now fully established.
  130. if err = s.setState(stateEstablished); err != nil {
  131. return
  132. }
  133. return nil
  134. }
  135. func (s *ServerConn) authenticate(transcriptDigest []byte) error {
  136. if err := s.setState(stateAuthenticate); err != nil {
  137. return err
  138. }
  139. // Receive the peer's authenticate frame.
  140. reqCmd, reqMsg, err := s.RecvRawRecord()
  141. if err != nil {
  142. return err
  143. }
  144. if reqCmd != framing.CmdAuthenticate {
  145. return ErrInvalidAuth
  146. }
  147. // Verify that the authentication is correct.
  148. ok, padLen := s.config.AuthFn(s, transcriptDigest, reqMsg)
  149. if !ok {
  150. return ErrInvalidAuth
  151. }
  152. // Send an authetication response.
  153. return s.SendRawRecord(framing.CmdAuthenticate, nil, padLen)
  154. }
  155. // NewServerConn initializes a ServerConn. Unlike NewClientConn this step may
  156. // and should be done right before Handshake is ready to be called.
  157. func NewServerConn(config *ServerConfig) (*ServerConn, error) {
  158. var err error
  159. if len(config.KEXMethods) == 0 {
  160. panic("basket2: no KEXMethods")
  161. }
  162. if len(config.PaddingMethods) == 0 {
  163. panic("basket2: no PaddingMethods")
  164. }
  165. if config.ReplayFilter == nil {
  166. panic("basket2: no replay filter")
  167. }
  168. if config.ServerPrivateKey == nil {
  169. panic("basket2: no server private key")
  170. }
  171. if config.ServerPrivateKey.Curve() != handshake.IdentityCurve {
  172. panic("basket2: invalid server private key curve")
  173. }
  174. if config.AuthPolicy == AuthMust && config.AuthFn == nil {
  175. panic("basket2: auth required but no AuthFn")
  176. }
  177. if config.PaddingParamFn == nil {
  178. config.PaddingParamFn = DefaultPaddingParams
  179. }
  180. s := new(ServerConn)
  181. s.config = config
  182. s.isClient = false
  183. if s.handshakeState, err = handshake.NewServerHandshake(rand.Reader, config.KEXMethods, config.ReplayFilter, config.ServerPrivateKey); err != nil {
  184. return nil, err
  185. }
  186. return s, nil
  187. }
  188. var _ net.Conn = (*ServerConn)(nil)