go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/providers/os/resources/ports/winports.go (about)

     1  // Copyright (c) Mondoo, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  package ports
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"io"
    10  	"strings"
    11  )
    12  
    13  type State int64
    14  
    15  const (
    16  	Closed      = 1
    17  	Listen      = 2
    18  	SynSent     = 3
    19  	SynReceived = 4
    20  	Established = 5
    21  	FinWait1    = 6
    22  	FinWait2    = 7
    23  	CloseWait   = 8
    24  	Closing     = 9
    25  	LastAck     = 10
    26  	TimeWait    = 11
    27  	DeleteTCB   = 12
    28  	Bound       = 13
    29  )
    30  
    31  type WinPort struct {
    32  	State         State
    33  	LocalAddress  string
    34  	LocalPort     int64
    35  	RemoteAddress string
    36  	RemotePort    int64
    37  	OwningProcess int64
    38  }
    39  
    40  func ParseWindowsNetTCPConnections(r io.Reader) ([]WinPort, error) {
    41  	data, err := io.ReadAll(r)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	entries := []WinPort{}
    47  	err = json.Unmarshal(data, &entries)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	// convert any ipv6 address (basically if they contain a ':')
    53  	// to a more ipv6-friendly address surrounded by []s
    54  	for i := range entries {
    55  		localAddress := entries[i].LocalAddress
    56  		if strings.ContainsAny(entries[i].LocalAddress, ":") {
    57  			localAddress = fmt.Sprintf("[%s]", entries[i].LocalAddress)
    58  		}
    59  		remoteAddress := entries[i].RemoteAddress
    60  		if strings.ContainsAny(entries[i].RemoteAddress, ":") {
    61  			remoteAddress = fmt.Sprintf("[%s]", entries[i].RemoteAddress)
    62  		}
    63  
    64  		entries[i].LocalAddress = localAddress
    65  		entries[i].RemoteAddress = remoteAddress
    66  	}
    67  
    68  	return entries, nil
    69  }