2
0

monitor_linux.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 msg.Header.Type == unix.RTM_NEWROUTE &&
  93. (rmsg.Attributes.Table == 255 || rmsg.Attributes.Table == 254) &&
  94. (dst.IP().IsMulticast() || dst.IP().IsLinkLocalUnicast()) {
  95. // Normal Linux route changes on new interface coming up; don't log or react.
  96. return ignoreMessage{}, nil
  97. }
  98. if rmsg.Table == tsTable && dst.IsSingleIP() {
  99. // Don't log. Spammy and normal to see a bunch of these on start-up,
  100. // which we make ourselves.
  101. } else if tsaddr.IsTailscaleIP(dst.IP()) {
  102. // Verbose only.
  103. c.logf("%s: [v1] src=%v, dst=%v, gw=%v, outif=%v, table=%v", typeStr,
  104. condNetAddrPrefix(src), condNetAddrPrefix(dst), condNetAddrIP(gw),
  105. rmsg.Attributes.OutIface, rmsg.Attributes.Table)
  106. } else {
  107. c.logf("%s: src=%v, dst=%v, gw=%v, outif=%v, table=%v", typeStr,
  108. condNetAddrPrefix(src), condNetAddrPrefix(dst), condNetAddrIP(gw),
  109. rmsg.Attributes.OutIface, rmsg.Attributes.Table)
  110. }
  111. if msg.Header.Type == unix.RTM_DELROUTE {
  112. // Just logging it for now.
  113. // (Debugging https://github.com/tailscale/tailscale/issues/643)
  114. return unspecifiedMessage{}, nil
  115. }
  116. return &newRouteMessage{
  117. Table: rmsg.Table,
  118. Src: src,
  119. Dst: dst,
  120. Gateway: gw,
  121. }, nil
  122. case unix.RTM_NEWRULE:
  123. // Probably ourselves adding it.
  124. return ignoreMessage{}, nil
  125. case unix.RTM_DELRULE:
  126. // For https://github.com/tailscale/tailscale/issues/1591 where
  127. // systemd-networkd deletes our rules.
  128. var rmsg rtnetlink.RouteMessage
  129. err := rmsg.UnmarshalBinary(msg.Data)
  130. if err != nil {
  131. c.logf("ip rule deleted; failed to parse netlink message: %v", err)
  132. } else {
  133. c.logf("ip rule deleted: %+v", rmsg)
  134. // On `ip -4 rule del pref 5210 table main`, logs:
  135. // 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:[]}}
  136. }
  137. return ipRuleDeletedMessage{
  138. table: rmsg.Table,
  139. priority: rmsg.Attributes.Priority,
  140. }, nil
  141. default:
  142. c.logf("unhandled netlink msg type %+v, %q", msg.Header, msg.Data)
  143. return unspecifiedMessage{}, nil
  144. }
  145. }
  146. func netaddrIP(std net.IP) netaddr.IP {
  147. ip, _ := netaddr.FromStdIP(std)
  148. return ip
  149. }
  150. func netaddrIPPrefix(std net.IP, bits uint8) netaddr.IPPrefix {
  151. ip, _ := netaddr.FromStdIP(std)
  152. return netaddr.IPPrefixFrom(ip, bits)
  153. }
  154. func condNetAddrPrefix(ipp netaddr.IPPrefix) string {
  155. if ipp.IP().IsZero() {
  156. return ""
  157. }
  158. return ipp.String()
  159. }
  160. func condNetAddrIP(ip netaddr.IP) string {
  161. if ip.IsZero() {
  162. return ""
  163. }
  164. return ip.String()
  165. }
  166. // newRouteMessage is a message for a new route being added.
  167. type newRouteMessage struct {
  168. Src, Dst netaddr.IPPrefix
  169. Gateway netaddr.IP
  170. Table uint8
  171. }
  172. const tsTable = 52
  173. func (m *newRouteMessage) ignore() bool {
  174. return m.Table == tsTable || tsaddr.IsTailscaleIP(m.Dst.IP())
  175. }
  176. // newAddrMessage is a message for a new address being added.
  177. type newAddrMessage struct {
  178. Delete bool
  179. Addr netaddr.IP
  180. Label string // netlink Label attribute (e.g. "tailscale0")
  181. }
  182. func (m *newAddrMessage) ignore() bool {
  183. return tsaddr.IsTailscaleIP(m.Addr)
  184. }
  185. type ignoreMessage struct{}
  186. func (ignoreMessage) ignore() bool { return true }