monitor_linux.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build !android
  5. // +build !android
  6. package monitor
  7. import (
  8. "net"
  9. "time"
  10. "github.com/jsimonetti/rtnetlink"
  11. "github.com/mdlayher/netlink"
  12. "golang.org/x/sys/unix"
  13. "inet.af/netaddr"
  14. "tailscale.com/net/tsaddr"
  15. "tailscale.com/types/logger"
  16. )
  17. // unspecifiedMessage is a minimal message implementation that should not
  18. // be ignored. In general, OS-specific implementations should use better
  19. // types and avoid this if they can.
  20. type unspecifiedMessage struct{}
  21. func (unspecifiedMessage) ignore() bool { return false }
  22. // nlConn wraps a *netlink.Conn and returns a monitor.Message
  23. // instead of a netlink.Message. Currently, messages are discarded,
  24. // but down the line, when messages trigger different logic depending
  25. // on the type of event, this provides the capability of handling
  26. // each architecture-specific message in a generic fashion.
  27. type nlConn struct {
  28. logf logger.Logf
  29. conn *netlink.Conn
  30. buffered []netlink.Message
  31. }
  32. func newOSMon(logf logger.Logf, m *Mon) (osMon, error) {
  33. conn, err := netlink.Dial(unix.NETLINK_ROUTE, &netlink.Config{
  34. // Routes get us most of the events of interest, but we need
  35. // address as well to cover things like DHCP deciding to give
  36. // us a new address upon renewal - routing wouldn't change,
  37. // but all reachability would.
  38. Groups: unix.RTMGRP_IPV4_IFADDR | unix.RTMGRP_IPV6_IFADDR |
  39. unix.RTMGRP_IPV4_ROUTE | unix.RTMGRP_IPV6_ROUTE |
  40. unix.RTMGRP_IPV4_RULE, // no IPV6_RULE in x/sys/unix
  41. })
  42. if err != nil {
  43. // Google Cloud Run does not implement NETLINK_ROUTE RTMGRP support
  44. logf("monitor_linux: AF_NETLINK RTMGRP failed, falling back to polling")
  45. return newPollingMon(logf, m)
  46. }
  47. return &nlConn{logf: logf, conn: conn}, nil
  48. }
  49. func (c *nlConn) Close() error { return c.conn.Close() }
  50. func (c *nlConn) Receive() (message, error) {
  51. if len(c.buffered) == 0 {
  52. var err error
  53. c.buffered, err = c.conn.Receive()
  54. if err != nil {
  55. return nil, err
  56. }
  57. if len(c.buffered) == 0 {
  58. // Unexpected. Not seen in wild, but sleep defensively.
  59. time.Sleep(time.Second)
  60. return ignoreMessage{}, nil
  61. }
  62. }
  63. msg := c.buffered[0]
  64. c.buffered = c.buffered[1:]
  65. // See https://github.com/torvalds/linux/blob/master/include/uapi/linux/rtnetlink.h
  66. // And https://man7.org/linux/man-pages/man7/rtnetlink.7.html
  67. switch msg.Header.Type {
  68. case unix.RTM_NEWADDR, unix.RTM_DELADDR:
  69. var rmsg rtnetlink.AddressMessage
  70. if err := rmsg.UnmarshalBinary(msg.Data); err != nil {
  71. c.logf("failed to parse type %v: %v", msg.Header.Type, err)
  72. return unspecifiedMessage{}, nil
  73. }
  74. return &newAddrMessage{
  75. Label: rmsg.Attributes.Label,
  76. Addr: netaddrIP(rmsg.Attributes.Local),
  77. Delete: msg.Header.Type == unix.RTM_DELADDR,
  78. }, nil
  79. case unix.RTM_NEWROUTE, unix.RTM_DELROUTE:
  80. typeStr := "RTM_NEWROUTE"
  81. if msg.Header.Type == unix.RTM_DELROUTE {
  82. typeStr = "RTM_DELROUTE"
  83. }
  84. var rmsg rtnetlink.RouteMessage
  85. if err := rmsg.UnmarshalBinary(msg.Data); err != nil {
  86. c.logf("%s: failed to parse: %v", typeStr, err)
  87. return unspecifiedMessage{}, nil
  88. }
  89. src := netaddrIPPrefix(rmsg.Attributes.Src, rmsg.SrcLength)
  90. dst := netaddrIPPrefix(rmsg.Attributes.Dst, rmsg.DstLength)
  91. gw := netaddrIP(rmsg.Attributes.Gateway)
  92. if rmsg.Table == tsTable && dst.IsSingleIP() {
  93. // Don't log. Spammy and normal to see a bunch of these on start-up,
  94. // which we make ourselves.
  95. } else {
  96. c.logf("%s: src=%v, dst=%v, gw=%v, outif=%v, table=%v", typeStr,
  97. condNetAddrPrefix(src), condNetAddrPrefix(dst), condNetAddrIP(gw),
  98. rmsg.Attributes.OutIface, rmsg.Attributes.Table)
  99. }
  100. if msg.Header.Type == unix.RTM_DELROUTE {
  101. // Just logging it for now.
  102. // (Debugging https://github.com/tailscale/tailscale/issues/643)
  103. return unspecifiedMessage{}, nil
  104. }
  105. return &newRouteMessage{
  106. Table: rmsg.Table,
  107. Src: src,
  108. Dst: dst,
  109. Gateway: gw,
  110. }, nil
  111. case unix.RTM_NEWRULE:
  112. // Probably ourselves adding it.
  113. return ignoreMessage{}, nil
  114. case unix.RTM_DELRULE:
  115. // For https://github.com/tailscale/tailscale/issues/1591 where
  116. // systemd-networkd deletes our rules.
  117. var rmsg rtnetlink.RouteMessage
  118. err := rmsg.UnmarshalBinary(msg.Data)
  119. if err != nil {
  120. c.logf("ip rule deleted; failed to parse netlink message: %v", err)
  121. } else {
  122. c.logf("ip rule deleted: %+v", rmsg)
  123. // On `ip -4 rule del pref 5210 table main`, logs:
  124. // monitor: ip rule deleted: {Family:2 DstLength:0 SrcLength:0 Tos:0 Table:254 Protocol:0 Scope:0 Type:1 Flags:0 Attributes:{Dst:<nil> Src:<nil> Gateway:<nil> OutIface:0 Priority:5210 Table:254 Mark:4294967295 Expires:<nil> Metrics:<nil> Multipath:[]}}
  125. }
  126. return ipRuleDeletedMessage{
  127. table: rmsg.Table,
  128. priority: rmsg.Attributes.Priority,
  129. }, nil
  130. default:
  131. c.logf("unhandled netlink msg type %+v, %q", msg.Header, msg.Data)
  132. return unspecifiedMessage{}, nil
  133. }
  134. }
  135. func netaddrIP(std net.IP) netaddr.IP {
  136. ip, _ := netaddr.FromStdIP(std)
  137. return ip
  138. }
  139. func netaddrIPPrefix(std net.IP, bits uint8) netaddr.IPPrefix {
  140. ip, _ := netaddr.FromStdIP(std)
  141. return netaddr.IPPrefixFrom(ip, bits)
  142. }
  143. func condNetAddrPrefix(ipp netaddr.IPPrefix) string {
  144. if ipp.IP().IsZero() {
  145. return ""
  146. }
  147. return ipp.String()
  148. }
  149. func condNetAddrIP(ip netaddr.IP) string {
  150. if ip.IsZero() {
  151. return ""
  152. }
  153. return ip.String()
  154. }
  155. // newRouteMessage is a message for a new route being added.
  156. type newRouteMessage struct {
  157. Src, Dst netaddr.IPPrefix
  158. Gateway netaddr.IP
  159. Table uint8
  160. }
  161. const tsTable = 52
  162. func (m *newRouteMessage) ignore() bool {
  163. return m.Table == tsTable || tsaddr.IsTailscaleIP(m.Dst.IP())
  164. }
  165. // newAddrMessage is a message for a new address being added.
  166. type newAddrMessage struct {
  167. Delete bool
  168. Addr netaddr.IP
  169. Label string // netlink Label attribute (e.g. "tailscale0")
  170. }
  171. func (m *newAddrMessage) ignore() bool {
  172. return tsaddr.IsTailscaleIP(m.Addr)
  173. }
  174. type ignoreMessage struct{}
  175. func (ignoreMessage) ignore() bool { return true }