de-vigil 0.8.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.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ *.egg-info/
5
+ dist/
6
+ .coverage
7
+ coverage.xml
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .arsenal/
11
+ data/
12
+ .DS_Store
de_vigil-0.8.0/LICENSE ADDED
@@ -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.
@@ -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,71 @@
1
+ # Vigil (`de-vigil`)
2
+
3
+ > 야간 순찰대. 정규화된 보안 로그에 탐지 룰을 실행하고, 룰이 비어 있는 곳을 알려 준다. (experimental)
4
+
5
+ 탐지 룰을 YAML 파일로 관리한다. 룰 하나는 메타데이터, `events`를 읽는 SELECT 한 개, 그리고 걸려야 하는
6
+ 케이스와 걸리면 안 되는 케이스로 이루어진다. 테스트가 없는 룰은 `vigil test`를 통과하지 못한다.
7
+
8
+ ## 설치
9
+
10
+ ```bash
11
+ pip install de-vigil
12
+ ```
13
+
14
+ ## 사용 예
15
+
16
+ ```bash
17
+ arsenal init cloudtrail-detect && arsenal run # 합성 CloudTrail 샘플 → data/events
18
+ vigil test # 룰마다 픽스처로 검증
19
+ vigil run --events data/events --out data/alerts # 새 alert만 기록 (다시 실행하면 0건)
20
+ vigil coverage --events data/events # 룰이 없는 ATT&CK 기법, 컬럼 NULL 비율
21
+ vigil unpack ./cloudtrail-logs --out input/ct.jsonl # CloudTrail 원본(*.json.gz)을 JSONL로
22
+ # (CloudTrail-Digest/ 아래 다이제스트 파일은 건너뜀)
23
+ ```
24
+
25
+ ## 룰 파일
26
+
27
+ ```yaml
28
+ id: aws-root-console-login
29
+ title: 루트 계정 콘솔 로그인
30
+ severity: high # low | medium | high | critical
31
+ attack: [T1078.004] # ATT&CK 기법 ID
32
+ source: cloudtrail
33
+ query: |
34
+ SELECT * FROM events
35
+ WHERE action = 'ConsoleLogin' AND actor_type = 'Root' AND outcome = 'success'
36
+ tests:
37
+ match:
38
+ - { action: ConsoleLogin, actor_type: Root, outcome: success }
39
+ no_match:
40
+ - { action: ConsoleLogin, actor_type: IAMUser, outcome: success }
41
+ ```
42
+
43
+ - `query`는 SELECT 한 개이고 결과에 `event_id`가 있어야 한다. `events` 말고는 읽지 못한다.
44
+ - 룰 파일은 `*.yaml`과 `*.yml`을 모두 읽는다.
45
+ - 탐지는 `event_id`가 `events`에 있는 이벤트다. `vigil test`와 `vigil run`이 같은 문장으로 센다. 그래서
46
+ `NULL AS event_id`를 돌려주는 룰이나 `event_id`가 NULL인 픽스처는 탐지로 세지 않는다.
47
+ - 케이스는 이벤트 하나이거나 이벤트 목록이다. 케이스마다 그 이벤트만 든 `events`에서 따로 실행한다.
48
+ - `events`의 컬럼은 [OCSF 대응표](../../docs/reference/vigil-ocsf-mapping.md)에 있다.
49
+
50
+ ## 종료 코드
51
+
52
+ | 코드 | 의미 |
53
+ |---|---|
54
+ | 0 | 정상 |
55
+ | 1 | 룰 테스트 실패, 실행 중 룰 오류, 또는 `--fail-on` 심각도 이상의 새 alert |
56
+ | 2 | 사용법이나 입력 오류 (룰 파일 오류, 이벤트 파일 없음, 필수 컬럼 없음이나 자료형 불일치, `--out`이 디렉터리가 아니거나 읽을 수 없는 Parquet이 있음, 쓰기 실패) |
57
+
58
+ ## 한계
59
+
60
+ - 배치만 한다. `vigil run`은 `events`를 메모리 DuckDB 테이블로 올려 읽으므로, 한 번에 읽는 이벤트가
61
+ 그 기계에 들어가야 한다.
62
+ - 로그 소스는 CloudTrail 관리 이벤트 하나다.
63
+ - 커버리지의 기준 기법 목록은 직접 고른 20개이고 ATT&CK 전체가 아니다.
64
+ - 같은 `--out`에 `vigil run`을 동시에 두 개 돌리면 같은 alert가 두 번 기록될 수 있다. 출력 디렉터리마다
65
+ 한 번에 하나만 실행한다.
66
+ - 룰 SQL에는 메모리 한도와 시간 제한이 없다. 아주 큰 조인은 DuckDB가 실행한 디렉터리의 `./.tmp`에 임시
67
+ 파일을 쓸 수 있다.
68
+ - `events`의 `event_time`은 `TIMESTAMP`(나노초 `TIMESTAMP_NS`도 허용)여야 한다. 문자열이나 시간대가 있는
69
+ 타임스탬프는 종료 코드 2로 거부한다.
70
+ - `mfa_used`와 `outcome`은 레시피의 `transform.yaml`이 정한 규칙으로 만든다. 그 밖의 로그를 쓰면 같은 규칙으로
71
+ 채워야 룰이 맞게 동작한다. 규칙은 [OCSF 대응표](../../docs/reference/vigil-ocsf-mapping.md)에 있다.
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "de-vigil"
3
+ version = "0.8.0"
4
+ description = "Vigil — run detection rules over normalized security logs and report coverage gaps"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ dependencies = [
10
+ "arsenal-core>=0.8,<0.9",
11
+ "duckdb>=1.0",
12
+ "pyarrow>=17",
13
+ "pydantic>=2",
14
+ "pyyaml>=6",
15
+ "typer>=0.12",
16
+ ]
17
+ classifiers = [
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "License :: OSI Approved :: Apache Software License",
22
+ "Operating System :: OS Independent",
23
+ "Intended Audience :: Developers",
24
+ "Topic :: Security",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/KooEric/de-arsenal"
29
+ Repository = "https://github.com/KooEric/de-arsenal"
30
+
31
+ [project.scripts]
32
+ vigil = "vigil.cli:app"
33
+
34
+ [build-system]
35
+ requires = ["hatchling"]
36
+ build-backend = "hatchling.build"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/vigil"]
@@ -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")
@@ -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)}))