connection_state.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package nebula
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "fmt"
  6. "sync"
  7. "sync/atomic"
  8. "github.com/flynn/noise"
  9. "github.com/sirupsen/logrus"
  10. "github.com/slackhq/nebula/cert"
  11. "github.com/slackhq/nebula/noiseutil"
  12. )
  13. const ReplayWindow = 1024
  14. type ConnectionState struct {
  15. eKey *NebulaCipherState
  16. dKey *NebulaCipherState
  17. H *noise.HandshakeState
  18. myCert cert.Certificate
  19. peerCert *cert.CachedCertificate
  20. initiator bool
  21. messageCounter atomic.Uint64
  22. window *Bits
  23. writeLock sync.Mutex
  24. }
  25. func NewConnectionState(l *logrus.Logger, cs *CertState, crt cert.Certificate, initiator bool, pattern noise.HandshakePattern) (*ConnectionState, error) {
  26. var dhFunc noise.DHFunc
  27. switch crt.Curve() {
  28. case cert.Curve_CURVE25519:
  29. dhFunc = noise.DH25519
  30. case cert.Curve_P256:
  31. if cs.pkcs11Backed {
  32. dhFunc = noiseutil.DHP256PKCS11
  33. } else {
  34. dhFunc = noiseutil.DHP256
  35. }
  36. default:
  37. return nil, fmt.Errorf("invalid curve: %s", crt.Curve())
  38. }
  39. var ncs noise.CipherSuite
  40. if cs.cipher == "chachapoly" {
  41. ncs = noise.NewCipherSuite(dhFunc, noise.CipherChaChaPoly, noise.HashSHA256)
  42. } else {
  43. ncs = noise.NewCipherSuite(dhFunc, noiseutil.CipherAESGCM, noise.HashSHA256)
  44. }
  45. static := noise.DHKey{Private: cs.privateKey, Public: crt.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: ncs,
  51. Random: rand.Reader,
  52. Pattern: pattern,
  53. Initiator: initiator,
  54. StaticKeypair: static,
  55. //NOTE: These should come from CertState (pki.go) when we finally implement it
  56. PresharedKey: []byte{},
  57. PresharedKeyPlacement: 0,
  58. })
  59. if err != nil {
  60. return nil, fmt.Errorf("NewConnectionState: %s", err)
  61. }
  62. // The queue and ready params prevent a counter race that would happen when
  63. // sending stored packets and simultaneously accepting new traffic.
  64. ci := &ConnectionState{
  65. H: hs,
  66. initiator: initiator,
  67. window: b,
  68. myCert: crt,
  69. }
  70. // always start the counter from 2, as packet 1 and packet 2 are handshake packets.
  71. ci.messageCounter.Add(2)
  72. return ci, nil
  73. }
  74. func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
  75. return json.Marshal(m{
  76. "certificate": cs.peerCert,
  77. "initiator": cs.initiator,
  78. "message_counter": cs.messageCounter.Load(),
  79. })
  80. }
  81. func (cs *ConnectionState) Curve() cert.Curve {
  82. return cs.myCert.Curve()
  83. }