83 lines
2.5 KiB
Go
83 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Provisioning, not managed init, supplies this marker and the dedicated mount.
|
|
func verifyManagedRuntime(dir string) error {
|
|
if dir != managedTargetDirectory {
|
|
return fmt.Errorf("unexpected managed target path")
|
|
}
|
|
marker, err := os.ReadFile("/etc/zapret-autotune/target-id")
|
|
if err != nil || string(marker) != managedTargetID+"\n" {
|
|
return fmt.Errorf("fresh target runtime marker unavailable")
|
|
}
|
|
mounts, err := os.ReadFile("/proc/self/mountinfo")
|
|
if err != nil || !managedMountpoint(string(mounts), dir) {
|
|
return fmt.Errorf("managed target directory must be a dedicated mountpoint")
|
|
}
|
|
for _, path := range []string{"/opt/zapret2/init.d/sysv/zapret2", "/opt/zapret2/nfq2/nfqws2", "/usr/bin/blockcheckw"} {
|
|
info, err := os.Stat(path)
|
|
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 {
|
|
return fmt.Errorf("zapret base runtime executable unavailable")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func managedMountpoint(mountinfo, dir string) bool {
|
|
for _, line := range strings.Split(mountinfo, "\n") {
|
|
fields := strings.Fields(line)
|
|
if len(fields) >= 10 && fields[4] == dir {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Match the listening socket to an ss-local executable in this PID/network
|
|
// namespace. Merely finding a process or an arbitrary loopback proxy is unsafe.
|
|
func verifyManagedSOCKS(port int) error {
|
|
tcp, err := os.ReadFile("/proc/net/tcp")
|
|
if err != nil {
|
|
return fmt.Errorf("target SOCKS listener unavailable")
|
|
}
|
|
inodes := map[string]bool{}
|
|
for _, line := range strings.Split(string(tcp), "\n") {
|
|
f := strings.Fields(line)
|
|
if len(f) > 9 && f[3] == "0A" && (f[1] == fmt.Sprintf("0100007F:%04X", port) || f[1] == fmt.Sprintf("00000000:%04X", port)) {
|
|
inodes["socket:["+f[9]+"]"] = true
|
|
}
|
|
}
|
|
processes, err := os.ReadDir("/proc")
|
|
if err != nil {
|
|
return fmt.Errorf("target ss-local runtime unavailable")
|
|
}
|
|
for _, process := range processes {
|
|
if _, err := strconv.Atoi(process.Name()); err != nil {
|
|
continue
|
|
}
|
|
root := filepath.Join("/proc", process.Name())
|
|
exe, err := os.Readlink(filepath.Join(root, "exe"))
|
|
if err != nil || filepath.Base(exe) != "ss-local" {
|
|
continue
|
|
}
|
|
fds, err := os.ReadDir(filepath.Join(root, "fd"))
|
|
if err != nil {
|
|
continue
|
|
}
|
|
for _, fd := range fds {
|
|
link, err := os.Readlink(filepath.Join(root, "fd", fd.Name()))
|
|
if err == nil && inodes[link] {
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
return fmt.Errorf("target SOCKS_PORT listener is not owned by ss-local")
|
|
}
|