connection_state.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. ready bool
  24. }
  25. func NewConnectionState(l *logrus.Logger, cipher string, certState *CertState, initiator bool, pattern noise.HandshakePattern, psk []byte, pskStage int) *ConnectionState {
  26. var dhFunc noise.DHFunc
  27. switch certState.Certificate.Details.Curve {
  28. case cert.Curve_CURVE25519:
  29. dhFunc = noise.DH25519
  30. case cert.Curve_P256:
  31. dhFunc = noiseutil.DHP256
  32. default:
  33. l.Errorf("invalid curve: %s", certState.Certificate.Details.Curve)
  34. return nil
  35. }
  36. var cs noise.CipherSuite
  37. if cipher == "chachapoly" {
  38. cs = noise.NewCipherSuite(dhFunc, noise.CipherChaChaPoly, noise.HashSHA256)
  39. } else {
  40. cs = noise.NewCipherSuite(dhFunc, noiseutil.CipherAESGCM, noise.HashSHA256)
  41. }
  42. static := noise.DHKey{Private: certState.PrivateKey, Public: certState.PublicKey}
  43. b := NewBits(ReplayWindow)
  44. // Clear out bit 0, we never transmit it and we don't want it showing as packet loss
  45. b.Update(l, 0)
  46. hs, err := noise.NewHandshakeState(noise.Config{
  47. CipherSuite: cs,
  48. Random: rand.Reader,
  49. Pattern: pattern,
  50. Initiator: initiator,
  51. StaticKeypair: static,
  52. PresharedKey: psk,
  53. PresharedKeyPlacement: pskStage,
  54. })
  55. if err != nil {
  56. return nil
  57. }
  58. // The queue and ready params prevent a counter race that would happen when
  59. // sending stored packets and simultaneously accepting new traffic.
  60. ci := &ConnectionState{
  61. H: hs,
  62. initiator: initiator,
  63. window: b,
  64. ready: false,
  65. myCert: certState.Certificate,
  66. }
  67. return ci
  68. }
  69. func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
  70. return json.Marshal(m{
  71. "certificate": cs.peerCert,
  72. "initiator": cs.initiator,
  73. "message_counter": cs.messageCounter.Load(),
  74. "ready": cs.ready,
  75. })
  76. }