File size: 6,546 Bytes
8c486a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595e190
8c486a8
49d1c75
8c486a8
595e190
 
 
8c486a8
 
595e190
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c486a8
 
 
 
 
 
 
49d1c75
 
 
8c486a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""Shared fixtures for OpenRange test suite."""

from pathlib import Path

import pytest

ROOT = Path(__file__).parent.parent


@pytest.fixture
def manifests_dir():
    return ROOT / "manifests"


@pytest.fixture
def tier1_manifest(manifests_dir):
    """Load tier1_basic.yaml as dict."""
    import yaml

    with open(manifests_dir / "tier1_basic.yaml") as f:
        return yaml.safe_load(f)


@pytest.fixture
def tier2_manifest(manifests_dir):
    """Load tier2_corporate.yaml as dict."""
    import yaml

    with open(manifests_dir / "tier2_corporate.yaml") as f:
        return yaml.safe_load(f)


@pytest.fixture
def tier3_manifest(manifests_dir):
    """Load tier3_enterprise.yaml as dict."""
    import yaml

    with open(manifests_dir / "tier3_enterprise.yaml") as f:
        return yaml.safe_load(f)


@pytest.fixture
def sample_snapshot_spec():
    """A valid SnapshotSpec for testing."""
    from open_range.protocols import (
        EvidenceItem,
        FlagSpec,
        GoldenPathStep,
        NPCTrafficSpec,
        SnapshotSpec,
        TaskSpec,
        TruthGraph,
        Vulnerability,
    )

    return SnapshotSpec(
        topology={
            "hosts": [
                "attacker", "firewall", "web", "mail",
                "db", "files", "ldap", "siem",
            ],
            "zones": {
                "external": ["attacker"],
                "dmz": ["web", "mail"],
                "internal": ["db", "files"],
                "management": ["ldap", "siem"],
            },
            "users": [
                {
                    "username": "admin",
                    "password": "admin123",
                    "groups": ["admins"],
                    "hosts": ["web", "db"],
                }
            ],
            "tier": 1,
        },
        truth_graph=TruthGraph(
            vulns=[
                Vulnerability(
                    id="vuln1",
                    type="sqli",
                    host="web",
                    service="php",
                    injection_point="/search?q=",
                    vulnerable_code=(
                        "$conn->query(\"SELECT * FROM products "
                        "WHERE name LIKE '%$_GET[q]%'\");"
                    ),
                    root_cause="Unsanitized input in SQL query",
                    blast_radius="data exposure",
                    remediation="Use parameterized queries",
                )
            ],
            exploit_chain=[],
        ),
        flags=[
            FlagSpec(
                id="flag1",
                value="FLAG{test_sqli_123}",
                path="/var/flags/flag1.txt",
                host="db",
            )
        ],
        golden_path=[
            GoldenPathStep(
                step=1,
                command="nmap -sV 10.0.1.0/24",
                expect_in_stdout="80/tcp open http",
            ),
            GoldenPathStep(
                step=2,
                command="curl 'http://web/search?q=test'",
                expect_in_stdout="products",
            ),
            GoldenPathStep(
                step=3,
                command=(
                    "curl 'http://web/search?q=test%27+UNION+"
                    "SELECT+flag+FROM+flags--'"
                ),
                expect_in_stdout="FLAG{test_sqli_123}",
            ),
            GoldenPathStep(
                step=4,
                command="nmap -sV 10.0.2.0/24",
                expect_in_stdout="3306/tcp open mysql",
            ),
            GoldenPathStep(
                step=5,
                command="curl http://web/",
                expect_in_stdout="Welcome",
            ),
            GoldenPathStep(
                step=6,
                command="curl http://web/login",
                expect_in_stdout="Login",
            ),
            GoldenPathStep(
                step=7,
                command="mysql -h db -u admin -padmin123 -e 'SHOW DATABASES'",
                expect_in_stdout="flags",
            ),
            GoldenPathStep(
                step=8,
                command="submit_flag FLAG{test_sqli_123}",
                expect_in_stdout="correct",
            ),
        ],
        evidence_spec=[
            EvidenceItem(
                type="log_entry",
                location="web_access_log",
                pattern="SQL injection pattern in access log",
            )
        ],
        npc_traffic=NPCTrafficSpec(level=0, rate_lambda=30.0),
        npc_personas=[],
        task=TaskSpec(
            red_briefing=(
                "Target network has web services. Find vulnerabilities "
                "and capture the flag."
            ),
            blue_briefing=(
                "Monitor SIEM for suspicious activity. Investigate "
                "and respond to threats."
            ),
        ),
    )


@pytest.fixture
def mock_containers():
    """Mock ContainerSet for testing without Docker."""

    class MockContainerSet:
        def __init__(self):
            self.exec_results = {}  # {(container, cmd_fragment): output}
            self.exec_status = {}  # {(container, cmd_fragment): exit_code}
            self.healthy = set()
            self.restarted = []  # track restart calls: list of container names

        @staticmethod
        def _lookup(mapping, container: str, cmd: str):
            for (c, pattern), result in mapping.items():
                if c == container and pattern in cmd:
                    return result
            return None

        async def exec_run(self, container: str, cmd: str, **kwargs):
            from open_range.protocols import ExecResult

            output = self._lookup(self.exec_results, container, cmd)
            status = self._lookup(self.exec_status, container, cmd)
            text = output if isinstance(output, str) else ""
            code = int(status) if status is not None else 0
            if code == 0:
                return ExecResult(stdout=text, exit_code=0)
            return ExecResult(stderr=text, exit_code=code)

        async def exec(self, container: str, cmd: str, **kwargs) -> str:
            result = await self.exec_run(container, cmd, **kwargs)
            return result.combined_output

        async def is_healthy(self, container: str) -> bool:
            return container in self.healthy

        async def cp(self, container, src, dest):
            pass

        async def restart(self, container: str, **kwargs) -> None:
            self.restarted.append(container)

    return MockContainerSet()