interface.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. package nebula
  2. import (
  3. "errors"
  4. "io"
  5. "net"
  6. "os"
  7. "time"
  8. "github.com/rcrowley/go-metrics"
  9. )
  10. const mtu = 9001
  11. type Inside interface {
  12. io.ReadWriteCloser
  13. Activate() error
  14. CidrNet() *net.IPNet
  15. DeviceName() string
  16. WriteRaw([]byte) error
  17. }
  18. type InterfaceConfig struct {
  19. HostMap *HostMap
  20. Outside *udpConn
  21. Inside Inside
  22. certState *CertState
  23. Cipher string
  24. Firewall *Firewall
  25. ServeDns bool
  26. HandshakeManager *HandshakeManager
  27. lightHouse *LightHouse
  28. checkInterval int
  29. pendingDeletionInterval int
  30. DropLocalBroadcast bool
  31. DropMulticast bool
  32. UDPBatchSize int
  33. MessageMetrics *MessageMetrics
  34. }
  35. type Interface struct {
  36. hostMap *HostMap
  37. outside *udpConn
  38. inside Inside
  39. certState *CertState
  40. cipher string
  41. firewall *Firewall
  42. connectionManager *connectionManager
  43. handshakeManager *HandshakeManager
  44. serveDns bool
  45. createTime time.Time
  46. lightHouse *LightHouse
  47. localBroadcast uint32
  48. dropLocalBroadcast bool
  49. dropMulticast bool
  50. udpBatchSize int
  51. version string
  52. metricHandshakes metrics.Histogram
  53. messageMetrics *MessageMetrics
  54. }
  55. func NewInterface(c *InterfaceConfig) (*Interface, error) {
  56. if c.Outside == nil {
  57. return nil, errors.New("no outside connection")
  58. }
  59. if c.Inside == nil {
  60. return nil, errors.New("no inside interface (tun)")
  61. }
  62. if c.certState == nil {
  63. return nil, errors.New("no certificate state")
  64. }
  65. if c.Firewall == nil {
  66. return nil, errors.New("no firewall rules")
  67. }
  68. ifce := &Interface{
  69. hostMap: c.HostMap,
  70. outside: c.Outside,
  71. inside: c.Inside,
  72. certState: c.certState,
  73. cipher: c.Cipher,
  74. firewall: c.Firewall,
  75. serveDns: c.ServeDns,
  76. handshakeManager: c.HandshakeManager,
  77. createTime: time.Now(),
  78. lightHouse: c.lightHouse,
  79. localBroadcast: ip2int(c.certState.certificate.Details.Ips[0].IP) | ^ip2int(c.certState.certificate.Details.Ips[0].Mask),
  80. dropLocalBroadcast: c.DropLocalBroadcast,
  81. dropMulticast: c.DropMulticast,
  82. udpBatchSize: c.UDPBatchSize,
  83. metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
  84. messageMetrics: c.MessageMetrics,
  85. }
  86. ifce.connectionManager = newConnectionManager(ifce, c.checkInterval, c.pendingDeletionInterval)
  87. return ifce, nil
  88. }
  89. func (f *Interface) Run(tunRoutines, udpRoutines int, buildVersion string) {
  90. // actually turn on tun dev
  91. if err := f.inside.Activate(); err != nil {
  92. l.Fatal(err)
  93. }
  94. f.version = buildVersion
  95. addr, err := f.outside.LocalAddr()
  96. if err != nil {
  97. l.WithError(err).Error("Failed to get udp listen address")
  98. }
  99. l.WithField("interface", f.inside.DeviceName()).WithField("network", f.inside.CidrNet().String()).
  100. WithField("build", buildVersion).WithField("udpAddr", addr).
  101. Info("Nebula interface is active")
  102. // Launch n queues to read packets from udp
  103. for i := 0; i < udpRoutines; i++ {
  104. go f.listenOut(i)
  105. }
  106. // Launch n queues to read packets from tun dev
  107. for i := 0; i < tunRoutines; i++ {
  108. go f.listenIn(i)
  109. }
  110. }
  111. func (f *Interface) listenOut(i int) {
  112. //TODO: handle error
  113. addr, err := f.outside.LocalAddr()
  114. if err != nil {
  115. l.WithError(err).Error("failed to discover udp listening address")
  116. }
  117. var li *udpConn
  118. if i > 0 {
  119. //TODO: handle error
  120. li, err = NewListener(udp2ip(addr).String(), int(addr.Port), i > 0)
  121. if err != nil {
  122. l.WithError(err).Error("failed to make a new udp listener")
  123. }
  124. } else {
  125. li = f.outside
  126. }
  127. li.ListenOut(f)
  128. }
  129. func (f *Interface) listenIn(i int) {
  130. packet := make([]byte, mtu)
  131. out := make([]byte, mtu)
  132. fwPacket := &FirewallPacket{}
  133. nb := make([]byte, 12, 12)
  134. for {
  135. n, err := f.inside.Read(packet)
  136. if err != nil {
  137. l.WithError(err).Error("Error while reading outbound packet")
  138. // This only seems to happen when something fatal happens to the fd, so exit.
  139. os.Exit(2)
  140. }
  141. f.consumeInsidePacket(packet[:n], fwPacket, nb, out)
  142. }
  143. }
  144. func (f *Interface) RegisterConfigChangeCallbacks(c *Config) {
  145. c.RegisterReloadCallback(f.reloadCA)
  146. c.RegisterReloadCallback(f.reloadCertKey)
  147. c.RegisterReloadCallback(f.reloadFirewall)
  148. c.RegisterReloadCallback(f.outside.reloadConfig)
  149. }
  150. func (f *Interface) reloadCA(c *Config) {
  151. // reload and check regardless
  152. // todo: need mutex?
  153. newCAs, err := loadCAFromConfig(c)
  154. if err != nil {
  155. l.WithError(err).Error("Could not refresh trusted CA certificates")
  156. return
  157. }
  158. trustedCAs = newCAs
  159. l.WithField("fingerprints", trustedCAs.GetFingerprints()).Info("Trusted CA certificates refreshed")
  160. }
  161. func (f *Interface) reloadCertKey(c *Config) {
  162. // reload and check in all cases
  163. cs, err := NewCertStateFromConfig(c)
  164. if err != nil {
  165. l.WithError(err).Error("Could not refresh client cert")
  166. return
  167. }
  168. // did IP in cert change? if so, don't set
  169. oldIPs := f.certState.certificate.Details.Ips
  170. newIPs := cs.certificate.Details.Ips
  171. if len(oldIPs) > 0 && len(newIPs) > 0 && oldIPs[0].String() != newIPs[0].String() {
  172. l.WithField("new_ip", newIPs[0]).WithField("old_ip", oldIPs[0]).Error("IP in new cert was different from old")
  173. return
  174. }
  175. f.certState = cs
  176. l.WithField("cert", cs.certificate).Info("Client cert refreshed from disk")
  177. }
  178. func (f *Interface) reloadFirewall(c *Config) {
  179. //TODO: need to trigger/detect if the certificate changed too
  180. if c.HasChanged("firewall") == false {
  181. l.Debug("No firewall config change detected")
  182. return
  183. }
  184. fw, err := NewFirewallFromConfig(f.certState.certificate, c)
  185. if err != nil {
  186. l.WithError(err).Error("Error while creating firewall during reload")
  187. return
  188. }
  189. oldFw := f.firewall
  190. conntrack := oldFw.Conntrack
  191. conntrack.Lock()
  192. defer conntrack.Unlock()
  193. fw.rulesVersion = oldFw.rulesVersion + 1
  194. // If rulesVersion is back to zero, we have wrapped all the way around. Be
  195. // safe and just reset conntrack in this case.
  196. if fw.rulesVersion == 0 {
  197. l.WithField("firewallHash", fw.GetRuleHash()).
  198. WithField("oldFirewallHash", oldFw.GetRuleHash()).
  199. WithField("rulesVersion", fw.rulesVersion).
  200. Warn("firewall rulesVersion has overflowed, resetting conntrack")
  201. } else {
  202. fw.Conntrack = conntrack
  203. }
  204. f.firewall = fw
  205. oldFw.Destroy()
  206. l.WithField("firewallHash", fw.GetRuleHash()).
  207. WithField("oldFirewallHash", oldFw.GetRuleHash()).
  208. WithField("rulesVersion", fw.rulesVersion).
  209. Info("New firewall has been installed")
  210. }
  211. func (f *Interface) emitStats(i time.Duration) {
  212. ticker := time.NewTicker(i)
  213. for range ticker.C {
  214. f.firewall.EmitStats()
  215. f.handshakeManager.EmitStats()
  216. }
  217. }