netstat_windows.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package netstat
  4. import (
  5. "errors"
  6. "fmt"
  7. "math/bits"
  8. "net/netip"
  9. "unsafe"
  10. "golang.org/x/sys/cpu"
  11. "golang.org/x/sys/windows"
  12. "tailscale.com/net/netaddr"
  13. )
  14. // OSMetadata includes any additional OS-specific information that may be
  15. // obtained during the retrieval of a given Entry.
  16. type OSMetadata interface {
  17. // GetModule returns the entry's module name.
  18. //
  19. // It returns ("", nil) if no entry is found. As of 2023-01-27, any returned
  20. // error is silently discarded by its sole caller in portlist_windows.go and
  21. // treated equivalently as returning ("", nil), but this may change in the
  22. // future. An error should only be returned in casees that are worthy of
  23. // being logged at least.
  24. GetModule() (string, error)
  25. }
  26. // See https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getextendedtcptable
  27. // TCP_TABLE_OWNER_MODULE_ALL means to include the PID and module. The table type
  28. // we get back from Windows depends on AF_INET vs AF_INET6:
  29. // MIB_TCPTABLE_OWNER_MODULE for v4 or MIB_TCP6TABLE_OWNER_MODULE for v6.
  30. const tcpTableOwnerModuleAll = 8
  31. // TCPIP_OWNER_MODULE_BASIC_INFO means to request "basic information" about the
  32. // owner module.
  33. const tcpipOwnerModuleBasicInfo = 0
  34. var (
  35. iphlpapi = windows.NewLazySystemDLL("iphlpapi.dll")
  36. getTCPTable = iphlpapi.NewProc("GetExtendedTcpTable")
  37. getOwnerModuleFromTcpEntry = iphlpapi.NewProc("GetOwnerModuleFromTcpEntry")
  38. getOwnerModuleFromTcp6Entry = iphlpapi.NewProc("GetOwnerModuleFromTcp6Entry")
  39. // TODO: GetExtendedUdpTable also? if/when needed.
  40. )
  41. // See https://web.archive.org/web/20221219211913/https://learn.microsoft.com/en-us/windows/win32/api/tcpmib/ns-tcpmib-mib_tcprow_owner_module
  42. type _MIB_TCPROW_OWNER_MODULE struct {
  43. state uint32
  44. localAddr uint32
  45. localPort uint32
  46. remoteAddr uint32
  47. remotePort uint32
  48. pid uint32
  49. createTimestamp int64
  50. owningModuleInfo [16]uint64
  51. }
  52. func (row *_MIB_TCPROW_OWNER_MODULE) asEntry() Entry {
  53. return Entry{
  54. Local: ipport4(row.localAddr, port(&row.localPort)),
  55. Remote: ipport4(row.remoteAddr, port(&row.remotePort)),
  56. Pid: int(row.pid),
  57. State: state(row.state),
  58. OSMetadata: row,
  59. }
  60. }
  61. type _MIB_TCPTABLE_OWNER_MODULE struct {
  62. numEntries uint32
  63. table _MIB_TCPROW_OWNER_MODULE
  64. }
  65. func (m *_MIB_TCPTABLE_OWNER_MODULE) getRows() []_MIB_TCPROW_OWNER_MODULE {
  66. return unsafe.Slice(&m.table, m.numEntries)
  67. }
  68. // See https://web.archive.org/web/20221219212442/https://learn.microsoft.com/en-us/windows/win32/api/tcpmib/ns-tcpmib-mib_tcp6row_owner_module
  69. type _MIB_TCP6ROW_OWNER_MODULE struct {
  70. localAddr [16]byte
  71. localScope uint32
  72. localPort uint32
  73. remoteAddr [16]byte
  74. remoteScope uint32
  75. remotePort uint32
  76. state uint32
  77. pid uint32
  78. createTimestamp int64
  79. owningModuleInfo [16]uint64
  80. }
  81. func (row *_MIB_TCP6ROW_OWNER_MODULE) asEntry() Entry {
  82. return Entry{
  83. Local: ipport6(row.localAddr, row.localScope, port(&row.localPort)),
  84. Remote: ipport6(row.remoteAddr, row.remoteScope, port(&row.remotePort)),
  85. Pid: int(row.pid),
  86. State: state(row.state),
  87. OSMetadata: row,
  88. }
  89. }
  90. type _MIB_TCP6TABLE_OWNER_MODULE struct {
  91. numEntries uint32
  92. table _MIB_TCP6ROW_OWNER_MODULE
  93. }
  94. func (m *_MIB_TCP6TABLE_OWNER_MODULE) getRows() []_MIB_TCP6ROW_OWNER_MODULE {
  95. return unsafe.Slice(&m.table, m.numEntries)
  96. }
  97. // See https://web.archive.org/web/20221219213143/https://learn.microsoft.com/en-us/windows/win32/api/iprtrmib/ns-iprtrmib-tcpip_owner_module_basic_info
  98. type _TCPIP_OWNER_MODULE_BASIC_INFO struct {
  99. moduleName *uint16
  100. modulePath *uint16
  101. }
  102. func get() (*Table, error) {
  103. t := new(Table)
  104. if err := t.addEntries(windows.AF_INET); err != nil {
  105. return nil, fmt.Errorf("failed to get IPv4 entries: %w", err)
  106. }
  107. if err := t.addEntries(windows.AF_INET6); err != nil {
  108. return nil, fmt.Errorf("failed to get IPv6 entries: %w", err)
  109. }
  110. return t, nil
  111. }
  112. func (t *Table) addEntries(fam int) error {
  113. var size uint32
  114. var addr unsafe.Pointer
  115. var buf []byte
  116. for {
  117. err, _, _ := getTCPTable.Call(
  118. uintptr(addr),
  119. uintptr(unsafe.Pointer(&size)),
  120. 1, // sorted
  121. uintptr(fam),
  122. tcpTableOwnerModuleAll,
  123. 0, // reserved; "must be zero"
  124. )
  125. if err == 0 {
  126. break
  127. }
  128. if err == uintptr(windows.ERROR_INSUFFICIENT_BUFFER) {
  129. const maxSize = 10 << 20
  130. if size > maxSize || size < 4 {
  131. return fmt.Errorf("unreasonable kernel-reported size %d", size)
  132. }
  133. buf = make([]byte, size)
  134. addr = unsafe.Pointer(&buf[0])
  135. continue
  136. }
  137. return windows.Errno(err)
  138. }
  139. if len(buf) < int(size) {
  140. return errors.New("unexpected size growth from system call")
  141. }
  142. buf = buf[:size]
  143. switch fam {
  144. case windows.AF_INET:
  145. info := (*_MIB_TCPTABLE_OWNER_MODULE)(unsafe.Pointer(&buf[0]))
  146. rows := info.getRows()
  147. for _, row := range rows {
  148. t.Entries = append(t.Entries, row.asEntry())
  149. }
  150. case windows.AF_INET6:
  151. info := (*_MIB_TCP6TABLE_OWNER_MODULE)(unsafe.Pointer(&buf[0]))
  152. rows := info.getRows()
  153. for _, row := range rows {
  154. t.Entries = append(t.Entries, row.asEntry())
  155. }
  156. }
  157. return nil
  158. }
  159. var states = []string{
  160. "",
  161. "CLOSED",
  162. "LISTEN",
  163. "SYN-SENT",
  164. "SYN-RECEIVED",
  165. "ESTABLISHED",
  166. "FIN-WAIT-1",
  167. "FIN-WAIT-2",
  168. "CLOSE-WAIT",
  169. "CLOSING",
  170. "LAST-ACK",
  171. "DELETE-TCB",
  172. }
  173. func state(v uint32) string {
  174. if v < uint32(len(states)) {
  175. return states[v]
  176. }
  177. return fmt.Sprintf("unknown-state-%d", v)
  178. }
  179. func ipport4(addr uint32, port uint16) netip.AddrPort {
  180. if !cpu.IsBigEndian {
  181. addr = bits.ReverseBytes32(addr)
  182. }
  183. return netip.AddrPortFrom(
  184. netaddr.IPv4(byte(addr>>24), byte(addr>>16), byte(addr>>8), byte(addr)),
  185. port)
  186. }
  187. func ipport6(addr [16]byte, scope uint32, port uint16) netip.AddrPort {
  188. ip := netip.AddrFrom16(addr).Unmap()
  189. if scope != 0 {
  190. // TODO: something better here?
  191. ip = ip.WithZone(fmt.Sprint(scope))
  192. }
  193. return netip.AddrPortFrom(ip, port)
  194. }
  195. func port(v *uint32) uint16 {
  196. if !cpu.IsBigEndian {
  197. return uint16(bits.ReverseBytes32(*v) >> 16)
  198. }
  199. return uint16(*v >> 16)
  200. }
  201. type moduleInfoConstraint interface {
  202. _MIB_TCPROW_OWNER_MODULE | _MIB_TCP6ROW_OWNER_MODULE
  203. }
  204. // moduleInfo implements OSMetadata.GetModule. It calls
  205. // getOwnerModuleFromTcpEntry or getOwnerModuleFromTcp6Entry.
  206. //
  207. // See
  208. // https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getownermodulefromtcpentry
  209. //
  210. // It may return "", nil indicating a successful call but with empty data.
  211. func moduleInfo[entryType moduleInfoConstraint](entry *entryType, proc *windows.LazyProc) (string, error) {
  212. var buf []byte
  213. var desiredLen uint32
  214. var addr unsafe.Pointer
  215. for {
  216. e, _, _ := proc.Call(
  217. uintptr(unsafe.Pointer(entry)),
  218. uintptr(tcpipOwnerModuleBasicInfo),
  219. uintptr(addr),
  220. uintptr(unsafe.Pointer(&desiredLen)),
  221. )
  222. err := windows.Errno(e)
  223. if err == windows.ERROR_SUCCESS {
  224. break
  225. }
  226. if err == windows.ERROR_NOT_FOUND {
  227. return "", nil
  228. }
  229. if err != windows.ERROR_INSUFFICIENT_BUFFER {
  230. return "", err
  231. }
  232. if desiredLen > 1<<20 {
  233. // Sanity check before allocating too much.
  234. return "", nil
  235. }
  236. buf = make([]byte, desiredLen)
  237. addr = unsafe.Pointer(&buf[0])
  238. }
  239. if addr == nil {
  240. // GetOwnerModuleFromTcp*Entry can apparently return ERROR_SUCCESS
  241. // (NO_ERROR) on the first call without the usual first
  242. // ERROR_INSUFFICIENT_BUFFER result. Windows said success, so interpret
  243. // that was sucessfully not having data.
  244. return "", nil
  245. }
  246. basicInfo := (*_TCPIP_OWNER_MODULE_BASIC_INFO)(addr)
  247. return windows.UTF16PtrToString(basicInfo.moduleName), nil
  248. }
  249. // GetModule implements OSMetadata.
  250. func (m *_MIB_TCPROW_OWNER_MODULE) GetModule() (string, error) {
  251. return moduleInfo(m, getOwnerModuleFromTcpEntry)
  252. }
  253. // GetModule implements OSMetadata.
  254. func (m *_MIB_TCP6ROW_OWNER_MODULE) GetModule() (string, error) {
  255. return moduleInfo(m, getOwnerModuleFromTcp6Entry)
  256. }