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
|
/*
Simple Netstat implementation.
Get data from /proc/net/tcp and /proc/net/udp and
and parse /proc/[0-9]/fd/[0-9].
Author: Rafael Santos <rafael@sourcecode.net.br>
*/
package GOnetstat
import (
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/opencontainers/runc/libcontainer/user"
)
const (
PROC_TCP = "/proc/net/tcp"
PROC_UDP = "/proc/net/udp"
PROC_TCP6 = "/proc/net/tcp6"
PROC_UDP6 = "/proc/net/udp6"
)
var STATE = map[string]string{
"01": "ESTABLISHED",
"02": "SYN_SENT",
"03": "SYN_RECV",
"04": "FIN_WAIT1",
"05": "FIN_WAIT2",
"06": "TIME_WAIT",
"07": "CLOSE",
"08": "CLOSE_WAIT",
"09": "LAST_ACK",
"0A": "LISTEN",
"0B": "CLOSING",
}
type Process struct {
User string
Name string
Pid string
Exe string
State string
Ip string
Port int64
ForeignIp string
ForeignPort int64
}
func getData(t string) ([]string, error) {
// Get data from tcp or udp file.
var proc_t string
if t == "tcp" {
proc_t = PROC_TCP
} else if t == "udp" {
proc_t = PROC_UDP
} else if t == "tcp6" {
proc_t = PROC_TCP6
} else if t == "udp6" {
proc_t = PROC_UDP6
} else {
fmt.Printf("%s is a invalid type, tcp and udp only!\n", t)
os.Exit(1)
}
data, err := ioutil.ReadFile(proc_t)
if err != nil {
return []string{}, err
}
lines := strings.Split(string(data), "\n")
// Return lines without Header line and blank line on the end
return lines[1 : len(lines)-1], nil
}
func hexToDec(h string) int64 {
// convert hexadecimal to decimal.
d, err := strconv.ParseInt(h, 16, 32)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return d
}
// Modified from https://github.com/hverr/status-dashboard/blob/master/widgets/connections.go
func reverseIPBytes(bytes []byte) {
j := len(bytes)
m := j / 2
j -= 1
i := 0
for i < m {
b := bytes[i]
bytes[i] = bytes[j]
bytes[j] = b
i += 1
j -= 1
}
}
func bytesToIP(bytes []byte) string {
switch len(bytes) {
case 4:
reverseIPBytes(bytes[0:4])
case 16:
reverseIPBytes(bytes[0:4])
reverseIPBytes(bytes[4:8])
reverseIPBytes(bytes[8:12])
reverseIPBytes(bytes[12:16])
default:
return ""
}
return strings.ToUpper(net.IP(bytes).String())
}
func convertIp(ip string) (string, error) {
ipb, err := hex.DecodeString(ip)
if err != nil {
return "", err
}
return bytesToIP(ipb), nil
}
func findPid(inode string) string {
// Loop through all fd dirs of process on /proc to compare the inode and
// get the pid.
pid := "-"
d, err := filepath.Glob("/proc/[0-9]*/fd/[0-9]*")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
re := regexp.MustCompile(inode)
for _, item := range d {
path, _ := os.Readlink(item)
out := re.FindString(path)
if len(out) != 0 {
pid = strings.Split(item, "/")[2]
}
}
return pid
}
func getProcessExe(pid string) string {
exe := fmt.Sprintf("/proc/%s/exe", pid)
path, _ := os.Readlink(exe)
return path
}
func getProcessName(exe string) string {
n := strings.Split(exe, "/")
name := n[len(n)-1]
return strings.Title(name)
}
func getUser(uid int) string {
u, _ := user.LookupUid(uid)
return u.Name
}
func removeEmpty(array []string) []string {
// remove empty data from line
var new_array []string
for _, i := range array {
if i != "" {
new_array = append(new_array, i)
}
}
return new_array
}
func getInode2pid() map[string]string {
// Loop through all fd dirs of process on /proc to compare the inode and
// get the pid.
inode2pid := make(map[string]string)
pid := "-"
d, err := filepath.Glob("/proc/[0-9]*/fd/[0-9]*")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
var inode string
for _, item := range d {
path, _ := os.Readlink(item)
if strings.Contains(path, "socket:[") {
inode = path[8 : len(path)-1]
pid = strings.Split(item, "/")[2]
inode2pid[inode] = pid
}
}
return inode2pid
}
func netstat(t string, lookupPids bool) ([]Process, error) {
// Return a array of Process with Name, Ip, Port, State .. etc
// Require Root acess to get information about some processes.
var Processes []Process
data, err := getData(t)
if err != nil {
return Processes, nil
}
var inode2pid map[string]string
if lookupPids {
inode2pid = getInode2pid()
}
for _, line := range data {
// local ip and port
line_array := removeEmpty(strings.Split(strings.TrimSpace(line), " "))
ip_port := strings.Split(line_array[1], ":")
ip, err := convertIp(ip_port[0])
if err != nil {
return Processes, err
}
port := hexToDec(ip_port[1])
// foreign ip and port
fip_port := strings.Split(line_array[2], ":")
fip, err := convertIp(fip_port[0])
if err != nil {
return Processes, err
}
fport := hexToDec(fip_port[1])
state := STATE[line_array[3]]
uid, err := strconv.Atoi(line_array[7])
if err != nil {
return Processes, err
}
userName := getUser(uid)
var pid, exe, name string
if lookupPids {
pid = inode2pid[line_array[9]]
exe = getProcessExe(pid)
name = getProcessName(exe)
}
p := Process{userName, name, pid, exe, state, ip, port, fip, fport}
Processes = append(Processes, p)
}
return Processes, nil
}
func Tcp(lookupPids bool) ([]Process, error) {
// Get a slice of Process type with TCP data
return netstat("tcp", lookupPids)
}
func Udp(lookupPids bool) ([]Process, error) {
// Get a slice of Process type with UDP data
return netstat("udp", lookupPids)
}
func Tcp6(lookupPids bool) ([]Process, error) {
// Get a slice of Process type with TCP6 data
return netstat("tcp6", lookupPids)
}
func Udp6(lookupPids bool) ([]Process, error) {
// Get a slice of Process type with UDP6 data
return netstat("udp6", lookupPids)
}
|