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. certState *CertState
  18. peerCert *cert.NebulaCertificate
  19. initiator bool
  20. messageCounter atomic.Uint64
  21. window *Bits
  22. queueLock sync.Mutex
  23. writeLock sync.Mutex
  24. ready bool
  25. }
  26. func (f *Interface) newConnectionState(l *logrus.Logger, initiator bool, pattern noise.HandshakePattern, psk []byte, pskStage int) *ConnectionState {
  27. var dhFunc noise.DHFunc
  28. curCertState := f.certState.Load()
  29. switch curCertState.certificate.Details.Curve {
  30. case cert.Curve_CURVE25519:
  31. dhFunc = noise.DH25519
  32. case cert.Curve_P256:
  33. dhFunc = noiseutil.DHP256
  34. default:
  35. l.Errorf("invalid curve: %s", curCertState.certificate.Details.Curve)
  36. return nil
  37. }
  38. cs := noise.NewCipherSuite(dhFunc, noiseutil.CipherAESGCM, noise.HashSHA256)
  39. if f.cipher == "chachapoly" {
  40. cs = noise.NewCipherSuite(dhFunc, noise.CipherChaChaPoly, noise.HashSHA256)
  41. }
  42. static := noise.DHKey{Private: curCertState.privateKey, Public: curCertState.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. certState: curCertState,
  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. }