"""Check TSA URL from USB Token certificate."""
import sys, ctypes
from ctypes import wintypes, c_void_p, c_byte, POINTER, Structure, cast, string_at
from asn1crypto import x509 as X

sys.path.insert(0, '.')

crypt32 = ctypes.WinDLL('crypt32.dll')
crypt32.CertOpenSystemStoreW.argtypes  = [c_void_p, wintypes.LPCWSTR]
crypt32.CertOpenSystemStoreW.restype   = c_void_p
crypt32.CertEnumCertificatesInStore.argtypes = [c_void_p, c_void_p]
crypt32.CertEnumCertificatesInStore.restype  = c_void_p
crypt32.CertCloseStore.argtypes = [c_void_p, wintypes.DWORD]

class CERT_CTX(Structure):
    _fields_ = [("enc", wintypes.DWORD), ("pb", POINTER(c_byte)),
                ("cb", wintypes.DWORD),  ("info", c_void_p), ("store", c_void_p)]

_TSA_MAP = [
    (["viettel"],                "http://ca.viettel.vn/tsa"),
    (["vnpt", "safeca"],         "http://ca.vnpt.vn/tsa"),
    (["fpt"],                    "http://ca.fpt.com.vn/tsa"),
    (["bkav"],                   "http://ca.bkav.com.vn/tsa"),
    (["smartsign","smart sign"], "http://ca.smartsign.vn/tsa"),
    (["misa"],                   "http://ca.misa.com.vn/tsa"),
    (["nacencomm"],              "http://ca.nacencomm.vn/tsa"),
    (["newca"],                  "http://ca.newca.vn/tsa"),
]

def detect_tsa(issuer_str):
    s = issuer_str.lower()
    for kws, url in _TSA_MAP:
        if any(k in s for k in kws):
            return url
    return None

import urllib.request

h = crypt32.CertOpenSystemStoreW(None, "My")
p = None
count = 0
print("=" * 55)
print("  DANH SÁCH CHỨNG THƯ TRONG WINDOWS STORE (My)")
print("=" * 55)
while True:
    p = crypt32.CertEnumCertificatesInStore(h, p)
    if not p:
        break
    try:
        ctx = cast(p, POINTER(CERT_CTX)).contents
        der = string_at(ctx.pb, ctx.cb)
        cert = X.Certificate.load(der)
        subj   = cert.subject.human_friendly
        issuer = cert.issuer.human_friendly
        tsa    = detect_tsa(issuer)
        count += 1
        print(f"\n[{count}] Subject : {subj[:70]}")
        print(f"    Issuer  : {issuer[:70]}")
        if tsa:
            # Test kết nối
            try:
                urllib.request.urlopen(tsa, timeout=4)
                status = "✅ KẾT NỐI OK"
            except Exception as e:
                status = f"❌ LỖI: {e}"
            print(f"    TSA URL : {tsa}")
            print(f"    TSA Test: {status}")
        else:
            print(f"    TSA URL : (Không nhận diện được CA VN)")
    except Exception as e:
        print(f"  [!] Bỏ qua cert lỗi: {e}")

crypt32.CertCloseStore(h, 0)
if count == 0:
    print("Không có cert nào trong store My. Hãy cắm USB Token vào!")
print("\n" + "=" * 55)
