#!/usr/bin/env python3
"""Create the fictional SecTools Lab phishing case via the MISP REST API, read it back,
check correlation, tagging, ATT&CK galaxy, publishing and STIX 2.1 export.
Run in lab/: python3 verify.py. Safe to rerun: fixed UUIDs keep the same events."""
import json
import uuid
from misplab import api, find_event

NS = uuid.UUID('6f1c9a52-7d0b-4f36-9a51-5ec7001ab000')
CASE = str(uuid.uuid5(NS, 'sectools-lab-phishing-case'))
FOLLOW = str(uuid.uuid5(NS, 'sectools-lab-follow-up-sighting'))
TLP = 'tlp:clear'
ATTACK = 'misp-galaxy:mitre-attack-pattern="Phishing - T1566"'

# 1. 本機載入分類法與 Galaxy（讀取映像內建 JSON，不需外部網路）
api('POST', '/taxonomies/update')
tlp = next(t['Taxonomy'] for t in api('GET', '/taxonomies/index') if t['Taxonomy']['namespace'] == 'tlp')
if not tlp['enabled']:
    api('POST', f"/taxonomies/enable/{tlp['id']}")
api('POST', f"/taxonomies/addTag/{tlp['id']}")  # 啟用後還要建立該分類法的標籤
api('POST', '/galaxies/update')
api('POST', '/objectTemplates/update')
print('PASS taxonomies, galaxies + object templates loaded locally; tlp taxonomy enabled')


def ensure_event(event_uuid, info, attributes):
    existing = find_event(event_uuid)
    if existing:
        return existing, False
    body = {'Event': {'uuid': event_uuid, 'info': info, 'date': '2026-11-27', 'distribution': 0,
                      'threat_level_id': 3, 'analysis': 1, 'Attribute': attributes}}
    created = api('POST', '/events/add', body)['Event']
    return created, True


attrs = [
    {'type': 'domain', 'category': 'Network activity', 'value': 'login.example', 'to_ids': False,
     'comment': 'Fictional phishing landing page named in the training report; purpose unknown.'},
    {'type': 'ip-dst', 'category': 'Network activity', 'value': '192.0.2.10', 'to_ids': True,
     'comment': 'RFC 5737 documentation address used as a fictional C2 example.'},
    {'type': 'email-src', 'category': 'Payload delivery', 'value': 'billing@login.example', 'to_ids': False},
    {'type': 'sha256', 'category': 'Payload delivery', 'to_ids': True,
     'value': '0000000000000000000000000000000000000000000000000000000000005ec7',
     'comment': 'Placeholder hash; no real sample exists.'},
]
event, created = ensure_event(CASE, 'SecTools Lab — 釣魚事件建模練習（虛構）', attrs)
eid = event['id']


def ensure_tag(event_id, event_uuid, tag):
    current = {t['name'] for t in (find_event(event_uuid).get('Tag') or [])}
    if tag not in current:
        assert api('POST', f'/events/addTag/{event_id}', {'tag': tag}).get('saved') is not False, tag


ensure_tag(eid, CASE, TLP)
cluster = api('POST', '/galaxy_clusters/restSearch', {'value': 'Phishing - T1566'})['response'][0]['GalaxyCluster']
api('POST', f'/galaxies/attachCluster/{eid}/event', {'Galaxy': {'target_id': cluster['id']}})

obj_template = 'domain-ip'
event = find_event(CASE)
if not any(o['name'] == obj_template for o in event.get('Object', [])):
    tpl = next(t['ObjectTemplate'] for t in api('GET', '/objectTemplates/index') if t['ObjectTemplate']['name'] == obj_template)
    api('POST', f"/objects/add/{eid}/{tpl['id']}", {'Object': {'name': obj_template, 'meta-category': 'network',
        'comment': 'Fictional pairing from the training report.',
        'Attribute': [{'object_relation': 'domain', 'type': 'domain', 'value': 'login.example', 'to_ids': False},
                      {'object_relation': 'ip', 'type': 'ip-dst', 'value': '192.0.2.10', 'to_ids': True}]}})

event = find_event(CASE)
values = {a['value'] for a in event['Attribute']}
assert {'login.example', '192.0.2.10', 'billing@login.example'} <= values
assert any(o['name'] == obj_template for o in event['Object'])
tags = {t['name'] for t in event.get('Tag', [])}
assert TLP in tags and ATTACK in tags, tags
assert any(g['type'] == 'mitre-attack-pattern' for g in event.get('Galaxy', []))
print(f"PASS write/read: event + {len(event['Attribute'])} attributes + domain-ip object ({'created' if created else 'reused'})")
print('PASS context: tlp:clear tag + ATT&CK galaxy cluster Phishing - T1566')

# 2. 第二個事件重複出現 192.0.2.10，應產生關聯（correlation）
follow, _ = ensure_event(FOLLOW, 'SecTools Lab — 後續觀察：同一測試 IP（虛構）', [
    {'type': 'ip-dst', 'category': 'Network activity', 'value': '192.0.2.10', 'to_ids': True,
     'comment': 'Same documentation address observed in a fictional follow-up.'}])
ensure_tag(follow['id'], FOLLOW, TLP)
event = find_event(CASE)
related = [r['Event']['uuid'] for r in event.get('RelatedEvent', [])]
assert FOLLOW in related, related
print('PASS correlation: 192.0.2.10 links the case to the follow-up event')

# 3. 重跑不會產生重複事件
again, created_again = ensure_event(CASE, 'ignored', [])
assert not created_again and again['id'] == eid
hits = api('POST', '/events/restSearch', {'eventinfo': 'SecTools Lab — 釣魚事件建模練習%', 'returnFormat': 'json', 'metadata': True})
assert len(hits['response']) == 1
print('PASS rerun: fixed UUID keeps one event')

# 4. 發布與搜尋
api('POST', f'/events/publish/{eid}')
event = find_event(CASE)
assert event['published'] is True
ids = api('POST', '/attributes/restSearch', {'eventid': eid, 'to_ids': 1, 'returnFormat': 'json'})['response']['Attribute']
assert {a['value'] for a in ids} >= {'192.0.2.10'} and 'login.example' not in {a['value'] for a in ids}
print(f'PASS publish + to_ids search: {len(ids)} detection-ready attributes; login.example stays context-only')

# 5. STIX 2.1 匯出（misp-stix 於 misp-core 內轉換）
bundle = api('POST', '/events/restSearch', {'uuid': CASE, 'returnFormat': 'stix2'})
types = [o['type'] for o in bundle['objects']]
assert bundle['type'] == 'bundle' and 'report' in types and 'indicator' in types and 'attack-pattern' in types, set(types)
print(f'PASS STIX 2.1 export: report + indicator + attack-pattern; objects={len(types)}')
print('RESULT ' + json.dumps({'event_uuid': CASE, 'follow_up_uuid': FOLLOW, 'stix_objects': len(types)}, ensure_ascii=False))
