ThaySan
  • 👋Bienvenue
    • Avant-propos
  • 🚩CTF & Writeups
    • 2025 | EC2
      • Let's Crax
    • 2025 | HackDay
      • 🔑Cryptographie
        • Drunk Christmas
        • Find Eve 1
        • Well hidden message - Standard Code Encryption
      • 🔎Forensic
        • Copperwire Extraction
        • Distracted user
        • I believe you can't fly
      • 🧠Misc
        • Hello Steve
      • 💾Programmation
        • Lonely bot
        • Lonely bot #2
        • Lonely bot #3
        • Useless Animals Sorting
        • Who cares about SSI anyway ?
      • ⚙️Reverse
        • Just dig
        • Rusty_rev
        • The Cogs of Blackmail
      • 🎭Steganographie
        • It says a lot when there is no music
        • Mona LSB
        • Well hidden message - Insignificant blue
      • 🌐Web
        • Super Website Verificator 3000
        • The analytical engine leak
        • The Watchful Gears: Uncover the Secrets Within
        • Your region's finest
    • 2024 | Efrei - CyberNight
      • 🔑Cryptographie
        • Clavier spécial
        • Le futur
        • Securechain 30.0
        • Cascade
        • Shared Flag
        • Weird Algorithm
      • 🧊Minecraft
        • Introduction
        • Non aux Bouquins Trafiqués
        • Redstone Gold Block
      • 💾Programmation
        • Captcha 1.0
        • Intro à la prog
        • Captcha 2.0
      • ⚙️Reverse
        • Reverse the Reverse
        • Find me if you can
        • HuGO Decrypt
        • Kitten eXORcism
        • M30W Vault Tech
        • The Ugandan Labyrinth
      • 🎭Stéganographie
        • Le message
        • bon Le ordre
        • COD FORFLAG
        • Mauvaise note
        • Bruit
        • Un (un ?) drôle de QR code
        • Randonnée Guillerette à Bordeaux
      • 💻Système
        • Marche-pied
        • Escabot
        • régulation des Données et des Normes de Sécurité
      • 🌐Web
        • cybernight.zip
        • Mon champion préféré
        • Co(mpressed)okies
        • Gitty Mistake
        • JWT Kiddo
        • Parseur Farceur
      • L'enquête
        • L'enquête 2/6
        • L'Enquête 1/6
        • Bienvenue, enquêteur
    • 2024 | Star-Hack
      • 🔑Cryptographie
        • César, mais pas César
        • Double ennui
        • Langage secret
        • Quadratique Mystérieuse
        • ReSultAt
        • Sup3r S3cr3t
        • Warmup
      • 🔎Forensic
        • Cache-cache
        • Fichier ZIP protégé par mot de passe
        • HEADER
        • Investigation 1
        • Investigation 2
      • 🧠Misc
        • B4l4d3 Urb41n3
        • Bruhh, c'est quoi ça ?
        • Cut13
        • Pika Pika
      • 😈Pwn
        • Pwn0x01
        • Pwn0x02
        • Pwn0x03
      • ⚙️Reverse
        • Assembly
        • Rev0x00
        • Rev0x01
        • Rev0x02
      • 🌐Web
        • Clone Udemy
        • Flask
        • Guess_The_Passcode
        • PHP
        • Tickets
        • Usine de Cookies
    • 2024 | ECW
      • 🔑Cryptographie
        • Course hipPIN
    • 2024 | CTFREI Intro
      • 🔑Cryptographie
        • AES Intro
        • Aléatoire
        • Game of Luck
        • RSA Intro
        • RSA2
        • RSA3
      • 🔎Forensic
        • Mais qui est le photographe ?
        • Mais où est passé mon flag ?
        • Mémoire 1/4
        • Mémoire 2/4
        • Mémoire 3/4
        • Mémoire 4/4
        • My computer is talking
      • 📚OSINT
        • Avion ✈
        • Geoint
        • Google!
        • Googlint
        • Le pivot
        • Le temps commence maintenant
        • Sacré dossier
        • Socint
      • 💾Programmation
        • Try Me
        • Answer Me
        • Eval Me
        • Time Based
      • 😈Pwn
        • BOF Intro
        • Shop
        • BOF 2
        • BOF win()
      • ⚙️Reverse
        • CrackMe1
        • CrackMe2
        • CrackMe3
        • Hidden...
        • Something changed?
        • ZZZ
      • 🎭Stéganographie
        • Cybernight être comme
        • Joli paysage
        • Petit poisson
        • StegHide 'n' Seek
        • Un canard pas comme les autres
      • 💻Système
        • Bash Jail
        • Bash Jail Revenge
        • BrokenBin
        • GTFO Of Here
        • Pyjail
        • Pyjail Revenge
        • Strange input, right?
      • 🌐Web
        • SQLi
        • POST This Money
        • Give me my Flask PIN
        • Access
        • Render
        • RenderV2
        • Touchy
    • 2024 | DefCamp
      • 🔑Cryptographie
        • conv
        • oracle-srl
        • ctr
      • 🔎Forensic
        • i-got-a-virus
        • Alternating
        • call-me-pliz
      • 🧠Misc
        • pyterm
      • 📱Mobile
        • mobisec
      • 📚OSINT
      • 😈Pwn
      • ⚙️Reverse
      • 🕵️Traque
      • 🌐Web
        • noogle
        • production-bay
    • 2024 | 404CTF
      • 🔑Cryptographie
        • Bébé nageur
        • Le petit bain
        • Poor Random Number Generator [1/2]
        • Plongeon Rapide Super Artistique
        • J'éponge donc j'essuie
        • Poor Random Number Generator [2/2]
        • La Seine
        • J'ai glissé chef !
        • SEA - La face cachée de l'Iceberg
      • 🔎Forensic
        • Le tir aux logs
        • Darts Bank
        • Vaut mieux sécuriser que guérir
        • De bons croissants au beurre
        • Poids Raw vs. Cours Jette [1/3]
      • 🔌Hardware
        • Serial killer
        • Le soulevé de GND
        • Comment est votre modulation ? [1/2]
        • Sea side channel [1/4] - Introduction
        • Comment est votre modulation ? [2/2]
        • Sea side channel [2/4] - Reconnaissance
        • Sea side channel [3/4] - Mais où sont les triggers ?
      • 🤖IA
        • Du poison [1/2]
        • Du poison [2/2]
        • Des portes dérobées
      • 🧠Misc
        • Discord
        • De la friture sur la ligne
        • Bienvenue
        • Revers(ibl)e Engineering [0/2]
      • 📚OSINT
        • Légende
        • Not on my watch
        • Secret Training [1/2]
      • 😈Pwn
        • Pseudoverflow
        • Jean Pile
        • Mordu du 100m
        • Antismash
      • 🐈‍⬛Quantique
        • Des trains superposés
        • De l'écoute, pas très discrète
        • De la multiplicité des problèmes
      • ⚙️Reverse
        • ⭐Échauffement
        • ⭐Intronisation du CHAUSSURE
        • ⭐Bugdroid Fight [1/2]
        • ⭐Revers(ibl)e Engineering [1/2]
        • ⭐Bugdroid Fight [2/2]
        • ⭐Nanocombattants
        • ⭐Revers(ibl)e Engineering [2/2]
        • Le Tableau Noir
      • 🎭Stéganographie
        • ⭐L'absence
        • ⭐Regarder en stéréo
        • ⭐La Barre Fixe
        • ⭐Le grand écart
        • ⭐La chute
      • 🌐Web
        • ⭐Vous êtes en RETARD
        • ⭐Le match du siècle [1/2]
        • ⭐Exploit mag
        • ⭐Le match du siècle [2/2]
        • ⭐LE GORFOU 42
        • ⭐La boutique officielle
    • 2024 | CTFREI - Bordeaux
      • 🔑Cryptographie
        • zzz
      • 📚OSINT
        • Alexis Dumas
        • Back to the bureau
        • Dr Octopus
        • Folie et ambition
        • GeoGuessr
        • Hugo Nelots : prélude
        • La fin ?
        • La fuite Dumas
        • Un réseau suspect
      • 💾Programmation
        • Eval me 1
        • Eval me 2
        • Time Based
      • 💻Système
        • Broken Binary 1
        • Broken Binary 2
        • GTFO of here
        • Pyjail 1
        • Pyjail 2
        • Pyjail 3
        • Pyjail 4
      • 🌐Web
        • Au commencement était le verb
        • Becadmin
        • PHP Juggler
    • 2024 | HTB - Cyber Apocalypse Challenges
      • 🔗Blockchain
        • Lucky Faucet
        • Recovery
        • Russian Roulette
      • 🔑Cryptographie
        • Blunt
        • Dynastic
        • Iced TEA
        • Makeshift
        • Primary Knowledge
      • 🔎Forensic
        • An unusual sighting
        • Data Siege
        • Fake Boost
        • Game Invitation
        • It Has Begun
        • Phreaky
        • Pursue The Tracks
        • Urgent
      • 🔌Hardware
        • BunnyPass
        • Flash-ing Logs
        • Maze
        • Rids
        • The PROM
      • 🧠Misc
        • Character
        • Cubicle Riddle
        • Path of Survival
        • Stop Drop and Roll
        • Unbreakable
        • Were Pickle Phreaks
        • Were Pickle Phreaks Revenge
      • 😈Pwn
        • Delulu
        • Pet Companion
        • Tutorial
        • Writing on the Wall
      • ⚙️Reverse
        • BoxCutter
        • Crushing
        • FollowThePath
        • LootStash
        • MazeOfPower
        • Metagaming
        • PackedAway
        • QuickScan
      • 🌐Web
        • Flag Command
        • KORP Terminal
        • Labyrinth Linguist
        • LockTalk
        • Testimonial
        • TimeKORP
    • 2024 | UNbreakable
      • 🔑Cryptographie
        • start-enc
        • traffic-e
      • 🔎Forensic
        • easy-hide
        • password-manager-is-a-must
      • 🧠Misc
        • rfc-meta
      • 📱Mobile
        • flagen
        • improper-configuration
      • 📡Network
        • wifi-basic
        • wifiland
      • 📚OSINT
        • persistent-reccon
        • safe-password
      • 😈Pwn
        • intro-to-assembly
      • ⚙️Reverse
        • fake-add
      • 🎭Stéganographie
        • secrets-of-winter
      • 🌐Web
        • pygment
        • sided-curl
        • you-can-trust-me
    • 2023 | EFREI - CyberNight
      • 📚OSINT
        • Invest Now !
      • 😈Pwn
        • NSA Call Converter
      • ⚙️Reverse
        • CryptoVirus
        • WebChaussettes
      • 🌐Web
        • DoctoLeak
    • 2023 | Flag4All
      • 🔑Cryptographie
        • Aes IV
        • Crypt my loop
        • Kentucky fried chicken
        • RSA primes
        • Xor
    • 2022 | EFREI - CyberNight
      • 🔑Cryptographie
        • Coupé-décalé
        • ExFILEtration
        • Il s'est baissé ou pas
        • J'ai pas roté
        • Les allemands !
        • RSA Strong Prime generator
      • 🔎Forensic
        • Bomberman 1/2
        • Bomberman 2/2
        • Magic
        • Peu importe le chemin
        • Sniff sniff
        • Souvenir
        • Xray
      • 🔌Hardware
        • Class4
        • Find me 2/3
        • Identify 1/3
        • Yo listen 3/3
      • 🧠Misc
        • Et je tombe tombe tombe
        • Des yeux partout
        • RiGOLe
        • Roomba tricheur
        • Survey
        • Tinder
      • 💾Programmation
        • Repeat
        • Startup
        • Timing
      • ⚙️Reverse
        • Auth 1
        • Auth2
        • Auth3
        • Cryptoroomba
        • Tenet
      • 🎭Stéganographie
        • 50 shades of stephane legar
        • Chess master
        • Deviens champion sers toi de tout ce que tu as appris
        • Drifting in the bits
        • Pyramide
        • Spirale
      • 🌐Web
        • Ah bah c'est du propre
        • Cooking roomba
        • Leaderboard
        • vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
Propulsé par GitBook
Sur cette page
  • Challenge
  • Solution

Cet article vous a-t-il été utile ?

  1. CTF & Writeups
  2. 2024 | Star-Hack
  3. Reverse

Rev0x01

PrécédentRev0x00SuivantRev0x02

Dernière mise à jour il y a 6 mois

Cet article vous a-t-il été utile ?

Flag: StarHack{KdgWZUZfUEi9Tl2}

Challenge

Description


Ce programme est trop grand mais il est inutile. Pouvez-vous extraire le flag ?

Solution

Ici, on ne peut pas débugger directement. On va passer par une attaque par bruteforce grâce à un side-channel : le nombre d'instructions CPU.

Quand on décompile le binaire, on s'aperçoit que les caractères sont vérifiés 1 par 1 et dès qu'un est mauvais, le processus se termine. Autrement dit, si on a la bonne lettre, on fera un tour de boucle en plus et nécessairement, on exécutera plus d'instructions. C'est ça qu'on peut détecter :

En jaune, on déduit que notre input doit faire 15 de longueur.

En bleu, c'est la condition qui quitte la fonctionne si le caractère n'est pas le bon.

On va passer par valgrind pour compter le nombre d'instructions puisque perf stat ne fonctionne pas sur la majorité des VM (pour ceux comme moi qui sont sur VMWare ou autre).

#!/usr/bin/python3

import argparse
import sys
import re
import subprocess
import tempfile
from string import ascii_lowercase, ascii_uppercase, digits, punctuation

not_allowed_chars = ['"', "'", "(", ")", ">", "<", "`", "|", "\\",
                     "#", ";", "&"]
punctuation = list(punctuation.strip(" "))
for char in not_allowed_chars:
    punctuation.remove(char)
punctuation = ''.join(punctuation)


def make_bold(text, index):
    return text[:index] + '\033[1m' + text[index] + '\033[0m' + text[index+1:]


def get_charset(code):
    return "NZKqdWgZZUfEUiT9lV2f"


def get_instruction_count(test_str, binary_filename):
    with tempfile.NamedTemporaryFile() as tmp:
        command = f'echo "{test_str}" | valgrind --tool=callgrind --callgrind-out-file={tmp.name}\
        {binary_filename}'
        try:
            with subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE) as valout:
                valout = valout.stderr.read()
                valout = int(re.findall('Collected : \d+',
                                        valout.decode())[0][12:])
                return valout
        except IndexError:
            print('here')
            pass


def find_char_at(test_str, location, binary_filename, verbose, charset_code):
    if verbose:
        print("Testing: ", make_bold(test_str, location), "at", location)
    charset = get_charset(charset_code)
    maximum = 0
    bestchoice = ""
    for char in charset:
        test = test_str[:location] + char + test_str[location+1:]
        val = get_instruction_count(test, binary_filename)
        if val is not None:
            if val > maximum:
                maximum = val
                bestchoice = test
        if verbose:
            print("    ", char, ":", val)
    return bestchoice


def find_length(binary_filename, maxlen, verbose):
    maximum = -1
    init_counts = get_instruction_count("a", binary_filename)
    length = -1
    for i in range(1, maxlen+1):
        val = get_instruction_count("a"*i, binary_filename)
        if verbose:
            print("a"*i, ":", val)
        if val is not None:
            if val > maximum:
                maximum = val
                length = i
    if init_counts != maximum:
        return length

def find_string(binary_filename, maxlen=35,
                verbose=False, reverse=False,
                lengthgiven=False, length=0,
                charset_code=0,
                flag_format=""):
    if not lengthgiven:
        length = find_length(binary_filename, maxlen, verbose)
        if length is None:
            print("[taCTF] I couldn't guess the length, sorry. Try -l LENGTH.")
            sys.exit()
    print("Length guess:", length)
    length_diff = length - len(flag_format)
    candidate = flag_format + 'a'*length_diff
    if not reverse:
        for i in range(len(flag_format), length):
            candidate = find_char_at(candidate, i, binary_filename, verbose,
                                     charset_code)
            print(candidate)
    else:
        for i in range(length-1, len(flag_format)-1, -1):
            candidate = find_char_at(candidate, i, binary_filename, verbose,
                                     charset_code)
            print(candidate)
    return candidate


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Run an instruction counting based timing attack on a given binary.')
    parser.add_argument('filename', type=str,
                        help='The file to run taCTF against')
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="Verbose mode, prints out what it's up to at every iteration")
    parser.add_argument('-r', '--reverse', action='store_true',
                        help='Try the timing attack starting at the end of the string.')
    parser.add_argument('-f', '--flag-format', type=str, default="",
                        help='Flag format: first N known characters in string.')
    parser.add_argument('-ml', '--max-length', type=int, default=35,
                        help='Maximum length to check strings till, if length unknown.')
    parser.add_argument('-l', '--length', type=int,
                        help='Length of string, if known.')
    parser.add_argument('-c', '--charset', type=int, default=0,
                        help='Set the charset code. Default is 0 (all chars).')
    args = parser.parse_args()

    lengthgivenbool = False
    if args.length is not None:
        lengthgivenbool = True
    find_string(args.filename, maxlen=args.max_length,
                verbose=args.verbose,
                reverse=args.reverse,
                lengthgiven=lengthgivenbool, length=args.length,
                charset_code=args.charset,
                flag_format=args.flag_format)

valgrind ne fonctionne pas dans un terminal émulé (comme celui-ci de VSCode), veillez bien à lancer le script depuis votre "vrai" terminal pour ne pas avoir de surprise de segfault.

On lance avec python3 taCTF.py "./task2" -l 15.

┌──(kali㉿kali)-[~/Documents/Reverse]
└─$ python3 taCTF.py "./task2" -l 15                                                                                                                                                                                                                                130 ⨯
Length guess: 15
Kaaaaaaaaaaaaaa
Kdaaaaaaaaaaaaa
Kdgaaaaaaaaaaaa
KdgWaaaaaaaaaaa
KdgWZaaaaaaaaaa
KdgWZUaaaaaaaaa
KdgWZUZaaaaaaaa
KdgWZUZfaaaaaaa
KdgWZUZfUaaaaaa
KdgWZUZfUEaaaaa
KdgWZUZfUEiaaaa
KdgWZUZfUEi9aaa
KdgWZUZfUEi9Taa
KdgWZUZfUEi9Tla
KdgWZUZfUEi9Tl2
                                                                                                                                                                                                                                                                          
┌──(kali㉿kali)-[~/Documents/Reverse]
└─$ ./task2 
give me The correct flag: KdgWZUZfUEi9Tl2
Good Job
Go ahead and submit
StarHack{KdgWZUZfUEi9Tl2}

J'ai simplement modifié le script de pour mettre notre charset et éviter de tester des caractères intuiles, ça donne :

🚩
⚙️
https://github.com/nebhrajani-a/taCTF
106KB
rev0x01.zip
archive