|
| 1 | +import glob |
| 2 | +import os |
| 3 | +import sys |
| 4 | +from typing import List, Literal, Optional |
| 5 | + |
| 6 | +import yaml |
| 7 | +from pydantic import BaseModel, HttpUrl, RootModel, ValidationError, constr, model_validator, field_validator, ConfigDict |
| 8 | + |
| 9 | +# Disable datetime parsing |
| 10 | +yaml.SafeLoader.yaml_implicit_resolvers = {k: [r for r in v if r[0] != 'tag:yaml.org,2002:timestamp'] for k, v in yaml.SafeLoader.yaml_implicit_resolvers.items()} |
| 11 | + |
| 12 | + |
| 13 | +safe_str = constr(pattern=r'^([a-zA-Z0-9\s.,!?\'"():;\-\+_*#@/\\&%~=]|`[a-zA-Z0-9\s.,!?\'"():;\-\+_*#@/\\&<>%\{\}~=]+`|->)+$') |
| 14 | + |
| 15 | + |
| 16 | +class LolbasModel(BaseModel): |
| 17 | + model_config = ConfigDict(extra="forbid") |
| 18 | + |
| 19 | + |
| 20 | +class AliasItem(LolbasModel): |
| 21 | + Alias: Optional[str] |
| 22 | + |
| 23 | + |
| 24 | +class TagItem(RootModel[dict[constr(pattern=r'^[A-Z]'), str]]): |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +class CommandItem(LolbasModel): |
| 29 | + Command: str |
| 30 | + Description: safe_str |
| 31 | + Usecase: safe_str |
| 32 | + Category: Literal['ADS', 'AWL Bypass', 'Compile', 'Conceal', 'Copy', 'Credentials', 'Decode', 'Download', 'Dump', 'Encode', 'Execute', 'Reconnaissance', 'Tamper', 'UAC Bypass', 'Upload'] |
| 33 | + Privileges: str |
| 34 | + MitreID: constr(pattern=r'^T[0-9]{4}(\.[0-9]{3})?$') |
| 35 | + OperatingSystem: str |
| 36 | + Tags: Optional[List[TagItem]] = None |
| 37 | + |
| 38 | + |
| 39 | +class FullPathItem(LolbasModel): |
| 40 | + Path: constr(pattern=r'^(([cC]:)\\([a-zA-Z0-9\-\_\. \(\)<>]+\\)*([a-zA-Z0-9_\-\.]+\.[a-z0-9]{3})|no default)$') |
| 41 | + |
| 42 | + |
| 43 | +class CodeSampleItem(LolbasModel): |
| 44 | + Code: str |
| 45 | + |
| 46 | + |
| 47 | +class DetectionItem(LolbasModel): |
| 48 | + IOC: Optional[str] = None |
| 49 | + Sigma: Optional[HttpUrl] = None |
| 50 | + Analysis: Optional[HttpUrl] = None |
| 51 | + Elastic: Optional[HttpUrl] = None |
| 52 | + Splunk: Optional[HttpUrl] = None |
| 53 | + BlockRule: Optional[HttpUrl] = None |
| 54 | + |
| 55 | + @model_validator(mode="after") |
| 56 | + def validate_exclusive_urls(cls, values): |
| 57 | + url_fields = ['IOC', 'Sigma', 'Analysis', 'Elastic', 'Splunk', 'BlockRule'] |
| 58 | + present = [field for field in url_fields if values.__dict__.get(field) is not None] |
| 59 | + |
| 60 | + if len(present) != 1: |
| 61 | + raise ValueError(f"Exactly one of the following must be provided: {url_fields}.", f"Currently set: {present or 'none'}") |
| 62 | + |
| 63 | + return values |
| 64 | + |
| 65 | + |
| 66 | +class ResourceItem(LolbasModel): |
| 67 | + Link: HttpUrl |
| 68 | + |
| 69 | + |
| 70 | +class AcknowledgementItem(LolbasModel): |
| 71 | + Person: str |
| 72 | + Handle: Optional[constr(pattern=r'^(@(\w){1,15})?$')] = None |
| 73 | + |
| 74 | + |
| 75 | +class MainModel(LolbasModel): |
| 76 | + Name: str |
| 77 | + Description: safe_str |
| 78 | + Aliases: Optional[List[AliasItem]] = None |
| 79 | + Author: str |
| 80 | + Created: constr(pattern=r'\d{4}-\d{2}-\d{2}') |
| 81 | + Commands: List[CommandItem] |
| 82 | + Full_Path: List[FullPathItem] |
| 83 | + Code_Sample: Optional[List[CodeSampleItem]] = None |
| 84 | + Detection: Optional[List[DetectionItem]] = None |
| 85 | + Resources: Optional[List[ResourceItem]] = None |
| 86 | + Acknowledgement: Optional[List[AcknowledgementItem]] = None |
| 87 | + |
| 88 | + |
| 89 | +if __name__ == "__main__": |
| 90 | + def escaper(x): return x.replace('%', '%25').replace('\r', '%0D').replace('\n', '%0A') |
| 91 | + |
| 92 | + yaml_files = glob.glob("yml/**", recursive=True) |
| 93 | + |
| 94 | + if not yaml_files: |
| 95 | + print("No YAML files found under 'yml/**'.") |
| 96 | + sys.exit(-1) |
| 97 | + |
| 98 | + has_errors = False |
| 99 | + for file_path in yaml_files: |
| 100 | + if os.path.isfile(file_path) and not file_path.startswith('yml/HonorableMentions/'): |
| 101 | + try: |
| 102 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 103 | + data = yaml.safe_load(f) |
| 104 | + MainModel(**data) |
| 105 | + print(f"✅ Valid: {file_path}") |
| 106 | + except ValidationError as ve: |
| 107 | + print(f"❌ Validation error in {file_path}:\n{ve}\n") |
| 108 | + for err in ve.errors(): |
| 109 | + # GitHub Actions error format |
| 110 | + print(err) |
| 111 | + path = '.'.join([str(x) for x in err.get('loc', [None])]) |
| 112 | + msg = err.get('msg', 'Unknown validation error') |
| 113 | + print(f"::error file={file_path},line=1,title={escaper(err.get('type') or 'Validation error')}::{escaper(msg)}: {escaper(path)}") |
| 114 | + has_errors = True |
| 115 | + except Exception as e: |
| 116 | + print(f"⚠️ Error processing {file_path}: {e}\n") |
| 117 | + print(f"::error file={file_path},line=1,title=Processing error::Error processing file: {escaper(e)}") |
| 118 | + has_errors = True |
| 119 | + |
| 120 | + sys.exit(-1 if has_errors else 0) |
0 commit comments