connection_state.go 2.4 KB

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