-
Notifications
You must be signed in to change notification settings - Fork 0
/
netstat_windows.go
565 lines (506 loc) · 13.5 KB
/
netstat_windows.go
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// +build amd64
package netstat
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net"
"reflect"
"syscall"
"unsafe"
)
const (
errInsuffBuff = syscall.Errno(122)
Th32csSnapProcess = uint32(0x00000002)
InvalidHandleValue = ^uintptr(0)
MaxPath = 260
)
var (
errNoMoreFiles = errors.New("no more files have been found")
modiphlpapi = syscall.NewLazyDLL("Iphlpapi.dll")
modkernel32 = syscall.NewLazyDLL("Kernel32.dll")
procGetTCPTable2 = modiphlpapi.NewProc("GetTcpTable2")
procGetTCP6Table2 = modiphlpapi.NewProc("GetTcp6Table2")
procGetExtendedUDPTable = modiphlpapi.NewProc("GetExtendedUdpTable")
procCreateSnapshot = modkernel32.NewProc("CreateToolhelp32Snapshot")
procProcess32First = modkernel32.NewProc("Process32First")
procProcess32Next = modkernel32.NewProc("Process32Next")
)
// Socket states
const (
Close SkState = 0x01
Listen = 0x02
SynSent = 0x03
SynRecv = 0x04
Established = 0x05
FinWait1 = 0x06
FinWait2 = 0x07
CloseWait = 0x08
Closing = 0x09
LastAck = 0x0a
TimeWait = 0x0b
DeleteTcb = 0x0c
)
var skStates = [...]string{
"UNKNOWN",
"", // CLOSE
"LISTEN",
"SYN_SENT",
"SYN_RECV",
"ESTABLISHED",
"FIN_WAIT1",
"FIN_WAIT2",
"CLOSE_WAIT",
"CLOSING",
"LAST_ACK",
"TIME_WAIT",
"DELETE_TCB",
}
func memToIPv4(p unsafe.Pointer) net.IP {
a := (*[net.IPv4len]byte)(p)
ip := make(net.IP, net.IPv4len)
copy(ip, a[:])
return ip
}
func memToIPv6(p unsafe.Pointer) net.IP {
a := (*[net.IPv6len]byte)(p)
ip := make(net.IP, net.IPv6len)
copy(ip, a[:])
return ip
}
func memtohs(n unsafe.Pointer) uint16 {
return binary.BigEndian.Uint16((*[2]byte)(n)[:])
}
type WinSock struct {
Addr uint32
Port uint32
}
func (w *WinSock) Sock() *SockAddr {
ip := memToIPv4(unsafe.Pointer(&w.Addr))
port := memtohs(unsafe.Pointer(&w.Port))
return &SockAddr{IP: ip, Port: port}
}
type WinSock6 struct {
Addr [net.IPv6len]byte
ScopeID uint32
Port uint32
}
func (w *WinSock6) Sock() *SockAddr {
ip := memToIPv6(unsafe.Pointer(&w.Addr[0]))
port := memtohs(unsafe.Pointer(&w.Port))
return &SockAddr{IP: ip, Port: port}
}
type MibTCPRow2 struct {
State uint32
LocalAddr WinSock
RemoteAddr WinSock
WinPid
OffloadState uint32
}
type WinPid uint32
func (pid WinPid) Process(snp ProcessSnapshot) *Process {
if pid < 1 {
return nil
}
return &Process{
Pid: int(pid),
Name: snp.ProcPIDToName(uint32(pid)),
}
}
func (m *MibTCPRow2) LocalSock() *SockAddr { return m.LocalAddr.Sock() }
func (m *MibTCPRow2) RemoteSock() *SockAddr { return m.RemoteAddr.Sock() }
func (m *MibTCPRow2) SockState() SkState { return SkState(m.State) }
type MibTCPTable2 struct {
NumEntries uint32
Table [1]MibTCPRow2
}
func (t *MibTCPTable2) Rows() []MibTCPRow2 {
var s []MibTCPRow2
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(unsafe.Pointer(&t.Table[0]))
hdr.Len = int(t.NumEntries)
hdr.Cap = int(t.NumEntries)
return s
}
// MibTCP6Row2 structure contains information that describes an IPv6 TCP
// connection.
type MibTCP6Row2 struct {
LocalAddr WinSock6
RemoteAddr WinSock6
State uint32
WinPid
OffloadState uint32
}
func (m *MibTCP6Row2) LocalSock() *SockAddr { return m.LocalAddr.Sock() }
func (m *MibTCP6Row2) RemoteSock() *SockAddr { return m.RemoteAddr.Sock() }
func (m *MibTCP6Row2) SockState() SkState { return SkState(m.State) }
// MibTCP6Table2 structure contains a table of IPv6 TCP connections on the
// local computer.
type MibTCP6Table2 struct {
NumEntries uint32
Table [1]MibTCP6Row2
}
func (t *MibTCP6Table2) Rows() []MibTCP6Row2 {
var s []MibTCP6Row2
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(unsafe.Pointer(&t.Table[0]))
hdr.Len = int(t.NumEntries)
hdr.Cap = int(t.NumEntries)
return s
}
// MibUDPRowOwnerPID structure contains an entry from the User Datagram
// Protocol (UDP) listener table for IPv4 on the local computer. The entry also
// includes the process ID (PID) that issued the call to the bind function for
// the UDP endpoint
type MibUDPRowOwnerPID struct {
WinSock
WinPid
}
func (m *MibUDPRowOwnerPID) LocalSock() *SockAddr { return m.Sock() }
func (m *MibUDPRowOwnerPID) RemoteSock() *SockAddr { return &SockAddr{net.IPv4zero, 0} }
func (m *MibUDPRowOwnerPID) SockState() SkState { return Close }
// MibUDPTableOwnerPID structure contains the User Datagram Protocol (UDP)
// listener table for IPv4 on the local computer. The table also includes the
// process ID (PID) that issued the call to the bind function for each UDP
// endpoint.
type MibUDPTableOwnerPID struct {
NumEntries uint32
Table [1]MibUDPRowOwnerPID
}
func (t *MibUDPTableOwnerPID) Rows() []MibUDPRowOwnerPID {
var s []MibUDPRowOwnerPID
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(unsafe.Pointer(&t.Table[0]))
hdr.Len = int(t.NumEntries)
hdr.Cap = int(t.NumEntries)
return s
}
// MibUDP6RowOwnerPID serves the same purpose as MibUDPRowOwnerPID, except that
// the information in this case is for IPv6.
type MibUDP6RowOwnerPID struct {
WinSock6
WinPid
}
func (m *MibUDP6RowOwnerPID) LocalSock() *SockAddr { return m.Sock() }
func (m *MibUDP6RowOwnerPID) RemoteSock() *SockAddr { return &SockAddr{net.IPv4zero, 0} }
func (m *MibUDP6RowOwnerPID) SockState() SkState { return Close }
// MibUDP6TableOwnerPID serves the same purpose as MibUDPTableOwnerPID for IPv6
type MibUDP6TableOwnerPID struct {
NumEntries uint32
Table [1]MibUDP6RowOwnerPID
}
func (t *MibUDP6TableOwnerPID) Rows() []MibUDP6RowOwnerPID {
var s []MibUDP6RowOwnerPID
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
hdr.Data = uintptr(unsafe.Pointer(&t.Table[0]))
hdr.Len = int(t.NumEntries)
hdr.Cap = int(t.NumEntries)
return s
}
// Processentry32 describes an entry from a list of the processes residing in
// the system address space when a snapshot was taken
type Processentry32 struct {
Size uint32
CntUsage uint32
Th32ProcessID uint32
Th32DefaultHeapID uintptr
Th32ModuleID uint32
CntThreads uint32
Th32ParentProcessID uint32
PriClassBase int32
Flags uint32
ExeFile [MaxPath]byte
}
func rawGetTCPTable2(proc uintptr, tab unsafe.Pointer, size *uint32, order bool) error {
var oint uintptr
if order {
oint = 1
}
r1, _, callErr := syscall.Syscall(
proc,
uintptr(3),
uintptr(tab),
uintptr(unsafe.Pointer(size)),
oint)
if callErr != 0 {
return callErr
}
if r1 != 0 {
return syscall.Errno(r1)
}
return nil
}
func getTCPTable2(proc uintptr, order bool) ([]byte, error) {
var (
size uint32
buf []byte
)
// determine size
err := rawGetTCPTable2(proc, unsafe.Pointer(nil), &size, false)
if err != nil && err != errInsuffBuff {
return nil, err
}
buf = make([]byte, size)
table := unsafe.Pointer(&buf[0])
err = rawGetTCPTable2(proc, table, &size, true)
if err != nil {
return nil, err
}
return buf, nil
}
// GetTCPTable2 function retrieves the IPv4 TCP connection table
func GetTCPTable2(order bool) (*MibTCPTable2, error) {
b, err := getTCPTable2(procGetTCPTable2.Addr(), true)
if err != nil {
return nil, err
}
return (*MibTCPTable2)(unsafe.Pointer(&b[0])), nil
}
// GetTCP6Table2 function retrieves the IPv6 TCP connection table
func GetTCP6Table2(order bool) (*MibTCP6Table2, error) {
b, err := getTCPTable2(procGetTCP6Table2.Addr(), true)
if err != nil {
return nil, err
}
return (*MibTCP6Table2)(unsafe.Pointer(&b[0])), nil
}
// The UDPTableClass enumeration defines the set of values used to indicate
// the type of table returned by calls to GetExtendedUDPTable
type UDPTableClass uint
// Possible table class values
const (
UDPTableBasic UDPTableClass = iota
UDPTableOwnerPID
UDPTableOwnerModule
)
func getExtendedUDPTable(table unsafe.Pointer, size *uint32, order bool, af uint32, cl UDPTableClass) error {
var oint uintptr
if order {
oint = 1
}
r1, _, callErr := syscall.Syscall6(
procGetExtendedUDPTable.Addr(),
uintptr(6),
uintptr(table),
uintptr(unsafe.Pointer(size)),
oint,
uintptr(af),
uintptr(cl),
uintptr(0))
if callErr != 0 {
return callErr
}
if r1 != 0 {
return syscall.Errno(r1)
}
return nil
}
// GetExtendedUDPTable function retrieves a table that contains a list of UDP
// endpoints available to the application
func GetExtendedUDPTable(order bool, af uint32, cl UDPTableClass) ([]byte, error) {
var size uint32
err := getExtendedUDPTable(nil, &size, order, af, cl)
if err != nil && err != errInsuffBuff {
return nil, err
}
buf := make([]byte, size)
err = getExtendedUDPTable(unsafe.Pointer(&buf[0]), &size, order, af, cl)
if err != nil {
return nil, err
}
return buf, nil
}
func GetUDPTableOwnerPID(order bool) (*MibUDPTableOwnerPID, error) {
b, err := GetExtendedUDPTable(true, syscall.AF_INET, UDPTableOwnerPID)
if err != nil {
return nil, err
}
return (*MibUDPTableOwnerPID)(unsafe.Pointer(&b[0])), nil
}
func GetUDP6TableOwnerPID(order bool) (*MibUDP6TableOwnerPID, error) {
b, err := GetExtendedUDPTable(true, syscall.AF_INET6, UDPTableOwnerPID)
if err != nil {
return nil, err
}
return (*MibUDP6TableOwnerPID)(unsafe.Pointer(&b[0])), nil
}
// ProcessSnapshot wraps the syscall.Handle, which represents a snapshot of
// the specified processes.
type ProcessSnapshot syscall.Handle
// CreateToolhelp32Snapshot takes a snapshot of the specified processes, as
// well as the heaps, modules, and threads used by these processes
func CreateToolhelp32Snapshot(flags uint32, pid uint32) (ProcessSnapshot, error) {
r1, _, callErr := syscall.Syscall(
procCreateSnapshot.Addr(),
uintptr(2),
uintptr(flags),
uintptr(pid), 0)
ret := ProcessSnapshot(r1)
if callErr != 0 {
return ret, callErr
}
if r1 == InvalidHandleValue {
return ret, fmt.Errorf("invalid handle value: %#v", r1)
}
return ret, nil
}
// ProcPIDToName translates PID to a name
func (snp ProcessSnapshot) ProcPIDToName(pid uint32) string {
var processEntry Processentry32
processEntry.Size = uint32(unsafe.Sizeof(processEntry))
handle := syscall.Handle(snp)
err := Process32First(handle, &processEntry)
if err != nil {
return ""
}
for {
if processEntry.Th32ProcessID == pid {
return StringFromNullTerminated(processEntry.ExeFile[:])
}
err = Process32Next(handle, &processEntry)
if err != nil {
return ""
}
}
}
// Close releases underlying win32 handle
func (snp ProcessSnapshot) Close() error {
return syscall.CloseHandle(syscall.Handle(snp))
}
// Process32First retrieves information about the first process encountered
// in a system snapshot
func Process32First(handle syscall.Handle, pe *Processentry32) error {
pe.Size = uint32(unsafe.Sizeof(*pe))
r1, _, callErr := syscall.Syscall(
procProcess32First.Addr(),
uintptr(2),
uintptr(handle),
uintptr(unsafe.Pointer(pe)), 0)
if callErr != 0 {
return callErr
}
if r1 == 0 {
return errNoMoreFiles
}
return nil
}
// Process32Next retrieves information about the next process
// recorded in a system snapshot
func Process32Next(handle syscall.Handle, pe *Processentry32) error {
pe.Size = uint32(unsafe.Sizeof(*pe))
r1, _, callErr := syscall.Syscall(
procProcess32Next.Addr(),
uintptr(2),
uintptr(handle),
uintptr(unsafe.Pointer(pe)), 0)
if callErr != 0 {
return callErr
}
if r1 == 0 {
return errNoMoreFiles
}
return nil
}
// StringFromNullTerminated returns a string from a nul-terminated byte slice
func StringFromNullTerminated(b []byte) string {
n := bytes.IndexByte(b, '\x00')
if n < 1 {
return ""
}
return string(b[:n])
}
type winSockEnt interface {
LocalSock() *SockAddr
RemoteSock() *SockAddr
SockState() SkState
Process(snp ProcessSnapshot) *Process
}
func toSockTabEntry(ws winSockEnt, snp ProcessSnapshot) SockTabEntry {
return SockTabEntry{
LocalAddr: ws.LocalSock(),
RemoteAddr: ws.RemoteSock(),
State: ws.SockState(),
Process: ws.Process(snp),
}
}
func osTCPSocks(accept AcceptFn) ([]SockTabEntry, error) {
tbl, err := GetTCPTable2(true)
if err != nil {
return nil, err
}
snp, err := CreateToolhelp32Snapshot(Th32csSnapProcess, 0)
if err != nil {
return nil, err
}
var sktab []SockTabEntry
s := tbl.Rows()
for i := range s {
ent := toSockTabEntry(&s[i], snp)
if accept(&ent) {
sktab = append(sktab, ent)
}
}
snp.Close()
return sktab, nil
}
func osTCP6Socks(accept AcceptFn) ([]SockTabEntry, error) {
tbl, err := GetTCP6Table2(true)
if err != nil {
return nil, err
}
snp, err := CreateToolhelp32Snapshot(Th32csSnapProcess, 0)
if err != nil {
return nil, err
}
var sktab []SockTabEntry
s := tbl.Rows()
for i := range s {
ent := toSockTabEntry(&s[i], snp)
if accept(&ent) {
sktab = append(sktab, ent)
}
}
snp.Close()
return sktab, nil
}
func osUDPSocks(accept AcceptFn) ([]SockTabEntry, error) {
tbl, err := GetUDPTableOwnerPID(true)
if err != nil {
return nil, err
}
snp, err := CreateToolhelp32Snapshot(Th32csSnapProcess, 0)
if err != nil {
return nil, err
}
var sktab []SockTabEntry
s := tbl.Rows()
for i := range s {
ent := toSockTabEntry(&s[i], snp)
if accept(&ent) {
sktab = append(sktab, ent)
}
}
snp.Close()
return sktab, nil
}
func osUDP6Socks(accept AcceptFn) ([]SockTabEntry, error) {
tbl, err := GetUDP6TableOwnerPID(true)
if err != nil {
return nil, err
}
snp, err := CreateToolhelp32Snapshot(Th32csSnapProcess, 0)
if err != nil {
return nil, err
}
var sktab []SockTabEntry
s := tbl.Rows()
for i := range s {
ent := toSockTabEntry(&s[i], snp)
if accept(&ent) {
sktab = append(sktab, ent)
}
}
snp.Close()
return sktab, nil
}