Files
capa/web/rules/scripts/modified-dates.py
Willi Ballenthin a33f67b48e add landing page and rules website (#2310)
* web: index: add gif of capa running

* index: add screencast of running capa

produced via:

```
asciinema capa.cast
./capa Practical\ Malware\ Analysis\ Lab\ 01-01.dll_
<ctrl-d>
agg --no-loop --theme solarized-light capa.cast capa.gif
```

* web: index: start to sketch out style

* web: landing page

* web: merge rules website

* web: rules: update bootstrap and integrate rules

* web: rules: use pygments to syntax highlight rules

Use the Pygments syntax-highlighting library to parse
and render the YAML rule content. This way we don't have
to manually traverse the rule nodes and emit lists; instead,
we rely on the fact that YAML is pretty easy for humans
to read and let them consume it directly, with some text 
formatting to help hint at the types/structure.

* web: rules: use capa to load rule content

capa (the library) has routines for deserializing the YAML
content into structured objects, which means we can use tools
like mypy to find bugs. So, prefer to use those routines instead
of parsing YAML ourselves.

* web: rules: linters

Run and fix the issues identified by the following linters:

  - isort
  - black
  - ruff
  - mypy

* web: rules: add some links to rule page

Add links to the following external resources:

  - GitHub rule source in capa-rules repo
  - VirusTotal search for matching samples

* web: rules: accept ?q= parameter for initial search

Update the rules landing page to accept a HTTP
query parameter named "q" that specifies an initial 
search term to to pass to pagefind. This enables
external pages link to rule searches.

* web: rules: add link to namespace search

* web: rules: use consistent header

Import header from root capa landing page.

* web: rules: add umami script

* web: add initial whats new section, TODOs

* web: rules: remove old images

* changelog

* CI: remove temporary branch push event triggers

* Delete web/rules/public/css/bootstrap-4.5.2.min.css

* Delete web/rules/public/js/bootstrap-4.5.2.min.js

* Delete web/public/img/capa.cast

* Rename readme.md to README.md

* web: rules: add scripts to pre-commit configs

* web: rules: add scripts to pre-commit configs

* lints

* ci: add temporary branch push trigger to get incremental builds

* web: rules: assert start_dir must exist

* ci: web: rules: deep checkout so we can get rule history

* web: rules: check output of subprocess

* web: rules: factor out common CSS

* web: rules: fix header links

* web: rules: only index rule content, not surrounding text

* ci: web: remote temporary branch push trigger
2024-08-22 09:42:40 +02:00

93 lines
3.4 KiB
Python

"""
Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at: [package root]/LICENSE.txt
Unless required by applicable law or agreed to in writing, software distributed under the License
is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
"""
import os
import sys
import logging
import subprocess
from pathlib import Path
from datetime import datetime, timedelta
logger = logging.getLogger(__name__)
start_dir = Path(sys.argv[1])
output_file = Path(sys.argv[2])
assert start_dir.exists(), "start directory must exist"
def get_yml_files_and_dates(start_dir: Path):
yml_files = []
for root, _, files in os.walk(start_dir):
for file in files:
if file.endswith(".yml") or file.endswith(".yaml"):
file_path = Path(root) / file
proc = subprocess.run(
[
"git",
"log",
"-1", # only show most recent commit
'--pretty="%ct"', # unix timestmp, https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt-emctem
file, # just the filename, will run from the containing directory
],
cwd=root, # the directory with the file we're inspecting
check=True,
capture_output=True,
)
last_modified_date = int(proc.stdout.decode("utf-8").partition("\n")[0].strip('"'))
yml_files.append((file_path, last_modified_date))
return yml_files
yml_files_and_dates = get_yml_files_and_dates(start_dir)
yml_files_and_dates.sort(key=lambda x: x[1], reverse=True)
current_date = datetime.now()
categories = [
("modified in the last day", current_date - timedelta(days=1)),
("modified in the last week", current_date - timedelta(days=7)),
("modified in the last month", current_date - timedelta(days=30)),
("modified in the last three months", current_date - timedelta(days=90)),
("modified in the last year", current_date - timedelta(days=365)),
]
def write_category(f, category_name, files):
f.write(f"=== {category_name} ===\n")
for file_path, last_modified_date in files:
last_modified_date_str = datetime.fromtimestamp(last_modified_date).strftime("%Y-%m-%d %H:%M:%S")
f.write(f"{file_path} {last_modified_date_str}\n")
f.write("\n")
with output_file.open("wt", encoding="utf-8") as f:
for title, delta in categories:
current_files = []
for file_path, last_modified_date in yml_files_and_dates:
last_modified_date_dt = datetime.fromtimestamp(last_modified_date)
if last_modified_date_dt > delta:
current_files.append((file_path, last_modified_date))
write_category(f, title, current_files)
for item in current_files:
yml_files_and_dates.remove(item)
write_category(f, "older", yml_files_and_dates)
logger.info("File names and modification dates have been written to %s", output_file)