2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-02-05 22:16:58 +00:00
|
|
|
|
|
|
|
package portlist
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
2022-10-22 17:29:37 +01:00
|
|
|
"bytes"
|
2022-10-24 02:02:02 +01:00
|
|
|
"errors"
|
2020-02-05 22:16:58 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2022-11-05 21:26:29 +00:00
|
|
|
"io/fs"
|
2022-10-24 02:02:02 +01:00
|
|
|
"log"
|
2020-02-05 22:16:58 +00:00
|
|
|
"os"
|
2021-03-04 04:12:09 +00:00
|
|
|
"path/filepath"
|
2020-07-28 21:17:38 +01:00
|
|
|
"runtime"
|
2020-02-05 22:16:58 +00:00
|
|
|
"strings"
|
2020-07-28 21:17:38 +01:00
|
|
|
"syscall"
|
2020-03-14 03:53:58 +00:00
|
|
|
"time"
|
2022-10-22 19:21:10 +01:00
|
|
|
"unsafe"
|
2020-03-14 03:53:58 +00:00
|
|
|
|
2021-09-12 00:45:12 +01:00
|
|
|
"go4.org/mem"
|
2020-03-14 03:53:58 +00:00
|
|
|
"golang.org/x/sys/unix"
|
2022-11-05 21:26:29 +00:00
|
|
|
"tailscale.com/util/dirwalk"
|
2022-10-22 17:29:37 +01:00
|
|
|
"tailscale.com/util/mak"
|
2020-02-05 22:16:58 +00:00
|
|
|
)
|
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
func init() {
|
|
|
|
newOSImpl = newLinuxImpl
|
2022-11-04 13:41:36 +00:00
|
|
|
// Reading the sockfiles on Linux is very fast, so we can do it often.
|
|
|
|
pollInterval = 1 * time.Second
|
2022-10-24 02:02:02 +01:00
|
|
|
}
|
2021-03-04 04:12:09 +00:00
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
type linuxImpl struct {
|
2022-11-05 21:26:29 +00:00
|
|
|
procNetFiles []*os.File // seeked to start & reused between calls
|
|
|
|
readlinkPathBuf []byte
|
2022-10-22 17:29:37 +01:00
|
|
|
|
2023-05-24 17:52:45 +01:00
|
|
|
known map[string]*portMeta // inode string => metadata
|
|
|
|
br *bufio.Reader
|
|
|
|
includeLocalhost bool
|
2022-10-22 17:29:37 +01:00
|
|
|
}
|
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
type portMeta struct {
|
|
|
|
port Port
|
2023-05-24 17:52:45 +01:00
|
|
|
pid int
|
2022-10-24 02:02:02 +01:00
|
|
|
keep bool
|
|
|
|
needsProcName bool
|
2022-10-22 17:29:37 +01:00
|
|
|
}
|
|
|
|
|
2023-05-24 17:52:45 +01:00
|
|
|
func newLinuxImplBase(includeLocalhost bool) *linuxImpl {
|
2022-10-24 02:02:02 +01:00
|
|
|
return &linuxImpl{
|
2023-05-24 17:52:45 +01:00
|
|
|
br: bufio.NewReader(eofReader),
|
|
|
|
known: map[string]*portMeta{},
|
|
|
|
includeLocalhost: includeLocalhost,
|
2022-10-22 17:29:37 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-24 17:52:45 +01:00
|
|
|
func newLinuxImpl(includeLocalhost bool) osImpl {
|
|
|
|
li := newLinuxImplBase(includeLocalhost)
|
2022-10-24 02:02:02 +01:00
|
|
|
for _, name := range []string{
|
|
|
|
"/proc/net/tcp",
|
|
|
|
"/proc/net/tcp6",
|
|
|
|
"/proc/net/udp",
|
|
|
|
"/proc/net/udp6",
|
|
|
|
} {
|
|
|
|
f, err := os.Open(name)
|
|
|
|
if err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
log.Printf("portlist warning; ignoring: %v", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
li.procNetFiles = append(li.procNetFiles, f)
|
|
|
|
}
|
|
|
|
return li
|
2022-10-22 17:29:37 +01:00
|
|
|
}
|
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
func (li *linuxImpl) Close() error {
|
|
|
|
for _, f := range li.procNetFiles {
|
|
|
|
f.Close()
|
2020-07-28 21:17:38 +01:00
|
|
|
}
|
2022-10-24 02:02:02 +01:00
|
|
|
li.procNetFiles = nil
|
|
|
|
return nil
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
const (
|
|
|
|
v6Localhost = "00000000000000000000000001000000:"
|
|
|
|
v6Any = "00000000000000000000000000000000:0000"
|
|
|
|
v4Localhost = "0100007F:"
|
|
|
|
v4Any = "00000000:0000"
|
|
|
|
)
|
|
|
|
|
|
|
|
var eofReader = bytes.NewReader(nil)
|
2022-10-22 17:29:37 +01:00
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
func (li *linuxImpl) AppendListeningPorts(base []Port) ([]Port, error) {
|
|
|
|
if runtime.GOOS == "android" {
|
2020-07-28 21:17:38 +01:00
|
|
|
// Android 10+ doesn't allow access to this anymore.
|
|
|
|
// https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
|
|
|
|
// Ignore it rather than have the system log about our violation.
|
2022-10-24 02:02:02 +01:00
|
|
|
return nil, nil
|
|
|
|
}
|
2020-07-28 21:17:38 +01:00
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
br := li.br
|
|
|
|
defer br.Reset(eofReader)
|
|
|
|
|
|
|
|
// Start by marking all previous known ports as gone. If this mark
|
|
|
|
// bit is still false later, we'll remove them.
|
|
|
|
for _, pm := range li.known {
|
|
|
|
pm.keep = false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, f := range li.procNetFiles {
|
|
|
|
name := f.Name()
|
|
|
|
_, err := f.Seek(0, io.SeekStart)
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-24 02:02:02 +01:00
|
|
|
return nil, err
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-22 17:29:37 +01:00
|
|
|
br.Reset(f)
|
2022-10-24 02:02:02 +01:00
|
|
|
err = li.parseProcNetFile(br, filepath.Base(name))
|
2020-02-05 22:16:58 +00:00
|
|
|
if err != nil {
|
2022-10-24 02:02:02 +01:00
|
|
|
return nil, fmt.Errorf("parsing %q: %w", name, err)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-22 17:29:37 +01:00
|
|
|
}
|
2022-10-24 02:02:02 +01:00
|
|
|
|
|
|
|
// Delete ports that aren't open any longer.
|
|
|
|
// And see if there are any process names we need to look for.
|
|
|
|
var needProc map[string]*portMeta
|
|
|
|
for inode, pm := range li.known {
|
|
|
|
if !pm.keep {
|
|
|
|
delete(li.known, inode)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if pm.needsProcName {
|
|
|
|
mak.Set(&needProc, inode, pm)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := li.findProcessNames(needProc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ret := base
|
|
|
|
for _, pm := range li.known {
|
|
|
|
ret = append(ret, pm.port)
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-24 02:02:02 +01:00
|
|
|
return sortAndDedup(ret), nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
|
2021-09-13 03:49:37 +01:00
|
|
|
// fileBase is one of "tcp", "tcp6", "udp", "udp6".
|
2022-10-24 02:02:02 +01:00
|
|
|
func (li *linuxImpl) parseProcNetFile(r *bufio.Reader, fileBase string) error {
|
2021-09-13 03:49:37 +01:00
|
|
|
proto := strings.TrimSuffix(fileBase, "6")
|
2021-03-04 04:12:09 +00:00
|
|
|
|
|
|
|
// skip header row
|
2021-09-13 16:48:38 +01:00
|
|
|
_, err := r.ReadSlice('\n')
|
2021-03-04 04:12:09 +00:00
|
|
|
if err != nil {
|
2022-10-24 02:02:02 +01:00
|
|
|
return err
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
|
|
|
|
2021-09-12 00:45:12 +01:00
|
|
|
fields := make([]mem.RO, 0, 20) // 17 current fields + some future slop
|
|
|
|
|
2021-09-13 03:49:37 +01:00
|
|
|
wantRemote := mem.S(v4Any)
|
|
|
|
if strings.HasSuffix(fileBase, "6") {
|
|
|
|
wantRemote = mem.S(v6Any)
|
|
|
|
}
|
|
|
|
|
2021-09-13 16:48:38 +01:00
|
|
|
// remoteIndex is the index within a line to the remote address field.
|
|
|
|
// -1 means not yet found.
|
|
|
|
remoteIndex := -1
|
|
|
|
|
|
|
|
// Add an upper bound on how many rows we'll attempt to read just
|
|
|
|
// to make sure this doesn't consume too much of their CPU.
|
|
|
|
// TODO(bradfitz,crawshaw): adaptively adjust polling interval as function
|
|
|
|
// of open sockets.
|
|
|
|
const maxRows = 1e6
|
|
|
|
rows := 0
|
|
|
|
|
|
|
|
// Scratch buffer for making inode strings.
|
|
|
|
inoBuf := make([]byte, 0, 50)
|
|
|
|
|
2021-03-04 04:12:09 +00:00
|
|
|
for err == nil {
|
2021-09-12 00:45:12 +01:00
|
|
|
line, err := r.ReadSlice('\n')
|
2021-03-04 04:12:09 +00:00
|
|
|
if err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if err != nil {
|
2022-10-24 02:02:02 +01:00
|
|
|
return err
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
2021-09-13 16:48:38 +01:00
|
|
|
rows++
|
|
|
|
if rows >= maxRows {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if len(line) == 0 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// On the first row of output, find the index of the 3rd field (index 2),
|
|
|
|
// the remote address. All the rows are aligned, at least until 4 billion open
|
|
|
|
// TCP connections, per the Linux get_tcp4_sock's "%4d: " on an int i.
|
|
|
|
if remoteIndex == -1 {
|
|
|
|
remoteIndex = fieldIndex(line, 2)
|
|
|
|
if remoteIndex == -1 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2021-03-04 04:12:09 +00:00
|
|
|
|
2021-09-13 16:48:38 +01:00
|
|
|
if len(line) < remoteIndex || !mem.HasPrefix(mem.B(line).SliceFrom(remoteIndex), wantRemote) {
|
2021-09-13 03:49:37 +01:00
|
|
|
// Fast path for not being a listener port.
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-03-04 04:12:09 +00:00
|
|
|
// sl local rem ... inode
|
2021-09-12 00:45:12 +01:00
|
|
|
fields = mem.AppendFields(fields[:0], mem.B(line))
|
|
|
|
local := fields[1]
|
|
|
|
rem := fields[2]
|
|
|
|
inode := fields[9]
|
2021-03-04 04:12:09 +00:00
|
|
|
|
2021-09-13 03:49:37 +01:00
|
|
|
if !rem.Equal(wantRemote) {
|
|
|
|
// not a "listener" port
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2021-03-04 04:12:09 +00:00
|
|
|
// If a port is bound to localhost, ignore it.
|
|
|
|
// TODO: localhost is bigger than 1 IP, we need to ignore
|
|
|
|
// more things.
|
2023-05-24 17:52:45 +01:00
|
|
|
if !li.includeLocalhost && (mem.HasPrefix(local, mem.S(v4Localhost)) || mem.HasPrefix(local, mem.S(v6Localhost))) {
|
2021-03-04 04:12:09 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Don't use strings.Split here, because it causes
|
|
|
|
// allocations significant enough to show up in profiles.
|
2021-09-12 00:45:12 +01:00
|
|
|
i := mem.IndexByte(local, ':')
|
2021-03-04 04:12:09 +00:00
|
|
|
if i == -1 {
|
2022-10-24 02:02:02 +01:00
|
|
|
return fmt.Errorf("%q unexpectedly didn't have a colon", local.StringCopy())
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
2021-09-12 00:45:12 +01:00
|
|
|
portv, err := mem.ParseUint(local.SliceFrom(i+1), 16, 16)
|
2021-03-04 04:12:09 +00:00
|
|
|
if err != nil {
|
2022-10-24 02:02:02 +01:00
|
|
|
return fmt.Errorf("%#v: %s", local.SliceFrom(9).StringCopy(), err)
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
2021-09-12 00:45:12 +01:00
|
|
|
inoBuf = append(inoBuf[:0], "socket:["...)
|
|
|
|
inoBuf = mem.Append(inoBuf, inode)
|
|
|
|
inoBuf = append(inoBuf, ']')
|
2022-10-24 02:02:02 +01:00
|
|
|
|
|
|
|
if pm, ok := li.known[string(inoBuf)]; ok {
|
|
|
|
pm.keep = true
|
|
|
|
// Rest should be unchanged.
|
|
|
|
} else {
|
|
|
|
li.known[string(inoBuf)] = &portMeta{
|
|
|
|
needsProcName: true,
|
|
|
|
keep: true,
|
|
|
|
port: Port{
|
|
|
|
Proto: proto,
|
|
|
|
Port: uint16(portv),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
return nil
|
2021-03-04 04:12:09 +00:00
|
|
|
}
|
|
|
|
|
2022-10-24 02:02:02 +01:00
|
|
|
// errDone is an internal sentinel error that we found everything we were looking for.
|
|
|
|
var errDone = errors.New("done")
|
|
|
|
|
|
|
|
// need is keyed by inode string.
|
|
|
|
func (li *linuxImpl) findProcessNames(need map[string]*portMeta) error {
|
|
|
|
if len(need) == 0 {
|
|
|
|
return nil
|
2020-03-14 03:53:58 +00:00
|
|
|
}
|
2022-10-24 02:02:02 +01:00
|
|
|
defer func() {
|
|
|
|
// Anything we didn't find, give up on and don't try to look for it later.
|
|
|
|
for _, pm := range need {
|
|
|
|
pm.needsProcName = false
|
|
|
|
}
|
|
|
|
}()
|
2020-03-14 03:53:58 +00:00
|
|
|
|
2022-11-05 21:26:29 +00:00
|
|
|
err := foreachPID(func(pid mem.RO) error {
|
|
|
|
var procBuf [128]byte
|
|
|
|
fdPath := mem.Append(procBuf[:0], mem.S("/proc/"))
|
|
|
|
fdPath = mem.Append(fdPath, pid)
|
|
|
|
fdPath = mem.Append(fdPath, mem.S("/fd"))
|
2020-07-28 21:17:38 +01:00
|
|
|
|
|
|
|
// Android logs a bunch of audit violations in logcat
|
|
|
|
// if we try to open things we don't have access
|
|
|
|
// to. So on Android only, ask if we have permission
|
|
|
|
// rather than just trying it to determine whether we
|
|
|
|
// have permission.
|
2022-11-05 21:26:29 +00:00
|
|
|
if runtime.GOOS == "android" && syscall.Access(string(fdPath), unix.R_OK) != nil {
|
2020-03-14 03:53:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-11-05 21:26:29 +00:00
|
|
|
dirwalk.WalkShallow(mem.B(fdPath), func(fd mem.RO, de fs.DirEntry) error {
|
|
|
|
targetBuf := make([]byte, 64) // plenty big for "socket:[165614651]"
|
|
|
|
|
|
|
|
linkPath := li.readlinkPathBuf[:0]
|
|
|
|
linkPath = fmt.Appendf(linkPath, "/proc/")
|
|
|
|
linkPath = mem.Append(linkPath, pid)
|
|
|
|
linkPath = append(linkPath, "/fd/"...)
|
|
|
|
linkPath = mem.Append(linkPath, fd)
|
|
|
|
linkPath = append(linkPath, 0) // terminating NUL
|
|
|
|
li.readlinkPathBuf = linkPath // to reuse its buffer next time
|
|
|
|
n, ok := readlink(linkPath, targetBuf)
|
|
|
|
if !ok {
|
|
|
|
// Not a symlink or no permission.
|
|
|
|
// Skip it.
|
2020-03-14 03:53:58 +00:00
|
|
|
return nil
|
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
|
|
|
|
pe := need[string(targetBuf[:n])] // m[string([]byte)] avoids alloc
|
|
|
|
if pe == nil {
|
2020-05-19 06:48:55 +01:00
|
|
|
return nil
|
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
bs, err := os.ReadFile(fmt.Sprintf("/proc/%s/cmdline", pid.StringCopy()))
|
2020-03-14 03:53:58 +00:00
|
|
|
if err != nil {
|
2022-11-05 21:26:29 +00:00
|
|
|
// Usually shouldn't happen. One possibility is
|
|
|
|
// the process has gone away, so let's skip it.
|
|
|
|
return nil
|
2020-03-14 03:53:58 +00:00
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
|
|
|
|
argv := strings.Split(strings.TrimSuffix(string(bs), "\x00"), "\x00")
|
2023-05-24 17:52:45 +01:00
|
|
|
if p, err := mem.ParseInt(pid, 10, 0); err == nil {
|
|
|
|
pe.pid = int(p)
|
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
pe.port.Process = argvSubject(argv...)
|
|
|
|
pe.needsProcName = false
|
|
|
|
delete(need, string(targetBuf[:n]))
|
|
|
|
if len(need) == 0 {
|
|
|
|
return errDone
|
2020-03-14 03:53:58 +00:00
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
return nil
|
2020-03-14 03:53:58 +00:00
|
|
|
})
|
2022-10-24 02:02:02 +01:00
|
|
|
if err == errDone {
|
|
|
|
return nil
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2022-10-24 02:02:02 +01:00
|
|
|
return err
|
2020-03-14 03:53:58 +00:00
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-11-05 21:26:29 +00:00
|
|
|
func foreachPID(fn func(pidStr mem.RO) error) error {
|
|
|
|
err := dirwalk.WalkShallow(mem.S("/proc"), func(name mem.RO, de fs.DirEntry) error {
|
|
|
|
if !isNumeric(name) {
|
2020-05-19 06:48:55 +01:00
|
|
|
return nil
|
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
return fn(name)
|
|
|
|
})
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
// This can happen if the directory we're
|
|
|
|
// reading disappears during the run. No big
|
|
|
|
// deal.
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
2020-02-05 22:16:58 +00:00
|
|
|
|
2022-11-05 21:26:29 +00:00
|
|
|
func isNumeric(s mem.RO) bool {
|
|
|
|
for i, n := 0, s.Len(); i < n; i++ {
|
|
|
|
b := s.At(i)
|
|
|
|
if b < '0' || b > '9' {
|
|
|
|
return false
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-05 21:26:29 +00:00
|
|
|
return s.Len() > 0
|
2020-02-05 22:16:58 +00:00
|
|
|
}
|
2021-09-13 03:49:37 +01:00
|
|
|
|
|
|
|
// fieldIndex returns the offset in line where the Nth field (0-based) begins, or -1
|
|
|
|
// if there aren't that many fields. Fields are separated by 1 or more spaces.
|
|
|
|
func fieldIndex(line []byte, n int) int {
|
|
|
|
skip := 0
|
|
|
|
for i := 0; i <= n; i++ {
|
|
|
|
// Skip spaces.
|
|
|
|
for skip < len(line) && line[skip] == ' ' {
|
|
|
|
skip++
|
|
|
|
}
|
|
|
|
if skip == len(line) {
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
if i == n {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
// Skip non-space.
|
|
|
|
for skip < len(line) && line[skip] != ' ' {
|
|
|
|
skip++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return skip
|
|
|
|
}
|
2022-10-22 19:21:10 +01:00
|
|
|
|
|
|
|
// path must be null terminated.
|
|
|
|
func readlink(path, buf []byte) (n int, ok bool) {
|
|
|
|
if len(buf) == 0 || len(path) < 2 || path[len(path)-1] != 0 {
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
var dirfd int = unix.AT_FDCWD
|
|
|
|
r0, _, e1 := unix.Syscall6(unix.SYS_READLINKAT,
|
|
|
|
uintptr(dirfd),
|
|
|
|
uintptr(unsafe.Pointer(&path[0])),
|
|
|
|
uintptr(unsafe.Pointer(&buf[0])),
|
|
|
|
uintptr(len(buf)),
|
|
|
|
0, 0)
|
|
|
|
n = int(r0)
|
|
|
|
if e1 != 0 {
|
|
|
|
return 0, false
|
|
|
|
}
|
|
|
|
return n, true
|
|
|
|
}
|