connection_state.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package nebula
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "sync"
  6. "sync/atomic"
  7. "github.com/flynn/noise"
  8. "github.com/sirupsen/logrus"
  9. "github.com/slackhq/nebula/cert"
  10. "github.com/slackhq/nebula/noiseutil"
  11. )
  12. const ReplayWindow = 1024
  13. type ConnectionState struct {
  14. eKey *NebulaCipherState
  15. dKey *NebulaCipherState
  16. H *noise.HandshakeState
  17. myCert *cert.NebulaCertificate
  18. peerCert *cert.NebulaCertificate
  19. initiator bool
  20. messageCounter atomic.Uint64
  21. window *Bits
  22. writeLock sync.Mutex
  23. }
  24. func NewConnectionState(l *logrus.Logger, cipher string, certState *CertState, initiator bool, pattern noise.HandshakePattern, psk []byte, pskStage int) *ConnectionState {
  25. var dhFunc noise.DHFunc
  26. switch certState.Certificate.Details.Curve {
  27. case cert.Curve_CURVE25519:
  28. dhFunc = noise.DH25519
  29. case cert.Curve_P256:
  30. dhFunc = noiseutil.DHP256
  31. default:
  32. l.Errorf("invalid curve: %s", certState.Certificate.Details.Curve)
  33. return nil
  34. }
  35. var cs noise.CipherSuite
  36. if cipher == "chachapoly" {
  37. cs = noise.NewCipherSuite(dhFunc, noise.CipherChaChaPoly, noise.HashSHA256)
  38. } else {
  39. cs = noise.NewCipherSuite(dhFunc, noiseutil.CipherAESGCM, noise.HashSHA256)
  40. }
  41. static := noise.DHKey{Private: certState.PrivateKey, Public: certState.PublicKey}
  42. b := NewBits(ReplayWindow)
  43. // Clear out bit 0, we never transmit it and we don't want it showing as packet loss
  44. b.Update(l, 0)
  45. hs, err := noise.NewHandshakeState(noise.Config{
  46. CipherSuite: cs,
  47. Random: rand.Reader,
  48. Pattern: pattern,
  49. Initiator: initiator,
  50. StaticKeypair: static,
  51. PresharedKey: psk,
  52. PresharedKeyPlacement: pskStage,
  53. })
  54. if err != nil {
  55. return nil
  56. }
  57. // The queue and ready params prevent a counter race that would happen when
  58. // sending stored packets and simultaneously accepting new traffic.
  59. ci := &ConnectionState{
  60. H: hs,
  61. initiator: initiator,
  62. window: b,
  63. myCert: certState.Certificate,
  64. }
  65. return ci
  66. }
  67. func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
  68. return json.Marshal(m{
  69. "certificate": cs.peerCert,
  70. "initiator": cs.initiator,
  71. "message_counter": cs.messageCounter.Load(),
  72. })
  73. }