gamai-tripwire 0.1.0__tar.gz
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.
- gamai_tripwire-0.1.0/LICENSE +21 -0
- gamai_tripwire-0.1.0/MANIFEST.in +3 -0
- gamai_tripwire-0.1.0/PKG-INFO +134 -0
- gamai_tripwire-0.1.0/README.md +115 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/PKG-INFO +134 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/SOURCES.txt +16 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/dependency_links.txt +1 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/entry_points.txt +3 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/requires.txt +1 -0
- gamai_tripwire-0.1.0/gamai_tripwire.egg-info/top_level.txt +1 -0
- gamai_tripwire-0.1.0/pyproject.toml +32 -0
- gamai_tripwire-0.1.0/setup.cfg +4 -0
- gamai_tripwire-0.1.0/tests/test_canary.py +65 -0
- gamai_tripwire-0.1.0/tests/test_detect.py +110 -0
- gamai_tripwire-0.1.0/tripwire/__init__.py +4 -0
- gamai_tripwire-0.1.0/tripwire/canary.py +104 -0
- gamai_tripwire-0.1.0/tripwire/cli.py +80 -0
- gamai_tripwire-0.1.0/tripwire/detect.py +118 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Renato Šuster (GAMA TRADE d.o.o. / gamAI)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gamai-tripwire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Detect an inbound AI agent by behaviour, not blocklists: planted canaries, spec-derived novel paths, tool switching, key probing.
|
|
5
|
+
Author-email: Renato Šuster <renato@gamatrade.ba>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gamai.io/tripwire.html
|
|
8
|
+
Project-URL: Repository, https://github.com/gamai-io/tripwire
|
|
9
|
+
Project-URL: Issues, https://github.com/gamai-io/tripwire/issues
|
|
10
|
+
Keywords: ai-agents,security,detection,canary,honeytoken,access-log
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Security
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: gama-mandate>=0.42
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# gamai-tripwire
|
|
21
|
+
|
|
22
|
+
Detect an **inbound** AI agent by what it does, not by who it claims to be.
|
|
23
|
+
|
|
24
|
+
Built from the November 2026 incident in which an attacker used an open-source
|
|
25
|
+
coding agent, a browser and `curl` against a financial firm: no blocklist
|
|
26
|
+
matched the address, and the only reliable signal was behaviour — a desktop
|
|
27
|
+
browser that switched to a fake phone user-agent, then to `curl`, from one
|
|
28
|
+
address inside a few minutes; a request for a path that existed only inside an
|
|
29
|
+
API document served seconds earlier; the same key, no key and a fabricated key
|
|
30
|
+
tried against one endpoint within seconds.
|
|
31
|
+
|
|
32
|
+
`mandate watch` (in `gama-mandate`) scores those behaviours. This package adds
|
|
33
|
+
the two things an inbound detector needs and an authorisation log cannot give:
|
|
34
|
+
|
|
35
|
+
1. **Planted canaries** — credential-shaped strings that no legitimate client
|
|
36
|
+
ever sends. Any use is decisive on its own.
|
|
37
|
+
2. **Spec-derived novel paths** — a path whose first appearance follows a fetch
|
|
38
|
+
of an API/spec document within 60 s. A person does not go from reading a spec
|
|
39
|
+
to a never-seen endpoint that fast; a script does.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install gamai-tripwire # pulls gama-mandate for the base rules + ledger
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Runs on Python 3.9+, no services, no model, no network calls at analysis time.
|
|
48
|
+
|
|
49
|
+
## Plant canaries
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
tripwire canary generate --count 3 --note "planted in /docs/api.md" --registry canaries.json
|
|
53
|
+
# prints the tokens ONCE; only their sha256 is stored
|
|
54
|
+
tripwire canary list --registry canaries.json
|
|
55
|
+
tripwire check --token tw_xxx --registry canaries.json # exit 0 = planted
|
|
56
|
+
tripwire canary revoke --id 3f9c1a2b4d5e --registry canaries.json
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Put one token in each place an intruder reads: a decoy API document, a sample
|
|
60
|
+
`.env`, a runbook, a Git history you know is scraped. A leaked registry does not
|
|
61
|
+
leak the tokens, so an attacker cannot learn what to avoid.
|
|
62
|
+
|
|
63
|
+
## Watch an access log
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
tripwire watch --log access.jsonl --registry canaries.json --window 600 \
|
|
67
|
+
--ledger alerts.jsonl --min-level medium
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Exit code `0` = nothing at or above `--min-level`, `1` = something is. Findings
|
|
71
|
+
are appended to the mandate ledger as `{"type":"control","action":"alert"}` in
|
|
72
|
+
the same hash chain as execution receipts, so an alert is evidence too.
|
|
73
|
+
|
|
74
|
+
Log line (JSONL), one per request:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{"ts": 1795558000.1, "ip": "81.2.3.4", "ua": "Mozilla/5.0 ... Chrome/157",
|
|
78
|
+
"method": "GET", "path": "/api/v1/invoices", "status": 200,
|
|
79
|
+
"ua_platform": "desktop", "auth": "key-A", "referer": "/docs/api.md", "query": ""}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`ua_platform` is optional (`desktop`/`mobile`) and is only used for the UA-flip
|
|
83
|
+
rule. nginx with `log_format ... escape=json` maps directly; Envoy's JSON access
|
|
84
|
+
log needs a three-field rename (`@timestamp`, `useragent`, `:path`).
|
|
85
|
+
|
|
86
|
+
## Rules and weights
|
|
87
|
+
|
|
88
|
+
| rule | points | what it sees |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `canary_used` | 10 | a planted key was sent — **critical on its own** |
|
|
91
|
+
| `key_probing` | 4 | 3+ distinct auth values (or none) on one path within 60 s |
|
|
92
|
+
| `tool_switch` | 3 | browser then curl/wget/httpx from one address within 15 min |
|
|
93
|
+
| `docs_link_follow` | 3 | request whose Referer is an API/spec document |
|
|
94
|
+
| `spec_derived_novel_path` | 3 | first request to a path right after a spec fetch |
|
|
95
|
+
| `ua_flip` | 2 | same address claims desktop and mobile within 5 min |
|
|
96
|
+
| `read_after_submit` | 2 | repeated GETs refused by submit-only endpoints |
|
|
97
|
+
| `low_and_slow_scan` | 2 | 10+ paths answering 4xx with a single UA |
|
|
98
|
+
| `velocity` | 1 | 15+ distinct paths in one minute |
|
|
99
|
+
|
|
100
|
+
Levels: `critical` (canary), `high` (>=6), `medium` (>=3), else `low`.
|
|
101
|
+
|
|
102
|
+
## Proof it works on the real timeline
|
|
103
|
+
|
|
104
|
+
`tests/test_detect.py` replays the reported sequence — refused front page, fake
|
|
105
|
+
Android UA 6 s later, API document, path from that document 13 s later, three
|
|
106
|
+
auth values within 4 s, submit-only endpoint read twice — and asserts **high**
|
|
107
|
+
plus the four decisive rules; a canary in the same log makes it **critical**; a
|
|
108
|
+
five-page visitor stays **low**; a quiet log writes nothing to the ledger.
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
python -m pytest -q tests/
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## What this is not
|
|
115
|
+
|
|
116
|
+
- **Not a WAF and not inline.** It reads logs after the fact; it cannot block a
|
|
117
|
+
request by itself. Use its verdict to drive nginx `deny`, an Envoy filter or a
|
|
118
|
+
key suspension — that is a separate change to your edge.
|
|
119
|
+
- **Not TLS-inspecting.** If your edge only logs `CONNECT`, there is nothing to
|
|
120
|
+
score. It needs method, path, status, UA and Referer.
|
|
121
|
+
- **Not a model.** There is no ML in the decision path and no LLM in the loop.
|
|
122
|
+
A judge model may explain a finding; it can never lower one.
|
|
123
|
+
- **Canaries only work if planted** and only if the same token is not used
|
|
124
|
+
legitimately. Treat a canary hit as an incident, not as a percentage.
|
|
125
|
+
- **It will fire on your own scanners and CI** unless you tag or exclude their
|
|
126
|
+
addresses. That is a configuration task, not a bug.
|
|
127
|
+
- **Not compliance.** It produces evidence of a detection attempt; it is not a
|
|
128
|
+
certification, and no number here should be read as one.
|
|
129
|
+
|
|
130
|
+
## Licence
|
|
131
|
+
|
|
132
|
+
MIT. Part of the gamAI control set: `gama-mandate` (signed approval of an
|
|
133
|
+
effect), `gamai-guard` (prompt-injection), `gamai-trust` (claim vs evidence),
|
|
134
|
+
`gamai-plugins` (policy/sandbox), `crossnode-bench` (false success).
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# gamai-tripwire
|
|
2
|
+
|
|
3
|
+
Detect an **inbound** AI agent by what it does, not by who it claims to be.
|
|
4
|
+
|
|
5
|
+
Built from the November 2026 incident in which an attacker used an open-source
|
|
6
|
+
coding agent, a browser and `curl` against a financial firm: no blocklist
|
|
7
|
+
matched the address, and the only reliable signal was behaviour — a desktop
|
|
8
|
+
browser that switched to a fake phone user-agent, then to `curl`, from one
|
|
9
|
+
address inside a few minutes; a request for a path that existed only inside an
|
|
10
|
+
API document served seconds earlier; the same key, no key and a fabricated key
|
|
11
|
+
tried against one endpoint within seconds.
|
|
12
|
+
|
|
13
|
+
`mandate watch` (in `gama-mandate`) scores those behaviours. This package adds
|
|
14
|
+
the two things an inbound detector needs and an authorisation log cannot give:
|
|
15
|
+
|
|
16
|
+
1. **Planted canaries** — credential-shaped strings that no legitimate client
|
|
17
|
+
ever sends. Any use is decisive on its own.
|
|
18
|
+
2. **Spec-derived novel paths** — a path whose first appearance follows a fetch
|
|
19
|
+
of an API/spec document within 60 s. A person does not go from reading a spec
|
|
20
|
+
to a never-seen endpoint that fast; a script does.
|
|
21
|
+
|
|
22
|
+
## Install
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pip install gamai-tripwire # pulls gama-mandate for the base rules + ledger
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Runs on Python 3.9+, no services, no model, no network calls at analysis time.
|
|
29
|
+
|
|
30
|
+
## Plant canaries
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
tripwire canary generate --count 3 --note "planted in /docs/api.md" --registry canaries.json
|
|
34
|
+
# prints the tokens ONCE; only their sha256 is stored
|
|
35
|
+
tripwire canary list --registry canaries.json
|
|
36
|
+
tripwire check --token tw_xxx --registry canaries.json # exit 0 = planted
|
|
37
|
+
tripwire canary revoke --id 3f9c1a2b4d5e --registry canaries.json
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Put one token in each place an intruder reads: a decoy API document, a sample
|
|
41
|
+
`.env`, a runbook, a Git history you know is scraped. A leaked registry does not
|
|
42
|
+
leak the tokens, so an attacker cannot learn what to avoid.
|
|
43
|
+
|
|
44
|
+
## Watch an access log
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
tripwire watch --log access.jsonl --registry canaries.json --window 600 \
|
|
48
|
+
--ledger alerts.jsonl --min-level medium
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Exit code `0` = nothing at or above `--min-level`, `1` = something is. Findings
|
|
52
|
+
are appended to the mandate ledger as `{"type":"control","action":"alert"}` in
|
|
53
|
+
the same hash chain as execution receipts, so an alert is evidence too.
|
|
54
|
+
|
|
55
|
+
Log line (JSONL), one per request:
|
|
56
|
+
|
|
57
|
+
```json
|
|
58
|
+
{"ts": 1795558000.1, "ip": "81.2.3.4", "ua": "Mozilla/5.0 ... Chrome/157",
|
|
59
|
+
"method": "GET", "path": "/api/v1/invoices", "status": 200,
|
|
60
|
+
"ua_platform": "desktop", "auth": "key-A", "referer": "/docs/api.md", "query": ""}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`ua_platform` is optional (`desktop`/`mobile`) and is only used for the UA-flip
|
|
64
|
+
rule. nginx with `log_format ... escape=json` maps directly; Envoy's JSON access
|
|
65
|
+
log needs a three-field rename (`@timestamp`, `useragent`, `:path`).
|
|
66
|
+
|
|
67
|
+
## Rules and weights
|
|
68
|
+
|
|
69
|
+
| rule | points | what it sees |
|
|
70
|
+
|---|---|---|
|
|
71
|
+
| `canary_used` | 10 | a planted key was sent — **critical on its own** |
|
|
72
|
+
| `key_probing` | 4 | 3+ distinct auth values (or none) on one path within 60 s |
|
|
73
|
+
| `tool_switch` | 3 | browser then curl/wget/httpx from one address within 15 min |
|
|
74
|
+
| `docs_link_follow` | 3 | request whose Referer is an API/spec document |
|
|
75
|
+
| `spec_derived_novel_path` | 3 | first request to a path right after a spec fetch |
|
|
76
|
+
| `ua_flip` | 2 | same address claims desktop and mobile within 5 min |
|
|
77
|
+
| `read_after_submit` | 2 | repeated GETs refused by submit-only endpoints |
|
|
78
|
+
| `low_and_slow_scan` | 2 | 10+ paths answering 4xx with a single UA |
|
|
79
|
+
| `velocity` | 1 | 15+ distinct paths in one minute |
|
|
80
|
+
|
|
81
|
+
Levels: `critical` (canary), `high` (>=6), `medium` (>=3), else `low`.
|
|
82
|
+
|
|
83
|
+
## Proof it works on the real timeline
|
|
84
|
+
|
|
85
|
+
`tests/test_detect.py` replays the reported sequence — refused front page, fake
|
|
86
|
+
Android UA 6 s later, API document, path from that document 13 s later, three
|
|
87
|
+
auth values within 4 s, submit-only endpoint read twice — and asserts **high**
|
|
88
|
+
plus the four decisive rules; a canary in the same log makes it **critical**; a
|
|
89
|
+
five-page visitor stays **low**; a quiet log writes nothing to the ledger.
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
python -m pytest -q tests/
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## What this is not
|
|
96
|
+
|
|
97
|
+
- **Not a WAF and not inline.** It reads logs after the fact; it cannot block a
|
|
98
|
+
request by itself. Use its verdict to drive nginx `deny`, an Envoy filter or a
|
|
99
|
+
key suspension — that is a separate change to your edge.
|
|
100
|
+
- **Not TLS-inspecting.** If your edge only logs `CONNECT`, there is nothing to
|
|
101
|
+
score. It needs method, path, status, UA and Referer.
|
|
102
|
+
- **Not a model.** There is no ML in the decision path and no LLM in the loop.
|
|
103
|
+
A judge model may explain a finding; it can never lower one.
|
|
104
|
+
- **Canaries only work if planted** and only if the same token is not used
|
|
105
|
+
legitimately. Treat a canary hit as an incident, not as a percentage.
|
|
106
|
+
- **It will fire on your own scanners and CI** unless you tag or exclude their
|
|
107
|
+
addresses. That is a configuration task, not a bug.
|
|
108
|
+
- **Not compliance.** It produces evidence of a detection attempt; it is not a
|
|
109
|
+
certification, and no number here should be read as one.
|
|
110
|
+
|
|
111
|
+
## Licence
|
|
112
|
+
|
|
113
|
+
MIT. Part of the gamAI control set: `gama-mandate` (signed approval of an
|
|
114
|
+
effect), `gamai-guard` (prompt-injection), `gamai-trust` (claim vs evidence),
|
|
115
|
+
`gamai-plugins` (policy/sandbox), `crossnode-bench` (false success).
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gamai-tripwire
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Detect an inbound AI agent by behaviour, not blocklists: planted canaries, spec-derived novel paths, tool switching, key probing.
|
|
5
|
+
Author-email: Renato Šuster <renato@gamatrade.ba>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://gamai.io/tripwire.html
|
|
8
|
+
Project-URL: Repository, https://github.com/gamai-io/tripwire
|
|
9
|
+
Project-URL: Issues, https://github.com/gamai-io/tripwire/issues
|
|
10
|
+
Keywords: ai-agents,security,detection,canary,honeytoken,access-log
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Security
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: gama-mandate>=0.42
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# gamai-tripwire
|
|
21
|
+
|
|
22
|
+
Detect an **inbound** AI agent by what it does, not by who it claims to be.
|
|
23
|
+
|
|
24
|
+
Built from the November 2026 incident in which an attacker used an open-source
|
|
25
|
+
coding agent, a browser and `curl` against a financial firm: no blocklist
|
|
26
|
+
matched the address, and the only reliable signal was behaviour — a desktop
|
|
27
|
+
browser that switched to a fake phone user-agent, then to `curl`, from one
|
|
28
|
+
address inside a few minutes; a request for a path that existed only inside an
|
|
29
|
+
API document served seconds earlier; the same key, no key and a fabricated key
|
|
30
|
+
tried against one endpoint within seconds.
|
|
31
|
+
|
|
32
|
+
`mandate watch` (in `gama-mandate`) scores those behaviours. This package adds
|
|
33
|
+
the two things an inbound detector needs and an authorisation log cannot give:
|
|
34
|
+
|
|
35
|
+
1. **Planted canaries** — credential-shaped strings that no legitimate client
|
|
36
|
+
ever sends. Any use is decisive on its own.
|
|
37
|
+
2. **Spec-derived novel paths** — a path whose first appearance follows a fetch
|
|
38
|
+
of an API/spec document within 60 s. A person does not go from reading a spec
|
|
39
|
+
to a never-seen endpoint that fast; a script does.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install gamai-tripwire # pulls gama-mandate for the base rules + ledger
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Runs on Python 3.9+, no services, no model, no network calls at analysis time.
|
|
48
|
+
|
|
49
|
+
## Plant canaries
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
tripwire canary generate --count 3 --note "planted in /docs/api.md" --registry canaries.json
|
|
53
|
+
# prints the tokens ONCE; only their sha256 is stored
|
|
54
|
+
tripwire canary list --registry canaries.json
|
|
55
|
+
tripwire check --token tw_xxx --registry canaries.json # exit 0 = planted
|
|
56
|
+
tripwire canary revoke --id 3f9c1a2b4d5e --registry canaries.json
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Put one token in each place an intruder reads: a decoy API document, a sample
|
|
60
|
+
`.env`, a runbook, a Git history you know is scraped. A leaked registry does not
|
|
61
|
+
leak the tokens, so an attacker cannot learn what to avoid.
|
|
62
|
+
|
|
63
|
+
## Watch an access log
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
tripwire watch --log access.jsonl --registry canaries.json --window 600 \
|
|
67
|
+
--ledger alerts.jsonl --min-level medium
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Exit code `0` = nothing at or above `--min-level`, `1` = something is. Findings
|
|
71
|
+
are appended to the mandate ledger as `{"type":"control","action":"alert"}` in
|
|
72
|
+
the same hash chain as execution receipts, so an alert is evidence too.
|
|
73
|
+
|
|
74
|
+
Log line (JSONL), one per request:
|
|
75
|
+
|
|
76
|
+
```json
|
|
77
|
+
{"ts": 1795558000.1, "ip": "81.2.3.4", "ua": "Mozilla/5.0 ... Chrome/157",
|
|
78
|
+
"method": "GET", "path": "/api/v1/invoices", "status": 200,
|
|
79
|
+
"ua_platform": "desktop", "auth": "key-A", "referer": "/docs/api.md", "query": ""}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`ua_platform` is optional (`desktop`/`mobile`) and is only used for the UA-flip
|
|
83
|
+
rule. nginx with `log_format ... escape=json` maps directly; Envoy's JSON access
|
|
84
|
+
log needs a three-field rename (`@timestamp`, `useragent`, `:path`).
|
|
85
|
+
|
|
86
|
+
## Rules and weights
|
|
87
|
+
|
|
88
|
+
| rule | points | what it sees |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `canary_used` | 10 | a planted key was sent — **critical on its own** |
|
|
91
|
+
| `key_probing` | 4 | 3+ distinct auth values (or none) on one path within 60 s |
|
|
92
|
+
| `tool_switch` | 3 | browser then curl/wget/httpx from one address within 15 min |
|
|
93
|
+
| `docs_link_follow` | 3 | request whose Referer is an API/spec document |
|
|
94
|
+
| `spec_derived_novel_path` | 3 | first request to a path right after a spec fetch |
|
|
95
|
+
| `ua_flip` | 2 | same address claims desktop and mobile within 5 min |
|
|
96
|
+
| `read_after_submit` | 2 | repeated GETs refused by submit-only endpoints |
|
|
97
|
+
| `low_and_slow_scan` | 2 | 10+ paths answering 4xx with a single UA |
|
|
98
|
+
| `velocity` | 1 | 15+ distinct paths in one minute |
|
|
99
|
+
|
|
100
|
+
Levels: `critical` (canary), `high` (>=6), `medium` (>=3), else `low`.
|
|
101
|
+
|
|
102
|
+
## Proof it works on the real timeline
|
|
103
|
+
|
|
104
|
+
`tests/test_detect.py` replays the reported sequence — refused front page, fake
|
|
105
|
+
Android UA 6 s later, API document, path from that document 13 s later, three
|
|
106
|
+
auth values within 4 s, submit-only endpoint read twice — and asserts **high**
|
|
107
|
+
plus the four decisive rules; a canary in the same log makes it **critical**; a
|
|
108
|
+
five-page visitor stays **low**; a quiet log writes nothing to the ledger.
|
|
109
|
+
|
|
110
|
+
```bash
|
|
111
|
+
python -m pytest -q tests/
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## What this is not
|
|
115
|
+
|
|
116
|
+
- **Not a WAF and not inline.** It reads logs after the fact; it cannot block a
|
|
117
|
+
request by itself. Use its verdict to drive nginx `deny`, an Envoy filter or a
|
|
118
|
+
key suspension — that is a separate change to your edge.
|
|
119
|
+
- **Not TLS-inspecting.** If your edge only logs `CONNECT`, there is nothing to
|
|
120
|
+
score. It needs method, path, status, UA and Referer.
|
|
121
|
+
- **Not a model.** There is no ML in the decision path and no LLM in the loop.
|
|
122
|
+
A judge model may explain a finding; it can never lower one.
|
|
123
|
+
- **Canaries only work if planted** and only if the same token is not used
|
|
124
|
+
legitimately. Treat a canary hit as an incident, not as a percentage.
|
|
125
|
+
- **It will fire on your own scanners and CI** unless you tag or exclude their
|
|
126
|
+
addresses. That is a configuration task, not a bug.
|
|
127
|
+
- **Not compliance.** It produces evidence of a detection attempt; it is not a
|
|
128
|
+
certification, and no number here should be read as one.
|
|
129
|
+
|
|
130
|
+
## Licence
|
|
131
|
+
|
|
132
|
+
MIT. Part of the gamAI control set: `gama-mandate` (signed approval of an
|
|
133
|
+
effect), `gamai-guard` (prompt-injection), `gamai-trust` (claim vs evidence),
|
|
134
|
+
`gamai-plugins` (policy/sandbox), `crossnode-bench` (false success).
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
README.md
|
|
4
|
+
pyproject.toml
|
|
5
|
+
gamai_tripwire.egg-info/PKG-INFO
|
|
6
|
+
gamai_tripwire.egg-info/SOURCES.txt
|
|
7
|
+
gamai_tripwire.egg-info/dependency_links.txt
|
|
8
|
+
gamai_tripwire.egg-info/entry_points.txt
|
|
9
|
+
gamai_tripwire.egg-info/requires.txt
|
|
10
|
+
gamai_tripwire.egg-info/top_level.txt
|
|
11
|
+
tests/test_canary.py
|
|
12
|
+
tests/test_detect.py
|
|
13
|
+
tripwire/__init__.py
|
|
14
|
+
tripwire/canary.py
|
|
15
|
+
tripwire/cli.py
|
|
16
|
+
tripwire/detect.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gama-mandate>=0.42
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tripwire
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gamai-tripwire"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Detect an inbound AI agent by behaviour, not blocklists: planted canaries, spec-derived novel paths, tool switching, key probing."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{name = "Renato Šuster", email = "renato@gamatrade.ba"}]
|
|
14
|
+
keywords = ["ai-agents", "security", "detection", "canary", "honeytoken", "access-log"]
|
|
15
|
+
dependencies = ["gama-mandate>=0.42"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Topic :: Security",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://gamai.io/tripwire.html"
|
|
24
|
+
Repository = "https://github.com/gamai-io/tripwire"
|
|
25
|
+
Issues = "https://github.com/gamai-io/tripwire/issues"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
tripwire = "tripwire.cli:main"
|
|
29
|
+
gamai-tripwire = "tripwire.cli:main"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools]
|
|
32
|
+
packages = ["tripwire"]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Canary tokens: generated once, stored as hashes, matched from any text."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
import unittest
|
|
8
|
+
|
|
9
|
+
from tripwire import canary
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Generate(unittest.TestCase):
|
|
13
|
+
def test_tokens_are_returned_once_and_only_hashes_stored(self) -> None:
|
|
14
|
+
with tempfile.TemporaryDirectory() as td:
|
|
15
|
+
path = os.path.join(td, "canaries.json")
|
|
16
|
+
res = canary.generate(3, "planted in /docs/api.md", path)
|
|
17
|
+
self.assertEqual(res["count"], 3)
|
|
18
|
+
self.assertEqual(len(set(res["tokens"])), 3)
|
|
19
|
+
raw = open(path, encoding="utf-8").read()
|
|
20
|
+
for token in res["tokens"]:
|
|
21
|
+
self.assertNotIn(token, raw, "the token must never be written to disk")
|
|
22
|
+
data = json.loads(raw)
|
|
23
|
+
self.assertTrue(all(len(c["sha256"]) == 64 for c in data["canaries"]))
|
|
24
|
+
|
|
25
|
+
def test_second_generation_appends(self) -> None:
|
|
26
|
+
with tempfile.TemporaryDirectory() as td:
|
|
27
|
+
path = os.path.join(td, "canaries.json")
|
|
28
|
+
canary.generate(2, path=path)
|
|
29
|
+
res = canary.generate(2, path=path)
|
|
30
|
+
self.assertEqual(res["count"], 4)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Match(unittest.TestCase):
|
|
34
|
+
def test_a_planted_token_is_matched(self) -> None:
|
|
35
|
+
with tempfile.TemporaryDirectory() as td:
|
|
36
|
+
path = os.path.join(td, "canaries.json")
|
|
37
|
+
token = canary.generate(1, path=path)["tokens"][0]
|
|
38
|
+
registry = canary.load(path)
|
|
39
|
+
hits = canary.match("Authorization: Bearer " + token, registry)
|
|
40
|
+
self.assertEqual(len(hits), 1)
|
|
41
|
+
|
|
42
|
+
def test_an_unplanted_token_is_not_matched(self) -> None:
|
|
43
|
+
with tempfile.TemporaryDirectory() as td:
|
|
44
|
+
path = os.path.join(td, "canaries.json")
|
|
45
|
+
canary.generate(1, path=path)
|
|
46
|
+
self.assertEqual(canary.match(canary.PREFIX + "made-up", canary.load(path)), [])
|
|
47
|
+
|
|
48
|
+
def test_missing_registry_matches_nothing(self) -> None:
|
|
49
|
+
self.assertEqual(canary.match("tw_abc", None), [])
|
|
50
|
+
|
|
51
|
+
def test_revoked_canary_stops_matching(self) -> None:
|
|
52
|
+
with tempfile.TemporaryDirectory() as td:
|
|
53
|
+
path = os.path.join(td, "canaries.json")
|
|
54
|
+
token = canary.generate(1, path=path)["tokens"][0]
|
|
55
|
+
cid = canary.load(path)["canaries"][0]["id"]
|
|
56
|
+
canary.revoke(cid, path)
|
|
57
|
+
self.assertEqual(canary.match(token, canary.load(path)), [])
|
|
58
|
+
|
|
59
|
+
def test_candidates_do_not_swallow_punctuation(self) -> None:
|
|
60
|
+
text = "?key=tw_abc-123&next=1"
|
|
61
|
+
self.assertEqual(canary.candidates(text), ["tw_abc-123"])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
unittest.main()
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""The Jesta/OpenCode incident as a regression test, plus the two inbound rules."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import tempfile
|
|
7
|
+
import time
|
|
8
|
+
import unittest
|
|
9
|
+
|
|
10
|
+
from tripwire import canary, detect
|
|
11
|
+
|
|
12
|
+
NOW = 1795558000.0
|
|
13
|
+
DESKTOP = "Mozilla/5.0 (Macintosh) Chrome/157.0"
|
|
14
|
+
PHONE = "Mozilla/5.0 (Linux; Android 15; Pixel 10) Chrome/157.0 Mobile"
|
|
15
|
+
CURL = "curl/8.7.1"
|
|
16
|
+
IP = "81.2.3.4"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def row(ts, ua, path, status=200, method="GET", auth="none", referer="", ip=IP):
|
|
20
|
+
return {"ts": ts, "ip": ip, "ua": ua, "method": method, "path": path,
|
|
21
|
+
"status": status, "auth": auth, "referer": referer,
|
|
22
|
+
"ua_platform": "mobile" if "Mobile" in ua else "desktop"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def incident(auths=("key-A", "none", "made-up")) -> list[dict]:
|
|
26
|
+
t = NOW - 400
|
|
27
|
+
rows = [
|
|
28
|
+
row(t, DESKTOP, "/", 403),
|
|
29
|
+
row(t + 6, PHONE, "/", 403),
|
|
30
|
+
row(t + 11, DESKTOP, "/api/openapi.json", 403),
|
|
31
|
+
row(t + 16, DESKTOP, "/decoy/openapi.md", 200),
|
|
32
|
+
row(t + 29, DESKTOP, "/api/v1/transactions", 200, referer="/decoy/openapi.md"),
|
|
33
|
+
row(t + 40, CURL, "/api/v1/transactions", 401, auth=auths[0]),
|
|
34
|
+
row(t + 42, CURL, "/api/v1/transactions", 401, auth=auths[1]),
|
|
35
|
+
row(t + 44, CURL, "/api/v1/transactions", 401, auth=auths[2]),
|
|
36
|
+
row(t + 60, CURL, "/api/v1/transactions/read", 405),
|
|
37
|
+
row(t + 70, CURL, "/api/v1/transactions/read", 405),
|
|
38
|
+
]
|
|
39
|
+
return rows
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Incident(unittest.TestCase):
|
|
43
|
+
def test_the_incident_scores_high_on_the_base_rules(self) -> None:
|
|
44
|
+
res = detect.analyse(incident(), now=NOW)
|
|
45
|
+
session = res["sessions"][IP]
|
|
46
|
+
rules = {f["rule"] for f in session["findings"]}
|
|
47
|
+
self.assertEqual(session["level"], "high", session)
|
|
48
|
+
self.assertTrue({"tool_switch", "ua_flip", "docs_link_follow",
|
|
49
|
+
"key_probing", "read_after_submit"} <= rules, rules)
|
|
50
|
+
|
|
51
|
+
def test_spec_derived_novel_path_is_flagged(self) -> None:
|
|
52
|
+
res = detect.analyse(incident(), now=NOW)
|
|
53
|
+
paths = [p["path"] for p in res["spec_derived_paths"]]
|
|
54
|
+
self.assertIn("/api/v1/transactions", paths)
|
|
55
|
+
rules = {f["rule"] for f in res["sessions"][IP]["findings"]}
|
|
56
|
+
self.assertIn("spec_derived_novel_path", rules)
|
|
57
|
+
|
|
58
|
+
def test_a_canary_hit_is_critical_on_its_own(self) -> None:
|
|
59
|
+
with tempfile.TemporaryDirectory() as td:
|
|
60
|
+
path = os.path.join(td, "canaries.json")
|
|
61
|
+
token = canary.generate(1, "planted in the decoy API doc", path)["tokens"][0]
|
|
62
|
+
rows = [row(NOW - 30, DESKTOP, "/api/v1/accounts", 200, auth=token)]
|
|
63
|
+
res = detect.analyse(rows, canary.load(path), now=NOW)
|
|
64
|
+
session = res["sessions"][IP]
|
|
65
|
+
self.assertEqual(session["level"], "critical")
|
|
66
|
+
self.assertEqual(len(res["canary_hits"]), 1)
|
|
67
|
+
self.assertIn("canary_used", {f["rule"] for f in session["findings"]})
|
|
68
|
+
|
|
69
|
+
def test_a_benign_visitor_stays_low(self) -> None:
|
|
70
|
+
rows = [row(NOW - 300 + i * 20, DESKTOP, "/pricing") for i in range(5)]
|
|
71
|
+
self.assertEqual(detect.analyse(rows, now=NOW)["sessions"][IP]["level"], "low")
|
|
72
|
+
|
|
73
|
+
def test_reading_a_spec_then_a_known_page_is_not_novel(self) -> None:
|
|
74
|
+
t = NOW - 100
|
|
75
|
+
rows = [row(t, DESKTOP, "/pricing"),
|
|
76
|
+
row(t + 5, DESKTOP, "/docs/api.md"),
|
|
77
|
+
row(t + 10, DESKTOP, "/pricing")]
|
|
78
|
+
# "/pricing" was seen before the document, so it is not spec-derived
|
|
79
|
+
self.assertEqual([p["path"] for p in detect.spec_derived_paths(rows)], [])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Ledger(unittest.TestCase):
|
|
83
|
+
def _write(self, rows: list[dict]) -> str:
|
|
84
|
+
td = tempfile.mkdtemp()
|
|
85
|
+
log = os.path.join(td, "access.jsonl")
|
|
86
|
+
with open(log, "w", encoding="utf-8") as fh:
|
|
87
|
+
for r in rows:
|
|
88
|
+
item = dict(r)
|
|
89
|
+
item["ts"] = time.time() - 60 # inside the default window
|
|
90
|
+
fh.write(json.dumps(item) + "\n")
|
|
91
|
+
return log
|
|
92
|
+
|
|
93
|
+
def test_an_alert_goes_into_the_mandate_chain(self) -> None:
|
|
94
|
+
td = tempfile.mkdtemp()
|
|
95
|
+
ledger = os.path.join(td, "alerts.jsonl")
|
|
96
|
+
res = detect.watch(self._write(incident()), ledger=ledger)
|
|
97
|
+
self.assertEqual(res["flagged"], 1)
|
|
98
|
+
body = json.loads(open(ledger, encoding="utf-8").read().strip().splitlines()[-1])["body"]
|
|
99
|
+
self.assertEqual((body["type"], body["action"]), ("control", "alert"))
|
|
100
|
+
|
|
101
|
+
def test_a_quiet_log_writes_nothing(self) -> None:
|
|
102
|
+
td = tempfile.mkdtemp()
|
|
103
|
+
ledger = os.path.join(td, "alerts.jsonl")
|
|
104
|
+
rows = [row(time.time() - 30 + i, DESKTOP, "/pricing") for i in range(4)]
|
|
105
|
+
detect.watch(self._write(rows), ledger=ledger)
|
|
106
|
+
self.assertFalse(os.path.exists(ledger))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
if __name__ == "__main__":
|
|
110
|
+
unittest.main()
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Canary tokens: keys that should never be used, and the alarm when one is.
|
|
2
|
+
|
|
3
|
+
A canary is a credential-shaped string planted where only a scanner, a confused
|
|
4
|
+
agent or an intruder reading our own docs would find it. Any use is a
|
|
5
|
+
high-signal event: no legitimate client has a reason to send it.
|
|
6
|
+
|
|
7
|
+
The registry stores the SHA-256 of each token, never the token itself, so a
|
|
8
|
+
leaked registry does not hand an attacker the strings that trip the alarm.
|
|
9
|
+
Tokens are printed once, at generation time; after that they cannot be
|
|
10
|
+
recovered, only revoked.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import secrets
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
PREFIX = "tw_"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _hash(token: str) -> str:
|
|
24
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _write(path: str, data: dict) -> None:
|
|
28
|
+
directory = os.path.dirname(os.path.abspath(path))
|
|
29
|
+
if directory:
|
|
30
|
+
os.makedirs(directory, exist_ok=True)
|
|
31
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
32
|
+
json.dump(data, fh, indent=1, sort_keys=True)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load(path: str = "canaries.json") -> dict:
|
|
36
|
+
if not os.path.exists(path):
|
|
37
|
+
return {"version": 1, "canaries": []}
|
|
38
|
+
with open(path, encoding="utf-8") as fh:
|
|
39
|
+
try:
|
|
40
|
+
data = json.load(fh)
|
|
41
|
+
except ValueError:
|
|
42
|
+
return {"version": 1, "canaries": []}
|
|
43
|
+
if not isinstance(data, dict) or not isinstance(data.get("canaries"), list):
|
|
44
|
+
return {"version": 1, "canaries": []}
|
|
45
|
+
return data
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def generate(count: int = 3, note: str = "", path: str = "canaries.json",
|
|
49
|
+
registry: dict | None = None) -> dict:
|
|
50
|
+
"""Add `count` canaries to the registry and return the plaintext tokens once."""
|
|
51
|
+
data = registry if registry is not None else load(path)
|
|
52
|
+
items = list(data.get("canaries") or [])
|
|
53
|
+
tokens = []
|
|
54
|
+
for _ in range(max(1, int(count))):
|
|
55
|
+
token = PREFIX + secrets.token_urlsafe(24)
|
|
56
|
+
tokens.append(token)
|
|
57
|
+
items.append({"id": secrets.token_hex(6), "sha256": _hash(token),
|
|
58
|
+
"note": note, "created": int(time.time()),
|
|
59
|
+
"revoked": False})
|
|
60
|
+
data = {"version": 1, "canaries": items}
|
|
61
|
+
_write(path, data)
|
|
62
|
+
return {"path": path, "tokens": tokens, "count": len(items)}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def match(text: str, registry: dict | None) -> list[dict]:
|
|
66
|
+
"""Return the registry entries whose hash appears in `text`."""
|
|
67
|
+
if not text or not registry:
|
|
68
|
+
return []
|
|
69
|
+
known = {c.get("sha256"): c for c in (registry.get("canaries") or [])
|
|
70
|
+
if isinstance(c, dict) and not c.get("revoked")}
|
|
71
|
+
if not known:
|
|
72
|
+
return []
|
|
73
|
+
hits = []
|
|
74
|
+
for candidate in candidates(text):
|
|
75
|
+
entry = known.get(_hash(candidate))
|
|
76
|
+
if entry is not None:
|
|
77
|
+
hits.append(entry)
|
|
78
|
+
return hits
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def candidates(text: str) -> list[str]:
|
|
82
|
+
"""Every substring shaped like a canary token."""
|
|
83
|
+
out = []
|
|
84
|
+
index = 0
|
|
85
|
+
while True:
|
|
86
|
+
index = text.find(PREFIX, index)
|
|
87
|
+
if index < 0:
|
|
88
|
+
return out
|
|
89
|
+
end = index + len(PREFIX)
|
|
90
|
+
while end < len(text) and (text[end].isalnum() or text[end] in "-_"):
|
|
91
|
+
end += 1
|
|
92
|
+
out.append(text[index:end])
|
|
93
|
+
index = end
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def revoke(canary_id: str, path: str = "canaries.json") -> dict:
|
|
97
|
+
data = load(path)
|
|
98
|
+
found = 0
|
|
99
|
+
for entry in data.get("canaries") or []:
|
|
100
|
+
if entry.get("id") == canary_id:
|
|
101
|
+
entry["revoked"] = True
|
|
102
|
+
found += 1
|
|
103
|
+
_write(path, data)
|
|
104
|
+
return {"revoked": found, "id": canary_id}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Command line: plant canaries, then watch an access log."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import canary, detect
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _emit(obj) -> None:
|
|
12
|
+
print(json.dumps(obj, indent=1, ensure_ascii=False, sort_keys=True))
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def main(argv=None) -> int:
|
|
16
|
+
ap = argparse.ArgumentParser(prog="tripwire",
|
|
17
|
+
description="Detect an inbound agent by behaviour, not blocklists.")
|
|
18
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
19
|
+
|
|
20
|
+
p_gen = sub.add_parser("canary", help="plant, list or revoke canary keys")
|
|
21
|
+
p_gen.add_argument("action", choices=("generate", "list", "revoke"))
|
|
22
|
+
p_gen.add_argument("--count", type=int, default=3)
|
|
23
|
+
p_gen.add_argument("--note", default="")
|
|
24
|
+
p_gen.add_argument("--id", default=None, help="canary id (revoke)")
|
|
25
|
+
p_gen.add_argument("--registry", default="canaries.json")
|
|
26
|
+
|
|
27
|
+
p_watch = sub.add_parser("watch", help="score an access log")
|
|
28
|
+
p_watch.add_argument("--log", required=True)
|
|
29
|
+
p_watch.add_argument("--registry", default="canaries.json")
|
|
30
|
+
p_watch.add_argument("--window", type=int, default=detect.agentwatch.WINDOW)
|
|
31
|
+
p_watch.add_argument("--ledger", default=None,
|
|
32
|
+
help="append control/alert records to this mandate ledger")
|
|
33
|
+
p_watch.add_argument("--min-level", dest="min_level",
|
|
34
|
+
choices=("low", "medium", "high", "critical"), default="medium")
|
|
35
|
+
|
|
36
|
+
p_check = sub.add_parser("check", help="is this string a planted canary?")
|
|
37
|
+
p_check.add_argument("--token", required=True)
|
|
38
|
+
p_check.add_argument("--registry", default="canaries.json")
|
|
39
|
+
|
|
40
|
+
a = ap.parse_args(argv)
|
|
41
|
+
|
|
42
|
+
if a.cmd == "canary":
|
|
43
|
+
if a.action == "generate":
|
|
44
|
+
res = canary.generate(a.count, a.note, a.registry)
|
|
45
|
+
_emit({"registry": res["path"], "count": res["count"],
|
|
46
|
+
"tokens": res["tokens"],
|
|
47
|
+
"note": "shown once: only sha256 is stored, revoke by id"})
|
|
48
|
+
return 0
|
|
49
|
+
if a.action == "list":
|
|
50
|
+
data = canary.load(a.registry)
|
|
51
|
+
_emit({"count": len([c for c in data.get("canaries", []) if not c.get("revoked")]),
|
|
52
|
+
"canaries": [{k: c.get(k) for k in ("id", "note", "created", "revoked")}
|
|
53
|
+
for c in data.get("canaries", [])]})
|
|
54
|
+
return 0
|
|
55
|
+
if not a.id:
|
|
56
|
+
_emit({"error": "usage", "message": "canary revoke --id ID"})
|
|
57
|
+
return 2
|
|
58
|
+
_emit(canary.revoke(a.id, a.registry))
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
if a.cmd == "watch":
|
|
62
|
+
registry = canary.load(a.registry) if a.registry else {"canaries": []}
|
|
63
|
+
res = detect.watch(a.log, registry, a.window, a.ledger)
|
|
64
|
+
order = {"low": 0, "medium": 1, "high": 2, "critical": 3}
|
|
65
|
+
floor = order[a.min_level]
|
|
66
|
+
flagged = {ip: s for ip, s in res["sessions"].items()
|
|
67
|
+
if order.get(s["level"], 0) >= floor}
|
|
68
|
+
_emit({"sources": res["sources"], "flagged": len(flagged),
|
|
69
|
+
"canary_hits": len(res["canary_hits"]),
|
|
70
|
+
"spec_derived_paths": len(res["spec_derived_paths"]),
|
|
71
|
+
"sessions": flagged})
|
|
72
|
+
return 0 if not flagged else 1
|
|
73
|
+
|
|
74
|
+
if a.cmd == "check":
|
|
75
|
+
hits = canary.match(a.token, canary.load(a.registry))
|
|
76
|
+
_emit({"planted": bool(hits), "canaries": [h.get("id") for h in hits]})
|
|
77
|
+
return 0 if hits else 1
|
|
78
|
+
|
|
79
|
+
ap.print_help(sys.stderr)
|
|
80
|
+
return 2
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Behavioural detection for an inbound agent, on top of the access log.
|
|
2
|
+
|
|
3
|
+
Two layers:
|
|
4
|
+
|
|
5
|
+
1. The rules shipped in `gama-mandate` (`mandate.agentwatch`): tool switching,
|
|
6
|
+
UA flipping, following a link that only existed in a document, key probing,
|
|
7
|
+
reading submit-only endpoints, velocity, low-and-slow scanning.
|
|
8
|
+
2. The two things an *inbound* detector needs and an authorisation log cannot
|
|
9
|
+
provide:
|
|
10
|
+
- **canary hits** — any use of a planted key is decisive on its own;
|
|
11
|
+
- **spec-derived novel paths** — a path whose first appearance follows a
|
|
12
|
+
request for an API document within 60 seconds. A human does not move from
|
|
13
|
+
reading a spec to a never-seen endpoint that fast; a script does.
|
|
14
|
+
|
|
15
|
+
Levels: any canary hit is `critical`; otherwise the mandate score applies
|
|
16
|
+
(>=6 high, >=3 medium). A judge model may explain a finding, never lower it.
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import time
|
|
21
|
+
from collections import defaultdict
|
|
22
|
+
|
|
23
|
+
from mandate import agentwatch
|
|
24
|
+
from mandate.core import append_receipt
|
|
25
|
+
|
|
26
|
+
from . import canary as canary_mod
|
|
27
|
+
|
|
28
|
+
SPEC_TOKENS = ("/openapi", "/swagger", "/docs", ".md", "/spec", "/redoc")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def is_doc_path(path: str) -> bool:
|
|
32
|
+
p = (path or "").lower()
|
|
33
|
+
return any(token in p for token in SPEC_TOKENS)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def spec_derived_paths(rows: list[dict], max_gap: float = 60.0) -> list[dict]:
|
|
37
|
+
"""First-time paths requested shortly after an API/spec document was fetched."""
|
|
38
|
+
by_ip = defaultdict(list)
|
|
39
|
+
for row in rows:
|
|
40
|
+
by_ip[str(row.get("ip") or "?")].append(row)
|
|
41
|
+
out = []
|
|
42
|
+
for ip, items in by_ip.items():
|
|
43
|
+
seen: set[str] = set()
|
|
44
|
+
last_doc_ts: float | None = None
|
|
45
|
+
for row in sorted(items, key=lambda r: float(r.get("ts") or 0)):
|
|
46
|
+
path = str(row.get("path") or "")
|
|
47
|
+
ts = float(row.get("ts") or 0)
|
|
48
|
+
is_doc = is_doc_path(path) # the path we served, not the Referer
|
|
49
|
+
if not is_doc and path not in seen and last_doc_ts is not None \
|
|
50
|
+
and 0 <= ts - last_doc_ts <= max_gap:
|
|
51
|
+
out.append({"ip": ip, "path": path, "ts": ts,
|
|
52
|
+
"seconds_after_doc": round(ts - last_doc_ts, 1)})
|
|
53
|
+
if is_doc:
|
|
54
|
+
last_doc_ts = ts
|
|
55
|
+
seen.add(path)
|
|
56
|
+
return out
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _raise_level(session: dict, points: int, level: str | None = None) -> None:
|
|
60
|
+
session["points"] += points
|
|
61
|
+
if session["points"] >= agentwatch.THRESHOLDS["high"]:
|
|
62
|
+
session["level"] = "high"
|
|
63
|
+
elif session["points"] >= agentwatch.THRESHOLDS["medium"]:
|
|
64
|
+
session["level"] = "medium"
|
|
65
|
+
if level is not None:
|
|
66
|
+
session["level"] = level
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def analyse(rows: list[dict], registry: dict | None = None, window: int = 600,
|
|
70
|
+
now: float | None = None) -> dict:
|
|
71
|
+
base = agentwatch.analyse(rows, window=window, now=now)
|
|
72
|
+
|
|
73
|
+
canary_hits = []
|
|
74
|
+
for row in rows:
|
|
75
|
+
text = " ".join(str(row.get(k) or "") for k in
|
|
76
|
+
("path", "ua", "referer", "query", "body", "auth"))
|
|
77
|
+
for hit in canary_mod.match(text, registry or {}):
|
|
78
|
+
canary_hits.append({"ip": row.get("ip"), "ts": row.get("ts"),
|
|
79
|
+
"path": row.get("path"), "canary": hit.get("id")})
|
|
80
|
+
|
|
81
|
+
spec_paths = spec_derived_paths(rows)
|
|
82
|
+
for item in spec_paths:
|
|
83
|
+
session = base["sessions"].get(item["ip"])
|
|
84
|
+
if session is not None:
|
|
85
|
+
session["findings"].append({
|
|
86
|
+
"rule": "spec_derived_novel_path", "points": 3,
|
|
87
|
+
"detail": "first request to %s %.1fs after an API document"
|
|
88
|
+
% (item["path"], item["seconds_after_doc"])})
|
|
89
|
+
_raise_level(session, 3)
|
|
90
|
+
|
|
91
|
+
for hit in canary_hits:
|
|
92
|
+
session = base["sessions"].get(str(hit["ip"]))
|
|
93
|
+
if session is not None:
|
|
94
|
+
session["findings"].append({
|
|
95
|
+
"rule": "canary_used", "points": 10,
|
|
96
|
+
"detail": "planted key %s used on %s" % (hit["canary"], hit["path"])})
|
|
97
|
+
_raise_level(session, 10, "critical")
|
|
98
|
+
|
|
99
|
+
return {"window_s": window, "sources": base["sources"],
|
|
100
|
+
"flagged": sum(1 for s in base["sessions"].values() if s["level"] != "low"),
|
|
101
|
+
"canary_hits": canary_hits, "spec_derived_paths": spec_paths,
|
|
102
|
+
"sessions": base["sessions"]}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def watch(log_path: str, registry: dict | None = None, window: int = 600,
|
|
106
|
+
ledger: str | None = None) -> dict:
|
|
107
|
+
rows = agentwatch.load(log_path)
|
|
108
|
+
result = analyse(rows, registry, window)
|
|
109
|
+
if ledger:
|
|
110
|
+
alerts = {ip: s for ip, s in result["sessions"].items() if s["level"] != "low"}
|
|
111
|
+
if alerts:
|
|
112
|
+
append_receipt(ledger, {"v": 1, "type": "control", "action": "alert",
|
|
113
|
+
"actor": "tripwire",
|
|
114
|
+
"reason": "inbound agent behaviour",
|
|
115
|
+
"ts": time.time(),
|
|
116
|
+
"canary_hits": result["canary_hits"],
|
|
117
|
+
"findings": alerts})
|
|
118
|
+
return result
|