BERKYT

task 1 v 3

Jun 7th, 2022 (edited)
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.31 KB | None | 0 0
  1. # ======================================================================================================================
  2.  
  3. # Authors: BERKYT, Walgala
  4. # Group: BSBO-08-19
  5.  
  6. # ======================================================================================================================
  7.  
  8. # Формат флага: XXX{}
  9. # Формат ссылки: https://task1.tasks.rubikoid.ru/md5(c3e97dd6e97fb5125688c97f36720cbe + secret )+ .php
  10.  
  11. import hashlib
  12. import random
  13. import re
  14. import easyocr
  15. import threading
  16. import time
  17.  
  18. from rich.console import Console
  19. from selenium import webdriver
  20. from selenium.webdriver.common.by import By
  21.  
  22.  
  23. link = 'https://task1.tasks.rubikoid.ru/c3e97dd6e97fb5125688c97f36720cbe.php'
  24. path_to_browser = r"D:\Downloads\chromedriver.exe"
  25. console = Console()
  26. ignore_words = ['Approved! Use secret to create a link for next step! next Chain step secret is:',
  27. 'gimmie a value whose MD5 ends with this 4 chars from captcha:', 'Cmon Human!', '<img src="captcha.php" alt="Captcha Image">']
  28. im_1_path = 'unknown.png'
  29.  
  30.  
  31. class Wait():
  32.     wait_flag = True
  33.     on_switch = True
  34.  
  35.  
  36. def switch():
  37.     while True:
  38.         waiting(10)
  39.         Wait.wait_flag = False
  40.         console.print(f'{Wait.wait_flag=}', style='bold underline yellow')
  41.  
  42.  
  43. def waiting(wait_time):
  44.     time.sleep(wait_time)
  45.  
  46.  
  47. def recognize_text(img_path):
  48.     reader = easyocr.Reader(['en'])
  49.     return reader.readtext(img_path)
  50.  
  51.  
  52. def replace_dict(dict_words: dict, line: str) -> str:
  53.     for old_word, new_word in dict_words.items():
  54.         line = line.replace(str(old_word), str(new_word))
  55.  
  56.     return line
  57.  
  58.  
  59. def log(data: str):
  60.     with open('tmp_log.txt', 'a') as log_file:
  61.         log_file.write(str(data) + '\n')
  62.  
  63.  
  64. def generate_key(alphabet: str = '0123456789abcdefghijklmnopqrstuvwxyz', length: int = 4) -> str:
  65.     key = ''
  66.  
  67.     for _ in range(length):
  68.         key += random.choice(alphabet)
  69.  
  70.     return key
  71.  
  72.  
  73. def parse_html( responce: str, pattern: str = r'(?<=name="hash" value=").+?(?=")') -> list:
  74.     return re.findall(pattern, responce)
  75.  
  76.  
  77. def get_secret(sourse_code_site: list) -> str:
  78.     for line in sourse_code_site:
  79.         secret = parse_html(line, r'(?<=<br>).+?(?=<br>)')
  80.         secret = str(list(set(secret) - set(ignore_words))[0]).replace('<br>', '')
  81.  
  82.         if secret:
  83.             console.print(f'Вариант секрета: {secret=}')
  84.             if secret not in ignore_words:
  85.                 return secret
  86.  
  87.             console.print(f'Неверно!', style='bold underline red')
  88.  
  89.  
  90. def create_new_link(secret: str, old_link: str) -> str:
  91.     hash_object = hashlib.md5(old_link.encode('utf-8') + secret.encode('utf-8'))
  92.     new_link = 'https://task1.tasks.rubikoid.ru/' + str(hash_object.hexdigest()) + '.php'
  93.  
  94.     return new_link
  95.  
  96.  
  97. def get_hash(sourse_code_site: list) -> str:
  98.     for line in sourse_code_site:
  99.         hash_capture = parse_html(line)
  100.  
  101.         if hash_capture:
  102.             return hash_capture[0]
  103.     else:
  104.         raise Exception('На сайте нет хеша.')
  105.  
  106.  
  107. def decrypt_md5(target_hash: str) -> str:
  108.     with console.status('[bold green]Waiting...[/bold green]'):
  109.         while True:
  110.             decrypt_hash = generate_key()
  111.             hash_object = hashlib.md5(decrypt_hash.encode('utf-8'))
  112.  
  113.             if hash_object.hexdigest() == target_hash:
  114.                 return decrypt_hash
  115.  
  116.  
  117. # создает хеш с 4 символами который совпадает с 4 последними символами капчи
  118. def find_target_hash(sub_line: str) -> tuple[str, str]:
  119.     with console.status('[bold green]Waiting...[/bold green]'):
  120.         while Wait.wait_flag:
  121.             target_decrypt_hash = generate_key()
  122.             hash_object = hashlib.md5(target_decrypt_hash.encode('utf-8'))
  123.             hash_str = str(hash_object.hexdigest())
  124.  
  125.             if hash_str[-4:] == sub_line:
  126.                 return hash_str, target_decrypt_hash
  127.         else:
  128.             return False
  129.  
  130.  
  131. def get_sourse_code_site() -> list:
  132.     return str(driver.page_source).split(r'\n')
  133.  
  134.  
  135. def write_secret_in_file(sub_secret: str, name_file: str = 'result_secret.txt') -> None:
  136.     with open(name_file, mode='a') as file_with_secret:
  137.         file_with_secret.write(sub_secret + ' ')
  138.  
  139.  
  140. def find_secret_auto():
  141.     while True:
  142.         global driver
  143.         global link
  144.         #  гавно с открытием
  145.         options = webdriver.ChromeOptions()
  146.         options.add_argument("--headless")
  147.         driver = webdriver.Chrome(options=options, executable_path=path_to_browser)
  148.         driver.get(link)
  149.  
  150.         sourse_code_site = get_sourse_code_site()
  151.         hash_capture = get_hash(sourse_code_site)
  152.         decrypt_hash_capture = decrypt_md5(hash_capture)
  153.         new_hash, key = find_target_hash(decrypt_hash_capture)
  154.        
  155.         print(f'{hash_capture=}; {decrypt_hash_capture=}')
  156.         print(f'{new_hash=}; {key=}')
  157.        
  158.         driver.find_element(By.NAME, "ch").send_keys(key)
  159.         driver.find_element(By.NAME, "s").click()
  160.  
  161.         refreshed_sourse_code_site = get_sourse_code_site()
  162.         secret = get_secret(refreshed_sourse_code_site)
  163.         console.print(f'{secret=}', style='bold underline red')
  164.  
  165.         log([secret, new_hash, key, decrypt_hash_capture, hash_capture])
  166.  
  167.         if secret not in ignore_words and secret is not None:
  168.             link = create_new_link(secret=secret, old_link=replace_dict(line=link, dict_words={
  169.                 'https://task1.tasks.rubikoid.ru/':'',
  170.                 '.php': '',
  171.                 }
  172.                 ))
  173.             console.print('Секрет найден!', style='bold underline green')
  174.             console.print(f'{secret=}, {link=}', style='bold underline red')
  175.             write_secret_in_file(secret)
  176.  
  177.  
  178. def find_secret():
  179.     capture = input('Введите капчу:\n>>>')
  180.     if capture:
  181.         new_hash, key = find_target_hash(capture)
  182.         print(f'{new_hash=}, {key=}')
  183.    
  184.  
  185. def find_with_easyocr():
  186.     global driver
  187.     global link
  188.  
  189.     thread = threading.Thread(
  190.         target=switch,
  191.         args=()
  192.     )
  193.  
  194.     thread.start()
  195.  
  196.     while True:
  197.         console.print(f'{Wait.wait_flag=}', style='bold underline yellow')
  198.         #  гавно с открытием
  199.         options = webdriver.ChromeOptions()
  200.         options.add_argument("--headless")
  201.         driver = webdriver.Chrome(options=options, executable_path=path_to_browser)
  202.         driver.get(link)
  203.         driver.find_element(By.TAG_NAME, "img").screenshot("img.jpg")
  204.  
  205.         sourse_code_site = get_sourse_code_site()
  206.         hash_capture = get_hash(sourse_code_site)
  207.         decrypt_hash_capture = recognize_text("img.jpg")[0][1]
  208.  
  209.         print(decrypt_hash_capture)
  210.  
  211.         Wait.wait_flag = True
  212.         res = find_target_hash(decrypt_hash_capture)
  213.         new_hash, key = res if res else (False, False)
  214.  
  215.         print(new_hash, key)
  216.  
  217.         if not res:
  218.             continue
  219.        
  220.         print(f'{hash_capture=}; {decrypt_hash_capture=}')
  221.         print(f'{new_hash=}; {key=}')
  222.        
  223.         driver.find_element(By.NAME, "ch").send_keys(key)
  224.         driver.find_element(By.NAME, "s").click()
  225.  
  226.         refreshed_sourse_code_site = get_sourse_code_site()
  227.         secret = get_secret(refreshed_sourse_code_site)
  228.         console.print(f'{secret=}', style='bold underline red')
  229.  
  230.         log([secret, new_hash, key, decrypt_hash_capture, hash_capture])
  231.  
  232.         if secret not in ignore_words and secret is not None:
  233.             link = create_new_link(secret=secret, old_link=replace_dict(line=link, dict_words={
  234.                 'https://task1.tasks.rubikoid.ru/':'',
  235.                 '.php': '',
  236.                 }
  237.                 ))
  238.             console.print('Секрет найден!', style='bold underline green')
  239.             console.print(f'{secret=}, {link=}', style='bold underline red')
  240.             write_secret_in_file(secret, name_file='result_secret_easyocr.txt')
  241.  
  242.  
  243. mode = input('Ручной режим - 1; Автоматический режим - 2; Поиск с помощью компьютерного зрения - 3\n>>>')
  244.  
  245. if mode == '1':
  246.     find_secret()
  247. elif mode == '2':
  248.     find_secret_auto()
  249. elif mode == '3':
  250.     find_with_easyocr()
  251.  
  252. input('Нажмите любую кнопку, чтобы закрыть...')
  253.  
Add Comment
Please, Sign In to add comment