summaryrefslogtreecommitdiffhomepage
path: root/net/netstat/netstat_windows.go
blob: 4b3edbdf8134bb2c23b95be53c07bd82f7ab03ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package netstat

import (
	"errors"
	"fmt"
	"math/bits"
	"net/netip"
	"unsafe"

	"golang.org/x/sys/cpu"
	"golang.org/x/sys/windows"
	"tailscale.com/net/netaddr"
)

// OSMetadata includes any additional OS-specific information that may be
// obtained during the retrieval of a given Entry.
type OSMetadata interface {
	// GetModule returns the entry's module name.
	//
	// It returns ("", nil) if no entry is found. As of 2023-01-27, any returned
	// error is silently discarded by its sole caller in portlist_windows.go and
	// treated equivalently as returning ("", nil), but this may change in the
	// future. An error should only be returned in casees that are worthy of
	// being logged at least.
	GetModule() (string, error)
}

// See https://docs.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getextendedtcptable

// TCP_TABLE_OWNER_MODULE_ALL means to include the PID and module. The table type
// we get back from Windows depends on AF_INET vs AF_INET6:
// MIB_TCPTABLE_OWNER_MODULE for v4 or MIB_TCP6TABLE_OWNER_MODULE for v6.
const tcpTableOwnerModuleAll = 8

// TCPIP_OWNER_MODULE_BASIC_INFO means to request "basic information" about the
// owner module.
const tcpipOwnerModuleBasicInfo = 0

var (
	iphlpapi                    = windows.NewLazySystemDLL("iphlpapi.dll")
	getTCPTable                 = iphlpapi.NewProc("GetExtendedTcpTable")
	getOwnerModuleFromTcpEntry  = iphlpapi.NewProc("GetOwnerModuleFromTcpEntry")
	getOwnerModuleFromTcp6Entry = iphlpapi.NewProc("GetOwnerModuleFromTcp6Entry")
	// TODO: GetExtendedUdpTable also? if/when needed.
)

// See https://web.archive.org/web/20221219211913/https://learn.microsoft.com/en-us/windows/win32/api/tcpmib/ns-tcpmib-mib_tcprow_owner_module
type _MIB_TCPROW_OWNER_MODULE struct {
	state            uint32
	localAddr        uint32
	localPort        uint32
	remoteAddr       uint32
	remotePort       uint32
	pid              uint32
	createTimestamp  int64
	owningModuleInfo [16]uint64
}

func (row *_MIB_TCPROW_OWNER_MODULE) asEntry() Entry {
	return Entry{
		Local:      ipport4(row.localAddr, port(&row.localPort)),
		Remote:     ipport4(row.remoteAddr, port(&row.remotePort)),
		Pid:        int(row.pid),
		State:      state(row.state),
		OSMetadata: row,
	}
}

type _MIB_TCPTABLE_OWNER_MODULE struct {
	numEntries uint32
	table      _MIB_TCPROW_OWNER_MODULE
}

func (m *_MIB_TCPTABLE_OWNER_MODULE) getRows() []_MIB_TCPROW_OWNER_MODULE {
	return unsafe.Slice(&m.table, m.numEntries)
}

// See https://web.archive.org/web/20221219212442/https://learn.microsoft.com/en-us/windows/win32/api/tcpmib/ns-tcpmib-mib_tcp6row_owner_module
type _MIB_TCP6ROW_OWNER_MODULE struct {
	localAddr        [16]byte
	localScope       uint32
	localPort        uint32
	remoteAddr       [16]byte
	remoteScope      uint32
	remotePort       uint32
	state            uint32
	pid              uint32
	createTimestamp  int64
	owningModuleInfo [16]uint64
}

func (row *_MIB_TCP6ROW_OWNER_MODULE) asEntry() Entry {
	return Entry{
		Local:      ipport6(row.localAddr, row.localScope, port(&row.localPort)),
		Remote:     ipport6(row.remoteAddr, row.remoteScope, port(&row.remotePort)),
		Pid:        int(row.pid),
		State:      state(row.state),
		OSMetadata: row,
	}
}

type _MIB_TCP6TABLE_OWNER_MODULE struct {
	numEntries uint32
	table      _MIB_TCP6ROW_OWNER_MODULE
}

func (m *_MIB_TCP6TABLE_OWNER_MODULE) getRows() []_MIB_TCP6ROW_OWNER_MODULE {
	return unsafe.Slice(&m.table, m.numEntries)
}

// See https://web.archive.org/web/20221219213143/https://learn.microsoft.com/en-us/windows/win32/api/iprtrmib/ns-iprtrmib-tcpip_owner_module_basic_info
type _TCPIP_OWNER_MODULE_BASIC_INFO struct {
	moduleName *uint16
	modulePath *uint16
}

func get() (*Table, error) {
	t := new(Table)
	if err := t.addEntries(windows.AF_INET); err != nil {
		return nil, fmt.Errorf("failed to get IPv4 entries: %w", err)
	}
	if err := t.addEntries(windows.AF_INET6); err != nil {
		return nil, fmt.Errorf("failed to get IPv6 entries: %w", err)
	}
	return t, nil
}

func (t *Table) addEntries(fam int) error {
	var size uint32
	var addr unsafe.Pointer
	var buf []byte
	for {
		err, _, _ := getTCPTable.Call(
			uintptr(addr),
			uintptr(unsafe.Pointer(&size)),
			1, // sorted
			uintptr(fam),
			tcpTableOwnerModuleAll,
			0, // reserved; "must be zero"
		)
		if err == 0 {
			break
		}
		if err == uintptr(windows.ERROR_INSUFFICIENT_BUFFER) {
			const maxSize = 10 << 20
			if size > maxSize || size < 4 {
				return fmt.Errorf("unreasonable kernel-reported size %d", size)
			}
			buf = make([]byte, size)
			addr = unsafe.Pointer(&buf[0])
			continue
		}
		return windows.Errno(err)
	}
	if len(buf) < int(size) {
		return errors.New("unexpected size growth from system call")
	}
	buf = buf[:size]

	switch fam {
	case windows.AF_INET:
		info := (*_MIB_TCPTABLE_OWNER_MODULE)(unsafe.Pointer(&buf[0]))
		rows := info.getRows()
		for _, row := range rows {
			t.Entries = append(t.Entries, row.asEntry())
		}
	case windows.AF_INET6:
		info := (*_MIB_TCP6TABLE_OWNER_MODULE)(unsafe.Pointer(&buf[0]))
		rows := info.getRows()
		for _, row := range rows {
			t.Entries = append(t.Entries, row.asEntry())
		}
	}

	return nil
}

var states = []string{
	"",
	"CLOSED",
	"LISTEN",
	"SYN-SENT",
	"SYN-RECEIVED",
	"ESTABLISHED",
	"FIN-WAIT-1",
	"FIN-WAIT-2",
	"CLOSE-WAIT",
	"CLOSING",
	"LAST-ACK",
	"DELETE-TCB",
}

func state(v uint32) string {
	if v < uint32(len(states)) {
		return states[v]
	}
	return fmt.Sprintf("unknown-state-%d", v)
}

func ipport4(addr uint32, port uint16) netip.AddrPort {
	if !cpu.IsBigEndian {
		addr = bits.ReverseBytes32(addr)
	}
	return netip.AddrPortFrom(
		netaddr.IPv4(byte(addr>>24), byte(addr>>16), byte(addr>>8), byte(addr)),
		port)
}

func ipport6(addr [16]byte, scope uint32, port uint16) netip.AddrPort {
	ip := netip.AddrFrom16(addr).Unmap()
	if scope != 0 {
		// TODO: something better here?
		ip = ip.WithZone(fmt.Sprint(scope))
	}
	return netip.AddrPortFrom(ip, port)
}

func port(v *uint32) uint16 {
	if !cpu.IsBigEndian {
		return uint16(bits.ReverseBytes32(*v) >> 16)
	}
	return uint16(*v >> 16)
}

type moduleInfoConstraint interface {
	_MIB_TCPROW_OWNER_MODULE | _MIB_TCP6ROW_OWNER_MODULE
}

// moduleInfo implements OSMetadata.GetModule. It calls
// getOwnerModuleFromTcpEntry or getOwnerModuleFromTcp6Entry.
//
// See
// https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getownermodulefromtcpentry
//
// It may return "", nil indicating a successful call but with empty data.
func moduleInfo[entryType moduleInfoConstraint](entry *entryType, proc *windows.LazyProc) (string, error) {
	var buf []byte
	var desiredLen uint32
	var addr unsafe.Pointer

	for {
		e, _, _ := proc.Call(
			uintptr(unsafe.Pointer(entry)),
			uintptr(tcpipOwnerModuleBasicInfo),
			uintptr(addr),
			uintptr(unsafe.Pointer(&desiredLen)),
		)
		err := windows.Errno(e)
		if err == windows.ERROR_SUCCESS {
			break
		}
		if err == windows.ERROR_NOT_FOUND {
			return "", nil
		}
		if err != windows.ERROR_INSUFFICIENT_BUFFER {
			return "", err
		}
		if desiredLen > 1<<20 {
			// Sanity check before allocating too much.
			return "", nil
		}
		buf = make([]byte, desiredLen)
		addr = unsafe.Pointer(&buf[0])
	}
	if addr == nil {
		// GetOwnerModuleFromTcp*Entry can apparently return ERROR_SUCCESS
		// (NO_ERROR) on the first call without the usual first
		// ERROR_INSUFFICIENT_BUFFER result. Windows said success, so interpret
		// that was sucessfully not having data.
		return "", nil
	}
	basicInfo := (*_TCPIP_OWNER_MODULE_BASIC_INFO)(addr)
	return windows.UTF16PtrToString(basicInfo.moduleName), nil
}

// GetModule implements OSMetadata.
func (m *_MIB_TCPROW_OWNER_MODULE) GetModule() (string, error) {
	return moduleInfo(m, getOwnerModuleFromTcpEntry)
}

// GetModule implements OSMetadata.
func (m *_MIB_TCP6ROW_OWNER_MODULE) GetModule() (string, error) {
	return moduleInfo(m, getOwnerModuleFromTcp6Entry)
}