connection_state.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package nebula
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "sync"
  6. "github.com/flynn/noise"
  7. "github.com/slackhq/nebula/cert"
  8. )
  9. const ReplayWindow = 1024
  10. type ConnectionState struct {
  11. eKey *NebulaCipherState
  12. dKey *NebulaCipherState
  13. H *noise.HandshakeState
  14. certState *CertState
  15. peerCert *cert.NebulaCertificate
  16. initiator bool
  17. messageCounter *uint64
  18. window *Bits
  19. queueLock sync.Mutex
  20. writeLock sync.Mutex
  21. ready bool
  22. }
  23. func (f *Interface) newConnectionState(initiator bool, pattern noise.HandshakePattern, psk []byte, pskStage int) *ConnectionState {
  24. cs := noise.NewCipherSuite(noise.DH25519, noise.CipherAESGCM, noise.HashSHA256)
  25. if f.cipher == "chachapoly" {
  26. cs = noise.NewCipherSuite(noise.DH25519, noise.CipherChaChaPoly, noise.HashSHA256)
  27. }
  28. curCertState := f.certState
  29. static := noise.DHKey{Private: curCertState.privateKey, Public: curCertState.publicKey}
  30. b := NewBits(ReplayWindow)
  31. // Clear out bit 0, we never transmit it and we don't want it showing as packet loss
  32. b.Update(0)
  33. hs, err := noise.NewHandshakeState(noise.Config{
  34. CipherSuite: cs,
  35. Random: rand.Reader,
  36. Pattern: pattern,
  37. Initiator: initiator,
  38. StaticKeypair: static,
  39. PresharedKey: psk,
  40. PresharedKeyPlacement: pskStage,
  41. })
  42. if err != nil {
  43. return nil
  44. }
  45. // The queue and ready params prevent a counter race that would happen when
  46. // sending stored packets and simultaneously accepting new traffic.
  47. ci := &ConnectionState{
  48. H: hs,
  49. initiator: initiator,
  50. window: b,
  51. ready: false,
  52. certState: curCertState,
  53. messageCounter: new(uint64),
  54. }
  55. return ci
  56. }
  57. func (cs *ConnectionState) MarshalJSON() ([]byte, error) {
  58. return json.Marshal(m{
  59. "certificate": cs.peerCert,
  60. "initiator": cs.initiator,
  61. "message_counter": cs.messageCounter,
  62. "ready": cs.ready,
  63. })
  64. }