forked from mtusi2026/mtusi2026lab7
Щербацевич-БПИ2302-на 3
This commit is contained in:
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-3 negative checks that the public smoke does not cover."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
CA = ROOT / "secrets" / "certs" / "ca.crt"
|
||||
BASE = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
|
||||
|
||||
|
||||
def compose(*args, timeout=180):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", str(ROOT / ".env"), *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def trusted():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
with urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=10) as response:
|
||||
body = response.read()
|
||||
if response.status != 200:
|
||||
raise SystemExit("trusted HTTPS did not return 200")
|
||||
return body
|
||||
|
||||
|
||||
def untrusted():
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
ctx.check_hostname = True
|
||||
try:
|
||||
urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=5).read()
|
||||
except urllib.error.URLError as exc:
|
||||
if not isinstance(exc.reason, ssl.SSLCertVerificationError):
|
||||
raise SystemExit("untrusted CA failed for a non-certificate reason")
|
||||
return
|
||||
raise SystemExit("empty trust store was accepted")
|
||||
|
||||
|
||||
def closed_port():
|
||||
import socket
|
||||
|
||||
sock = socket.socket()
|
||||
sock.settimeout(2)
|
||||
try:
|
||||
result = sock.connect_ex(("127.0.0.1", 8080))
|
||||
finally:
|
||||
sock.close()
|
||||
if result == 0:
|
||||
raise SystemExit("plaintext port 8080 is reachable on the host")
|
||||
|
||||
|
||||
def rate_limit():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
raw = base64.b64encode(b"rate_limit_user:wrong-password-value").decode("ascii")
|
||||
saw = None
|
||||
for _ in range(12):
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
method="POST",
|
||||
headers={"Authorization": "Basic " + raw, "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(request, context=ctx, timeout=20).read()
|
||||
code = 200
|
||||
headers = {}
|
||||
except urllib.error.HTTPError as exc:
|
||||
code = exc.code
|
||||
headers = exc.headers
|
||||
exc.read()
|
||||
saw = code
|
||||
if code == 429:
|
||||
if not headers.get("Retry-After"):
|
||||
raise SystemExit("429 without Retry-After")
|
||||
return
|
||||
raise SystemExit("login was not rate limited, last status %s" % saw)
|
||||
|
||||
|
||||
def oversized():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
payload = b'{"username":"abc","display_name":"x","password":"' + (b"a" * 70000) + b'"}'
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/users",
|
||||
data=payload,
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json", "Accept": "application/json"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(request, context=ctx, timeout=20).read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 413:
|
||||
raise SystemExit("oversized body returned %s" % exc.code) from None
|
||||
return
|
||||
raise SystemExit("oversized body was accepted")
|
||||
|
||||
|
||||
def openbao_deny():
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.environ["BAO_ADDR"] = "https://127.0.0.1:8200"
|
||||
os.environ["BAO_CACERT"] = str(CA)
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
role = (ROOT / "secrets" / "runtime" / "worker" / "role_id").read_text(encoding="utf-8").strip()
|
||||
secret = (ROOT / "secrets" / "runtime" / "worker" / "secret_id").read_text(encoding="utf-8").strip()
|
||||
body = json.dumps({"role_id": role, "secret_id": secret}).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/auth/approle/login",
|
||||
data=body,
|
||||
method="POST",
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
|
||||
token = json.loads(response.read().decode("utf-8"))["auth"]["client_token"]
|
||||
own = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/secret/data/messenger/worker",
|
||||
headers={"X-Vault-Token": token},
|
||||
)
|
||||
with urllib.request.urlopen(own, context=ctx, timeout=10) as response:
|
||||
if response.status != 200:
|
||||
raise SystemExit("worker cannot read its own secret")
|
||||
foreign = urllib.request.Request(
|
||||
"https://127.0.0.1:8200/v1/secret/data/messenger/api",
|
||||
headers={"X-Vault-Token": token},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(foreign, context=ctx, timeout=10).read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 403:
|
||||
raise SystemExit("worker read of api secret returned %s" % exc.code) from None
|
||||
return
|
||||
raise SystemExit("worker token read the api secret")
|
||||
|
||||
|
||||
def mtls():
|
||||
proc = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
"-v",
|
||||
"%s:/probe.py:ro" % (ROOT / "scripts" / "mtls_probe.py"),
|
||||
"-v",
|
||||
"%s:/certs:ro" % (ROOT / "secrets" / "certs"),
|
||||
"api",
|
||||
"/probe.py",
|
||||
)
|
||||
sys.stdout.write(proc.stdout)
|
||||
sys.stderr.write(proc.stderr)
|
||||
if proc.returncode != 0:
|
||||
raise SystemExit("mTLS probe failed")
|
||||
|
||||
|
||||
def main():
|
||||
trusted()
|
||||
print("PASS trusted HTTPS")
|
||||
untrusted()
|
||||
print("PASS untrusted CA rejected")
|
||||
closed_port()
|
||||
print("PASS host port 8080 is closed")
|
||||
rate_limit()
|
||||
print("PASS login rate limit")
|
||||
oversized()
|
||||
print("PASS request size limit")
|
||||
openbao_deny()
|
||||
print("PASS OpenBao worker policy deny")
|
||||
mtls()
|
||||
evidence = ROOT / "evidence"
|
||||
evidence.mkdir(exist_ok=True)
|
||||
(evidence / "level7.json").write_text(
|
||||
json.dumps({"result": "pass", "base_url": BASE}, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print("PASS level 3 security checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user