de-vigil 0.8.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.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: de-vigil
3
+ Version: 0.8.0
4
+ Summary: Vigil — run detection rules over normalized security logs and report coverage gaps
5
+ Project-URL: Homepage, https://github.com/KooEric/de-arsenal
6
+ Project-URL: Repository, https://github.com/KooEric/de-arsenal
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Topic :: Security
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: arsenal-core<0.9,>=0.8
18
+ Requires-Dist: duckdb>=1.0
19
+ Requires-Dist: pyarrow>=17
20
+ Requires-Dist: pydantic>=2
21
+ Requires-Dist: pyyaml>=6
22
+ Requires-Dist: typer>=0.12
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Vigil (`de-vigil`)
26
+
27
+ > 야간 순찰대. 정규화된 보안 로그에 탐지 룰을 실행하고, 룰이 비어 있는 곳을 알려 준다. (experimental)
28
+
29
+ 탐지 룰을 YAML 파일로 관리한다. 룰 하나는 메타데이터, `events`를 읽는 SELECT 한 개, 그리고 걸려야 하는
30
+ 케이스와 걸리면 안 되는 케이스로 이루어진다. 테스트가 없는 룰은 `vigil test`를 통과하지 못한다.
31
+
32
+ ## 설치
33
+
34
+ ```bash
35
+ pip install de-vigil
36
+ ```
37
+
38
+ ## 사용 예
39
+
40
+ ```bash
41
+ arsenal init cloudtrail-detect && arsenal run # 합성 CloudTrail 샘플 → data/events
42
+ vigil test # 룰마다 픽스처로 검증
43
+ vigil run --events data/events --out data/alerts # 새 alert만 기록 (다시 실행하면 0건)
44
+ vigil coverage --events data/events # 룰이 없는 ATT&CK 기법, 컬럼 NULL 비율
45
+ vigil unpack ./cloudtrail-logs --out input/ct.jsonl # CloudTrail 원본(*.json.gz)을 JSONL로
46
+ # (CloudTrail-Digest/ 아래 다이제스트 파일은 건너뜀)
47
+ ```
48
+
49
+ ## 룰 파일
50
+
51
+ ```yaml
52
+ id: aws-root-console-login
53
+ title: 루트 계정 콘솔 로그인
54
+ severity: high # low | medium | high | critical
55
+ attack: [T1078.004] # ATT&CK 기법 ID
56
+ source: cloudtrail
57
+ query: |
58
+ SELECT * FROM events
59
+ WHERE action = 'ConsoleLogin' AND actor_type = 'Root' AND outcome = 'success'
60
+ tests:
61
+ match:
62
+ - { action: ConsoleLogin, actor_type: Root, outcome: success }
63
+ no_match:
64
+ - { action: ConsoleLogin, actor_type: IAMUser, outcome: success }
65
+ ```
66
+
67
+ - `query`는 SELECT 한 개이고 결과에 `event_id`가 있어야 한다. `events` 말고는 읽지 못한다.
68
+ - 룰 파일은 `*.yaml`과 `*.yml`을 모두 읽는다.
69
+ - 탐지는 `event_id`가 `events`에 있는 이벤트다. `vigil test`와 `vigil run`이 같은 문장으로 센다. 그래서
70
+ `NULL AS event_id`를 돌려주는 룰이나 `event_id`가 NULL인 픽스처는 탐지로 세지 않는다.
71
+ - 케이스는 이벤트 하나이거나 이벤트 목록이다. 케이스마다 그 이벤트만 든 `events`에서 따로 실행한다.
72
+ - `events`의 컬럼은 [OCSF 대응표](../../docs/reference/vigil-ocsf-mapping.md)에 있다.
73
+
74
+ ## 종료 코드
75
+
76
+ | 코드 | 의미 |
77
+ |---|---|
78
+ | 0 | 정상 |
79
+ | 1 | 룰 테스트 실패, 실행 중 룰 오류, 또는 `--fail-on` 심각도 이상의 새 alert |
80
+ | 2 | 사용법이나 입력 오류 (룰 파일 오류, 이벤트 파일 없음, 필수 컬럼 없음이나 자료형 불일치, `--out`이 디렉터리가 아니거나 읽을 수 없는 Parquet이 있음, 쓰기 실패) |
81
+
82
+ ## 한계
83
+
84
+ - 배치만 한다. `vigil run`은 `events`를 메모리 DuckDB 테이블로 올려 읽으므로, 한 번에 읽는 이벤트가
85
+ 그 기계에 들어가야 한다.
86
+ - 로그 소스는 CloudTrail 관리 이벤트 하나다.
87
+ - 커버리지의 기준 기법 목록은 직접 고른 20개이고 ATT&CK 전체가 아니다.
88
+ - 같은 `--out`에 `vigil run`을 동시에 두 개 돌리면 같은 alert가 두 번 기록될 수 있다. 출력 디렉터리마다
89
+ 한 번에 하나만 실행한다.
90
+ - 룰 SQL에는 메모리 한도와 시간 제한이 없다. 아주 큰 조인은 DuckDB가 실행한 디렉터리의 `./.tmp`에 임시
91
+ 파일을 쓸 수 있다.
92
+ - `events`의 `event_time`은 `TIMESTAMP`(나노초 `TIMESTAMP_NS`도 허용)여야 한다. 문자열이나 시간대가 있는
93
+ 타임스탬프는 종료 코드 2로 거부한다.
94
+ - `mfa_used`와 `outcome`은 레시피의 `transform.yaml`이 정한 규칙으로 만든다. 그 밖의 로그를 쓰면 같은 규칙으로
95
+ 채워야 룰이 맞게 동작한다. 규칙은 [OCSF 대응표](../../docs/reference/vigil-ocsf-mapping.md)에 있다.
@@ -0,0 +1,15 @@
1
+ vigil/__init__.py,sha256=VxVxbxNn6_jcrEnJAjO84S2tMbBVfcsH63Cdty-oE-U,138
2
+ vigil/cli.py,sha256=PAqur2kvz5xYFCeQq669yggsCn0GEfiKDOEzn-lQxro,5617
3
+ vigil/coverage.py,sha256=TpLFsiCeGcqr0V2K8tw2Wd-xVhayeRN3o4q1VaCHaAc,4083
4
+ vigil/events.py,sha256=wfoC3iArwORyfMsEte6l-G2-JQ4amL6wsJQBed09Ujg,4177
5
+ vigil/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ vigil/rule.py,sha256=Rw2YjnJfz2RxMOlcXeuYJx9h3iRpay9DdpDZ-jenQhk,5207
7
+ vigil/run.py,sha256=cCQNAOFhNUKwSmnskLkH0CRvmXBpqv1wPxZjqUhH7gs,4172
8
+ vigil/testing.py,sha256=NdyGoOlXcz5PGaH_4pwtGzW4lLJkwmvxgJWvhQg4Cx0,1981
9
+ vigil/unpack.py,sha256=As4r4I7rvGr43DkAuqtuV709SmDOL29i6THQ7FVrLZ0,2565
10
+ vigil/reference/cloudtrail-techniques.yaml,sha256=47XT4wJZogiBFU7nMEjSowkO3gcoOIuUxy_IxJhES5Q,1402
11
+ de_vigil-0.8.0.dist-info/METADATA,sha256=cc-lFB3K0eBIq7PhpeXUoQ9hW11gpPgO5I8fSrqUKsw,4625
12
+ de_vigil-0.8.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ de_vigil-0.8.0.dist-info/entry_points.txt,sha256=tIbFtKJFSKvB3nuJ23uT7N6IF44QwqAgAe_kE3LFwCM,40
14
+ de_vigil-0.8.0.dist-info/licenses/LICENSE,sha256=WTs1rVkTNuOCIvQ_ldW6eviSy82pE0M5c1Y99l5AJ20,11337
15
+ de_vigil-0.8.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ vigil = vigil.cli:app
@@ -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 2026 KooEric
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.
vigil/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Vigil — detection rules over normalized security logs."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ __version__ = version("de-vigil")
vigil/cli.py ADDED
@@ -0,0 +1,171 @@
1
+ """vigil CLI. JSON on stdout, people on stderr. Exit 0 ok, 1 failures, 2 tool error."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from datetime import UTC, datetime
7
+ from enum import StrEnum
8
+ from pathlib import Path
9
+ from typing import Annotated
10
+
11
+ import typer
12
+
13
+ from arsenal_core.errors import ArsenalError
14
+ from vigil.coverage import CoverageReport, build_coverage
15
+ from vigil.events import load_events
16
+ from vigil.rule import SEVERITY_ORDER, Rule, load_rules
17
+ from vigil.run import run_rules
18
+ from vigil.testing import check_rules
19
+ from vigil.unpack import unpack_cloudtrail
20
+
21
+ app = typer.Typer(
22
+ help="Vigil — detection rules over normalized security logs.", no_args_is_help=True
23
+ )
24
+
25
+ EXIT_FAILURES = 1
26
+ EXIT_TOOL_ERROR = 2
27
+
28
+ RulesOption = Annotated[Path, typer.Option("--rules", help="Directory of rule YAML files.")]
29
+
30
+
31
+ @app.callback()
32
+ def main() -> None:
33
+ """Vigil — detection rules over normalized security logs."""
34
+
35
+
36
+ def _err(message: str) -> None:
37
+ typer.echo(message, err=True)
38
+
39
+
40
+ def _fail(error: ArsenalError) -> typer.Exit:
41
+ _err(f"vigil: {error}")
42
+ return typer.Exit(EXIT_TOOL_ERROR)
43
+
44
+
45
+ def _load(rules_dir: Path) -> list[Rule]:
46
+ try:
47
+ return load_rules(rules_dir)
48
+ except ArsenalError as e:
49
+ raise _fail(e) from e
50
+
51
+
52
+ @app.command("test")
53
+ def test_command(rules: RulesOption = Path("rules")) -> None:
54
+ """Check every rule against its fixture cases."""
55
+ loaded = _load(rules)
56
+ try:
57
+ results = check_rules(loaded)
58
+ except ArsenalError as e:
59
+ raise _fail(e) from e
60
+ for rule_id, failures in results.items():
61
+ _err(f"{'FAIL' if failures else 'ok '} {rule_id}")
62
+ for failure in failures:
63
+ _err(f" {failure}")
64
+ failed = {rule_id: failures for rule_id, failures in results.items() if failures}
65
+ typer.echo(json.dumps({"rules": len(results), "failed": failed}))
66
+ if failed:
67
+ raise typer.Exit(EXIT_FAILURES)
68
+
69
+
70
+ class FailOn(StrEnum):
71
+ LOW = "low"
72
+ MEDIUM = "medium"
73
+ HIGH = "high"
74
+ CRITICAL = "critical"
75
+
76
+
77
+ @app.command("run")
78
+ def run_command(
79
+ events: Annotated[str, typer.Option("--events", help="Glob or directory of events Parquet.")],
80
+ out: Annotated[Path, typer.Option("--out", help="Directory alerts are appended to.")],
81
+ rules: RulesOption = Path("rules"),
82
+ fail_on: Annotated[
83
+ FailOn | None, typer.Option("--fail-on", help="Exit 1 on a new alert at or above this.")
84
+ ] = None,
85
+ ) -> None:
86
+ """Run every rule over the events lake and record new alerts."""
87
+ loaded = _load(rules)
88
+ try:
89
+ con = load_events(events)
90
+ except ArsenalError as e:
91
+ raise _fail(e) from e
92
+ try:
93
+ summary = run_rules(loaded, con, out, datetime.now(UTC).replace(tzinfo=None))
94
+ except ArsenalError as e:
95
+ raise _fail(e) from e
96
+ finally:
97
+ con.close()
98
+ for rule_id, count in summary.new_by_rule.items():
99
+ _err(f"{count:>5} new {rule_id}")
100
+ for rule_id, reason in summary.failed.items():
101
+ _err(f"ERROR {rule_id}: {reason}")
102
+ typer.echo(
103
+ json.dumps(
104
+ {
105
+ "rules": len(loaded),
106
+ "new_alerts": sum(summary.new_by_rule.values()),
107
+ "by_rule": summary.new_by_rule,
108
+ "failed": summary.failed,
109
+ }
110
+ )
111
+ )
112
+ rank = {name: position for position, name in enumerate(SEVERITY_ORDER)}
113
+ over = fail_on is not None and any(
114
+ rank[severity] >= rank[fail_on.value] for severity in summary.new_severities
115
+ )
116
+ if summary.failed or over:
117
+ raise typer.Exit(EXIT_FAILURES)
118
+
119
+
120
+ def _print_coverage(report: CoverageReport) -> None:
121
+ _err(f"{report.rules} rules")
122
+ for technique in report.techniques:
123
+ mark = " " if technique.rules else "GAP "
124
+ _err(f"{mark}{technique.id:<10} {len(technique.rules)} rules {technique.name}")
125
+ for source in report.sources:
126
+ _err(f"source {source.source}: {source.rules} rules, last event {source.last_event_time}")
127
+ for column in report.columns:
128
+ ratio = "n/a" if column.null_ratio is None else f"{column.null_ratio:.1%}"
129
+ _err(f"column {column.column}: NULL {ratio}, used by {len(column.used_by)} rules")
130
+ if report.unlisted:
131
+ _err(f"techniques not in the reference list: {', '.join(report.unlisted)}")
132
+
133
+
134
+ @app.command("coverage")
135
+ def coverage_command(
136
+ rules: RulesOption = Path("rules"),
137
+ events: Annotated[
138
+ str | None, typer.Option("--events", help="Glob or directory of events Parquet.")
139
+ ] = None,
140
+ json_only: Annotated[bool, typer.Option("--json-only", help="Print JSON only.")] = False,
141
+ ) -> None:
142
+ """Report techniques without rules, and NULL ratios of the columns rules read."""
143
+ loaded = _load(rules)
144
+ con = None
145
+ if events is not None:
146
+ try:
147
+ con = load_events(events)
148
+ except ArsenalError as e:
149
+ raise _fail(e) from e
150
+ try:
151
+ report = build_coverage(loaded, con)
152
+ finally:
153
+ if con is not None:
154
+ con.close()
155
+ if not json_only:
156
+ _print_coverage(report)
157
+ typer.echo(report.model_dump_json())
158
+
159
+
160
+ @app.command("unpack")
161
+ def unpack_command(
162
+ src: Annotated[Path, typer.Argument(help="Directory of CloudTrail *.json / *.json.gz files.")],
163
+ out: Annotated[Path, typer.Option("--out", help="JSONL file to write.")],
164
+ ) -> None:
165
+ """Unpack CloudTrail log files into JSONL, one event per line."""
166
+ try:
167
+ count = unpack_cloudtrail(src, out)
168
+ except ArsenalError as e:
169
+ raise _fail(e) from e
170
+ _err(f"{count} events -> {out}")
171
+ typer.echo(json.dumps({"events": count, "out": str(out)}))
vigil/coverage.py ADDED
@@ -0,0 +1,126 @@
1
+ """Coverage: which techniques have rules, which have none, and whether the data rules need is there.
2
+
3
+ `CoverageReport` is the stdout JSON contract (schemas/vigil-coverage.json).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from datetime import datetime
10
+ from importlib import resources
11
+ from typing import Any, Final, Literal
12
+
13
+ import duckdb
14
+ import yaml
15
+ from pydantic import BaseModel, ConfigDict
16
+
17
+ from vigil.events import EVENT_COLUMNS
18
+ from vigil.rule import Rule
19
+
20
+ _TECHNIQUES_FILE: Final = "cloudtrail-techniques.yaml"
21
+ _RATIO_DIGITS: Final = 4
22
+
23
+
24
+ class _Frozen(BaseModel):
25
+ model_config = ConfigDict(frozen=True, extra="forbid")
26
+
27
+
28
+ class Technique(_Frozen):
29
+ id: str
30
+ name: str
31
+
32
+
33
+ class TechniqueCoverage(_Frozen):
34
+ id: str
35
+ name: str
36
+ rules: list[str]
37
+ tests: int
38
+
39
+
40
+ class SourceCoverage(_Frozen):
41
+ source: str
42
+ rules: int
43
+ last_event_time: datetime | None
44
+
45
+
46
+ class ColumnHealth(_Frozen):
47
+ column: str
48
+ used_by: list[str]
49
+ null_ratio: float | None
50
+
51
+
52
+ class CoverageReport(_Frozen):
53
+ schema_version: Literal[1] = 1
54
+ rules: int
55
+ techniques: list[TechniqueCoverage]
56
+ uncovered: list[str]
57
+ unlisted: list[str]
58
+ sources: list[SourceCoverage]
59
+ columns: list[ColumnHealth]
60
+
61
+
62
+ def load_techniques() -> list[Technique]:
63
+ text = (resources.files("vigil") / "reference" / _TECHNIQUES_FILE).read_text(encoding="utf-8")
64
+ raw: list[dict[str, Any]] = yaml.safe_load(text)
65
+ return [Technique.model_validate(item) for item in raw]
66
+
67
+
68
+ def build_coverage(rules: list[Rule], con: duckdb.DuckDBPyConnection | None) -> CoverageReport:
69
+ """`con` is a connection from `vigil.events.load_events`, or None to read rule files only."""
70
+ known = load_techniques()
71
+ techniques = [_technique_coverage(technique, rules) for technique in known]
72
+ known_ids = {technique.id for technique in known}
73
+ used_ids = {technique_id for rule in rules for technique_id in rule.attack}
74
+ return CoverageReport(
75
+ rules=len(rules),
76
+ techniques=techniques,
77
+ uncovered=[item.id for item in techniques if not item.rules],
78
+ unlisted=sorted(used_ids - known_ids),
79
+ sources=_sources(rules, con),
80
+ columns=_columns(rules, con),
81
+ )
82
+
83
+
84
+ def _technique_coverage(technique: Technique, rules: list[Rule]) -> TechniqueCoverage:
85
+ covering = [rule for rule in rules if technique.id in rule.attack]
86
+ tests = sum(len(rule.tests.match) + len(rule.tests.no_match) for rule in covering)
87
+ return TechniqueCoverage(
88
+ id=technique.id, name=technique.name, rules=[rule.id for rule in covering], tests=tests
89
+ )
90
+
91
+
92
+ def _sources(rules: list[Rule], con: duckdb.DuckDBPyConnection | None) -> list[SourceCoverage]:
93
+ result: list[SourceCoverage] = []
94
+ for source in sorted({rule.source for rule in rules}):
95
+ last: datetime | None = None
96
+ if con is not None:
97
+ row = con.execute(
98
+ "SELECT max(event_time) FROM events WHERE source = ?", [source]
99
+ ).fetchone()
100
+ last = row[0] if row else None
101
+ count = sum(1 for rule in rules if rule.source == source)
102
+ result.append(SourceCoverage(source=source, rules=count, last_event_time=last))
103
+ return result
104
+
105
+
106
+ def _columns(rules: list[Rule], con: duckdb.DuckDBPyConnection | None) -> list[ColumnHealth]:
107
+ """Columns at least one rule names in its query. Matching is by whole word in the SQL text."""
108
+ result: list[ColumnHealth] = []
109
+ for column in EVENT_COLUMNS:
110
+ word = re.compile(rf"\b{column}\b")
111
+ used_by = [rule.id for rule in rules if word.search(rule.query)]
112
+ if not used_by:
113
+ continue
114
+ result.append(
115
+ ColumnHealth(column=column, used_by=used_by, null_ratio=_null_ratio(con, column))
116
+ )
117
+ return result
118
+
119
+
120
+ def _null_ratio(con: duckdb.DuckDBPyConnection | None, column: str) -> float | None:
121
+ if con is None:
122
+ return None
123
+ row = con.execute(f"SELECT count(*), count({column}) FROM events").fetchone()
124
+ if row is None or row[0] == 0:
125
+ return None
126
+ return round(1 - row[1] / row[0], _RATIO_DIGITS)
vigil/events.py ADDED
@@ -0,0 +1,118 @@
1
+ """The `events` table that rules read, and the locked connections that hold it.
2
+
3
+ Every connection returned here has external access switched off, so a rule query can read
4
+ `events` and nothing else on disk or over the network. DuckDB does not let the setting be
5
+ switched back on while the connection is open.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import glob as globlib
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any, Final
14
+
15
+ import duckdb
16
+
17
+ from arsenal_core.errors import FatalError
18
+
19
+ EVENT_COLUMNS: Final[dict[str, str]] = {
20
+ "event_id": "VARCHAR",
21
+ "event_time": "TIMESTAMP",
22
+ "source": "VARCHAR",
23
+ "service": "VARCHAR",
24
+ "action": "VARCHAR",
25
+ "actor_type": "VARCHAR",
26
+ "actor_id": "VARCHAR",
27
+ "src_ip": "VARCHAR",
28
+ "region": "VARCHAR",
29
+ "outcome": "VARCHAR",
30
+ "mfa_used": "BOOLEAN",
31
+ "resource": "VARCHAR",
32
+ "raw": "VARCHAR",
33
+ }
34
+
35
+ # Other DuckDB types accepted for a column. A nanosecond timestamp (Parquet written by
36
+ # pandas, for one) runs through `vigil run` end to end; alerts keep microsecond precision.
37
+ ACCEPTED_TYPES: Final[dict[str, frozenset[str]]] = {"event_time": frozenset({"TIMESTAMP_NS"})}
38
+
39
+ # event_time given to a fixture event that does not set one.
40
+ FIXTURE_TIME: Final = datetime(2026, 1, 1)
41
+
42
+
43
+ def _lock(con: duckdb.DuckDBPyConnection) -> None:
44
+ con.execute("SET enable_external_access=false")
45
+
46
+
47
+ def empty_events() -> duckdb.DuckDBPyConnection:
48
+ con = duckdb.connect()
49
+ columns = ", ".join(f"{name} {kind}" for name, kind in EVENT_COLUMNS.items())
50
+ con.execute(f"CREATE TABLE events ({columns})")
51
+ _lock(con)
52
+ return con
53
+
54
+
55
+ def fixture_events(rows: list[dict[str, Any]]) -> duckdb.DuckDBPyConnection:
56
+ """`events` holding exactly `rows`. Columns a row leaves out are NULL.
57
+
58
+ Raises FatalError for an unknown column and duckdb.Error for a value of the wrong type;
59
+ the connection is closed first in both cases.
60
+ """
61
+ con = empty_events()
62
+ placeholders = ", ".join("?" for _ in EVENT_COLUMNS)
63
+ for index, row in enumerate(rows):
64
+ unknown = sorted(set(row) - set(EVENT_COLUMNS))
65
+ if unknown:
66
+ con.close()
67
+ raise FatalError(f"fixture event has unknown columns: {unknown}")
68
+ full: dict[str, Any] = dict.fromkeys(EVENT_COLUMNS)
69
+ full["event_id"] = f"fixture-{index}"
70
+ full["event_time"] = FIXTURE_TIME
71
+ full.update(row)
72
+ try:
73
+ con.execute(f"INSERT INTO events VALUES ({placeholders})", list(full.values()))
74
+ except duckdb.Error:
75
+ con.close()
76
+ raise
77
+ return con
78
+
79
+
80
+ def resolve_event_files(pattern: str) -> list[str]:
81
+ """A directory means every *.parquet under it; anything else is a glob."""
82
+ path = Path(pattern)
83
+ if path.is_dir():
84
+ files = sorted(str(p) for p in path.rglob("*.parquet"))
85
+ else:
86
+ files = sorted(globlib.glob(pattern, recursive=True))
87
+ if not files:
88
+ raise FatalError(f"no event files match {pattern}")
89
+ return files
90
+
91
+
92
+ def load_events(pattern: str) -> duckdb.DuckDBPyConnection:
93
+ """Copy the lake into an in-memory `events` table, then lock the connection."""
94
+ files = resolve_event_files(pattern)
95
+ listing = ", ".join("'" + name.replace("'", "''") + "'" for name in files)
96
+ con = duckdb.connect()
97
+ try:
98
+ con.execute(
99
+ f"CREATE TABLE events AS SELECT * FROM read_parquet([{listing}], union_by_name=true)"
100
+ )
101
+ except duckdb.Error as e:
102
+ con.close()
103
+ raise FatalError(f"cannot read events from {pattern}: {e}") from e
104
+ found = {str(row[0]): str(row[1]) for row in con.execute("DESCRIBE events").fetchall()}
105
+ missing = [name for name in EVENT_COLUMNS if name not in found]
106
+ if missing:
107
+ con.close()
108
+ raise FatalError(f"events is missing columns: {missing}")
109
+ wrong = [
110
+ f"{name} is {found[name]}, expected {kind}"
111
+ for name, kind in EVENT_COLUMNS.items()
112
+ if found[name] != kind and found[name] not in ACCEPTED_TYPES.get(name, frozenset())
113
+ ]
114
+ if wrong:
115
+ con.close()
116
+ raise FatalError(f"events column types differ: {'; '.join(wrong)}")
117
+ _lock(con)
118
+ return con
vigil/py.typed ADDED
File without changes
@@ -0,0 +1,22 @@
1
+ # ATT&CK techniques that AWS CloudTrail management events can show.
2
+ # Source: MITRE ATT&CK Enterprise v20 (October 2026), IaaS matrix. Hand-picked 2026-11-28; not the full matrix.
3
+ - { id: T1078.004, name: "Valid Accounts: Cloud Accounts" }
4
+ - { id: T1087.004, name: "Account Discovery: Cloud Account" }
5
+ - { id: T1098.001, name: "Account Manipulation: Additional Cloud Credentials" }
6
+ - { id: T1098.003, name: "Account Manipulation: Additional Cloud Roles" }
7
+ - { id: T1110, name: "Brute Force" }
8
+ - { id: T1136.003, name: "Create Account: Cloud Account" }
9
+ - { id: T1485, name: "Data Destruction" }
10
+ - { id: T1496, name: "Resource Hijacking" }
11
+ - { id: T1526, name: "Cloud Service Discovery" }
12
+ - { id: T1530, name: "Data from Cloud Storage" }
13
+ - { id: T1535, name: "Unused/Unsupported Cloud Regions" }
14
+ - { id: T1537, name: "Transfer Data to Cloud Account" }
15
+ - { id: T1556.006, name: "Modify Authentication Process: Multi-Factor Authentication" }
16
+ - { id: T1578.001, name: "Modify Cloud Compute Infrastructure: Create Snapshot" }
17
+ - { id: T1578.002, name: "Modify Cloud Compute Infrastructure: Create Cloud Instance" }
18
+ - { id: T1580, name: "Cloud Infrastructure Discovery" }
19
+ - { id: T1619, name: "Cloud Storage Object Discovery" }
20
+ - { id: T1648, name: "Serverless Execution" }
21
+ - { id: T1651, name: "Cloud Administration Command" }
22
+ - { id: T1685.002, name: "Disable or Modify Tools: Disable or Modify Cloud Log" }
vigil/rule.py ADDED
@@ -0,0 +1,142 @@
1
+ """Detection rule files. One YAML file is one rule; every rule is validated on load."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any, Final, Literal
8
+
9
+ import duckdb
10
+ import yaml
11
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
12
+
13
+ from arsenal_core.errors import FatalError
14
+ from vigil.events import empty_events
15
+
16
+ Severity = Literal["low", "medium", "high", "critical"]
17
+ SEVERITY_ORDER: Final[tuple[Severity, ...]] = ("low", "medium", "high", "critical")
18
+
19
+ Event = dict[str, Any]
20
+ # One event, or several events that must be looked at together (correlation rules).
21
+ Case = Event | list[Event]
22
+
23
+ _TECHNIQUE: Final = re.compile(r"T\d{4}(\.\d{3})?")
24
+
25
+
26
+ class RuleTests(BaseModel):
27
+ model_config = ConfigDict(frozen=True, extra="forbid")
28
+
29
+ match: list[Case] = Field(default_factory=lambda: list[Case]())
30
+ no_match: list[Case] = Field(default_factory=lambda: list[Case]())
31
+
32
+
33
+ class Rule(BaseModel):
34
+ """The rule file contract (schemas/vigil-rule.json)."""
35
+
36
+ model_config = ConfigDict(frozen=True, extra="forbid")
37
+
38
+ id: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$")
39
+ title: str = Field(min_length=1)
40
+ severity: Severity
41
+ attack: list[str] = Field(min_length=1)
42
+ source: str = Field(min_length=1)
43
+ query: str
44
+ tests: RuleTests = Field(default_factory=RuleTests)
45
+
46
+ @field_validator("attack")
47
+ @classmethod
48
+ def _technique_ids(cls, value: list[str]) -> list[str]:
49
+ bad = [item for item in value if not _TECHNIQUE.fullmatch(item)]
50
+ if bad:
51
+ raise ValueError(f"not ATT&CK technique ids (T1234 or T1234.001): {bad}")
52
+ return value
53
+
54
+ @field_validator("query")
55
+ @classmethod
56
+ def _one_select(cls, value: str) -> str:
57
+ text = _drop_final_semicolon(value.strip())
58
+ try:
59
+ statements = duckdb.extract_statements(text)
60
+ except duckdb.Error as e:
61
+ raise ValueError(f"does not parse: {e}") from e
62
+ if len(statements) != 1 or statements[0].type != duckdb.StatementType.SELECT:
63
+ raise ValueError("must be exactly one SELECT statement")
64
+ return text
65
+
66
+
67
+ def detection_sql(query: str) -> str:
68
+ """The statement that lists detected events for a rule query.
69
+
70
+ A detection is a row whose `event_id` is an event in `events`. `vigil test` and
71
+ `vigil run` both count detections with this statement, so they cannot disagree.
72
+ """
73
+ return (
74
+ "SELECT DISTINCT e.event_id, e.event_time, e.actor_id "
75
+ f"FROM ({query}\n) AS q JOIN events AS e ON e.event_id = q.event_id "
76
+ "ORDER BY e.event_time, e.event_id"
77
+ )
78
+
79
+
80
+ def _drop_final_semicolon(text: str) -> str:
81
+ """Remove a statement-ending `;` so the query can be embedded as a subquery.
82
+
83
+ Comments after the `;` stay in the text. The tokenizer keeps `;` inside strings as part
84
+ of the string token, so the last non-comment token tells the truth. DuckDB 2 returns
85
+ comments as tokens of their own; DuckDB 1 drops them and has no `comment` token type.
86
+ """
87
+ comment = getattr(duckdb.token_type, "comment", None)
88
+ tokens = [token for token in duckdb.tokenize(text) if token[1] != comment]
89
+ if not tokens:
90
+ return text
91
+ offset, kind = tokens[-1]
92
+ if kind == duckdb.token_type.operator and text[offset] == ";":
93
+ return (text[:offset] + text[offset + 1 :]).strip()
94
+ return text
95
+
96
+
97
+ def load_rules(rules_dir: Path) -> list[Rule]:
98
+ if not rules_dir.is_dir():
99
+ raise FatalError(f"rules directory not found: {rules_dir}")
100
+ paths = sorted([*rules_dir.glob("*.yaml"), *rules_dir.glob("*.yml")], key=lambda p: p.name)
101
+ if not paths:
102
+ raise FatalError(f"no rule files (*.yaml, *.yml) in {rules_dir}")
103
+ rules: list[Rule] = []
104
+ seen: dict[str, Path] = {}
105
+ for path in paths:
106
+ rule = _load_one(path)
107
+ if rule.id in seen:
108
+ raise FatalError(f"duplicate rule id {rule.id!r}: {seen[rule.id]} and {path}")
109
+ seen[rule.id] = path
110
+ rules.append(rule)
111
+ return rules
112
+
113
+
114
+ def _load_one(path: Path) -> Rule:
115
+ try:
116
+ raw: Any = yaml.safe_load(path.read_text(encoding="utf-8"))
117
+ except (OSError, yaml.YAMLError) as e:
118
+ raise FatalError(f"{path}: cannot read rule: {e}") from e
119
+ try:
120
+ rule = Rule.model_validate(raw)
121
+ except ValidationError as e:
122
+ problems = "; ".join(
123
+ f"{'.'.join(str(part) for part in error['loc']) or 'rule'}: {error['msg']}"
124
+ for error in e.errors()
125
+ )
126
+ raise FatalError(f"{path}: {problems}") from e
127
+ _check_against_events(path, rule)
128
+ return rule
129
+
130
+
131
+ def _check_against_events(path: Path, rule: Rule) -> None:
132
+ """Run the query on an empty `events`: catches unknown columns and a missing event_id."""
133
+ con = empty_events()
134
+ try:
135
+ description = con.execute(f"SELECT * FROM ({rule.query}\n) LIMIT 0").description
136
+ except duckdb.Error as e:
137
+ raise FatalError(f"{path}: query fails against events: {e}") from e
138
+ finally:
139
+ con.close()
140
+ names = [str(column[0]) for column in description or []]
141
+ if "event_id" not in names:
142
+ raise FatalError(f"{path}: query must return event_id (returns: {names})")
vigil/run.py ADDED
@@ -0,0 +1,122 @@
1
+ """Run rules over `events` and append new alerts to a Parquet directory.
2
+
3
+ An alert is identified by (rule, event). Running again over the same lake finds the same
4
+ ids, sees they are already on disk, and writes nothing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import os
11
+ from dataclasses import dataclass
12
+ from datetime import datetime
13
+ from pathlib import Path
14
+ from typing import Any, Final
15
+ from uuid import uuid4
16
+
17
+ import duckdb
18
+ import pyarrow as pa
19
+ import pyarrow.parquet as pq
20
+
21
+ from arsenal_core.errors import FatalError
22
+ from vigil.rule import Rule, detection_sql
23
+
24
+ ALERT_SCHEMA: Final = pa.schema(
25
+ [
26
+ ("alert_id", pa.string()),
27
+ ("rule_id", pa.string()),
28
+ ("severity", pa.string()),
29
+ ("attack", pa.list_(pa.string())),
30
+ ("event_id", pa.string()),
31
+ ("event_time", pa.timestamp("us")),
32
+ ("actor_id", pa.string()),
33
+ ("detected_at", pa.timestamp("us")),
34
+ ]
35
+ )
36
+
37
+ _ALERT_ID_LENGTH: Final = 32
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class RunSummary:
42
+ new_by_rule: dict[str, int]
43
+ failed: dict[str, str]
44
+ new_severities: frozenset[str]
45
+
46
+
47
+ def alert_id(rule_id: str, event_id: str) -> str:
48
+ digest = hashlib.sha256(f"{rule_id}\x1f{event_id}".encode()).hexdigest()
49
+ return digest[:_ALERT_ID_LENGTH]
50
+
51
+
52
+ def existing_alert_ids(out_dir: Path) -> set[str]:
53
+ ids: set[str] = set()
54
+ if not out_dir.exists():
55
+ return ids
56
+ if not out_dir.is_dir():
57
+ raise FatalError(f"alerts output is not a directory: {out_dir}")
58
+ for file in sorted(out_dir.glob("*.parquet")):
59
+ try:
60
+ table = pq.read_table(file, columns=["alert_id"]) # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
61
+ ids.update(table.column("alert_id").to_pylist()) # pyright: ignore[reportUnknownArgumentType, reportUnknownMemberType]
62
+ except (pa.ArrowException, OSError, KeyError) as e:
63
+ raise FatalError(f"cannot read alerts from {file}: {e}") from e
64
+ return ids
65
+
66
+
67
+ def run_rules(
68
+ rules: list[Rule], con: duckdb.DuckDBPyConnection, out_dir: Path, detected_at: datetime
69
+ ) -> RunSummary:
70
+ seen = existing_alert_ids(out_dir)
71
+ rows: list[dict[str, Any]] = []
72
+ new_by_rule: dict[str, int] = {}
73
+ failed: dict[str, str] = {}
74
+ for rule in rules:
75
+ try:
76
+ hits = con.execute(detection_sql(rule.query)).fetchall()
77
+ except duckdb.Error as e:
78
+ failed[rule.id] = str(e)
79
+ continue
80
+ count = 0
81
+ for event_id, event_time, actor_id in hits:
82
+ identifier = alert_id(rule.id, str(event_id))
83
+ if identifier in seen:
84
+ continue
85
+ seen.add(identifier)
86
+ count += 1
87
+ rows.append(
88
+ {
89
+ "alert_id": identifier,
90
+ "rule_id": rule.id,
91
+ "severity": rule.severity,
92
+ "attack": rule.attack,
93
+ "event_id": event_id,
94
+ "event_time": event_time,
95
+ "actor_id": actor_id,
96
+ "detected_at": detected_at,
97
+ }
98
+ )
99
+ new_by_rule[rule.id] = count
100
+ if rows:
101
+ _write(out_dir, rows, detected_at)
102
+ return RunSummary(new_by_rule, failed, frozenset(str(row["severity"]) for row in rows))
103
+
104
+
105
+ def _write(out_dir: Path, rows: list[dict[str, Any]], detected_at: datetime) -> None:
106
+ """Write to a temp name and rename, so a crash leaves the existing alerts untouched."""
107
+ try:
108
+ out_dir.mkdir(parents=True, exist_ok=True)
109
+ except OSError as e:
110
+ raise FatalError(f"cannot write alerts to {out_dir}: {e}") from e
111
+ stamp = detected_at.strftime("%Y%m%dT%H%M%S")
112
+ final = out_dir / f"alerts-{stamp}-{uuid4().hex[:8]}.parquet"
113
+ temp = out_dir / f".{final.name}.tmp"
114
+ try:
115
+ pq.write_table(pa.Table.from_pylist(rows, schema=ALERT_SCHEMA), temp) # pyright: ignore[reportUnknownMemberType]
116
+ os.replace(temp, final)
117
+ except OSError as e:
118
+ temp.unlink(missing_ok=True)
119
+ raise FatalError(f"cannot write alerts to {out_dir}: {e}") from e
120
+ except BaseException:
121
+ temp.unlink(missing_ok=True)
122
+ raise
vigil/testing.py ADDED
@@ -0,0 +1,54 @@
1
+ """Run each rule against its own fixture cases. A case runs alone in a fresh `events`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import duckdb
6
+
7
+ from arsenal_core.errors import FatalError
8
+ from vigil.events import fixture_events
9
+ from vigil.rule import Case, Rule, detection_sql
10
+
11
+
12
+ def check_rule(rule: Rule) -> list[str]:
13
+ """Failure messages for one rule; an empty list means it passes."""
14
+ failures: list[str] = []
15
+ if not rule.tests.match:
16
+ failures.append("no match case (tests.match is empty)")
17
+ if not rule.tests.no_match:
18
+ failures.append("no no_match case (tests.no_match is empty)")
19
+ for index, case in enumerate(rule.tests.match):
20
+ label = f"match[{index}]"
21
+ hits, error = _run_case(rule, label, case)
22
+ if error:
23
+ failures.append(error)
24
+ elif hits == 0:
25
+ failures.append(f"{label}: expected a detection, got none")
26
+ for index, case in enumerate(rule.tests.no_match):
27
+ label = f"no_match[{index}]"
28
+ hits, error = _run_case(rule, label, case)
29
+ if error:
30
+ failures.append(error)
31
+ elif hits:
32
+ failures.append(f"{label}: expected no detection, got {hits}")
33
+ return failures
34
+
35
+
36
+ def check_rules(rules: list[Rule]) -> dict[str, list[str]]:
37
+ return {rule.id: check_rule(rule) for rule in rules}
38
+
39
+
40
+ def _run_case(rule: Rule, label: str, case: Case) -> tuple[int, str | None]:
41
+ """(hit count, None), or (0, failure message) when DuckDB rejects the case or the query."""
42
+ rows = case if isinstance(case, list) else [case]
43
+ try:
44
+ con = fixture_events(rows)
45
+ except FatalError as e:
46
+ raise FatalError(f"rule {rule.id!r} {label}: {e}") from e
47
+ except duckdb.Error as e:
48
+ return 0, f"{label}: error running case: {e}"
49
+ try:
50
+ return len(con.execute(detection_sql(rule.query)).fetchall()), None
51
+ except duckdb.Error as e:
52
+ return 0, f"{label}: error running case: {e}"
53
+ finally:
54
+ con.close()
vigil/unpack.py ADDED
@@ -0,0 +1,66 @@
1
+ """Turn CloudTrail log files into JSONL that Pugio's file source can read.
2
+
3
+ CloudTrail delivers `{"Records": [event, ...]}` files, usually gzipped. Each event becomes
4
+ one line `{"raw": "<the event as a JSON string>"}`: one string column, so events with
5
+ different nested shapes still load with a fixed schema. Field extraction happens later in SQL.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import gzip
11
+ import json
12
+ import os
13
+ import zlib
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from arsenal_core.errors import FatalError
18
+
19
+ # Trails with log file validation also write digest files here; they have no `Records`.
20
+ DIGEST_DIR = "CloudTrail-Digest"
21
+
22
+
23
+ def unpack_cloudtrail(src_dir: Path, out_file: Path) -> int:
24
+ if not src_dir.is_dir():
25
+ raise FatalError(f"source directory not found: {src_dir}")
26
+ files = sorted(
27
+ file
28
+ for file in [*src_dir.rglob("*.json"), *src_dir.rglob("*.json.gz")]
29
+ if DIGEST_DIR not in file.relative_to(src_dir).parts
30
+ )
31
+ if not files:
32
+ raise FatalError(f"no CloudTrail files (*.json, *.json.gz) under {src_dir}")
33
+ out_file.parent.mkdir(parents=True, exist_ok=True)
34
+ temp = out_file.with_name(f".{out_file.name}.tmp")
35
+ count = 0
36
+ try:
37
+ with temp.open("w", encoding="utf-8") as handle:
38
+ for file in files:
39
+ for record in _records(file):
40
+ raw = json.dumps(record, ensure_ascii=False, separators=(",", ":"))
41
+ handle.write(json.dumps({"raw": raw}, ensure_ascii=False) + "\n")
42
+ count += 1
43
+ os.replace(temp, out_file)
44
+ except FatalError:
45
+ temp.unlink(missing_ok=True)
46
+ raise
47
+ except OSError as e:
48
+ temp.unlink(missing_ok=True)
49
+ raise FatalError(f"cannot write {out_file}: {e}") from e
50
+ except BaseException:
51
+ temp.unlink(missing_ok=True)
52
+ raise
53
+ return count
54
+
55
+
56
+ def _records(file: Path) -> list[Any]:
57
+ opener = gzip.open if file.suffix == ".gz" else open
58
+ try:
59
+ with opener(file, "rt", encoding="utf-8") as handle:
60
+ document: Any = json.load(handle)
61
+ except (OSError, ValueError, EOFError, zlib.error) as e:
62
+ raise FatalError(f"cannot read {file}: {e}") from e
63
+ records: Any = document.get("Records") if isinstance(document, dict) else None # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
64
+ if not isinstance(records, list):
65
+ raise FatalError(f'{file}: not a CloudTrail log file (no "Records" array)')
66
+ return records # pyright: ignore[reportUnknownVariableType]