netaudit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netaudit/__init__.py +3 -0
- netaudit/allowlist.py +130 -0
- netaudit/cli.py +109 -0
- netaudit/integrations/__init__.py +1 -0
- netaudit/parser.py +193 -0
- netaudit/py.typed +0 -0
- netaudit/reporter.py +110 -0
- netaudit/runner.py +66 -0
- netaudit-0.1.0.dist-info/METADATA +302 -0
- netaudit-0.1.0.dist-info/RECORD +13 -0
- netaudit-0.1.0.dist-info/WHEEL +4 -0
- netaudit-0.1.0.dist-info/entry_points.txt +2 -0
- netaudit-0.1.0.dist-info/licenses/LICENSE +201 -0
netaudit/__init__.py
ADDED
netaudit/allowlist.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Allowlist engine — loads rules from YAML and matches ConnectEvents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import ipaddress
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Protocol
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from netaudit.parser import ConnectEvent
|
|
13
|
+
|
|
14
|
+
# ---------------------------------------------------------------------------
|
|
15
|
+
# Rule protocol
|
|
16
|
+
# ---------------------------------------------------------------------------
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Rule(Protocol):
|
|
20
|
+
def matches(self, event: ConnectEvent) -> bool: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
# Concrete rule types
|
|
25
|
+
# ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class IPv4Rule:
|
|
29
|
+
"""Allow connections whose destination falls within a CIDR block."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, cidr: str) -> None:
|
|
32
|
+
self._network = ipaddress.IPv4Network(cidr, strict=False)
|
|
33
|
+
|
|
34
|
+
def matches(self, event: ConnectEvent) -> bool:
|
|
35
|
+
if event.family != "AF_INET" or event.addr is None:
|
|
36
|
+
return False
|
|
37
|
+
try:
|
|
38
|
+
return ipaddress.IPv4Address(event.addr) in self._network
|
|
39
|
+
except ValueError:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class IPv6Rule:
|
|
44
|
+
"""Allow connections whose destination falls within an IPv6 CIDR block."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, cidr: str) -> None:
|
|
47
|
+
self._network = ipaddress.IPv6Network(cidr, strict=False)
|
|
48
|
+
|
|
49
|
+
def matches(self, event: ConnectEvent) -> bool:
|
|
50
|
+
if event.family != "AF_INET6" or event.addr is None:
|
|
51
|
+
return False
|
|
52
|
+
try:
|
|
53
|
+
return ipaddress.IPv6Address(event.addr) in self._network
|
|
54
|
+
except ValueError:
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class UnixSocketRule:
|
|
59
|
+
"""Allow Unix socket connections whose path matches a glob pattern."""
|
|
60
|
+
|
|
61
|
+
def __init__(self, path_glob: str) -> None:
|
|
62
|
+
self._glob = path_glob
|
|
63
|
+
|
|
64
|
+
def matches(self, event: ConnectEvent) -> bool:
|
|
65
|
+
if event.family != "AF_UNIX" or event.addr is None:
|
|
66
|
+
return False
|
|
67
|
+
return fnmatch.fnmatch(event.addr, self._glob)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class NetlinkRule:
|
|
71
|
+
"""Allow all AF_NETLINK connections (glibc resolver internals etc.)."""
|
|
72
|
+
|
|
73
|
+
def matches(self, event: ConnectEvent) -> bool:
|
|
74
|
+
return event.family == "AF_NETLINK"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------------------
|
|
78
|
+
# Built-in defaults
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
_BUILTIN_RULES: list[Rule] = [
|
|
82
|
+
IPv4Rule("127.0.0.0/8"), # IPv4 loopback
|
|
83
|
+
IPv6Rule("::1/128"), # IPv6 loopback
|
|
84
|
+
UnixSocketRule("*"), # all AF_UNIX
|
|
85
|
+
NetlinkRule(), # all AF_NETLINK
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
# AllowList
|
|
90
|
+
# ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _rule_from_dict(entry: dict[str, Any]) -> Rule:
|
|
94
|
+
family = entry.get("family", "")
|
|
95
|
+
if family == "AF_INET":
|
|
96
|
+
cidr = entry.get("cidr") or f"{entry['addr']}/32"
|
|
97
|
+
return IPv4Rule(cidr)
|
|
98
|
+
if family == "AF_INET6":
|
|
99
|
+
cidr = entry.get("cidr") or f"{entry['addr']}/128"
|
|
100
|
+
return IPv6Rule(cidr)
|
|
101
|
+
if family == "AF_UNIX":
|
|
102
|
+
glob = entry.get("path_glob") or entry.get("path_prefix", "") + "*"
|
|
103
|
+
return UnixSocketRule(glob)
|
|
104
|
+
if family == "AF_NETLINK":
|
|
105
|
+
return NetlinkRule()
|
|
106
|
+
raise ValueError(f"Unknown family in allowlist entry: {family!r}")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class AllowList:
|
|
110
|
+
def __init__(self, rules: list[Rule], includes_builtins: bool = True) -> None:
|
|
111
|
+
self._rules: list[Rule] = list(rules)
|
|
112
|
+
if includes_builtins:
|
|
113
|
+
self._rules = _BUILTIN_RULES + self._rules
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def from_yaml(cls, path: Path) -> "AllowList":
|
|
117
|
+
raw = yaml.safe_load(path.read_text())
|
|
118
|
+
includes_builtins = raw.get("includes_builtins", True)
|
|
119
|
+
rules: list[Rule] = []
|
|
120
|
+
for entry in raw.get("allowlist", []):
|
|
121
|
+
rules.append(_rule_from_dict(entry))
|
|
122
|
+
return cls(rules, includes_builtins=includes_builtins)
|
|
123
|
+
|
|
124
|
+
@classmethod
|
|
125
|
+
def empty(cls) -> "AllowList":
|
|
126
|
+
"""Allowlist with only built-in rules."""
|
|
127
|
+
return cls([], includes_builtins=True)
|
|
128
|
+
|
|
129
|
+
def is_allowed(self, event: ConnectEvent) -> bool:
|
|
130
|
+
return any(rule.matches(event) for rule in self._rules)
|
netaudit/cli.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""CLI entry point for netaudit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import click
|
|
10
|
+
|
|
11
|
+
from netaudit import __version__
|
|
12
|
+
from netaudit.allowlist import AllowList
|
|
13
|
+
from netaudit.parser import StraceParser
|
|
14
|
+
from netaudit.reporter import Reporter, Violation
|
|
15
|
+
from netaudit.runner import StraceNotFoundError, StraceRunner
|
|
16
|
+
|
|
17
|
+
_DEFAULT_ALLOWLIST = "netaudit.yaml"
|
|
18
|
+
|
|
19
|
+
# Exit codes
|
|
20
|
+
_EXIT_CLEAN = 0
|
|
21
|
+
_EXIT_VIOLATIONS = 1
|
|
22
|
+
_EXIT_STRACE_MISSING = 2
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _load_allowlist(allowlist: str | None) -> AllowList:
|
|
26
|
+
if allowlist is not None:
|
|
27
|
+
return AllowList.from_yaml(Path(allowlist))
|
|
28
|
+
default = Path(_DEFAULT_ALLOWLIST)
|
|
29
|
+
if default.exists():
|
|
30
|
+
return AllowList.from_yaml(default)
|
|
31
|
+
return AllowList.empty()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _emit(violations: list[Violation], fmt: str) -> None:
|
|
35
|
+
|
|
36
|
+
if fmt == "json":
|
|
37
|
+
click.echo(Reporter.format_json(violations))
|
|
38
|
+
else:
|
|
39
|
+
Reporter.format(violations, stream=sys.stdout)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@click.group()
|
|
43
|
+
@click.version_option(version=__version__, prog_name="netaudit")
|
|
44
|
+
def main() -> None:
|
|
45
|
+
"""netaudit — CI-native network egress auditing via strace."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@main.command("run")
|
|
49
|
+
@click.option(
|
|
50
|
+
"--allowlist",
|
|
51
|
+
default=None,
|
|
52
|
+
metavar="YAML",
|
|
53
|
+
help=f"Allowlist file (default: {_DEFAULT_ALLOWLIST} in cwd if present).",
|
|
54
|
+
)
|
|
55
|
+
@click.option(
|
|
56
|
+
"--format",
|
|
57
|
+
"fmt",
|
|
58
|
+
type=click.Choice(["text", "json"]),
|
|
59
|
+
default="text",
|
|
60
|
+
show_default=True,
|
|
61
|
+
help="Output format.",
|
|
62
|
+
)
|
|
63
|
+
@click.argument("command", nargs=-1, required=True)
|
|
64
|
+
def run_cmd(allowlist: str | None, fmt: str, command: tuple[str, ...]) -> None:
|
|
65
|
+
"""Trace COMMAND under strace and report network violations."""
|
|
66
|
+
try:
|
|
67
|
+
runner = StraceRunner()
|
|
68
|
+
except StraceNotFoundError as exc:
|
|
69
|
+
click.echo(f"netaudit: {exc}", err=True)
|
|
70
|
+
sys.exit(_EXIT_STRACE_MISSING)
|
|
71
|
+
|
|
72
|
+
al = _load_allowlist(allowlist)
|
|
73
|
+
|
|
74
|
+
with tempfile.NamedTemporaryFile(suffix=".strace", delete=False) as tf:
|
|
75
|
+
strace_out = Path(tf.name)
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
runner.run(list(command), strace_out)
|
|
79
|
+
events = StraceParser().parse_stream(strace_out.read_text().splitlines())
|
|
80
|
+
violations = Reporter.check(events, al)
|
|
81
|
+
_emit(violations, fmt)
|
|
82
|
+
sys.exit(_EXIT_VIOLATIONS if violations else _EXIT_CLEAN)
|
|
83
|
+
finally:
|
|
84
|
+
strace_out.unlink(missing_ok=True)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@main.command("analyze")
|
|
88
|
+
@click.option(
|
|
89
|
+
"--allowlist",
|
|
90
|
+
default=None,
|
|
91
|
+
metavar="YAML",
|
|
92
|
+
help=f"Allowlist file (default: {_DEFAULT_ALLOWLIST} in cwd if present).",
|
|
93
|
+
)
|
|
94
|
+
@click.option(
|
|
95
|
+
"--format",
|
|
96
|
+
"fmt",
|
|
97
|
+
type=click.Choice(["text", "json"]),
|
|
98
|
+
default="text",
|
|
99
|
+
show_default=True,
|
|
100
|
+
help="Output format.",
|
|
101
|
+
)
|
|
102
|
+
@click.argument("strace_log", type=click.Path(exists=True, dir_okay=False))
|
|
103
|
+
def analyze_cmd(allowlist: str | None, fmt: str, strace_log: str) -> None:
|
|
104
|
+
"""Analyze an existing strace log file for network violations."""
|
|
105
|
+
al = _load_allowlist(allowlist)
|
|
106
|
+
events = StraceParser().parse_stream(Path(strace_log).read_text().splitlines())
|
|
107
|
+
violations = Reporter.check(events, al)
|
|
108
|
+
_emit(violations, fmt)
|
|
109
|
+
sys.exit(_EXIT_VIOLATIONS if violations else _EXIT_CLEAN)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Framework-specific integrations for netaudit."""
|
netaudit/parser.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""strace output parser — produces ConnectEvent dataclasses from raw lines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Iterable
|
|
8
|
+
|
|
9
|
+
# ---------------------------------------------------------------------------
|
|
10
|
+
# Regexes
|
|
11
|
+
# ---------------------------------------------------------------------------
|
|
12
|
+
|
|
13
|
+
# Matches a complete connect() line, e.g.:
|
|
14
|
+
# PID TS connect(fd, {sa_family=AF_INET, sin_addr=inet_addr("1.2.3.4"),
|
|
15
|
+
# sin_port=htons(443)}, 16) = -1 EINPROGRESS (...)
|
|
16
|
+
# PID TS connect(fd, {sa_family=AF_UNIX, sun_path="/run/foo.sock"}, 20) = 0
|
|
17
|
+
# PID TS connect(fd, {sa_family=AF_NETLINK, ...}, 12) = 0
|
|
18
|
+
_HEADER = r"(?P<pid>\d+)\s+(?P<ts>\d+:\d+:\d+\.\d+)\s+"
|
|
19
|
+
_RESULT = r"\)\s*=\s*(?P<result>-?\d+)"
|
|
20
|
+
|
|
21
|
+
_RE_INET = re.compile(
|
|
22
|
+
_HEADER
|
|
23
|
+
+ r"connect\(\d+,\s*\{sa_family=(?P<family>AF_INET),(?P<struct>[^}]*)\}"
|
|
24
|
+
+ r".*?"
|
|
25
|
+
+ _RESULT,
|
|
26
|
+
)
|
|
27
|
+
# Field extractors for AF_INET struct — order varies across strace versions
|
|
28
|
+
_RE_INET_ADDR = re.compile(r'sin_addr=inet_addr\("(?P<addr>[^"]+)"\)')
|
|
29
|
+
_RE_INET_PORT = re.compile(r"sin_port=htons\((?P<port>\d+)\)")
|
|
30
|
+
|
|
31
|
+
_RE_INET6 = re.compile(
|
|
32
|
+
_HEADER
|
|
33
|
+
+ r"connect\(\d+,\s*\{sa_family=(?P<family>AF_INET6),(?P<struct>[^}]*)\}"
|
|
34
|
+
+ r".*?"
|
|
35
|
+
+ _RESULT,
|
|
36
|
+
)
|
|
37
|
+
# Field extractors for AF_INET6 struct — order varies across strace versions
|
|
38
|
+
_RE_INET6_ADDR = re.compile(r'sin6_addr=inet_pton\(AF_INET6,\s*"(?P<addr>[^"]+)"\)')
|
|
39
|
+
_RE_INET6_PORT = re.compile(r"sin6_port=htons\((?P<port>\d+)\)")
|
|
40
|
+
|
|
41
|
+
_RE_UNIX = re.compile(
|
|
42
|
+
_HEADER
|
|
43
|
+
+ r'connect\(\d+,\s*\{sa_family=(?P<family>AF_UNIX),\s*sun_path="(?P<path>[^"]+)"'
|
|
44
|
+
+ r".*?"
|
|
45
|
+
+ _RESULT,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# AF_UNIX abstract namespace: sun_path=@"..." or sun_path="\0..."
|
|
49
|
+
_RE_UNIX_ABSTRACT = re.compile(
|
|
50
|
+
_HEADER
|
|
51
|
+
+ r"connect\(\d+,\s*\{sa_family=(?P<family>AF_UNIX),\s*sun_path=@?\"(?P<path>[^\"]+)\""
|
|
52
|
+
+ r".*?"
|
|
53
|
+
+ _RESULT,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
_RE_NETLINK = re.compile(
|
|
57
|
+
_HEADER + r"connect\(\d+,\s*\{sa_family=(?P<family>AF_NETLINK)" + r".*?" + _RESULT,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Resumed lines: "12345 12:34:56.789 <... connect resumed>) = 0"
|
|
61
|
+
_RE_RESUMED = re.compile(
|
|
62
|
+
r"(?P<pid>\d+)\s+(?P<ts>\d+:\d+:\d+\.\d+)\s+<\.\.\.\s+connect\s+resumed>" + r".*?" + _RESULT,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _normalise_result(result: int, raw_line: str) -> int:
|
|
67
|
+
"""Return 0 for EINPROGRESS (non-blocking connect in flight), else result."""
|
|
68
|
+
if result == -1 and "EINPROGRESS" in raw_line:
|
|
69
|
+
return 0
|
|
70
|
+
return result
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _parse_ts(ts: str) -> float:
|
|
74
|
+
"""Convert HH:MM:SS.ffffff to seconds-since-midnight float."""
|
|
75
|
+
h, m, rest = ts.split(":")
|
|
76
|
+
return int(h) * 3600 + int(m) * 60 + float(rest)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ---------------------------------------------------------------------------
|
|
80
|
+
# Data type
|
|
81
|
+
# ---------------------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class ConnectEvent:
|
|
86
|
+
pid: int
|
|
87
|
+
timestamp: float
|
|
88
|
+
family: str
|
|
89
|
+
addr: str | None # IP address or socket path; None for netlink
|
|
90
|
+
port: int | None # TCP/UDP port; None for unix/netlink
|
|
91
|
+
result: int # 0 = success; negative errno value
|
|
92
|
+
raw_line: str
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
# ---------------------------------------------------------------------------
|
|
96
|
+
# Parser
|
|
97
|
+
# ---------------------------------------------------------------------------
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class StraceParser:
|
|
101
|
+
"""Parse strace -e trace=connect -tt -f output into ConnectEvents."""
|
|
102
|
+
|
|
103
|
+
def parse_line(self, line: str) -> ConnectEvent | None:
|
|
104
|
+
"""Return a ConnectEvent for *line*, or None if unrecognised."""
|
|
105
|
+
line = line.rstrip()
|
|
106
|
+
|
|
107
|
+
# Skip unfinished lines (the resumed counterpart carries the result)
|
|
108
|
+
if "<unfinished ...>" in line:
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
# Resumed lines — we can extract pid/ts/result but not family/addr
|
|
112
|
+
m = _RE_RESUMED.match(line)
|
|
113
|
+
if m:
|
|
114
|
+
return ConnectEvent(
|
|
115
|
+
pid=int(m.group("pid")),
|
|
116
|
+
timestamp=_parse_ts(m.group("ts")),
|
|
117
|
+
family="AF_UNKNOWN",
|
|
118
|
+
addr=None,
|
|
119
|
+
port=None,
|
|
120
|
+
result=int(m.group("result")),
|
|
121
|
+
raw_line=line,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# AF_INET — extract addr/port from struct body (field order varies by strace version)
|
|
125
|
+
m = _RE_INET.match(line)
|
|
126
|
+
if m:
|
|
127
|
+
struct = m.group("struct")
|
|
128
|
+
addr_m = _RE_INET_ADDR.search(struct)
|
|
129
|
+
port_m = _RE_INET_PORT.search(struct)
|
|
130
|
+
if addr_m and port_m:
|
|
131
|
+
return ConnectEvent(
|
|
132
|
+
pid=int(m.group("pid")),
|
|
133
|
+
timestamp=_parse_ts(m.group("ts")),
|
|
134
|
+
family=m.group("family"),
|
|
135
|
+
addr=addr_m.group("addr"),
|
|
136
|
+
port=int(port_m.group("port")),
|
|
137
|
+
result=_normalise_result(int(m.group("result")), line),
|
|
138
|
+
raw_line=line,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# AF_INET6 — extract addr/port from struct body (field order varies by strace version)
|
|
142
|
+
m = _RE_INET6.match(line)
|
|
143
|
+
if m:
|
|
144
|
+
struct = m.group("struct")
|
|
145
|
+
addr_m6 = _RE_INET6_ADDR.search(struct)
|
|
146
|
+
port_m6 = _RE_INET6_PORT.search(struct)
|
|
147
|
+
if addr_m6 and port_m6:
|
|
148
|
+
return ConnectEvent(
|
|
149
|
+
pid=int(m.group("pid")),
|
|
150
|
+
timestamp=_parse_ts(m.group("ts")),
|
|
151
|
+
family=m.group("family"),
|
|
152
|
+
addr=addr_m6.group("addr"),
|
|
153
|
+
port=int(port_m6.group("port")),
|
|
154
|
+
result=_normalise_result(int(m.group("result")), line),
|
|
155
|
+
raw_line=line,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
# AF_UNIX (named path)
|
|
159
|
+
m = _RE_UNIX.match(line)
|
|
160
|
+
if m:
|
|
161
|
+
return ConnectEvent(
|
|
162
|
+
pid=int(m.group("pid")),
|
|
163
|
+
timestamp=_parse_ts(m.group("ts")),
|
|
164
|
+
family=m.group("family"),
|
|
165
|
+
addr=m.group("path"),
|
|
166
|
+
port=None,
|
|
167
|
+
result=int(m.group("result")),
|
|
168
|
+
raw_line=line,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# AF_NETLINK
|
|
172
|
+
m = _RE_NETLINK.match(line)
|
|
173
|
+
if m:
|
|
174
|
+
return ConnectEvent(
|
|
175
|
+
pid=int(m.group("pid")),
|
|
176
|
+
timestamp=_parse_ts(m.group("ts")),
|
|
177
|
+
family=m.group("family"),
|
|
178
|
+
addr=None,
|
|
179
|
+
port=None,
|
|
180
|
+
result=int(m.group("result")),
|
|
181
|
+
raw_line=line,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
def parse_stream(self, lines: Iterable[str]) -> list[ConnectEvent]:
|
|
187
|
+
"""Parse all lines, returning only recognised ConnectEvents."""
|
|
188
|
+
events: list[ConnectEvent] = []
|
|
189
|
+
for line in lines:
|
|
190
|
+
event = self.parse_line(line)
|
|
191
|
+
if event is not None:
|
|
192
|
+
events.append(event)
|
|
193
|
+
return events
|
netaudit/py.typed
ADDED
|
File without changes
|
netaudit/reporter.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Violation grouping and human-readable reporting."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, TextIO
|
|
9
|
+
|
|
10
|
+
from netaudit.allowlist import AllowList
|
|
11
|
+
from netaudit.parser import ConnectEvent
|
|
12
|
+
|
|
13
|
+
# ---------------------------------------------------------------------------
|
|
14
|
+
# Violation
|
|
15
|
+
# ---------------------------------------------------------------------------
|
|
16
|
+
|
|
17
|
+
_ViolationKey = tuple[str, str | None, int | None]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Violation:
|
|
22
|
+
family: str
|
|
23
|
+
addr: str | None
|
|
24
|
+
port: int | None
|
|
25
|
+
pids: set[int] = field(default_factory=set)
|
|
26
|
+
count: int = 0
|
|
27
|
+
first_timestamp: float = 0.0
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def key(self) -> _ViolationKey:
|
|
31
|
+
return (self.family, self.addr, self.port)
|
|
32
|
+
|
|
33
|
+
def _addr_str(self) -> str:
|
|
34
|
+
if self.addr is None:
|
|
35
|
+
return "<unknown>"
|
|
36
|
+
if self.port is not None:
|
|
37
|
+
return f"{self.addr}:{self.port}"
|
|
38
|
+
return self.addr
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
pids_str = ", ".join(str(p) for p in sorted(self.pids))
|
|
42
|
+
return f"{self.family} {self._addr_str()} (count={self.count}, pids=[{pids_str}])"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
# Reporter
|
|
47
|
+
# ---------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Reporter:
|
|
51
|
+
@staticmethod
|
|
52
|
+
def check(events: list[ConnectEvent], allowlist: AllowList) -> list[Violation]:
|
|
53
|
+
"""Return violations — events not matched by any allowlist rule."""
|
|
54
|
+
violations: dict[_ViolationKey, Violation] = {}
|
|
55
|
+
for event in events:
|
|
56
|
+
if allowlist.is_allowed(event):
|
|
57
|
+
continue
|
|
58
|
+
key: _ViolationKey = (event.family, event.addr, event.port)
|
|
59
|
+
if key not in violations:
|
|
60
|
+
violations[key] = Violation(
|
|
61
|
+
family=event.family,
|
|
62
|
+
addr=event.addr,
|
|
63
|
+
port=event.port,
|
|
64
|
+
first_timestamp=event.timestamp,
|
|
65
|
+
)
|
|
66
|
+
v = violations[key]
|
|
67
|
+
v.pids.add(event.pid)
|
|
68
|
+
v.count += 1
|
|
69
|
+
return list(violations.values())
|
|
70
|
+
|
|
71
|
+
@staticmethod
|
|
72
|
+
def format(violations: list[Violation], stream: TextIO | None = None) -> str:
|
|
73
|
+
"""Render violations as a human-readable box. Returns the string and
|
|
74
|
+
optionally writes it to *stream*."""
|
|
75
|
+
buf = io.StringIO()
|
|
76
|
+
if not violations:
|
|
77
|
+
buf.write("netaudit: no violations\n")
|
|
78
|
+
else:
|
|
79
|
+
count = len(violations)
|
|
80
|
+
noun = "violation" if count == 1 else "violations"
|
|
81
|
+
border = "=" * 60
|
|
82
|
+
buf.write(f"\n{border}\n")
|
|
83
|
+
buf.write(f" netaudit: {count} {noun} detected\n")
|
|
84
|
+
buf.write(f"{border}\n")
|
|
85
|
+
for v in violations:
|
|
86
|
+
buf.write(f" {v}\n")
|
|
87
|
+
buf.write(f"{border}\n\n")
|
|
88
|
+
|
|
89
|
+
result = buf.getvalue()
|
|
90
|
+
if stream is not None:
|
|
91
|
+
stream.write(result)
|
|
92
|
+
return result
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def format_json(violations: list[Violation]) -> str:
|
|
96
|
+
"""Render violations as a JSON string."""
|
|
97
|
+
data: dict[str, Any] = {
|
|
98
|
+
"violations": [
|
|
99
|
+
{
|
|
100
|
+
"family": v.family,
|
|
101
|
+
"addr": v.addr,
|
|
102
|
+
"port": v.port,
|
|
103
|
+
"count": v.count,
|
|
104
|
+
"pids": sorted(v.pids),
|
|
105
|
+
}
|
|
106
|
+
for v in violations
|
|
107
|
+
],
|
|
108
|
+
"summary": {"total": len(violations)},
|
|
109
|
+
}
|
|
110
|
+
return json.dumps(data, indent=2)
|
netaudit/runner.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""strace subprocess runner — spawns a command under strace and captures output."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class StraceNotFoundError(RuntimeError):
|
|
11
|
+
"""Raised when strace is not available on PATH."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _strace_cmd(output_path: Path) -> list[str]:
|
|
15
|
+
return ["strace", "-e", "trace=connect", "-f", "-tt", "-o", str(output_path)]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StraceProcess:
|
|
19
|
+
"""Handle to a running strace-wrapped process."""
|
|
20
|
+
|
|
21
|
+
def __init__(self, proc: subprocess.Popen[bytes]) -> None:
|
|
22
|
+
self._proc = proc
|
|
23
|
+
|
|
24
|
+
def stop(self) -> subprocess.CompletedProcess[bytes]:
|
|
25
|
+
"""Wait for the process to finish and return a CompletedProcess."""
|
|
26
|
+
stdout, stderr = self._proc.communicate()
|
|
27
|
+
return subprocess.CompletedProcess(
|
|
28
|
+
args=self._proc.args,
|
|
29
|
+
returncode=self._proc.returncode,
|
|
30
|
+
stdout=stdout,
|
|
31
|
+
stderr=stderr,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class StraceRunner:
|
|
36
|
+
"""Spawns commands under strace, writing connect() events to a file."""
|
|
37
|
+
|
|
38
|
+
def __init__(self) -> None:
|
|
39
|
+
if shutil.which("strace") is None:
|
|
40
|
+
raise StraceNotFoundError(
|
|
41
|
+
"strace not found on PATH; install it (e.g. apt install strace)"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def run(self, command: list[str], output_path: Path) -> subprocess.CompletedProcess[bytes]:
|
|
45
|
+
"""Run *command* under strace, blocking until it exits.
|
|
46
|
+
|
|
47
|
+
strace output is written to *output_path*; stdout/stderr of the wrapped
|
|
48
|
+
command are captured and returned in the CompletedProcess.
|
|
49
|
+
"""
|
|
50
|
+
return subprocess.run(
|
|
51
|
+
_strace_cmd(output_path) + command,
|
|
52
|
+
capture_output=True,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def start(self, command: list[str], output_path: Path) -> StraceProcess:
|
|
56
|
+
"""Spawn *command* under strace and return immediately.
|
|
57
|
+
|
|
58
|
+
Call `.stop()` on the returned :class:`StraceProcess` to wait for
|
|
59
|
+
completion and retrieve the result.
|
|
60
|
+
"""
|
|
61
|
+
proc: subprocess.Popen[bytes] = subprocess.Popen(
|
|
62
|
+
_strace_cmd(output_path) + command,
|
|
63
|
+
stdout=subprocess.PIPE,
|
|
64
|
+
stderr=subprocess.PIPE,
|
|
65
|
+
)
|
|
66
|
+
return StraceProcess(proc)
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netaudit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: CI-native network egress auditing via strace
|
|
5
|
+
Project-URL: Homepage, https://github.com/CyberSecAuto-Labs/netaudit
|
|
6
|
+
Project-URL: Documentation, https://netaudit.readthedocs.io
|
|
7
|
+
Author: CyberSecAuto-Labs
|
|
8
|
+
License: Apache License
|
|
9
|
+
Version 2.0, January 2004
|
|
10
|
+
http://www.apache.org/licenses/
|
|
11
|
+
|
|
12
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
13
|
+
|
|
14
|
+
1. Definitions.
|
|
15
|
+
|
|
16
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
17
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
18
|
+
|
|
19
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
20
|
+
the copyright owner that is granting the License.
|
|
21
|
+
|
|
22
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
23
|
+
other entities that control, are controlled by, or are under common
|
|
24
|
+
control with that entity. For the purposes of this definition,
|
|
25
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
26
|
+
direction or management of such entity, whether by contract or
|
|
27
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
28
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
29
|
+
|
|
30
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
31
|
+
exercising permissions granted by this License.
|
|
32
|
+
|
|
33
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
34
|
+
including but not limited to software source code, documentation
|
|
35
|
+
source, and configuration files.
|
|
36
|
+
|
|
37
|
+
"Object" form shall mean any form resulting from mechanical
|
|
38
|
+
transformation or translation of a Source form, including but
|
|
39
|
+
not limited to compiled object code, generated documentation,
|
|
40
|
+
and conversions to other media types.
|
|
41
|
+
|
|
42
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
43
|
+
Object form, made available under the License, as indicated by a
|
|
44
|
+
copyright notice that is included in or attached to the work
|
|
45
|
+
(an example is provided in the Appendix below).
|
|
46
|
+
|
|
47
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
48
|
+
form, that is based on (or derived from) the Work and for which the
|
|
49
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
50
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
51
|
+
of this License, Derivative Works shall not include works that remain
|
|
52
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
53
|
+
the Work and Derivative Works thereof.
|
|
54
|
+
|
|
55
|
+
"Contribution" shall mean any work of authorship, including
|
|
56
|
+
the original version of the Work and any modifications or additions
|
|
57
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
58
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
59
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
60
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
61
|
+
means any form of electronic, verbal, or written communication sent
|
|
62
|
+
to the Licensor or its representatives, including but not limited to
|
|
63
|
+
communication on electronic mailing lists, source code control systems,
|
|
64
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
65
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
66
|
+
excluding communication that is conspicuously marked or otherwise
|
|
67
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
68
|
+
|
|
69
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
70
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
71
|
+
subsequently incorporated within the Work.
|
|
72
|
+
|
|
73
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
77
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
78
|
+
Work and such Derivative Works in Source or Object form.
|
|
79
|
+
|
|
80
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
81
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
82
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
83
|
+
(except as stated in this section) patent license to make, have made,
|
|
84
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
85
|
+
where such license applies only to those patent claims licensable
|
|
86
|
+
by such Contributor that are necessarily infringed by their
|
|
87
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
88
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
89
|
+
institute patent litigation against any entity (including a
|
|
90
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
91
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
92
|
+
or contributory patent infringement, then any patent licenses
|
|
93
|
+
granted to You under this License for that Work shall terminate
|
|
94
|
+
as of the date such litigation is filed.
|
|
95
|
+
|
|
96
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
97
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
98
|
+
modifications, and in Source or Object form, provided that You
|
|
99
|
+
meet the following conditions:
|
|
100
|
+
|
|
101
|
+
(a) You must give any other recipients of the Work or
|
|
102
|
+
Derivative Works a copy of this License; and
|
|
103
|
+
|
|
104
|
+
(b) You must cause any modified files to carry prominent notices
|
|
105
|
+
stating that You changed the files; and
|
|
106
|
+
|
|
107
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
108
|
+
that You distribute, all copyright, patent, trademark, and
|
|
109
|
+
attribution notices from the Source form of the Work,
|
|
110
|
+
excluding those notices that do not pertain to any part of
|
|
111
|
+
the Derivative Works; and
|
|
112
|
+
|
|
113
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
114
|
+
distribution, then any Derivative Works that You distribute must
|
|
115
|
+
include a readable copy of the attribution notices contained
|
|
116
|
+
within such NOTICE file, excluding those notices that do not
|
|
117
|
+
pertain to any part of the Derivative Works, in at least one
|
|
118
|
+
of the following places: within a NOTICE text file distributed
|
|
119
|
+
as part of the Derivative Works; within the Source form or
|
|
120
|
+
documentation, if provided along with the Derivative Works; or,
|
|
121
|
+
within a display generated by the Derivative Works, if and
|
|
122
|
+
wherever such third-party notices normally appear. The contents
|
|
123
|
+
of the NOTICE file are for informational purposes only and
|
|
124
|
+
do not modify the License. You may add Your own attribution
|
|
125
|
+
notices within Derivative Works that You distribute, alongside
|
|
126
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
127
|
+
that such additional attribution notices cannot be construed
|
|
128
|
+
as modifying the License.
|
|
129
|
+
|
|
130
|
+
You may add Your own copyright statement to Your modifications and
|
|
131
|
+
may provide additional or different license terms and conditions
|
|
132
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
133
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
134
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
135
|
+
the conditions stated in this License.
|
|
136
|
+
|
|
137
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
138
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
139
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
140
|
+
this License, without any additional terms or conditions.
|
|
141
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
142
|
+
the terms of any separate license agreement you may have executed
|
|
143
|
+
with Licensor regarding such Contributions.
|
|
144
|
+
|
|
145
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
146
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
147
|
+
except as required for reasonable and customary use in describing the
|
|
148
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
149
|
+
|
|
150
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
151
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
152
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
153
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
154
|
+
implied, including, without limitation, any warranties or conditions
|
|
155
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
156
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
157
|
+
appropriateness of using or redistributing the Work and assume any
|
|
158
|
+
risks associated with Your exercise of permissions under this License.
|
|
159
|
+
|
|
160
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
161
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
162
|
+
unless required by applicable law (such as deliberate and grossly
|
|
163
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
164
|
+
liable to You for damages, including any direct, indirect, special,
|
|
165
|
+
incidental, or consequential damages of any character arising as a
|
|
166
|
+
result of this License or out of the use or inability to use the
|
|
167
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
168
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
169
|
+
other commercial damages or losses), even if such Contributor
|
|
170
|
+
has been advised of the possibility of such damages.
|
|
171
|
+
|
|
172
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
173
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
174
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
175
|
+
or other liability obligations and/or rights consistent with this
|
|
176
|
+
License. However, in accepting such obligations, You may act only
|
|
177
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
178
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
179
|
+
defend, and hold each Contributor harmless for any liability
|
|
180
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
181
|
+
of your accepting any such warranty or additional liability.
|
|
182
|
+
|
|
183
|
+
END OF TERMS AND CONDITIONS
|
|
184
|
+
|
|
185
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
186
|
+
|
|
187
|
+
To apply the Apache License to your work, attach the following
|
|
188
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
189
|
+
replaced with your own identifying information. (Don't include
|
|
190
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
191
|
+
comment syntax for the file format. We also recommend that a
|
|
192
|
+
file or class name and description of purpose be included on the
|
|
193
|
+
same "printed page" as the copyright notice for easier
|
|
194
|
+
identification within third-party archives.
|
|
195
|
+
|
|
196
|
+
Copyright [yyyy] [name of copyright owner]
|
|
197
|
+
|
|
198
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
199
|
+
you may not use this file except in compliance with the License.
|
|
200
|
+
You may obtain a copy of the License at
|
|
201
|
+
|
|
202
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
203
|
+
|
|
204
|
+
Unless required by applicable law or agreed to in writing, software
|
|
205
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
206
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
207
|
+
See the License for the specific language governing permissions and
|
|
208
|
+
limitations under the License.
|
|
209
|
+
License-File: LICENSE
|
|
210
|
+
Keywords: auditing,ci,network,security,strace
|
|
211
|
+
Classifier: Development Status :: 4 - Beta
|
|
212
|
+
Classifier: Environment :: Console
|
|
213
|
+
Classifier: Intended Audience :: Developers
|
|
214
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
215
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
216
|
+
Classifier: Programming Language :: Python :: 3
|
|
217
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
218
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
219
|
+
Classifier: Topic :: Security
|
|
220
|
+
Classifier: Topic :: Software Development :: Testing
|
|
221
|
+
Requires-Python: >=3.11
|
|
222
|
+
Requires-Dist: click>=8.0
|
|
223
|
+
Requires-Dist: pyyaml>=6.0
|
|
224
|
+
Provides-Extra: dev
|
|
225
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
226
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
227
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
228
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
229
|
+
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
|
|
230
|
+
Provides-Extra: docs
|
|
231
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
232
|
+
Description-Content-Type: text/markdown
|
|
233
|
+
|
|
234
|
+
# netaudit
|
|
235
|
+
|
|
236
|
+
[](https://github.com/CyberSecAuto-Labs/netaudit/actions/workflows/ci.yml)
|
|
237
|
+
[](https://pypi.org/project/netaudit/)
|
|
238
|
+
[](https://pypi.org/project/netaudit/)
|
|
239
|
+
[](LICENSE)
|
|
240
|
+
|
|
241
|
+
CI-native network egress auditing via strace. Wrap any process or test suite, declare what connections are allowed, get pass/fail — no raw strace noise.
|
|
242
|
+
|
|
243
|
+
## Install
|
|
244
|
+
|
|
245
|
+
```bash
|
|
246
|
+
pip install netaudit
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
**Requires `strace`** (Linux only):
|
|
250
|
+
|
|
251
|
+
```bash
|
|
252
|
+
sudo apt-get install strace # Debian/Ubuntu
|
|
253
|
+
sudo dnf install strace # RHEL/Fedora
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
## Quick start
|
|
257
|
+
|
|
258
|
+
1. Create `netaudit.yaml` in your project root:
|
|
259
|
+
|
|
260
|
+
```yaml
|
|
261
|
+
version: 1
|
|
262
|
+
allowlist:
|
|
263
|
+
- comment: "Internal API"
|
|
264
|
+
family: AF_INET
|
|
265
|
+
addr: 10.0.0.1
|
|
266
|
+
port: 8080
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
2. Run:
|
|
270
|
+
|
|
271
|
+
```bash
|
|
272
|
+
# Trace pytest (or any command) and fail on unexpected connections
|
|
273
|
+
netaudit run -- pytest
|
|
274
|
+
|
|
275
|
+
# Offline analysis of an existing strace log
|
|
276
|
+
netaudit analyze /tmp/trace.log
|
|
277
|
+
|
|
278
|
+
# Machine-readable output for CI artifacts
|
|
279
|
+
netaudit run --format json -- make test
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
**Exit codes:** `0` clean · `1` violations · `2` strace not found
|
|
283
|
+
|
|
284
|
+
## Documentation
|
|
285
|
+
|
|
286
|
+
Full docs at **[netaudit.readthedocs.io](https://netaudit.readthedocs.io)**:
|
|
287
|
+
|
|
288
|
+
- [CLI Reference](docs/cli-reference.md)
|
|
289
|
+
- [Allowlist DSL](docs/allowlist-dsl.md)
|
|
290
|
+
- [Architecture](docs/architecture.md)
|
|
291
|
+
|
|
292
|
+
## How it works
|
|
293
|
+
|
|
294
|
+
`netaudit run` spawns your command under `strace -e trace=connect -f -tt`, parses every `connect()` syscall, and checks each against your allowlist. Built-in rules automatically permit loopback, Unix sockets, and AF_NETLINK — you only need to list external destinations.
|
|
295
|
+
|
|
296
|
+
## Development
|
|
297
|
+
|
|
298
|
+
```bash
|
|
299
|
+
python3.11 -m venv .venv
|
|
300
|
+
.venv/bin/pip install -e ".[dev]"
|
|
301
|
+
.venv/bin/pytest
|
|
302
|
+
```
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
netaudit/__init__.py,sha256=eAEhAYXPLjs-9WNvDBUJ1ujxwCR5wnp15W2AxVAtKeo,88
|
|
2
|
+
netaudit/allowlist.py,sha256=7dM9QftkTNkZz553tWtY5L-UC7i1hfsKiy7YGtzIS-M,4226
|
|
3
|
+
netaudit/cli.py,sha256=CXYKxVY7GDRDSulLlu-18ahhOaIaLYWGELVGaAC6zl8,3127
|
|
4
|
+
netaudit/parser.py,sha256=jmOygJCtt9JAOAsXhrjemdmJ7tbv8lhvHT7KO6C_T38,6705
|
|
5
|
+
netaudit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
netaudit/reporter.py,sha256=KQ_zP53ygEdcBVFsKsQLbDDRedTIe_bbV2cJvnFBm_c,3571
|
|
7
|
+
netaudit/runner.py,sha256=P12iW5BiRmeP3Vi7GouPSyEWO7fTH4yHK7_3QW4TItA,2198
|
|
8
|
+
netaudit/integrations/__init__.py,sha256=DN5h_PFPuzgrnQ3fyZj3l0BwCZ51HE5p90Q_rlXKQE8,52
|
|
9
|
+
netaudit-0.1.0.dist-info/METADATA,sha256=zTA65Ja1a_JDXN__OqA0d3OOD5qpY4QCp5_-1ZP4wcQ,16126
|
|
10
|
+
netaudit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
11
|
+
netaudit-0.1.0.dist-info/entry_points.txt,sha256=-zs0bJqJLRYpgAuuuFTnmZZjEGNqqBr6k3uYqesW3Uo,47
|
|
12
|
+
netaudit-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
13
|
+
netaudit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|