Compare commits

...
52 Commits
Author SHA1 Message Date
juju 2b68e0e7f5 update nginx 2026-11-18 16:39:50 +01:00
juju b2c3f0c0ac remove synacktiv link 2025-09-26 21:29:41 +02:00
juju 12f7f79b32 fix megalosaure title
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-15 15:44:11 +02:00
juju 5ad8ea7bfa fix wus dates
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-15 14:45:05 +02:00
juju ac5a0ab6fd fix megalosaure path and remove legacy solver code
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-15 10:59:53 +02:00
juju 35e083d2d3 fix typo in archiver
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-15 10:46:52 +02:00
juju af328857d7 fix emoji rendering
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-14 23:13:12 +02:00
juju 619056a0a7 fix points
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-14 22:01:36 +02:00
juju 95852bee94 add archiver writeup
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-14 14:08:03 +02:00
juju 32286c8a62 add megalosaure and fix svartalfheim wus
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-14 12:15:23 +02:00
juju 171c5040b2 add svartalheim writeup
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-04-11 10:33:38 +02:00
juju 17d731e9b8 update photo
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2024-02-12 20:11:25 +01:00
juju e9faa02482 typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-16 10:38:02 +02:00
juju 275d979282 fix main.c comment
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 23:26:49 +02:00
juju cab326b68e add favicon
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 21:13:46 +02:00
juju 562502a72c add favicon
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 21:09:45 +02:00
juju 3233d4a1a0 fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 20:35:51 +02:00
juju 3d25b6e1ea fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 14:28:57 +02:00
juju f8fe772406 fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 11:48:20 +02:00
juju bb81fd917e fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 11:24:30 +02:00
juju a680b32e79 fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 10:57:32 +02:00
juju 5dbb6d6699 fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 10:33:33 +02:00
juju e06fd7908f fixed typos in picasso
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 10:20:56 +02:00
juju 8dcf9f9a82 add picasso writeup
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-04 00:57:11 +02:00
juju 01057cae54 Merge branch 'master' of git.juju.re:juju/juju.re 2023-05-03 01:49:50 +02:00
juju 8625c57d1a working on picasso wu
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-03 01:49:47 +02:00
juju 5011f2280c fixed solver language in brachio
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-03 01:49:05 +02:00
juju 48042cf2d6 fix typo in brachio again
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-02 16:19:27 +02:00
juju 8c76c365fb fix typo in brachio again
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-02 11:30:50 +02:00
juju a8e9831646 fix typo in brachio again
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-02 11:23:45 +02:00
juju 9db0aae90d fix typo in brachio
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-02 10:47:35 +02:00
juju f3e0ce09f6 fix small error in brachiosaure wu
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 17:22:19 +02:00
juju e11eceaa85 add brachiosaure meme
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 14:31:05 +02:00
juju 03c99ff603 Merge branch 'master' of git.juju.re:juju/juju.re 2023-05-01 13:55:43 +02:00
juju fd576889fe cleaner main decompiler for brachio
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 13:55:21 +02:00
juju bed1beea4f Merge branch 'master' of git.juju.re:juju/juju.re 2023-05-01 13:41:01 +02:00
juju 4e1e081827 fix typo in brachiosaure
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 13:40:44 +02:00
juju 84dc98ebd4 Merge branch 'master' of git.juju.re:juju/juju.re 2023-05-01 12:31:45 +02:00
juju b5677d547c remove submodules
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 12:31:39 +02:00
juju 532f34c6ab add brachiosaure wu
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 12:28:41 +02:00
juju 9c991511b4 embedded hello friend because i'm lazy
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 07:48:08 +02:00
juju 4af776a3e1 remove submodules
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-05-01 07:43:49 +02:00
juju 4b76534d10 add twitter link
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2023-02-09 10:22:54 +01:00
juju 5358dc632f fixing typos
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-09-04 21:40:59 +02:00
juju 55075855bb add exterminated writeup and fix diplodocus typos
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-05-10 18:26:48 +02:00
juju 3e9261a7c8 fix add diplodocus writeup
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-05-10 00:14:17 +02:00
juju 34be6a4a96 fix: fix new github url and typo in q-solved
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-04-10 11:44:55 +02:00
juju 68086057fb feat(q-solved): better explanations, add circtuit drawings
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-03-26 13:19:38 +01:00
juju d4b4d1df2e fix(q-solved): add table of contents and typo fixes
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-03-26 11:32:54 +01:00
juju 355dede8e1 fix(typo): add gitignore for public folder and fixed a typo in q-solved
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-03-25 22:52:09 +01:00
juju 6f5bbb7ceb feat(q-solved): add first q-solved writeup
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-03-25 22:45:24 +01:00
juju 8cbb1a0b89 fix(config): remove placeholder description
Signed-off-by: Julien CLEMENT <julien.clement@epita.fr>
2022-02-11 19:43:44 +01:00
769 changed files with 57913 additions and 279 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
jujure/public
-6
View File
@@ -1,6 +0,0 @@
[submodule "jujure/themes/hello_friend"]
path = jujure/themes/hello_friend
url = git@github.com:rhazdon/hugo-theme-hello-friend-ng.git
[submodule "jujure/themes/terminal"]
path = jujure/themes/terminal
url = git@github.com:panr/hugo-theme-terminal.git
+1 -1
View File
@@ -3,7 +3,7 @@ version: "3.3"
services: services:
nginx: nginx:
restart: always restart: always
image: nginx:1.21.4 image: nginx:alpine
ports: ports:
- "8000:80" - "8000:80"
volumes: volumes:
-133
View File
@@ -1,133 +0,0 @@
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
.sr-only {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
::-moz-selection {
color: #000b13;
background: #c42337;
}
::selection {
color: #040404;
background: #d7d9ce;
}
body {
background-color: #040404;
color: #119da4;
font-family: monospace;
font-size: 1.0em;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
max-width: 1500px;
margin: auto;
}
header {
text-align: center;
font-size: 1.2em;
}
header h1 {
font-size: 4em;
}
header h2 {
font-size: 2em;
}
header img {
border-radius: 100%;
width: 220px;
margin: 10px;
}
header .socials {
margin-top: 5px;
list-style-type: none;
font-size: 1.4em;
}
header .socials li {
display: inline-block;
}
header .socials a {
color: inherit;
text-decoration: none;
}
header .socials a:hover {
color: #d7d9ce;
}
.articles {
margin-top: 50px;
font-size: 1.3em;
}
.articles h3 {
font-size: 1em;
font-weight: 800;
color: #f4b65c;
}
.articles ul {
list-style-type: none;
}
.articles li {
margin-top: 0.4em;
margin-bottom: 0.4em;
}
.articles a {
color: #7f8589;
text-decoration: none;
}
.articles a:hover {
color: #c42337;
}
article h1 {
color: #f4b65c;
margin-bottom: 0.7em;
}
article {
font-size: 1.3em;
}
article p {
padding-top: 3px;
padding-bottom: 3px;
text-align: justify;
}
article a {
color: #119da4;
text-decoration: none;
}
article a:hover {
color: #d7d9ce;
}
-17
View File
@@ -1,17 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Juju</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6">
<link rel="stylesheet" href="../assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body>
<article>
<h1>Article</h1>
<p>Test</p>
</article>
</body>
</html>
-25
View File
@@ -1,25 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Juju</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6">
<link rel="stylesheet" href="../../assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body>
<article>
<h1>Introduction à la rétro-ingénierie et à l'exploitation logicielle</h1>
<h2>
<a href="https://www.youtube.com/watch?v=5g2eZSST7YE">
<i class="ri-youtube-line"></i>
</a>
<a href="binary_exploitation.pdf">
<i class="ri-slideshow-line"></i>
</a>
</h2>
</article>
</body>
</html>
-19
View File
@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Juju</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6">
<link rel="stylesheet" href="../assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body>
<article>
<h1>Posts</h1>
<li>
<h3><a href=conf_exploit/>Introduction à la rétro-ingénierie et à l'exploitation logicielle [FR]</a></h3>
</li>
</article>
</body>
</html>
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

-60
View File
@@ -1,60 +0,0 @@
<!--
Credits where it's due, https://landryl.fr who allowed me to use his css
-->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Juju</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.6">
<link rel="stylesheet" href="assets/style.css">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
</head>
<body>
<header>
<img src="juju.jpg" alt="Photo of myself">
<h1>Juju</h1>
<ul class="socials">
<li>
<a href="https://github.com/Azomasiel/">
<i class="ri-github-line"></i>
<span class="sr-only">Github profile</span>
</a>
</li>
<li>
<a href="https://git.juju.re/explore/repos">
<i class="ri-open-source-line"></i>
<span class="sr-only">Turbogit</span>
</a>
</li>
<li>
<a href="https://www.linkedin.com/in/julien-clement-0891ab199/">
<i class="ri-linkedin-box-line"></i>
<span class="sr-only">Linkedin profile</span>
</a>
</li>
<li>
<a href="https://www.root-me.org/Azomasiel">
<i class="ri-skull-line"></i>
<span class="sr-only">Root-me profile</span>
</a>
</li>
<li>
<a href="https://cryptohack.org/user/Azomasiel/">
<i class="ri-shield-keyhole-line"></i>
<span class="sr-only">Cryptohack profile</span>
</a>
</li>
</ul>
<ul class="socials">
<li>
<a href="blog/">
<i class="ri-booklet-line"></i>
<span class="sr-only">Github profile</span>
</a>
</li>
</ul>
</header>
</body>
</html>
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

+17 -15
View File
@@ -7,6 +7,8 @@ paginate = 10
PygmentsCodeFences = true PygmentsCodeFences = true
PygmentsStyle = "monokai" PygmentsStyle = "monokai"
enableEmoji = true
[author] [author]
name = "Julien CLEMENT" name = "Julien CLEMENT"
@@ -17,7 +19,7 @@ PygmentsStyle = "monokai"
dateformNumTime = "2006-01-02 15:04" dateformNumTime = "2006-01-02 15:04"
# Subtitle for home # Subtitle for home
homeSubtitle = "de la conf de Julien" homeSubtitle = ""
# Set disableReadOtherPosts to true in order to hide the links to other posts. # Set disableReadOtherPosts to true in order to hide the links to other posts.
disableReadOtherPosts = false disableReadOtherPosts = false
@@ -26,13 +28,13 @@ PygmentsStyle = "monokai"
enableSharingButtons = true enableSharingButtons = true
# Metadata mostly used in document's head # Metadata mostly used in document's head
description = "My new homepage or blog" description = ""
keywords = "homepage, blog, crypto, reverse" keywords = "homepage, blog, crypto, reverse, exploit"
images = [""] images = [""]
[[params.social]] [[params.social]]
name = "github" name = "github"
url = "https://github.com/Azomasiel" url = "https://github.com/Jujure"
[[params.social]] [[params.social]]
name = "gitea" name = "gitea"
@@ -42,6 +44,10 @@ PygmentsStyle = "monokai"
name = "linkedin" name = "linkedin"
url = "https://www.linkedin.com/in/julien-clement-0891ab199/" url = "https://www.linkedin.com/in/julien-clement-0891ab199/"
[[params.social]]
name = "twitter"
url = "https://twitter.com/Juju_RE_"
[params.portrait] [params.portrait]
path = "/juju.jpg" path = "/juju.jpg"
@@ -56,22 +62,13 @@ PygmentsStyle = "monokai"
[params.footer] [params.footer]
author = true author = true
[taxonomies]
category = "blog"
tag = "tags"
series = "series"
[languages] [languages]
[languages.en] [languages.en]
title = "Juju" title = "Juju"
subtitle = ""
keywords = "Crypto, Reverse"
copyright = '<a href="https://creativecommons.org/licenses/by-nc/4.0/" target="_blank" rel="noopener">CC BY-NC 4.0</a>'
readOtherPosts = "Read other posts"
[languages.en.params.logo] [languages.en.params.logo]
logoMark = "juju@synacktiv ~$ " logoMark = "juju@pwningway ~$ "
logoText = "cryptoratio" logoText = "objdump -d"
logoHomeLink = "/" logoHomeLink = "/"
logoCursorColor = "#3884FF" logoCursorColor = "#3884FF"
# or # or
@@ -84,3 +81,8 @@ PygmentsStyle = "monokai"
identifier = "posts" identifier = "posts"
name = "Posts" name = "Posts"
url = "/post/" url = "/post/"
[[menu.main]]
identifier = "writeups"
name = "Writeups"
url = "/writeups/"
Regular → Executable
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.3 MiB

+1 -1
View File
@@ -8,5 +8,5 @@ tags: ["Reverse", "Exploit"]
{{< youtube 5g2eZSST7YE >}} {{< youtube 5g2eZSST7YE >}}
{{< rawhtml >}} {{< rawhtml >}}
<embed src="/post/conf_exploit.pdf" type="application/pdf" width="100%" height="430"> <embed src="/conf_exploit/slides.pdf" type="application/pdf" width="100%" height="430">
{{< /rawhtml >}} {{< /rawhtml >}}
Binary file not shown.
@@ -0,0 +1,288 @@
---
title: "Decrypting cryptolocked partition | EXTerminated @ FCSC 2022"
date: "2022-05-08 19:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
EXTerminated is a malware reversing challenge. You are handed an EXT4 partition
that has been encrypted by a malware, your goal is to recover the original
unencrypted files.
The description of the challenge tells us that the malware does not use any
known cryptosystem to encrypt data, let's find this out.
{{< image src="/EXTerminated/panik.png" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `472 pts` `12 solves` :star::star:
```
Un client a détecté un seveur compromis sur son parc. Ce serveur semble avoir
perdu l'ensemble de ses données suite à une infection. Il nous indique que les
attaquants exigent une rançon et affirment pouvoir récupérer les fichiers
disparus.
Une analyse rapide du virus indique que ce dernier ne disposerait à première
vue d'aucun algorithme cryptographique connu.
On vous demande d'analyser ce disque, et de récupérer les fichiers originaux.
SHA256(disk.img) = a9e7891224868af43e2aa134152beaa2a83f43cde21af8038d138001377157dc.
```
Author: `Nofix`
## Given files
[disk.img](/EXTerminated/disk.img)
# Writeup
## Overview
So we can see we are given an EXT4 partition.
```console
$ file disk.img
disk.img: Linux rev 1.0 ext4 filesystem data,
UUID=c26167b3-e0b9-441d-ab4d-a5f4b5b1fcd0 (extents) (64bit) (large files)
(huge files)
```
Let's try to mount it.
We can see that there are multiple pictures, a pdf and an executable called
`wannaweep`, which is probably our malware.
```console
$ sudo mount -o loop ./disk.img mnt/
$ tree mnt/
mnt/
├── Documents
│   └── anssi-guide-ransomware_attacks_all_concerned-v1.0.pdf
├── Images
│   ├── accident.png
│   ├── disk.jpg
│   ├── flag.jpg
│   ├── martine.jpg
│   ├── smile.png
│   ├── tintin.jpeg
│   └── valide.png
├── lost+found [error opening dir]
└── wannaweep
3 directories, 9 files
```
By further investigating we can see that all data of the files have been erased
except for wannaweep, which definitely is the malware, an x64 stripped and
dinamically linked ELF.
```console
$ file mnt/Images/flag.jpg
mnt/Images/flag.jpg: data
$ xxd mnt/Images/flag.jpg | head
00000000: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000010: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000030: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000070: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000080: 0000 0000 0000 0000 0000 0000 0000 0000 ................
00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................
$ file mnt/wannaweep
mnt/wannaweep: ELF 64-bit LSB executable, x86-64, version 1 (SYSV),
dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2,
BuildID[sha1]=590a9f68cde37ffceb8e7441db343742e4032f47, for GNU/Linux
3.2.0, stripped
```
We can see that the binary links to `libext2fs.so.2`, a library for EXT file
system parsing and manipulation. Since it is dinamically linked we will still
have the corresponding symbols so I'm guessing I won't have too much trouble
understanding what the malware does even though I do not know the EXT
specification.
```console
$ ldd mnt/wannaweep
linux-vdso.so.1 (0x00007ffccb2b3000)
libext2fs.so.2 => /usr/lib/libext2fs.so.2 (0x00007f8059117000)
libcom_err.so.2 => /usr/lib/libcom_err.so.2 (0x00007f8059111000)
libc.so.6 => /usr/lib/libc.so.6 (0x00007f8058f07000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f80591ad000)
```
## Main
It is now the perfect time for me to absolutely not launch this program, I
could have setup a sandboxed environment but it turned out it wasn't necessary,
the code was really straight forward.
So I start my favorite decompiler and I download the source code of libext2fs.
A small fast forward in time as the main function is really straight forward,
The program takes the path to the device to encrypt as argument, calls a bunch
of function that are mostly wrappers around libext2fs functions to initialize
some global variables holding structures of the EXT filesystem. It also checks
that some flags are set in the structures of libext2fs, I do not know if these
flags are implementation specific or are standard EXT flags but I did not
bother too much with this.
The interesting stuff is at the end, I can see that it calls a function that
I called `encrypt_folder` after reversing it. It then flushes the filesystem to
disk and write the inode bitmap.
{{< code file="/static/EXTerminated/main.c" language="c" >}}
## Encrypt folder
Alright so let's take a look at the `encrypt_folder` to understand why I called
it this way.
I could clearly see from `main` that this function was called with the string
`.` to reference the current directory, and a function pointer that was still
unkown to me at the time but that I renamed `encrypt_file`.
How I knew that the function was encrypting folders and that the parameter was
a callback to encrypt files is really simple, you can clearly see the libc
symbols calling `opendir` on the path given as argument (`.`), reading all the
entries of the directory and calling the callback if the entry is a file.
If it is not a file, it will `chdir` in the said directory, before recursively
calling itself with the same arguments.
{{< code file="/static/EXTerminated/encrypt_folder.c" language="c" >}}
## Encrypt file
Let's now look at the `encrypt_file` we guessed. Again, mostly wrapper
functions so I did not bother to show you why I named them this way, the code
basically reads the content of the file to encrypt, encrypts it in a dedicated
block, puts it in the file system before deleting the original content of the
file.
{{< code file="/static/EXTerminated/encrypt_file.c" language="c" >}}
## Encrypt block
Well, I was scared of custom cryptography but this seems simple enough for me.
To encrypt a plain text block, the malware starts at the last byte of the block
and xor it with the previous one until it reaches the start.
Actually this function does a heap buffer underflow when xoring the first byte
of the block, since it will xor it with the byte right before the block in the
heap.
Reversing the encryption is trivial, the only undefined behaviours is with the
underflow because we cannot know the value of the byte preceding the block.
However, I assumed it would really likely be 0.
{{< code file="/static/EXTerminated/encrypt_block.c" language="c" >}}
## Decrypting
So to decrypt a block, we simply need to know the value of the byte preceding
the buffer. Let's assume it is 0 since it is the most likely.
I will xor this byte with the first byte of cipher text and that will give
me the first byte of plain text, I then repeat the operation, xoring the
first byte of plain text with the second byte of cipher text and I do this
for the whole block to recover the entire block.
## Solve
So know I know how to decrypt a block, let's decrypt the whole filesystem.
I could do something really smart and overengineered to recover a valid
decrypted EXT filesystem that I could mount to recover the original files.
However I'm not familiar with the EXT specification and their are still small
shadow zones in the malware code for me, so I try a naive solution.
I'm guessing that data blocks of files or all alligned on `0x1000`, it would be
kind of weird otherwise for me. So if I just cut the whole filesystem in
`0x1000` sized blocks without any consideration of the semantic of those blocks
in the EXT structure, I could just decrypt each of these blocks individually,
and prey that I recover some files whose blocks were contiguous in the EXT
structure.
Obviously that will corrupt all the EXT metadata but it doesn't really matter
as long as I can recover the files.
{{< code file="/static/EXTerminated/decrypt.py" language="py" >}}
Now let's try to output the result and see if we find any file signatures:
```console
$ ./decrypt.py > decrypted.img
$ binwalk decrypted.img
DECIMAL HEXADECIMAL DESCRIPTION
--------------------------------------------------------------------------------
9289728 0x8DC000 PNG image, 473 x 306, 8-bit/color RGB, non-interlaced
9531392 0x917000 JPEG image data, JFIF standard 1.01
9625600 0x92E000 PNG image, 500 x 564, 8-bit/color RGBA, non-interlaced
10125312 0x9A8000 JPEG image data, JFIF standard 1.01
10212833 0x9BD5E1 bix header, header size: 64 bytes, header CRC: 0x6003083D, created: 2004-01-10 13:39:36, image size: 2097152 bytes, Data Address: 0x22120000, Entry Point: 0x1E040003, data CRC: 0xD2100008, CPU: IA64, image name: ""
10231808 0x9C2000 JPEG image data, EXIF standard
10231820 0x9C200C TIFF image data, big-endian, offset of first image directory: 8
10330112 0x9DA000 JPEG image data, EXIF standard
10330124 0x9DA00C TIFF image data, big-endian, offset of first image directory: 8
10403840 0x9EC000 PNG image, 482 x 367, 8-bit/color RGB, non-interlaced
10403902 0x9EC03E Zlib compressed data, default compression
34263365 0x20AD145 Cisco IOS experimental microcode, for ""
46640306 0x2C7ACB2 MySQL ISAM compressed data file Version 9
46691658 0x2C8754A GIF image data 15531 x
```
We do! So let's try to extract them
```console
$ binwalk --dd='.*' decrypted.img
DECIMAL HEXADECIMAL DESCRIPTION
--------------------------------------------------------------------------------
9289728 0x8DC000 PNG image, 473 x 306, 8-bit/color RGB, non-interlaced
9531392 0x917000 JPEG image data, JFIF standard 1.01
9625600 0x92E000 PNG image, 500 x 564, 8-bit/color RGBA, non-interlaced
10125312 0x9A8000 JPEG image data, JFIF standard 1.01
10212833 0x9BD5E1 bix header, header size: 64 bytes, header CRC: 0x6003083D, created: 2004-01-10 13:39:36, image size: 2097152 bytes, Data Address: 0x22120000, Entry Point: 0x1E040003, data CRC: 0xD2100008, CPU: IA64, image name: ""
10231808 0x9C2000 JPEG image data, EXIF standard
10231820 0x9C200C TIFF image data, big-endian, offset of first image directory: 8
10330112 0x9DA000 JPEG image data, EXIF standard
10330124 0x9DA00C TIFF image data, big-endian, offset of first image directory: 8
10403840 0x9EC000 PNG image, 482 x 367, 8-bit/color RGB, non-interlaced
10403902 0x9EC03E Zlib compressed data, default compression
34263365 0x20AD145 Cisco IOS experimental microcode, for ""
46640306 0x2C7ACB2 MySQL ISAM compressed data file Version 9
46691658 0x2C8754A GIF image data 15531 x
$ file _decrypted.img.extracted/*
_decrypted.img.extracted/2C7ACB2: MySQL ISAM compressed data file Version 9
_decrypted.img.extracted/2C8754A: GIF image data 15531 x
_decrypted.img.extracted/8DC000: PNG image data, 473 x 306, 8-bit/color RGB, non-interlaced
_decrypted.img.extracted/9A8000: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, progressive, precision 8, 660x424, components 3
_decrypted.img.extracted/9BD5E1: data
_decrypted.img.extracted/9C200C: TIFF image data, big-endian, direntries=0
_decrypted.img.extracted/9C2000: JPEG image data, Exif standard: [TIFF image data, big-endian, direntries=0], comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90", baseline, precision 8, 481x600, components 3
_decrypted.img.extracted/9DA000: JPEG image data, Exif standard: [TIFF image data, big-endian, direntries=0], baseline, precision 8, 683x500, components 3
_decrypted.img.extracted/9DA00C: TIFF image data, big-endian, direntries=0
_decrypted.img.extracted/9EC000: PNG image data, 482 x 367, 8-bit/color RGB, non-interlaced
_decrypted.img.extracted/9EC03E: empty
_decrypted.img.extracted/9EC03E-0: zlib compressed data
_decrypted.img.extracted/20AD145: cisco IOS experimental microcode for ''
_decrypted.img.extracted/92E000: PNG image data, 500 x 564, 8-bit/color RGBA, non-interlaced
_decrypted.img.extracted/917000: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 495x669, components 3
```
Displaying the images we just extracted, we find the following one, giving us
the flag.
{{< image src="/EXTerminated/flag.png" style="border-radius: 8px;" >}}
@@ -0,0 +1,404 @@
---
title: "Exploiting logical bug to solve NP-complete reversing puzzle | Diplodocus @ FCSC 2022"
date: "2022-05-08 18:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
Diplodocus is I think by far my favorite challenge of the 2022 edition of the
FCSC. First it is a reverse challenge, my reference category, then it does not
feature weird unknown CPU architecture, just plain x64 with the only layer of
obfuscation being the heavy optimization of the compiler. Finally it is an
algorithmic problem, and I love algorithms.
The complexity of this challenge relies on the underlying problem it
implements. Diplodocus is the successor of Triceratops, a similar challenge
from the 2021 edition of the FCSC where you were also asked to solve an
NP-complete puzzle to get the flag.
The twist here is that a conceptual flaw of the program allows us to recover
the flag without actually solving the intended puzzle, but more on that later.
{{< image src="/diplodocus/yee-dinosaur.gif" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `477 pts` `10 solves` :star::star::star:
```
Trouvez une entrée qui valide, et soumettez-la au service en ligne pour obtenir
le flag.
`nc challenges.france-cybersecurity-challenge.fr 2201`
SHA256(`diplodocus`) =
`9af3062da630d2b94ad3bfa0b5fd67328d2c6c7bbb79607d7d2fa28a67c7ff9c`.
```
Author: `\J`
## Given files
[diplodocus](/diplodocus/diplodocus)
# Writeup
## Overview
As stated the program is simply an x64 stripped ELF.
```console
$ file diplodocus
diplodocus: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2,
BuildID[sha1]=c489721789271e74d301cda200feb877bd22d80a, for GNU/Linux 3.2.0,
stripped
```
If we try to execute the program, it reads a line from standard input and exits
with status code 1.
```console
$ ./diplodocus
input
$ echo $status
1
```
stracing and ltracing doesn't apport much more information, the program indeed
only calls `read(2)`.
## Main
It's now time to open our favorite decompiler and investigate the main
function.
After cleaning up the decompiler output and renaming the variables we get the
following code:
{{< code file="/static/diplodocus/main.c" language="c" >}}
The code is really simple here, it reads the standard input and pass the input
to a function that seems to perform a check.
If the check is sucessful, the program prints the flag, otherwise it exits with
1.
## Check
The Check function starts by setting up some local variables like a pointer to
the start and to the end of the input and what seems to be a struct that I
called context that may contain informations relevant to the ongoing puzzle.
Most of this struct is set to 0:
{{< code file="/static/diplodocus/check_init.c" language="c" >}}
## Instruction fetching and dispatch
My first observation of this main function made me think it was a really small
virtual machine. We can see it goes through every character in the input and
matches it against opcodes between 0 and 4 included. Every other values seems
to end the main loop with a return value of 1, indicating an error.
Since I see that the return value is set by oring a field of the context (which
I assumed at that time was a processor structure) I assume that this field holds
some sort of error flags that will invalidate our puzzle.
We then have the main dispatcher, processing the correct instruction. One thing
that can be noted is the two `break` statement in `case 0`, this is obviously
my decompiler trolling me but what he is trying to say is that this case will
end the main loop as well. It thus probably is the only way to end the function
with a return value of 0. It must then be the instruction performing the final
check after executing all our instructions. We will take a look at it last
since other instructions will give us a better idea of the internal structure
of the context and are easier to reverse.
{{< code file="/static/diplodocus/check_loop.c" language="c" >}}
### Case 1
This instruction is really simple, it makes one field of the context cycle
between 0 and 3 included. Let's simply remember the offset of this field
(`0xa0`) for now to see where it is used.
{{< code file="/static/diplodocus/case1.c" language="c" >}}
### Case 2
Well we did not need to wait a long time to see where the field from case 1
is used. Right at the beginning of case 2, the program matches the value of the
variable against all its possible values, it then creates a copy of two other
variable of the context and update them depending on our matching.
The 2 variables are then bound checked against `0xb` and used to index what
seems to be an array of `int32_t`. We can therefore understand that the two
variables are indexes of this array and that the variable from case 1 is an
enum describing possible movements in this array. I therefore name them `move`,
`i` and `j`.
Next we notice that we check that the `jth` bit of the `ith` row of the array,
if is not set, it sets the said bit and update the coordinates in the context.
If however it is already set, the program sets the error flag that we already
identified earlier.
Clearly this is some sort of 12 * 12 bitboard implementation, the first thing
that came to my mind is chess since I'm familiar with bitboard based chess
engines programming so it was at this exact moment that I understood this
problem was probably a puzzle or some sort of board game.
So to rephrase all this information, this instruction changes our coordinates
on a 12 * 12 board based on a preselected move from case 1, it places a marker
at our new coordinates and errors if we already visited this tile.
I now know one rule of the game: I cannot step twice on the same tile. By lack
of inspiration, I name this bitboard `visited` since it keeps track of all my
visited tiles.
Bellow is the cleaned up pseudo-C code from the decompiler with all variables
renamed accordingly.
{{< code file="/static/diplodocus/case2.c" language="c" >}}
And here is the moves enum to understand better how case 1 manipulates our
moves.
{{< code file="/static/diplodocus/move_enum.c" language="c" >}}
### Case 3
Case 3 uses a variable from the context that we previously saw initialized to
`0xffffff` at the very start of the check function without understanding it.
We can now see that it is in fact a queue of 24 bits that is popped in case 3
to place the said bit on a different bitboard than case 2 but with the same
coordinates. If the bit queue is empty then we output an error.
So I understand here that we must place 24 bits on another board while
simultaneously moving on the first one that tracks the tiles we already visited.
Seems easy enough, however, the instruction does not end here, it calls a
function passing the row of the bitboard as parameter, if the return value of
this function is more than `2` we output an error.
{{< code file="/static/diplodocus/case3_stripped.c" language="c" >}}
#### Pop count
Here is the said function, so it seems to perform magic bitwise operation.
Could be anything really, my intuition tells me it count the number of bits set
on the line but it may as well be some weird bitboard magic, I mean you never
know the stuff I found on [chess programming](chessprogramming.org) while
working on chess engines really blows my mind.
By googling the first constant `0x5555555555555555` I confirm really fast my
intuition. It is indeed a population count function, the fifth result of the
search being, guess what? [Chess programming wiki on population
count](https://www.chessprogramming.org/Population_Count). I now really start
thinking that this is actually a chess problem.
{{< code file="/static/diplodocus/pop_count.c" language="c" >}}
With this information we can now rename the variables and symbols from case 3
and we now understand that we place a bit from the bit queue on the board, we
cannot allign more than 2 bits on the same line.
{{< code file="/static/diplodocus/case3.c" language="c" >}}
### Case 4
Do not be misled, this instruction seems simple enough but is by far the
hardest one of the challenge.
So first this instruction fetch 2 operand, these operands are later used to
access a third bitboard, so I name them accordingly `i` and `j`.
Then we check if our bit queue is empty, if it is not then we output an error.
This mean that we can call this instruction only when we placed all the 24
points at our disposition.
Now comes the fun part, we call a function passing the coordinates and the
whole context as parameter, this function will output a bit that will be placed
on a third bitboard at the coordinates indexed by the operands.
So my decompiler really despise this function, I told you it took the whole
context as parameters but its not exactly true as it actually packs the whole
context in 10 `int128_t` arguments using SIMD instructions. I cleaned up the
function call for your eyes so you do not have de keep track of the 12
parameters of the function.
{{< code file="/static/diplodocus/case4_stripped.c" language="c" >}}
#### \J dabbing on me
You can see below a decompilation of the function, looks fun right? And this is
actually cleaned up so you don't see the SIMD registers and weird struct
packing. Now I really recommend you to not actually read this code but to get
the main idea from the comments and my explanations. A much more readable python
reimplementation is available right after for your sanity.
Most variables are not renamed correctly because I did not actually reverse and
understood all this function. This is simply what it looked like in my
decompiler at the moment I undestood enough to throw it by the window, modulo
of course SIMD and stack fengshui :eyes:.
Let's not care too much about weird constants and implementation details for
now as I did not understood them at the time either.
The main idea of this is code is that it will run through all possible
increments combinations that will iterate on the second board (the one from
case 3, where we manually place our bits from the bit queue).
Basically, we check every possible way we can run through the board.
For each of these increment combination we see a weird loop performing modulos
of the increments. This is actually the euclidean algorithm that computes the
GCD of 2 numbers. This GCD is compared to 1. If it is not one then we skip this
increments combination and go to the next loop iteration. We are therefore only
concerned about running through the board using coprime increments, confusing I
know.
We then iterate on the board using these increments and count the number of
bits set while doing so. If at any point we encounter more than 2 points during
the same passing of the board we set a result flag. The function will output
`1` if and only if no result flag was set for any iteration. Meaning for any
traversal of the board, we did not encounter more than 2 bits.
Here I was really scared because I started to think that this was maybe `\J`
trolling me with again a cryptography problem modelised using bitboards are
something. And everyone who checks my results of the FCSC know how bad I am at
cryptography.
{{< code file="/static/diplodocus/check_align.c" language="c" >}}
#### Alignement count
So now I am really unhappy, I was having fun finding out puzzle and placing
bits on boards but now `\J` is throwing modular arithmetic at me.
I take a break crying in my bed after these findings before actually thinking.
Running through the array using coprime increments probably has a really
interesting property that may be plotted visually.
So I reimplemented this function in python but instead of summing the bits I
encountered, I mark the bits I would have summed to see the path that I take in
the array.
Which gives us this much more readable code:
{{< code file="/static/diplodocus/show.py" language="py" >}}
With this output (only a sample):
{{< code file="/static/diplodocus/show.out" >}}
It is now obvious what this function is doing, it draws every straight line
passing through the point given as parameter and checks if more than 2 points
of the board are alligned.
If we remember the context were this function is used, it means that we will
set a bit in the third bitboard if and only if no line passing through this
point intersects more than 2 points.
### Case 0 (Final check)
So case 0 is the instruction that performs the final check to see if our board
match the desired state. Again there is a lot of SIMD magic going on so I tried
to clean it a little bit, you lose the actual result of the decompilation but
the code is semantically equivalent.
First we perform a pop count on all lines of the `visited` bitboard, comparing
the total sum to `0x90` which is `12 * 12`, the total number of tiles. We must
therefore go through every single tile of the board exactly once.
Then, we pack the third bitboard (the one that stores if 3 points are alligned)
into the `zmm0` 128 bit register because why not? And basically `shifting` and
`bitwise anding` it to check that every bit of the board are set. So its
basically the same check than before but for the third bitboard, meaning that
no line drawn from any point on the board must intersect with more than 2
points.
The last check simply performs a xor on every line of the board and outputs
an error if it is different from 0. This means that every column of the board
must contain an even number of points.
{{< code file="/static/diplodocus/case0.c" language="c" >}}
Great we have everything ready to go! We simply need to go trough the board and
place 24 points on it and make sure there are never 3 points alligned.
So it turns out this problem is NP-complete (I learned after solving the
challenge that is called the Not-three-in-line problem), I might have a hard
time solving it manually. I might start to implement a SAT solver or som...
But wait, did you spot something sus with this implementation ?
{{< image src="/diplodocus/the_rock.gif" style="border-radius: 8px;" >}}
## Bypassing the puzzle
There are actually two distinct bugs in this implementation of the puzzle.
First, the program does not check that you place a point when there is already
one. It does check that you do not go twice on the same tile but you can still
place multiple points without moving.
The second, the one I exploited here, is that the weird function we
reimplemented actually only count alligned points on all straight lines
**except** for lines and columns.
The special case of the line is checked independently in case 3 when inserting
the point if you remember well.
However the only columns check is in case 0 where it simply checks that there
is an even number of point per column.
Nothing forbids us to put 12 points on the first and last column, which
validates all our constraints.
```
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
|X| | | | | | | | | | |X|
```
{{< image src="/diplodocus/stop_the_count.png" style="border-radius: 8px;" >}}
## Solve
We now simply need to write the input that will give instructions to the
program to write this bugged board.
We first fill the first column, by going downward.
Then we go through the 10 next columns without placing any bit and we fill
the last one.
Finally we need to fill the third bitboard by manually performing the alignment
check for every point in the bitboard so we call case 4 for every coordinates.
We do not forget to put case 0 at the end to validate everything went fine.
{{< code file="/static/diplodocus/solve.py" language="py" >}}
```console
$ ./solve.py | ./diplodocus
Well done! You can submit your input to the remote service to grab the flag!
```
```console
$ ./solve.py | nc challenges.france-cybersecurity-challenge.fr 2201
Well done, the flag is FCSC{bf809d2614501166a890740116103410a69ede950b57a9186bf49eb734eaa1a1}
```
@@ -0,0 +1,378 @@
---
title: "Inverting a bunch of matrices because reverse engineering or something | Brachiosaure @ FCSC 2023"
date: "2023-05-01 18:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
Brachiosaure is a math/puzzle challenge from `\J` for the 2023 edition of the
FCSC. It's difficulty is not in the reversing process, which is fairly trivial
here, but in solving the underlying problem.
{{< image src="/brachiosaure/meme.jpg" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `477 pts` `10 solves` :star::star:
```
Vous aimez les QR Codes ? On vous demande d'écrire un générateur d'entrées
valides pour ce binaire, puis de le valider sur le service web fourni où un nom
aléatoire est proposé toutes les 5 secondes.
```
Author: `\J`
## Given files
[brachiosaure](/brachiosaure/brachiosaure)
# Writeup
## Overview
As we can guess from the challenge description, this binary will take images
as input. QR codes images for that matter.
```console
$ file brachiosaure
brachiosaure: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV),
dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1
=3e4d225f1053b2a64de1cd133563e6e655049aca, for GNU/Linux 3.2.0, stripped
$ ldd brachiosaure
linux-vdso.so.1 (0x00007ffd833bd000)
libzbar.so.0 => /usr/lib/libzbar.so.0 (0x00007f3ec2325000)
libpng16.so.16 => /usr/lib/libpng16.so.16 (0x00007f3ec22ec000)
libcrypto.so.1.1 => /usr/lib/libcrypto.so.1.1 (0x00007f3ec1fff000)
libc.so.6 => /usr/lib/libc.so.6 (0x00007f3ec1e18000)
libdbus-1.so.3 => /usr/lib/libdbus-1.so.3 (0x00007f3ec1dc7000)
libv4l2.so.0 => /usr/lib/libv4l2.so.0 (0x00007f3ec1db8000)
libX11.so.6 => /usr/lib/libX11.so.6 (0x00007f3ec1c73000)
libXv.so.1 => /usr/lib/libXv.so.1 (0x00007f3ec1c6b000)
libjpeg.so.8 => /usr/lib/libjpeg.so.8 (0x00007f3ec1be8000)
libz.so.1 => /usr/lib/libz.so.1 (0x00007f3ec1bce000)
libm.so.6 => /usr/lib/libm.so.6 (0x00007f3ec1ae6000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007f3ec23a2000)
libsystemd.so.0 => /usr/lib/libsystemd.so.0 (0x00007f3ec1a09000)
libv4lconvert.so.0 => /usr/lib/libv4lconvert.so.0 (0x00007f3ec198e000)
libxcb.so.1 => /usr/lib/libxcb.so.1 (0x00007f3ec1963000)
libXext.so.6 => /usr/lib/libXext.so.6 (0x00007f3ec194e000)
libcap.so.2 => /usr/lib/libcap.so.2 (0x00007f3ec1942000)
libgcrypt.so.20 => /usr/lib/libgcrypt.so.20 (0x00007f3ec17fa000)
liblzma.so.5 => /usr/lib/liblzma.so.5 (0x00007f3ec17c7000)
libzstd.so.1 => /usr/lib/libzstd.so.1 (0x00007f3ec16f5000)
liblz4.so.1 => /usr/lib/liblz4.so.1 (0x00007f3ec16d3000)
libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0x00007f3ec16b3000)
libXau.so.6 => /usr/lib/libXau.so.6 (0x00007f3ec16ae000)
libXdmcp.so.6 => /usr/lib/libXdmcp.so.6 (0x00007f3ec16a6000)
libgpg-error.so.0 => /usr/lib/libgpg-error.so.0 (0x00007f3ec1680000)
```
That's a lot of libraries, this is really good news because we can just look up
the documentation of those libraries to understand what is going on.
The most important ones are `libpng` to read the image data and `libzbar` which
is used to read data from a QR code. Turns out symbols are really self
explanatory by themselves, the code basically reads like sources even though it
is stripped.
By executing it, we can already what the program is expecting: a username,
and two png, one for the username and one for the serial, probably QR codes
encoding said username and its serial.
```console
$ ./brachiosaure
Usage: ./brachiosaure <username> <username.png> <serial.png>
```
So is this just a simple keygen that needs to output its key as a QR code ?
(Spoiler it isn't)
## Reversing
### Main
I'm saving you the trouble of renaming the variables, the function I called
`get_qr_data` reads like a charm. It basically is just a succession of calls to
`libpng` and `libzbar`, it does exactly what you think it does, reads an image
file, decode the QR code it contains and outputs everything in the pointers
passed as parameters so I won't show the process of reversing it.
The only thing worth pointing is that it grayscales the input image.
{{< code file="/static/brachiosaure/main.c" language="c" >}}
So we compute the `sha512` of the username, this gives us a digest, that we will
keep for later, just remember that we have this digest of the username.
We then decode the 2 QR codes, both seem to need to encode `0x40` bytes of data.
(I know you already guessed it, a sha512 is also 0x40 bytes long).
And finally we perform some checks:
- Both pictures needs to be a square of the same size
- The encoded data of the user QR code needs to be equal to the user digest
- The serial check, taking both QR datas as input
- And finally a last check but this time taking both images data instead of the QR data.
### check_serial
{{< code file="/static/brachiosaure/check_serial.c" language="c" >}}
Hmmm we find again the same interesting check that was performed in the main
function, something is already interesting but let's first note things that
we can already guess from this:
Since it take our images as input in main and image width, it certainly
interprets the data as a linearized 2 dimensionnal array, taking the width as
parameter. We can confirm this since the check serial is called with size `0x8`
as parameter and `0x8 * 0x8 == 0x40`.
Now let's see what is different:
```c
// Inside check serial
something_interesting(user_digest, user_digest, &buff, size);
res = memcmp(serial, buff, size * size) == 0;
// Inside main
int32_t win = something_interesting(username_img_data, serial_img_data,
&an_interesting_output, user_width);
```
First the result is not used in the same way:
- Inside `check_serial`, the return value is discarded, and the output buffer is
compared to the serial, so it is bascically a keygen, seems easy enough
- Inside `main`, the output buffer is discarded and only the return value is
checked
Then in the `main`, the function is called with the user and serial images data,
but in check_serial, it is called with the digest data twice.
OK let's see what this does, we need to understand what doest it put in the
output buffer since it will be the serial we will need to encode in the second
QR code of the input, but we also need to understand the return value.
### dot_product
Cutting drama right now, it is simply a matrix dot product:
{{< code file="/static/brachiosaure/dot_product.c" language="c" >}}
Alright so to recap what actually happens:
- In check serial, we perform the dot product of the user digest, interpreted
as a linearized 8 * 8 matrix, with itself, effectively squaring it, which
gives us our serial (also in a linearized 8 * 8 matrix).
- In main, we perform the dot product of the user and serial IMAGES, and we can
see from the code that the return value indicates wether or not the resulting
dot product is the identity matrix.
So yeah, congratulation, it is the end of the reversing part.
We now need to, given a random username:
- Compute its digest
- Square it to get the serial
- Output both the digest and the serial to a QR code each
- (The fun part) Make sure that the images of said QR codes are invertible
## Splitting the problem
So at first I though this was impossible, but I gradually had more and more
tricks up my sleeve to solve this, which I finally almost all threw by the
window when I discovered how easy the solver actually is.
I still think that even though completely over engineered and full of dead ends,
my thought process may be of value for someone I guess.
### Recontextualizing
So first we need to understand that we are not doing any kind of dot product and
are not working with any kind of matrices.
Both only operate over the unsigned integers modulo 256, since the dot product
stores its output on a `char`. This will be the key to make the matrix
invertible.
You can then notice that in the fieds of integers modulo 256, `0xff * 0xff ==
1`. When I noticed I started to think that I could carefully place white pixels
on the QR code to specifically put some 1s where I wanted, but since patching a
single byte of the first/second matrix will impact the entire corresponding
row/column of the dot product, it doesn't work obviously
Now, obviously we will need to patch the QR code image, the question is how much
so that `libzbar` still decodes the correct digests and serial. So obviously,
we may resize the images of the QR codes to add some data.
### Dead end
So then this is where I had a really dumb idea. I thought that maybe I could
append carefully crafted columns and empty lines to the first matrix, and
carefully crafted line and empty columns to the second matrix so that the result
of the dot product int overflow back to 0 or 1. Thus outputing 2 new images with the QR code in the top left corner.
And it actually kind of worked, but not entirely so I won't detail the
algorithm, I still implemented it entirely because I was really convincend this
was the intended way.
Why it doesn't work is because yes by adding rows and columns like that, being
carefull that everything cancels nicely with the data you inject on the other
matrix, the first N rows and columns of the original images have indeed been
inverted, but now you have a matrix which is somewhat bigger, and the parts you
added are not inverted, it was entirely 0 if I did not put the diagonal to 1 to
the rows/columns I added. If I decided to put the diagonal, then the bytes you
carefully injected are then reflected allong the dot product in this new bigger
matrix. So either way you need to perform the same process to repatch everyting
over this bigger matrix, infinetely recursing.
### How it's actually done
OK, so after this misadventure, the next step is to understand that a single
element of coordinates (i, j) from the dot product is impacted by all elements
of the ith line of the first matrix and all elements of the jth column of the
second. (You actually already needed to understand this to implement my dumb
idea but now we will make it interesting).
Let's say that I take my first QR code and I double it's height and width like
this where the purple ones are all 0 matrices and the green one is the identity:
{{< image src="/brachiosaure/resizing.png" style="border-radius: 8px;" >}}
You can clearly see that if you patch any bytes in the identity matrix in the bottom right you will never impact the result of the top left corner of the dot
product.
If you are not convinced: take this more striking example:
{{< image src="/brachiosaure/dissociate.png" style="border-radius: 8px;" >}}
See how you can perform the dot product on each of the corner independently ?
That is the key to solving this, because now instead of putting the identity
matrix in the corresponding corner in the other image, we can simply compute the
inverse of the QR code:
{{< image src="/brachiosaure/overlap_inverses.png" style="border-radius: 8px;" >}}
## Inverting the two matrices
You may think "Ok this is over GG NO RE", but it is not that simple, at least it
wasn't for me because I suck at maths.
So I tried multiple implementations of the matrix modular inversion, some
worked, some didn't, but most importantly, all of them took ages to run on
actual images, about 10 minutes for most, and we are limited to 5 seconds on the
remote service.
The best implementation was the `sagemath` one which computed real size images
inverses in about 20 seconds, still too slow. But at least I could test locally
that the generated images were accepted by the program, and they were, so I knew
I was on the right track.
I tried reducing the size of the QR code to make it faster, and it ran in less
than a second, but the program could not recognize the data in the QR code
anymore.
Well we need another strategy. First because it is taking too long, but also
because not every matrix turns out to be invertible at all. And I don't want to
bruteforce the remote service to be lucky to have a username AND a serial matrix
that are both invertible and then be lucky enough that the program successfully
decodes the QR code.
## If it isn't invertible, juste make it invertible duh
So I go for a cleaner approach. I am not guaranteed that the QR code is invertible, fine, patch it to make it invertible.
And there is a really interesting property indeed:
{{< image src="/brachiosaure/invertible.png" style="border-radius: 8px;" >}}
By adding identity matrices and an empty matrix in the bottom right corner, the
resulting matrix is always invertible, and the inverse can be trivially
computed since it is simply moving matrices arround and negating the original
image modulo 256 `notice the "-(QRuser)" in the inverted matrix`.
## Putting everything together
So what we need to do given a random username:
- Compute its sha512 digest
- Compute the serial, the square of the matrix of the digest
- Generate a QR code for the digest and another one for the serial
- Make both QR code invertible by adding empty and identity matrices as shown above
- Compute the said inverse of said matrices
- In the result user.png put:
- The invertible digest QR code in the top left corner
- The inverted serial QR code in the bottom right corner
- In the result serial.png put:
- The inverted digest QR code in the top left corner
- The invertible serial QR code in the bottom right corner
{{< image src="/brachiosaure/final.png" style="border-radius: 8px;" >}}
## Solver
Here is the final solver script, which also automates fetching the username
from the remote service and the upload of the images to recover the flag.
But before leaving this writeup there is still something I want to show you at the end.
{{< code file="/static/brachiosaure/solve_writeup.py" language="python" >}}
```console
$ ./solve_writeup.py
<strong>FCSC{c2ddbd0310bcf5f65c576453ee9697774afd38dc887b64f4dccc63ac598d084b}</strong>
```
## Side notes
Here are examples of images generated by this solver for username `90QOCSdkzFE3rrYD2GdkrZkh4q`:
The original user digest QR code:
{{< image src="/brachiosaure/user.png" style="border-radius: 8px;" >}}
The original serial QR code:
{{< image src="/brachiosaure/serial.png" style="border-radius: 8px;" >}}
The patched user png
{{< image src="/brachiosaure/90QOCSdkzFE3rrYD2GdkrZkh4q_usr.png" style="border-radius: 8px;" >}}
The patched serial png
{{< image src="/brachiosaure/90QOCSdkzFE3rrYD2GdkrZkh4q_serial.png" style="border-radius: 8px;" >}}
As you can notice, there isn't any noise visible by naked eye, this script therefore gets the flag 100% of the time.
Why is it so clean ? Simply because of the strategy we used to compute the
inverse matrix:
- We add empty matrices: they are black so no noise
- We add identity matrices: they only have the diagonal set to 1 so only a little bit grayer than theso here you go.
- We add the opposite of the matrix, and this is the clean part: our original matrices only hold black and white pixels so respectively `0x0` and `0xff`, so the opposite of `0` is still `0` and the opposite of `0xff` if `1` modulo 256, so like the identity matrix, they are nearly invisible. If you look closely though :eyes: you will see that all white pixels of the QR code were indeed reflected as very faint taint of gray in its inverse matrix on the other image.
@@ -0,0 +1,522 @@
---
title: "Reversing and solving nested puzzles | Picasso @ FCSC 2023"
date: "2023-05-01 18:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
Yes, this is yet another puzzle reversing challenge from `\J` for the FCSC 2023,
yes I swear I'm also able to flag other types of challenges too, I can't help I
like algorithms too much. I will try to make lower level content soon :tm:
:eyes:.
Yes I also know that `face0xff` already did a
[writeup](https://ctf.0xff.re/2023/fcsc-2023/picasso) on this, but I still want
to writeup it because I liked the challenge and even though my solution is kind
of overengineered compared to the one of `face0xff`, I really enjoyed writing
the solver algorithm for the first puzzle so here you go.
{{< image src="/picasso/meme.jpg" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `482 pts` `8 solves` :star::star::star:
```
Trouvez une entrée permettant d'afficher le message de réussite, et envoyez-la
sur le service distant pour récupérer le flag.
nc challenges.france-cybersecurity-challenge.fr 2251
SHA256(picasso) =
f3d6aafce2c069fdf486fce75112ccc09593ddd54452407d4cf066be12daf7fd.
```
Author: `\J`
## Given files
[picasso](/picasso/picasso)
# Writeup
## Reverse
### Overview
OK, nothing magic you know how this works: it's a puzzle, we need to find the
input that solves said puzzle. Now the twist is that knowing how `\J` writes his
challenges, the problem is either NP-complete, obfuscated with 50+ nanomites or
put together with 12 other puzzles that must be solved together with the same
input. Make your bet, which one is it this time ?
So I open up my decompiler and I find a single function, the whole thing holds
in a single function in less than `0x200` bytes of machine code. Let's look this
up.
{{< code file="/static/picasso/main.c" language="c" >}}
So I cleared everything so you can understand the structure of the code. It is
really simple:
- First the program copies `0x36` bytes from the init_state array to a local array
- It then prompts for the password, asking for a maximum of 24 bytes
- Initialize an index that will be used to iterate over the input in an infinite loop
- We have 2 clear parts in this loop:
- The first one when we are done iterating on the input: We will go back to what this does later but we can clearly see that it performs the final check and prints us the flag if we are good.
- The second one is the part that iterates on the input, so the one that is executed first. We can also see that it matches the characters from our input against lower case letters, instantly exiting the program if it isn't one
A first look at the init state shows us that it only contains only numbers
between 0x0 and 0xf, a good hint that it may be used to index an array of `0x10`
elements.
### Permutations on the state
Let's start by looking inside that `else` block since it is the one doing stuff
with our input.
Ok so first thing you need to notice: you may think that characters are matched
on all lowercase letters but if you look closely, the `'i'` and the `'o'`
are missing, thus giving us an alphabet of 24 elements.
I know what you are thinking `"But that's also the total size of the input, so
characters from the input are used to index said input"`, yeah that could have
been a good idea, but it doesn't do that and it is simply a coincidence.
So anyway we recover the index of the character in the alphabet and divide it
by 4. The remainder is kept for later and the quotient is used to index
a permutations matrix, which holds 6 permutation tables of 0x36 elements each.
The permutation matrix is linearized though so I already redefined the
dimesions so that's why it's showing really nicely in the code below. But to
know the dimensions I basically saw that the permutation matrix was indexed by
`(pos / 4) * 0x36`, since our alphabet holds 24 characters, that gives us `24 /
4 == 6` arrays of size `0x36` in the matrix. We can confirm the 0x36 because we
will iterate over `0x36` elements of the permutation array right after this.
We then copy the state and apply the permutations given by the fetched
permutation array. We repeat this process N times, N being `pos % 4`. We do not
actually really care about the copy, it is simply there as temporary buffer so
that permutations don't cancel each other or erase data in the state, it is
just an implementation detail.
So to sum this up, each character from our input will chose a permutation array
to apply to our state and how many times to apply the permutation. They are 6
permutations table possibles, and we can apply the same permutation between 0
and 3 times with a single input character.
So basically our input controls how we will shuffle the initial state.
You can also see right bellow the code a sample of the permutations matrix,
values seem really arbitrary but let's see if you can already get a feeling of
what this is doing, I will explain it after understanding the entire `if` block
containing the final check.
{{< code file="/static/picasso/permutations.c" language="c" >}}
And here a sample of the permutation matrix, telling you where each index of the
state is going to be moved.
{{< code file="/static/picasso/permutations_array.c" language="c" >}}
### State checker
OK so the first part shuffled the state, so now I guess this simply checks if
the resulting shuffled state is valid.
This one may be kind of tricky if you want to understand the implementations
details, if you don't care you can just skip right when I will recap what the
puzzle actually is.
So I already renamed everything to keep it clear, I invite you to follow the
code and its explanations a bit lower in parallel.
{{< code file="/static/picasso/slide.c" language="c" >}}
Basically you start with a board represented as an `uint64_t` intialized at
`0x3da8e0915f2c4b67`. For now, view this board as an array of 16 elements, each element being 4 bits (`4 * 16 = 64`).
As you know 4 bits is a single hexadecimal digit, so actually each hexadecimal
digit from this board is an element, so the initial board is:
`[3, d, a, 8, e, 0, 9, 1, 5, f, 2, c, 4, b, 6, 7]`
You may have noticed that every element is unique, they represent the entire
range of numbers between 0x0 and 0xf, this is no coincidence.
We then create some variables that we will ignore for now, and an index (`i`)
that will be used to iterate over the state that was shuffled in the first part.
While iterating on the state, we fetch the current byte from the state, extended
to 64 bits. Remember how we told that state only held values between `0` and
`0xf` at the beginning ? Good, you are starting to see a pattern.
We create a pointer to a variable I called `allowed_moves`, it is once again a
two dimensionnal array because we iterate over it in a nested loop. I knew its
dimensions because this is the part to go to the next sub-array:
```c
allowed_moves += 0x28;
```
So I knew each sub-array is `0x28` bytes, and I saw that the index used to
iterrate the outer loop is the `shifter` variable, initialized to `0x3c` and
decremented by `4` each loop until it is strictly negative, so a total of `0x10`
iterations. We then have a matrix containing `0x10` arrays of `0x28` bytes.
I also knew that the `0x28` bytes corresponded to 5 `uint64_t` since the inner
loop iterate over an `uint64_t *`
I pasted the entire content of this matrix below so you can have a look, you
will see that every element of this matrix has a single bit set to 1, and bits that are all sets at a position of `0 % 4` for that matter.
Okay let's take a look at the `shifter`. It is initialized to `0x3c` and is used
to shift the `board`, before keeping only the lowest weight hex-digit with the
`& 0xf`. The hex digit is then compared against the byte we fetched from our
state. If they differ, we basically skip this loop, decrementing the `shifter`
by 4 (meaning that on the next iteration we will select the next hex digit of
the board), and go to the next array in the `allowed_moves` matrix.
So to recap this, if you consider the `board` as an array of 4 bits elements,
`shifter` is actually an index used to iterate over this array. So we are
iterating to find at which index is the byte from the `state` inside the
`board`. `allowed_moves` will follow the same iterations, meaning that we will
select an `allowed_moves` sub-array based on where the `state` byte is located
in the `board`.
Good, so once we find our `state` byte inside `board` we start iterating over
the `allowed_moves`, basically the move is multiplied by `0xf`, which will
effectively set the 4 bits corresponding to the single bit in the initial move,
this will now be used as a mask on the board.
So this move simply selects an hex digit from the board actually, if the
selected byte is NOT 0, then we continue the loop, skipping the move, but if it
is 0, then we exit the loop. Final check to see if the move itself was not 0, if
it is then we go back to trying the next `shifter` and `allowed_moves`, if not
then gg we selected a move. If at the end, no move was selected we go out of the
loop and basically lose.
So whatever this means, a valid move from a certain position in the board, must
match with the `0` digit from the `board` being at certain indexes, which, for
now, since we did not dig up the `allowed_moves` matrix yet, feel kind of arbitrary.
Feeling confused ? Don't worry it will soon make sense.
{{< code file="/static/picasso/allowed_moves.c" language="c" >}}
Great, we now have a `move` which is the index of the `0` element of the board,
a `shifter`, being the index of the byte from our `state` in the same board. The
previous paragraph was meant to make sure this move/shifter association is
valid.
Let's talk about the `swapper` now, it is composed of 2 parts:
- `c << shifter`: so it will be the representation of the board as if only `c`
was on it
- `c * move`: the representation of the board as if `c` was at the position
indicated by the move, and no other element on the board. So it the board, with
c at the position of the 0 and nothing else on the board
We then compute the next board by `xoring` the current one with the swapper.
This will have the effect to `xor` the current element of the `state` AND the
current `0` from the board with the current element of the `state`. This will
have the effect to actually swap the `0` and our element of the `state`.
And after that we simply go the next `state` byte, until we have done all `0x36`
of them.
Let's recap:
- each character from the `state` selects the corresponding hex digit in the
board.
- According to its position in the board, we will try to find a valid move,
being a move that have `0` as destination, but only certains positions of `0`
are allowed according to were the hex digit was in the board.
- If a valid move was found, then we swap the `0` and the `state` byte.
FINALLY, there is the final check, after all the moves from the state have been applied, the board must be `0x123456789abcdef0`.
Great, now let's look at the `allowed_moves`.
So what I did to understand what all those valid moves were was to take a pen,
drew an array of 16 elements, and for each element I drew an arrow to every
valid moves from that position. So just ignore that there has to be a `0` at
these positions for now, it's simply a matter of "if there was a 0 there, could
I move here ?". And it started looking like this for the first few elements:
{{< image src="/picasso/swaps.png" style="border-radius: 8px;" >}}
What you need to notice is that every move can be inverted, so you can go back to your position after moving. MOST tiles can go to the tiles right next to them or to the tiles that are 4 tiles farther. For example, tile at index 1 can go either at 0, 2, or 5. You are probably starting to understand, let's just put
the final touch: 3 cannot go to 4 and vise-versa.
So this is simply a flattened 4 * 4 grid, where you can only move to the
adjacent tiles. Let's now replace the indexes I put in the diagram above with
the actual values of the initial board (`0x3da8e0915f2c4b67`) we have:
{{< image src="/picasso/starting_grid.png" style="border-radius: 8px;" >}}
I know you understood everything but let's just see the target board
(`0x123456789abcdef0`):
{{< image src="/picasso/target_grid.png" style="border-radius: 8px;" >}}
So we need to get from one to the other in `0x36` moves exactly, each move swapping the 0 with an adjacent tile.
Cool, all of this simply for a slide puzzle. Each element of the state corresponds to the tile that we must push on the `0` (which represents the empty tile in the slide puzzle). Let's go and solve th...
### But wait there was a first step
I hope you did not forget that the state used to select which tiles are moved in
which order was shuffled by the first step according to our input.
Maybe it's time to understand how this shuffle work.
OK so I got this one super fast actually, let's just get you the context back:
- 6 permutations tables possibles
- each can be applied `[0;4[` times each time
- `0x36 == 54` elements in the state
If you are a puzzle fan you already know what this is I don't even need to show
you the permutation matrix again but hey:
```c
char permutations[0x6][0x36] =
{
[0x0] =
{
[0x00] = 0x09
[0x01] = 0x01
[0x02] = 0x02
[0x03] = 0x0c
[0x04] = 0x04
[0x05] = 0x05
[0x06] = 0x0f
[0x07] = 0x07
[0x08] = 0x08
[0x09] = 0x2d
...
[0x34] = 0x34
[0x35] = 0x35
}
[0x1] =
{
[0x00] = 0x00
[0x01] = 0x01
...
```
Literally what I did is I saw the first permutation table, noticed that only 1
element out of 3 were moving (so I though this was a 3 * 3 array) and that the
first ones were moving 9 tiles further than there original location (so probaly
a 3 * 3 * 3 cube), oh wait did I say cube ? 6 faces ? can be rotated up to 3 times ? 54 elements ? yeah ok you got it aswell.
It's a rubiks cube.
Each permutation table is a counter-clockwise rotation of a face of the cube.
The process of mapping the cube in its flattened representation and to know
which permutations corresponds to which face is just teadious so I will just
give you this one out.
Do keep in mind that I was not familiar with standard rubiks cube notations, so
I named a move by the color of the face that is rotating instead of the usual
U,F,... it felt more intuitive to me.
Here are the indexes of each cube tile on the flatenned state:
{{< image src="/picasso/cube_indexes.png" style="border-radius: 8px;" >}}
I attributed colors to faces arbitrarily to respect the usual cube
configuration, but as long as I keep everything coherent with this representation
I will do just fine.
With the above cube, fold it back and see how the first permutation array indeed performs a counter-clockwise rotation of the red face.
Here is the initial state of the cube:
{{< image src="/picasso/cube_init.png" style="border-radius: 8px;" >}}
## Solving the slide puzzle
### Recap everything
So now we are done with the reversing part. With our input, the program will:
- Consider each character as a move on a rubiks cube, applying said move
- Consider the flatenned shuffled cube as a list of slide puzzle moves
Basically we need to solve a rubik's cube in order to ordonate a slide puzzle
solution.
To solve this, we will need to take one problem at a time, first find a solutions to the slide puzzle, then map the solution to a cube which we will consider as the solved cube, then map the color of the solved cube back to
the starting cube in order to solve it.
### Naive backtracking
So to start I want to say that I am really impressed that the solver of
`face0xff` found a solution this fast, I was really convinced that without the
little tricks that I will show you, it would take too long to search for a 54
moves solution, but hey seems like it works if you implement every slide puzzle
heuristics you may think of.
So my approach was a backtracking algorithm, however you can clearly see why
backtracking 54 moves is not a good solution so we will need to add some
heuristics to narrow down the search for valid moves.
Basically the algorithm works as follow given a current state of the grid:
- If the puzzle is solved it's won
- If you have no move left it's lost
- generate all possible moves
- try each move by applying the move and recursively calling this procedure
- if the recursive call returned true then it's won
- else cancel the move and try the next
- if no move returned true there is no solution
### Slide puzzle heuristics
Okay this algorithm will take way too long, we need to cancel some search paths
early so that we will not further go down the calls if we can already know that we cannot solve anymore from a given grid.
#### Cannot cancel previous move
This heuristic takes the assumption that you cannot play the same move as the
previous one, because otherwise you will go back to same state as the previous
move, effectively doing 2 moves for nothing.
Okay this heuristic is not exactly 100% reliable, since actually the puzzle is
also solvable this way, simply with useless moves. But I was convinced that 54
was the optimal solution, I don't imagine that `\J` would have asked us to solve
a puzzle in a non-optimal way.
#### Last move
Since the tile in bottom right needs to be `0`, this means that the last move
needs to be `f` or `c`, so if at any point, both of these tiles do not have
anymore remaining moves while the puzzle isn't already solved then you can
already tell it's unsolvable.
Oh I didn't talk about the limited number of moves per tiles ? Don't worry I'll
explain in a minute.
### Rubik's cube heuristics
These are the heuristics you can determine based on the fact that the moves
are shuffled from a rubik's cube initial state.
#### Face centers
In a rubik's cube the center tile of each face CANNOT move, this means that
since we know the starting position of the cube, we already know that:
- Move `4` will be `f`
- Move `d` will be `2`
- Move `16` will be `c`
- Move `1f` will be `a`
- Move `28` will be `a`
- Move `31` will be `4`
#### Move counts and manhattan distance
Of course I kept the best one for the end, this is by far the most effective
one and it is probably enough to solve the whole thing by itself.
This heuristic is based on the fact that we can only shuffle the cube, we can
never add or remove moves, therefore we can know how many times a tile will be
moved. For example there are 4 `1` on the cube, so this means that the `1` tile
of the slide puzzle must be played exactly 4 times, no more no less.
So now, knowing this, while backtracking, we can keep track of how many times a tile has moved by decrementing its move counter.
Then, we can compute the manhattan distance of the tile to its supposed
location, which is the minimum number of moves that would be required for the
tile to go to that location if there were no other tile on the grid. For example
tile `f` placed in the top left corner will have a manhattan distance of 5 to
its supposed location.
So whenever the move counter of a tile becomes lower than its manhattan
distance to its supposed location, you know that you will never be able to place
the tile back to where it is supposed to be.
### Solver
So I implemented this in rust because I wanted this to be fast:
{{< code file="/static/picasso/slide_solver.rs" language="rust" >}}
And guess what ? It was super duper fast:
```console
$ time cargo run --release
Finished release [optimized] target(s) in 0.00s
Running `target/release/picasso`
[e, 5, 4, b, f, e, d, 3, 5, 4, e, d, 9, 2, 6, f, b, e, d, 9, 2, 1, c, 7, f, b, e, d, 9, 2, 1, a, 3, 1, 4, 5, 1, 4, 2, 6, a, 3, 4, 2, 6, a, 7, c, 8, 4, 3, 7, b, f]
________________________________________________________
Executed in 77.37 millis fish external
usr time 71.83 millis 182.00 micros 71.65 millis
sys time 3.93 millis 673.00 micros 3.26 millis
```
That shit is probably completely overengineered and I don't care, I had fun
writing it.
I checked manually that this solution was correct and moved to the next step.
## Solving the rubik's cube
We now have our solution for the slide puzzle, so let's map it as a solved
rubik's cube, we know the mapping using the index cube net which gives us which
tiles of the cube corresponds to which move index on the slide puzzle:
{{< image src="/picasso/solved_cube.png" style="border-radius: 8px;" >}}
Since this is the solved cube, we attribute all the colors of the tiles.
We now need to attribute the corresponding colors to the initial state of the
cube so that we can input a valid cube to a solver.
To do this, we use the fact that tiles that are connected along an edge or a
corner will always be linked, so this way we can identify the tile groups on the
cube and identify their color from the solved cube.
{{< image src="/picasso/cube_init_colors.png" style="border-radius: 8px;" >}}
Then I basically just used [this online
solver](https://www.grubiks.com/solvers/rubiks-cube-3x3x3/), put manually all
the colors, clicked on solve, and the site instantly found a solution in 22
moves. So I noted manually every move, which face was supposed to move and wrote
a script that mapped the moves back to the expected input of the program.
In the script `('g', 2)` means rotate the green face 2 times, `('o', 3)` means rotate the orange face 3 times counter-clock wise ...
{{< code file="/static/picasso/solve.py" language="python" >}}
And piping this script in the program indeed gets us the flag.
```console
$ ./solve.py | ./picasso
Password: Win!
Send your input on the remote service to retrieve the flag.
$ ./solve.py | nc challenges.france-cybersecurity-challenge.fr 2251
Password: Win!
FCSC{235b605a121bdd4b09adc4823bdf0967c446647c1ec69234813068a916fd83a6}
```
@@ -0,0 +1,323 @@
---
title: "Black box reversing | Archiver @ FCSC 2024"
date: "2024-04-14 22:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
This writeup is not a really serious one, if you are reading this
as part of the FCSC writeup reviews, my submitted writeups are
actually for `svartalfheim` and `megalosaure`. I still thought
it would be funny to include this one as it is not that long and
I think my solution is kind of unintended.
Basically we are given a `Windows` stripped binary, compiled
from `rust`. The binary is an encrypted archive manager.
This challenge managed to put every single reverser red flag
in a single binary.
I tried opening up the binary in `binary ninja` or `IDA`, but it
was as expected: stripped `rust`.
So let's close this up, never touch it again and see what we can
do without reading the code or debugging.
{{< image src="/archiver/meme.jpg" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `490 pts` `5 solves` :star::star:
```
Notre équipe SIGINT a intercepté un e-mail contenant une pièce jointe
result.fcsc. Vu l'extension, il doit s'agir d'une archive au format
propriétaire FCSC. Nous avons pu récupérer l'utilitaire dans sa version
Windows, archiver.exe.
Vu le contenu de l'e-mail, ça a l'air assez important. Est-ce qu'on a une
chance de savoir ce qu'il y a dedans ?
Votre prédécesseur, après avoir réussi une analyse similaire, a sombré
dans la folie et réside désormais dans un asile psychiatrique. Il
murmurait des mots étranges comme "TTD" et parlait sans arrêt de hardware
breakpoint.
Note : La chaîne que vous trouverez est à mettre entre FCSC{} pour avoir
le flag.
```
Authors: `commial` `YoMama`
## Given files
[archiver.exe](/archiver/archiver.exe)
[result.fcsc](/archiver/result.fcsc)
# Writeup
## Overview
With the binary, we are also given a `result.fcsc`, which is
an archive encrypted with the given binary.
This archive contains the flag and we must decrypt it.
```console
$ xxd result.fcsc
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: d44a b96f ea76 8c55 73a0 7266 1a5e b5fd .J.o.v.Us.rf.^..
00000040: c3bf cc29 8ed7 e925 1800 0000 0000 0000 ...)...%........
00000050: f96d be51 956d 9342 7e3d 1c0d bbef ad7a .m.Q.m.B~=.....z
00000060: bc57 7bf0 f36a cb23 .W{..j.#
```
## Common fields
### Sizes
First thing we can see are 3 `uint64_t` packed in little endian at offsets:
* `0x0`
* `0x28`
* `0x48`
Given how small these numbers are, they are probably representing
some sizes.
If we count manually, we see that the last two `uint64_t` represent the size of the data that immediatly follows them.
The first one is still unknown but as it is `1`, it probably just
is the number of files in the archive.
### sha256
Now let's try to create our own archive:
```console
$ echo -n 'FCSC{test_flag}' > flag.txt
$ ./archiver.exe create password test.db flag.txt
$ xxd test.db
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: 8257 3ccc 2608 498d b6b7 5801 740f 2e4e .W<.&.I...X.t..N
00000040: 8b36 0169 9273 2c91 1f00 0000 0000 0000 .6.i.s,.........
00000050: a278 0ee8 7308 548a 84af 1ad4 6c0c 0844 .x..s.T.....l..D
00000060: de13 a830 ea7f 4d37 19ea 7efe 14b5 c5 ...0..M7..~....
```
Two things are already weird:
* Everything is identical to the given archive until offset `0x30`
* This archive is larger than the given one. Either the flag is really small or data is compressed.
Let's try to archive a really low entropy file to see if the archive is smaller:
```console
$ echo -n 'aaaaaaaaaaaaaaa' > aaaaaaaa
$ ./archiver.exe create password low_entropy.db aaaaaaaa
$ xxd low_entropy.db
00000000: 0100 0000 0000 0000 1f3c e404 15a2 081f .........<......
00000010: a3ee e75f c39f ff8e 56c2 2270 d1a9 78a7 ..._....V."p..x.
00000020: 249b 592d cebd 20b4 1800 0000 0000 0000 $.Y-.. .........
00000030: b2b6 ed4e 38bb 52b8 5cd7 12a7 7df6 261b ...N8.R.\...}.&.
00000040: 2bbf f8df 77c4 dfe8 1f00 0000 0000 0000 +...w...........
00000050: b2b6 ed4e 38bb 52b8 8876 7671 b114 9799 ...N8.R..vvq....
00000060: cb38 24e6 02f9 26f9 25ec a7b8 bdb9 56 .8$...&.%.....V
```
I put exactly the same sizes in the file name and size data.
The resulting archive is exactly the same size so no compression
is performed.
But wait ! Something changed !
In our first archive, the firsts `0x30` bytes where identical
but now they differ starting at `0x8`, they differ for `0x20` bytes
before becoming the same again on the field we identified as a size.
Well, we changed two things: the filename and the file data.
It is unlikely that we guessed the file data on our first try.
But the filename however ? What if the the format stores a hash
of the filename on `0x20` bytes at offset `0x8` ?
```console
$ echo -n 'flag.txt' | sha256sum
21e2ae0fb85fde7bb246ed90194f601e041b3c8ac6e937b1878bd8e0e796a098 -
```
Bingo ! It matches the bytes we have in our first custom archive
and the one given.
So we know that the filename is `flag.txt` and that the archives
stores the `sha256` of the filename at offset `0x8`.
### Cipher texts
I wil now try to play with data sizes to identify what are the sizes in the binary refering to.
Let's create an archive with a filename 1 byte smaller, and data 1 byte larger:
```console
$ echo -n 'aaaaaaaaaaaaaaaa' > aaaaaaa
$ ./archiver.exe create password sizes.db aaaaaaa
$ xxd sizes.db
00000000: 0100 0000 0000 0000 e462 4071 4b5d b3a2 .........b@qK]..
00000010: 3eee 6047 9a62 3efb a4d6 33d2 7fe4 f03c >.`G.b>...3....<
00000020: 904b 9e21 9a7f be60 1700 0000 0000 0000 .K.!...`........
00000030: 8ab9 acd8 126c cc48 064e 9843 2fa1 9492 .....l.H.N.C/...
00000040: 8503 ce34 399c 9820 0000 0000 0000 008a ...49.. ........
00000050: b9ac d812 6ccc f370 a362 da68 de94 c7d2 ....l..p.b.h....
00000060: aa91 eb29 2be2 0aa3 a74f fd99 4dc0 ca ...)+....O..M..
```
Notice that the first `uint64_t` went from `0x18` to `0x17` and
the second one from `0x1f` to `0x20`
Thus the first size and data correspond to the encrypted file name, and the second one to the encrypted data.
We can also see that encrypted data is always exactly `0x10` bytes
larger that the plaintext. So it probably just adds a `0x10` bytes IV in front of it.
Looking back at the original archive, we can thus see that the
the filename is `0x8` bytes large (which matches the `flag.txt`
we found) and the data is also `0x8` bytes large, thus confirming
the really small flag. (see below for a reminder of the original
archive)
```console
$ xxd result.fcsc
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: d44a b96f ea76 8c55 73a0 7266 1a5e b5fd .J.o.v.Us.rf.^..
00000040: c3bf cc29 8ed7 e925 1800 0000 0000 0000 ...)...%........
00000050: f96d be51 956d 9342 7e3d 1c0d bbef ad7a .m.Q.m.B~=.....z
00000060: bc57 7bf0 f36a cb23 .W{..j.#
```
## Figuring out the crypto
Now I will try to get a file as close as possible as the original
flag and see how the resulting archive behaves to small
input mutations:
```console
$ echo -n '12345678' > flag.txt
$ ./archiver.exe create password 12345678.db flag.txt
$ echo -n '22345678' > flag.txt
$ ./archiver.exe create password 22345678.db flag.txt
$ xxd 12345678.db
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: 8257 3ccc 2608 498d b6b7 5801 740f 2e4e .W<.&.I...X.t..N
00000040: 8b36 0169 9273 2c91 1800 0000 0000 0000 .6.i.s,.........
00000050: d509 6e9f 3d4a 06c1 9daa bebe f6cb c23b ..n.=J.........;
00000060: cf4e 3d32 2b68 09cf .N=2+h..
$ xxd 22345678.db
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: 8257 3ccc 2608 498d b6b7 5801 740f 2e4e .W<.&.I...X.t..N
00000040: 8b36 0169 9273 2c91 1800 0000 0000 0000 .6.i.s,.........
00000050: d609 6e9f 3d4a 06c1 cc6e be60 dd5d 8214 ..n.=J...n.`.]..
00000060: 05bb cadc 0bf1 e4b8 ........
```
Most part of the two archives are identical, as expected.
But maybe a little bit too much identical:
Look at the IV of the file data's cipher text (offset `0x50`)
The first 8 bytes are almost identical, only the first one
has been increased by one.
Could it be that the IV is generated with the clear text data ?
Let's try with an other data:
```console
$ echo -n '32345678' > flag.txt
$ ./archiver.exe create password 32345678.db flag.txt
$ xxd 32345678.db
00000000: 0100 0000 0000 0000 21e2 ae0f b85f de7b ........!...._.{
00000010: b246 ed90 194f 601e 041b 3c8a c6e9 37b1 .F...O`...<...7.
00000020: 878b d8e0 e796 a098 1800 0000 0000 0000 ................
00000030: 8257 3ccc 2608 498d b6b7 5801 740f 2e4e .W<.&.I...X.t..N
00000040: 8b36 0169 9273 2c91 1800 0000 0000 0000 .6.i.s,.........
00000050: d709 6e9f 3d4a 06c1 fcd2 be2a c42f bdf1 ..n.=J.....*./..
00000060: 43e8 9879 eb86 bf95 C..y....
```
Again, patching slightly the `n`th byte of the clear text only
patched slightly the `n`th byte of the IV.
I played with some values and noticed that the operation performed
is actually a xor:
```console
>>> 0xd7 ^ ord('3')
228
>>> 0xd6 ^ ord('2')
228
>>> 0xd5 ^ ord('1')
228
```
So the clear text is xored with a key to generate the IV,
but I do not know the said key, which seems to be derived
from the archive password.
## Known plaintext
Or do I ?
Remember that I know that filename is `flag.txt`, and that I have
an associated ciphertext.
With a little bit of luck, the IV of the filename cipher text
is generated with the same key:
```console
>>> 0x82 ^ ord('f')
228
```
Looks like it does.
Since I have a known plaintext and example cipher text, I can simply, xor
the plaintext with the filename IV to recover the xor key.
Then apply the same key to the file data IV to recover the
plain text:
```python
#!/usr/bin/env python3
from pwn import *
filename = b'flag.txt'
IV = b'\xd4\x4a\xb9\x6f\xea\x76\x8c\x55'
c = b'\xf9\x6d\xbe\x51\x95\x6d\x93\x42'
key = xor(IV, filename)
flag = xor(c, key)
print('FCSC{' + flag.decode() + '}')
```
```console
$ ./solve.py
FCSC{KKfYQogc}
```
@@ -0,0 +1,786 @@
---
title: "Decompiling a multi-process VM back to C | Megalosaure @ FCSC 2024"
date: "2024-04-14 22:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
Yes it's the third year in a row that I writeup the dinosaur reverse challenge.
But this time it is neither a math or puzzle challenge.
We are instead met with a program that takes 20 minutes to validate the input and forks tens of thousands of processes.
{{< image src="/megalosaure/meme.jpg" style="border-radius: 8px;" >}}
## Challenge description
`reverse` | `487 pts` `6 solves` :star::star::star:
```
Voici un binaire qui vérifie si ce qu'on lui passe est le flag. À vous de jouer !
```
Author: `Cryptanalyse`
## Given files
[megalosaure](/megalosaure/src/megalosaure)
# Writeup
## Overview
Nothing out of the ordinary at the first look.
```console
$ file megalosaure
megalosaure: ELF 64-bit LSB pie executable, x86-64, version 1
(SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2,
BuildID[sha1]=b8bd171568d3bd03eca826edb869205684411dab, for GNU/Linux 3.2.0,
stripped
```
Dynamic analysis however ... the binary first tells us to add a
capability to the binary, `stracing` and `gdb` will thus require higher
privileges to not drop said capability.
`stracing` will show us that the program starts by creating about 10 thousands `pipes`. Before prompting for the flag, inputting
a correctly formatted `FCSC{...}` flag will then cause the program
to fork endlessly for about 20 minutes before refusing the flag.
## Code analysis
### Main function
Here is a decompiled main function.
We can see that the code creates the pipes in `setup_process_limit_and_IPC`,
then creates a shared memory mapping..
It will then ask for the flag, check its format, and split the
input into `0x12` `uint32_t`.
These `int` are then xored in the shared memory by groups of two
and the same function is ran `0x2c` times for each group but more
on this later.
Once this is done, the program saves some bytes in the shared
memory else where, and shift the global shared memory pointer,
before doing the same thing for the next 2 `int` in the input.
The final check simply is an equality test of all the saved values
mentionned above against an hardcoded reference array.
```c
uint32_t* shared_mem = nullptr;
int32_t main(int32_t argc, char** argv, char** envp)
{
setup_process_limit_and_IPC();
shared_mem = mmap(nullptr, 0x100000, 3, 0x21, 0xffffffff, 0);
if (shared_mem == -1)
{
perror("mmap");
exit(1);
}
int32_t* shared_mem_original = shared_mem;
puts("Enter the flag:");
char input[0x46];
memset(&input, 0, 0x46);
if (read(0, &input, 0x46) <= 0)
{
perror("read");
exit(1);
}
if (check_format(&input) != 0)
{
puts("Wrong flag format!");
exit(1);
}
uint32_t (* input_ints)[0x12] = &input;
for (int32_t i = 0; i <= 0x11; i += 2)
{
shared_mem[0] = (shared_mem[0] ^ input_ints[i]);
shared_mem[1] = (shared_mem[1] ^ input_ints[i + 1]);
for (int32_t j = 0; j < 0x2c; j += 1)
start_pod(pod_infos[j].n_children, code, 9);
*(uint64_t*)(((((i + (i >> 0x1f)) >> 1) + 0x100) << 3) + shared_mem_original)
= *(uint64_t*)(shared_mem + 0xb0);
shared_mem = &shared_mem[0x2c];
}
shared_mem = shared_mem_original;
int64_t lose = 0;
for (int32_t i = 0; i <= 8; i++)
lose = (lose | (ref[i] ^ *(uint64_t*)(shared_mem + 0x800) + (i_1 << 3)));
if (lose != 0)
puts("Nope.");
else
puts("Win!!");
if (munmap(shared_mem, 1) != 0xffffffff)
return 0;
perror("munmap");
exit(1);
}
```
### Check format
Let's take a quick look at the `check_format` function:
```c
uint64_t check_format(int32_t* input)
{
shared_mem[0] = input[0];
shared_mem[1] = 0x1337;
shared_mem[2] = 0xa4e1a60a;
start_pod(5, check_bytecode, 0x78 / 10);
return 0 | shared_mem[0] | shared_mem[1] | shared_mem[2];
}
```
We can see that it initializes the shared memory with the first
`uint32_t` of the input then starts the same `start_pod` function
than in main.
### Start pod
The `start_pod` function takes as first parameter what I called a
`pod_info` struct, which is just two `uint32_t`, the first one
is the number of children the pod will fork, the second one is an
offset in some array of `uint16_t` I called `code` given in
parameter, you will understand the name really fast once we check
the `child` function.
The last parameter is the size of a single `code` block given to
`child`. Thus offsetting by this much between each `fork`.
In my terminology, a `pod` is a complete run of all the children
denoted by their `pod_info` and associated `code`.
```c
__pid_t start_pod(int32_t pod_info[2], uint16_t* code, int64_t code_size)
{
for (int32_t i = 0; i < pod_info[0]; i = (i + 1))
{
pid_t pid = fork();
if (pid == 0xffffffff)
{
perror("fork");
exit(1);
}
if (pid == 0)
{
child(&code[(i + pod_info[1]) * code_size]);
/* no return */
}
}
__pid_t i;
do
{
i = wait(nullptr);
} while (i > 0);
return i;
}
```
### Child
We are met with a `while true` loop, which selects an `uint16_t`
from the `code` array and dispatches it in a huge switch.
I immediatly recognize the pattern of a virtual machine,
and start identifying the instruction pointer `ip` and the
`stack` by looking the first few instructions of the switch.
I will not show how I reversed all the instruction as many of
them are really similar but I will show the interesting ones.
```c
void child(uint16_t* code) __noreturn
{
uint32_t stack[0x400];
memset(&stack, 0, 0x1000);
int32_t next_ip = 0;
int32_t sp = 0;
uint16_t opcode;
while (true)
{
int32_t ip = netx_ip;
next_ip = ip + 1;
opcode = code[ip];
switch (opcode)
{
case 0x0:
{
...
}
case 0x1:
...
}
}
if (opcode != 0x12)
exit(1);
exit(0);
}
```
## Instruction set analysis
### Push
First let's look at opcodes `0x1` and `0x2`.
These are how I recognized and was able to rename the stack
memory and stack pointers.
We can see that the first instruction takes one operand right
after the opcode, it then increments the stack pointer, fetches
an `uint32_t` from the shared memory, indexed by the first
operand, and stores it in the stack.
Basically a `push mem` instruction
The second one is really similar but takes two immediate operands,
both operands are `uint16_t` but they are packed as a single
`uint32_t` and stored on the stack, so this is the `push imm`
instruction
```c
case 1:
{
int32_t operand_ptr = next_ip;
next_ip = (operand_ptr + 1);
int32_t old_sp = sp;
sp = old_sp + 1;
stack[old_sp] = shared_mem[code[operand_ptr]];
break;
}
case 2:
{
int32_t operand2_ptr = next_ip + 1;
int64_t operand1_ptr = next_ip;
next_ip = operand2_ptr + 1;
int32_t old_sp = sp;
sp = old_sp + 1;
stack[old_sp] = code[operand1_ptr] | (code[operand2_ptr] << 0x10);
break;
}
```
### Pop
This is the inverse operation, takes an `uint32_t` from the stack
and stores it in the shared memory indexed on the instruction's
operand.
```c
case 4:
{
int32_t operand_ptr = next_ip;
next_ip = operand_ptr + 1;
uint32_t operand = code[operand_ptr];
sp = sp - 1;
int32_t val = stack[sp];
stack[sp] = 0;
shared_mem[operand] = val;
break;
}
```
### Add
I will show only a single arithmetic instruction, all the others
work in a similar way:
This one pops two operands from the stack, add them together, and
stores the result back on the stack.
So we now know that this VM is stack based, similar to `python`
or `WASM` bytecode, operands and result of each instruction are
fetched and stored from/on the stack.
```c
case 6:
{
int32_t first_op_ptr = (sp - 1);
int32_t stack_op = stack[first_op_ptr];
stack[first_op_ptr] = 0;
int32_t second_op_ptr = first_op_ptr - 1;
int32_t stack_op2 = stack[second_op_ptr];
stack[second_op_ptr] = 0;
sp = second_op_ptr + 1;
stack[second_op_ptr] = stack_op2 + stack_op;
break;
}
```
### IPC
Before doing more work, two other instructions are really
important, check the code first:
```c
case 3:
{
int32_t operand_ptr = next_ip;
next_ip = (operand_ptr + 1);
uint32_t operand_1 = code[operand_ptr];
sp = sp - 1;
int32_t val = stack[sp];
stack[sp] = 0;
for (int32_t i = 0; i < operand; i++)
{
int32_t operand_i_ptr = next_ip;
next_ip = operand_i_ptr + 1;
if (write(pipes[code[operand_i_ptr]][1], &val, 4) == -1)
{
perror("write");
exit(1);
}
}
break;
}
```
This instruction takes one operand from the stack and one operand
after the opcode.
The operand encoded in the instruction is used to know how many
more operands are left.
For each of them, the instruction will write the stack operand in
the pipe corresponding to the current operand.
We can guess that this is how IPC is performed between each child.
So let's look at the read instruction:
It works in a really similar way and takes the same operand,
except that this time it will setup an epoll instance to read on
very pipe given as operand and store the `read` output on the
stack for each operand.
```c
case 0:
{
int32_t n_operands_ptr = next_ip;
next_ip = n_operands_ptr + 1;
uint32_t n_operands = code[n_operands_ptr];
int32_t epoll = epoll_create1(0);
if (epoll == 0xffffffff)
{
perror("epoll_create1");
exit(1);
}
for (int32_t i = 0; i < n_operands; i++)
{
int32_t n_operands_i_ptr = next_ip;
next_ip = n_operands_i_ptr + 1;
int32_t fd = pipes[code[n_operands_i_ptr]][0];
int32_t epoll_event = 1;
int64_t var_1100_1 = fd | (i << 0x20);
if (epoll_ctl(epoll, 1, fd, &epoll_event) != 0)
{
perror("epoll_ctl");
exit(1);
}
}
uint32_t n_operands_cpy = n_operands;
do
{
struct epoll_event events;
int32_t nb_events = epoll_wait(epoll, &events, 1, 0xffffffff);
for (int32_t j = 0; j < nb_events; j++)
{
// Weird but basically recovers the FD from the event
int64_t fd = *(j * 0xc + &var_8) - 0x1104;
if (read(fd, &stack[(fd >> 0x20) + sp], 4) <= 0)
{
perror("read");
exit(1);
}
}
n_operands_cpy = n_operands_cpy - 1;
} while (n_operands_cpy != 0);
sp = sp + n_operands;
if (close(epoll) != 0)
{
perror("close");
exit(1);
}
break;
}
```
## Disassembling
Right, so let's not look too much at the IPC thingy.
I will start by disassembling the byte code of independant
children, then we will see if we can deduce patterns.
So I implemented a `binaryninja` plugin (my predilection decompiler) for the VM.
{{< code file="/static/megalosaure/src/plugin/__init__.py" language="python" >}}
Remember the `start_pod` and `check_format` functions ?
The check format passed a specific byte code to only 5 children.
This is probably a good first look
Here is how the plugin looked like on the check format bytecode:
{{< image src="/megalosaure/binja_plugin.png" style="border-radius: 8px;" >}}
Every function defined here is a specific child.
The first one pushes the first `uint32_t` of the `shared_memory`
(I wrote this as `m[0x0]` in the disassembler)
on the stack, then pops it and writes it on the first pipe (`r0x0`).
I consider pipes as registers.
The second child does the same but with `m[0x1]` and `r0x1`.
Third child reads `r0x0`, then `r0x1`, multiplies the two values
and writes the result to `r0x2`
Fourth child reads `r0x2`, pushes `m[0x2]`, xor both values,
and writes the result to `r0x3`.
Finally, the last child reads `r0x3`, dupplicates the value on the
stack twice and pop them all in `m[0x0]`, `m[0x1]` and `m[0x2]`
If we look again at the `check_format` function:
```c
uint64_t check_format(int32_t* input)
{
shared_mem[0] = input[0];
shared_mem[1] = 0x1337;
shared_mem[2] = 0xa4e1a60a;
start_pod(5, check_bytecode, 0x78 / 10);
return 0 | shared_mem[0] | shared_mem[1] | shared_mem[2];
}
```
It checks that once the pod has executed, `m[0:3]` is all `0`.
Doing it in the inverse order, it means that the result of the
xor must be 0, thus `input[0] * 0x1337 == 0xa4e1a60a`
This small script does the modular inverse the retrieve
`input[0]`:
```python
#!/usr/bin/env python3
from Crypto.Util.number import inverse
import struct
import os
N = 2**32
def reverse(desired_out, mult):
return ((desired_out) * inverse(mult, N)) % N
first = reverse(0xa4e1a60a, 0x1337)
print(struct.pack('<L', first))
```
With this output:
```console
$ ./invert.py
b'FCSC'
```
Good, we are definitely on the right track.
## Lifting
Great but now if we look at real pods launched for the flag checking,
they contain thousands of children, and have 2 inputs instead of one
(given through `m[0x0]` and `m[0x1]`)
We need to do something smart.
We noticed in the `check_format` example that children essentialy
recover one or two inputs (from memory, immediate, or register),
perform a single operation, and output the result to a register
or memory.
Looking back at the `code_size` given to `start_pod` in the `main` function, we can see that there are at most 9 instructions per child.
So it is unlikely that the real check children can do much more
than take inputs, compute a single operation and send its outputs.
The `binja` plugin must be improved, and we will throw away the
binja part actually.
Instead of disassembling independant children, I need to disassemble
a whole pod.
### Creating an AST
First thing we can build is each child's register dependencies.
I will simply mark which registers the child reads from and which
ones he writes to.
Now, knowing by which register a child is "locked" by reading
and which one he "unlocks" by writing, I can build the dependency
graph of all children.
To do that I implemented a simple algorithm which marks locked
and ready registers and by which child a register was unlocked.
Any child wanting to read a register will be able to do so only
if it is unlocked, if it is, I will give the current child a
reference to the child which originally unlocked the register
it is trying to read. The register will thus be consumed by the
child and be marked as locked again.
Any child which wants to write to a regiser will simply unlock
the register and mark itself as the one which unlocked it.
Obviously, this can only be done if all the child's registers
where consumed, otherwise, the child is still waiting for its
input and cannot write its output.
We do this in a loop until all children have been scheduled.
Inspecting the built graph, I quickly notice that all children
converge to a single output child and that there is no circular
dependency. The graph is thus an AST.
Each node of the AST performs and outputs a single operation based
on one or two inputs registers.
The leafs of the AST do not have dependencies, they simply
take inputs from immediate values or shared memory.
I also notice that the root of the AST has a single input,
which is simply outputed in shared memory.
Further analysis will show me that in the AST of every pod, given
pod number `n`:
* Only the root child outputs to memory, and at index `n+2`
* Only the leafs reads from memory, at indexes `n` and `n+1`
### Recalling the objective
As a reminder, here is the for loop which computes the result
tested against the `ref`.
```c
uint32_t (* input_ints)[0x12] = &input;
for (int32_t i = 0; i <= 0x11; i = (i + 2))
{
shared_mem[0] = (shared_mem[0] ^ input_ints[i]);
shared_mem[1] = (shared_mem[1] ^ input_ints[i + 1]);
for (int32_t j = 0; j < 0x2c; j++)
start_pod(pod_infos[j].n_children, code, 9);
*(uint64_t*)(((((i + (i >> 0x1f)) >> 1) + 0x100) << 3) + shared_mem_original)
= *(uint64_t*)(shared_mem + 0xb0);
shared_mem = &shared_mem[0x2c];
}
```
The output is recovered from `shared_memory[0x2c]` (`0xb0` is `0x2c * 4`) on 8 bytes, which are the output of the two last pods
So we have `0x2c` pods, each one outputting the inputs for the next
one.
Once all pods have run, notice we shift, the shared_mem by `0x2c`
thus right on the last pods output. Which will be used to xor
the next input for the run of `0x2b` pods.
This seems like a `cbc` mode of operation but I did not made any
link to block ciphers at that time.
I will split the problem by solving each block of 8 input bytes
independently.
So I have a reference `uint64_t`, I want to find the two
`uint32_t` which will give this output after passing in all
of my `0x2c` ASTs.
### Do the intstructions backward :clown:
I thought about simply taking the desired output and inverting
every operation since I have the complete AST. However I quickly
noticed it was not possible because of operations like `shl`, `shr`, `or` and `and`.
These operations plus the fact that our inputs are fetched from
multiple leafs of the AST make the whole thing close to
impossible to invert.
### z3 attempt
This is actually not the attempt I made first but I went back and
forth on many ideas so I will explain my failed ideas here so
it doesn't cut the flow of the rest of the writeup.
So at some point I tried to build a z3 solver by traversing the
AST.
It did not work out in the end because I found a promising
solution which was showing results in parallel.
Now I know that it didn't find anything because I built the
solver by traversing all the `0x2c` ASTs, which is too much
obviously.
Basically my mistake was that at the time, I didn't know that
the VM was a symetric cipher, thus I has no idea of the unicity
of the input. So I thought that I NEEDED, to add a constraint
on the first input `uint32_t` (which I knew was `FCSC`) to
find a single solution.
But now I know that the input of every AST is unique so
solving ASTs one by one is much easier.
### Lifting to C
My actual first idea was that I knew that the flag started with
`FCSC{`, which only let me 3 unknown bytes in the first block.
This would be fairly trivial to bruteforce if the VM did not need
3 minutes to compute a single block.
I could have implemented an interpreter on top of the AST, but
since I decided to go for the bruteforce solution, I went for it
all and transpiled it to C.
{{< code file="/static/megalosaure/src/disasm.py" language="python" >}}
Running it will give this output, and a file `megalosaure.c`
```console
$ ./disasm.py
[*] '/home/juju/ctf/fcsc_2024/reverse/megalosaure/megalosaure'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: PIE enabled
[+] Loading virtual machines
[+] Lifting AST
[+] Transpiling to C
[+] Transpiled to ./megalosaure.c
```
The `megalosaure.c` file is an implementation of a single run of
all the `0x2c` pods.
If you are interesed the disasm.py script also contains the code
of my z3 attempt.
## Bruteforcing until we win
### First block
The first block is trivial to bruteforce so I implemented a
simple bruteforce c program which links against a heavily optimised `megalosaure.c`.
{{< code file="/static/megalosaure/src/simple.c" language="c" >}}
With the following `Makefile` (which also has the final targets for the final
solver)
{{< code file="/static/megalosaure/src/Makefile" language="makefile" >}}
You can run `make simple` to build this simple bruteforcer for the first block.
```console
$ ./simple
FCSC{454
```
Great I have the first 8 bytes of the flag. Now what ?
This strategy will not work on other blocks, where all of the 8
bytes are unknown.
### Angr attempt
So since I had the source code, I thought that I could try angr
on this one, surprisingly enough, this did not give anything.
For the same reason as z3, doing all the pods at once is just
too much.
### Reducing the character set
Now things are becoming really nasty for my solver, I was
working in parallel on the z3 solver and as I ran it on my first
try, I thought
> Hey "FCSC{454" does not look like a funny string, maybe this flag is only a hexstring
So I started bruteforcing all the blocks but only on hex digits,
which comes back to 2^32 iterations per block, completly doable.
However just remember that before being inputted in the first
pod, the input is xored with the output of the previous block.
Since I have the reference array, I know the desired output of
all the blocks and can bruteforce them in parralel.
Watch out, the code is dirty.
{{< code file="/static/megalosaure/src/main.c" language="c" >}}
You can run `make` to compile the solver.
It takes about 20 minutes to run, and prints each block when it
finds one.
```console
$ time ./solver
Block 6: 06a5611b
Block 1: 2d32e27c
Block 4: 4016b156
Block 8: 420ac}
Block 7: c18edd32
Block 3: d3418e7a
Block 2: de2d7cf7
Block 5: e4df7f0c
real 21m18,662s
user 107m44,082s
sys 0m0,936s
```
I then reconstituted the flag manually by pasting each block
`FCSC{4542d32e27cde2d7cf7d3418e7a4016b156e4df7f0c06a5611bc18edd32420ac}`
After solving the challenge and discussing with its author,
I learned that the VM actually implemented a symetric block cipher (SIMON-64-128), with a null IV, and CBC mode of operation.
The key was embeded in the code, so it was actually a whitebox.
Looking back at everything, we can clearly see that one pod is
actually a round of encryption, a block is encrypted through
`0x2c` rounds, with each block input being xored with the output
of the previous block (0 for the first block), thus the CBC and
null IV.
@@ -0,0 +1,431 @@
---
title: "Lifting a reloc based VM | Svartalfheim @ FCSC 2024"
date: "2024-04-14 22:00:00"
author: "Juju"
tags: ["Reverse", "Writeup", "fcsc"]
toc: true
---
# Intro
Svartalfheim is a weird reversing challenge. It seems like a simple x64 ELF with
only a few bytes of machine code, but after playing with it, you might notice
some quantum behaviours. The program might be patching itself when you are
not looking at it, so stay alert :eyes:.
## Challenge description
`reverse` | `467 pts` `14 solves` :star::star::star:
```
Trouvez le flag accepté par le binaire.
```
Author: `Quanthor_ic`
## Given files
[svartalfheim](/svartalfheim/svartalfheim)
# Writeup
## Overview
Things are already weird without opening up any disassembler:
`file` tells us the the binary is dynamically linked but ldd says otherwise.
```console
$ file svartalfheim
svartalfheim: ELF 64-bit LSB executable, x86-64, version 1 (SYSV),
dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, no
section header
$ ldd svartalfheim
not a dynamic executable
```
Here is the decompiled code of the entrypoint.
{{< code file="/static/svartalfheim/main.c" language="c" >}}
Basically, it simply deletes a file named `_` from the current directory, then
re-create it and open it write mode.
The process then dumps itself into the opened file, close it and execve the
dumped file.
Cool so this should do absolutely nothing except calling itself endlessly.
But what if we give it a try:
```console
./svartalfheim
Welcome to Svartalfheim
FCSC{test}
Nope
```
WTF is going on ?
## Quantum binary
So first I wanted a way to see what was happening between each execution.
I patched the `execve` with a breakpoint in the binary.
It will now crash instead of starting itself again and I can inspect the
`_` file before the next instance deletes it.
Here is the diff of the hexdump of the patched binary (breakpoint instead
of execve) with the hexdump of the `_` file after a single execution:
```console
$ diff svartalfheim_breakpointed.hex first_run.hex
517c517
< 00002040: 0700 0000 0000 0000 e821 0400 0000 0000 .........!......
---
> 00002040: 0700 0000 0000 0000 3037 0400 0000 0000 ........07......
519c519
< 00002060: 0800 0000 0000 0000 3000 0000 0000 0000 ........0.......
---
> 00002060: 0800 0000 0000 0000 6000 0000 0000 0000 ........`.......
```
A total of 3 bytes have changed, so I go check the corresponding addresses
in my decompiler:
{{< image src="/svartalfheim/rela_patched.png" style="border-radius: 8px;" >}}
The first two bytes that are patched are the relocation table addr inside
the dynamic table.
The last byte patched is the size of said relocation table.
This means that at the next execution, the program will have different relocations.
Maybe we should take a look at the original relocation table:
{{< image src="/svartalfheim/original_relocs.png" style="border-radius: 8px;" >}}
Unusual relocations indeed. So the first one points to the relocation table
address inside the dynamic table and the second one to the relocation table
size, also in the dynamic table, the two values that were patched in the next
binary. We can already guess that the relocation table will be patched at
every execution, running new relocations every time, just like a processor
run instructions and increments its program counter. This might be a
relocation based virtual machine.
## Reloc based virtual machine
### Figuring out the instruction set
So since the relocation table have changed in the next binary, let's open this
one and check the new relocation table:
{{< image src="/svartalfheim/second_relocs.png" style="border-radius: 8px;" >}}
Once again we can see relocs pointing to DT_RELA and DT_RELASZ values, but there are also two other addresses that are patched.
When looking them up, we can see that these two addresses are located inside
the symbol table. To be precise, the values of symbol `1` and `2` are patched.
Below is the corresponding symbol table:
{{< image src="/svartalfheim/second_symtab.png" style="border-radius: 8px;" >}}
Great so now let's run the binary a second time and inspect the third relocation table.
I will stop on this one a bit longer because it actually contains the entire
instruction set.
But first, what is *really* happening ?
The relocation table holds ... relocations indeed.
Relocations are applied by `ldso` when a process is loaded into memory
(so at `execve`).
Applying a relocation has different effects depending on the relocation type
(denoted in the lower 32 bits of the `info` field of the reloc).
However, most relocation types imply dereferencing the `value` of a symbol (see the above screenshot for an example of the symbol table) and storing it in the relocation address.
The said symbol is denoted by the higher 32 bits of the `info` field of the reloc.
Now let's really look at the third relocation table and run it in our mind:
{{< image src="/svartalfheim/third_relocs.png" style="border-radius: 8px;" >}}
The first relocation is of type `0x8`, and has symbol `0x0` (which mean no symbol)
It points to the address of the `value` of symbol `0x5`.
Relocation type `0x8` will simply put its `addend` value at the address pointed by its `addr` field. Thus storing `0xff` in the `0x5` symbol `value`
Basically this relocation is a `mov mem, imm` instruction.
Second relocation is of type `0x1` and symbol `0x1`.
This relocation will take the `value` of symbol `0x1`, add the reloc
`addend` value, and store the result at the relocation `addr`
So it looks like some sorts of `add mem, reg, imm` instruction, considering
symbols as registers.
I'll do the third relocation and we will have the whole instruction set:
The type is `0x5`, symbol `0x1`. It will take the value of the corresponding symbol, dereference it, and store it in the reloc `addr`.
The assembly for this might look like `mov mem, [reg]`
Here we go, that's it, an instruction set of 3 instructions,
there isn't even an instruction to branch or to add two registers together.
Let's write an interpreter for the VM so we can debug it.
### Writing the interpreter
Basically the interpreter will have multiple roles in the analysis:
* Get an execution trace and disassembly of the virtual machine
* Set breakpoints during execution
* Dump process to inspect the patched ELF at any stage easily and fast
{{< code file="/static/svartalfheim/interpreter.py" language="py" >}}
This interpreter stops every time that the VM patches the native code section
of the binary, this way I can stop whenever IO is performed, dump the binary
and analyse it.
The VM patches the native code a total of 7 times:
* Setup a syscall to write the prompt on stdout
* Immediately after, reset the native code to its original content
* Setup a syscall to read the flag from stdin
* Immediately after, reset the native code to its original content
* Setup a syscall to write the flag validation
* Immediately after, reset the native code to its original content
* Setup a syscall to exit the program instead of the `execve` it again
Investigating the third dumped binary will show us the flag address given to `read`, which will allow us to inject it in our interpreter:
{{< image src="/svartalfheim/radare_read.png" style="border-radius: 8px;" >}}
The interpreter also builds a disassembled execution trace:
I tried to make it readable as if it was intel assembly.
I added some comments for easier analysis:
* NATIVE CODE LOADING means that this block (a complete run of a single relocation table) has patched the native code section
* The commented hexstring is the data that is being outputed in the destination operand
* PATCHING CODE means that this instruction has a destination address pointing to the next instruction, meaning it is trying to patch its own code
* PATCHING FAR is the same but on an instruction of the same block but not the next one
These were really helpful during analysis to have a reminder to check for code patching.
You might be saying that the example assembly below doesn't correspond to the
instruction set defined above as there was no such instruction as
`add reg, reg, imm`, it is indeed true, but the trick is that every register
are memory mapped (since they are simply symbols in the symtab of the ELF), so a memory deref can actually be a register and my disassembler lifts this.
```console
0x48080: mov [0x480f0], $0xffffffffffffffa0 # a0ffffffffffffff PATCHING FAR
0x48098: add [0x480b0], r4, $0x480d8 # f080040000000000 PATCHING CODE
0x480b0: mov [0x480f0], $0x0 # 0000000000000000 PATCHING FAR
0x480c8: add r1, r1, $0x0 # 1036040000000000
0x480e0: add r1, r1, $0x0 # 1036040000000000
0x480f8: add r1, r1, $0x10 # 2036040000000000
0x48110: mov DT_RELA, [r1].8 # 5881040000000000
0x48128: add r2, r1, $0x8 # 2836040000000000
0x48140: mov DT_RELASZ, [r2].8 # 7800000000000000
#End of block
0x48158: mov r7, $0x5 # 0500000000000000
0x48170: add r1, r1, $0x10 # 3036040000000000
0x48188: mov DT_RELA, [r1].8 # d081040000000000
0x481a0: add r2, r1, $0x8 # 3836040000000000
0x481b8: mov DT_RELASZ, [r2].8 # f000000000000000
#End of block
# NATIVE CODE LOADING:
0x481d0: mov [0x4100e], $0xba48 # 48ba000000000000
0x481e8: mov [0x41016], $0xbe480000 # 000048be00000000
0x48200: mov [0x4101e], $0x6a5f016a00000000 # 000000006a015f6a
0x48218: mov [0x41026], $0x90909090050f5801 # 01580f0590909090
0x48230: add [0x41010], r7, $0x0 # 0500000000000000
0x48248: add [0x4101a], r8, $0x0 # 23a2050000000000
0x48260: add r1, r1, $0x10 # 4036040000000000
0x48278: mov DT_RELA, [r1].8 # c082040000000000
0x48290: add r2, r1, $0x8 # 4836040000000000
0x482a8: mov DT_RELASZ, [r2].8 # c000000000000000
#End of block
```
### Side channel attempt
My first attempt at a solver was really simple, I thought that maybe the
VM would check bytes one by one.
So I added a method to inject the flag into my interpreter's memory and tried
to bruteforce the first char, watching for the length of the execution trace every time.
But all 256 possible bytes gave the same number of instructions
At this points I was thinking about lifting the code a little more to reduce
the trace size before reading it, but I was in the mood to read 65000+ lines of the same 3 instructions.
## Analysing the execution trace
Just kidding I did not actually read the whole execution trace.
I knew that the flag start with `FCSC{`, so I dumped 2 execution trace:
* One with the flag as `FCSC{test`
* The other one with `HCSC{test`
I put them side by side (`FCSC{` on the left, `HCSC{` on the right), jumped right after the `read` call, and started comparing them, and lifting the code on paper.
{{< image src="/svartalfheim/trace_read.png" style="border-radius: 8px;" >}}
I will not show you the whole execution trace to keep your eyes safe, but
the VM starts by a bunch of `mov reg, imm` instructions to initialize some
variables.
And then a fun pattern appears:
### `add mem, reg, reg`
{{< image src="/svartalfheim/add_reg_reg.png" style="border-radius: 8px;" >}}
These three instructions together can actually be lifted to `add r13.b, r6, r13`
It is crucial to understand this simple pattern before we continue to how
branching are handled in this VM.
Start by looking the first instruction: it takes the value of `r13`, add 0,
and store it at `0x45a50`. The first thing to notice is that `add mem, reg,
$0x0` is actually equivalent to a `mov mem, reg`, but there is no such
instruction in our instruction set (`mov mem, [reg]` will deref the reg) thus the add instruction trick.
Then if you look the destination address, it points to the the next instruction `addend`. Looking at the comment, we know that the output value is `0x0` on 8 bytes.
So now when we look at the second instruction, it is indeed `add r13, r6,
$0x0`, but said immediate `$0x0` was patched by previous instruction, with the
value of `r13`, even if the instruction add an immediate, in this context,
the immediate was patched with a register. Thus performing a `add mem, reg, reg`
The third instruction simply zeroes out the 7 higher bytes of the `r13`
register, my disassembler did not lift the addresses of the higher bytes of
regs but trust me on this one.
The comment on the second instruction shows us that the addition had a result of `0x1` (64 bits little endian) (`r6` had value 1), so these 3 instructions simply increment `r13`.
### Lookup tables
I skipped a few instructions, all you need to know is that `r3` points
to the first byte of the flag, and that `r12` was initialized with a byte
coming from an array indexed with the same counter as the flag.
{{< image src="/svartalfheim/lut_lookup.png" style="border-radius: 8px;" >}}
The first block simply loads the current flag byte in `r11` (`0x46` = `'F'`)
and the second one basically substitutes the byte from the flag based on a lookup table.
The LuT is indexed based on the flag byte and `r12`, which I assume is some
sort of nonce to add the information of the position of the byte in the
flag during the substitution.
Here is a c equivalent I lifted on paper:
```c
uint64_t r12 = nonce[i];
uint64_t r11 = flag[i];
uint64_t r3 = (r11 << 32) + r12;
uint64_t *LuT = 0x49000;
r11 = *(LuT + r3);
```
The next few blocks are not that important, they store the LuTed byte in memory, increment string iterators and decrement size counters
But then comes the one most important code pattern of this VM:
### Branching
{{< image src="/svartalfheim/for.png" style="border-radius: 8px;" >}}
These two blocks perform a branch
It essentially is a `test r7, r7; jne mem`
Here is how it works after lifting:
```c
// First block
jump_table = 0x59000;
r4 = jump_table[r7]; // r7 is remaining flag len
// Second block
r1 = r1 + 0x10 - 0xf0 + r4;
// DT_RELA = r1, r1 is the program counter
```
So `0x59000` contains a jump table indexed on the remaining flag size.
Here you can see at instruction `0x46628`, the jump offset is in the comment.
I noticed it changed when `r7` reached 0.
It is essentialy the first `for` loop iterating on the flag, applying lookup
tables on each byte.
### Flag checking
After that there is a really similar block of code, also performing lookups
of some sort I did not really bother to understand (as the ones of the
previous step) because I found a really interesting branch which was not a loop.
I notice a similar pattern than the for loop above, sligthly different but
still some kind of jump table.
What stroke me is that as you can see on the screenshot bellow, it was
the first time in the whole execution trace, that my purposely wrong flag, ran
to a different branch than the one starting with `FCSC{`
{{< image src="/svartalfheim/check.png" style="border-radius: 8px;" >}}
What I did not notice at first is that there are two different branchments in
the screenshot (with the jump offsets marked in red). I noticed it quickly and
backported it to my solver.
I do not actually know what is the meaning of these 2 checks regarding the
previous look up tables but all I know is that I needed to hit jump
offset `0x18` twice for a flag byte to be valid.
So I modified my interpreter to add a breakpoint at the addresses marked in red,
check the value moved in `r4` is `0x18`.
And then bruteforced byte by byte:
While bruteforcing the `n`th byte, I need to hit the breakpoint succesfully (with `0x18` in `r4`) `2*n` times. If the breakpoint check fails once then the byte is fucked up.
# Solver
Here is the complete solver code, with the interpreter, correct breakpoints and
bruteforcing
{{< code file="/static/svartalfheim/solve.py" language="python" >}}
```console
$ ./solve.py
bytearray(b'F\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(b'FC\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(b'FCS\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
...
bytearray(b'FCSC{162756828312aad562394d47c854134803a092d7f5b9eb795528f4a0f16f7c65}')
$ ./svartalfheim
Welcome to Svartalfheim
FCSC{162756828312aad562394d47c854134803a092d7f5b9eb795528f4a0f16f7c65}
Well done!
```
+237
View File
@@ -0,0 +1,237 @@
---
title: "Reversing quantum algorithms ~~for ctf points~~ | q-solved @ zer0pts 2022"
date: "2022-03-25 18:00:00"
author: "Juju"
tags: ["Reverse", "Quantum", "Writeup", "zer0pts"]
toc: true
---
# Intro
## Challenge description
`quantum` `reverse` | `304 pts` `8 solves`
```
I copied the solver of a reversing task from the future. But it doesn't
show the flag forever :thinking:
```
## Given files
[solve.py](/q-solved/solve.py)
{{< code file="/static/q-solved/solve.py" language="py" >}}
[circuit.json](/q-solved/circuit.json)
# Writeup
## TL;DR
The script builds a quantum circuit describing an unstructured search
algorithm inspired by the grover's algorithm. Its goal is to find among all
possible inputs, the one(s) with the highest probability to match a predefined
criteria.
It is composed of an `oracle` and a `diffuser`. The oracle is a black-box
function taking a state vector as input and introducing a phase shift in the
target qubit if the input matches the predefined criteria.
The diffuser then performs amplitude amplification using the target qubit's
phase kickback when the oracle matches, thus increasing the probability of a
matching input vector to be measured.
Basically, the output of the circuit is the input matching the criteria
described by the oracle.
All that remains to do for us is to understand what that criteria is.
## Reversing the Oracle
We can see that the oracle is built using the `circuit.json`.
```json
{
"memory": 560,
"ancilla": 1408,
"circuit": [
[
[
false,
0
]
],
[
[
true,
0
],
[
false,
8
],
[
false,
280
]
],
[
[
false,
0
],
[
true,
8
],
[
false,
280
]
],
[
[
true,
280
],
[
false,
0
],
[
false,
8
]
],
[
[
true,
0
],
[
true,
8
],
[
true,
280
]
],
...
```
The oracle is composed of 1408 multi-controlled X (MCX) gates, each controlled by 1
or 3 input qubits with a control state given in the json. Each MCX gate
acts on a dedicated ancilla qubit.
On the sample above, we can see that the `circuit` key of the json is an array
of 1408 elements. On all examples, we will work on the 5 first elements which
are enough to understand what is going on.
So each element of the `circuit` array corresponds to a MCX, those MCX are
themselves array of 1 or 3 elements representing the control qubits of the said
gate. Control qubits are represented with an integer and a boolean. The integer
is simply the index of the qubit, and the boolean is the opposite of the
control state of the qubit. For example `False`, means that the qubit will have
control state 1.
If we take the fist 2 MCX described in the json, it means that we will have the
first MCX on the first ancilla qubit controlled by the first input qubit with a
control state of 1. The second MCX will act on the second ancilla and will be
controlled by the 1st, 9th and 281st input qubits with control states 0, 1 and
1 respectively
Below is a simplified view of the circuit described by the 5 first gates above,
where the ancilla qubits are from `q3` to `q7` and where `q0`, `q1` and `q2`
correspond to the 1st, 9th and 281st input qubits of the real circuit
respectively.
{{< image src="/q-solved/ancillas.png" style="border-radius: 8px;" >}}
After all 1408 MCX, the circuit adds an other MCX on the target qubit
controlled by all ancillas with all control states set to 0. The target qubit
is therefore introduced a phase shift when all ancillas are in `|0>`.
Here, the target qubit is represented by `q8`, see how the `q8`'s gate is active
only if all ancillas are `|0>`:
{{< image src="/q-solved/oracle.png" style="border-radius: 8px;" >}}
So we want all ancillas to be `|0>` but it is also their original state. We
therfore have to influence the control qubits of each MCX so that none actually
performs the X gate on any ancilla. This means that among all control qubits of
a MCX, at least one must have a state different from its control state, thus
deactivating the gate.
Remember, inputs must be different from their control state specified on the
gate. Therefore a qubit marked as `False`, must take value `|0>` to deactivate
the gate since `False`, gives the qubit a control state of 1. Similarly, a qubit marked `True` must take value `|1>`.
So we said earlier that the MCX have either 3 or 1 control bits and that at
least 1 of the control qubits must mismatch from their control state.
## POC with trivial qubits
Obviously this results in an equation system but let's see what we get with
only the obvious qubits: the ones controlling an ancilla by themselves.
Indeed if an ancilla is controlled by a single input qubit then this qubit MUST
be different from his control state so the X gate stays disabled. Therefore, any input qubit marked as `False` and as the only control of a gate MUST be set to `|0>` to match the oracle. Same is true for qubits marked as `True` that must be in state `|1>`.
We can illustrate this with the circuit below: `q3` MUST be set to `|0>` so the
gate must be deactivated, so `q0` MUST be `|0>` (control state 1) to deactivate
the gate.
{{< image src="/q-solved/oracle.png" style="border-radius: 8px;" >}}
So let's try to set all obvious qubits:
{{< code file="/static/q-solved/poc_flag.py" language="py" >}}
{{< image src="/q-solved/poc_flag.png" style="border-radius: 8px;" >}}
Well, most of them are 0, except, the first byte: `z`
Which is a good sign that we are indeed decoding a flag of the form
`zer0pts{...}`
## Equation system
For MCX with 3 control qubits, we simply need to put them in an equation
system alongside the trivial qubits.
We will have a total of 1408 equations, 1 for each MCX, each equation basically
saying that at least 1 qubit must be different from its control state, and
therefore equal to its assigned boolean in the json.
Let's take the same circuit again, we will have the following system:
```
q0 == 0
q0 == 1 OR q1 == 0 OR q2 == 0
q0 == 0 OR q1 == 1 OR q2 == 0
q0 == 0 OR q1 == 0 OR q2 == 1
q0 == 1 OR q1 == 1 OR q2 == 1
```
{{< image src="/q-solved/oracle.png" style="border-radius: 8px;" >}}
```
note: The above system does not have a unique solution, but adding the rest of
the circuit will make the solution unique.
```
Once the system is solved, we will know the state of all qubits that match the
oracle, which is the one outputed by the quantum circuit. We will then be able
to decode it to get the flag.
## Solve
I used z3 to build and solve the equation system:
{{< code file="/static/q-solved/flag.py" language="py" >}}
Running the script outputs us the equation system, `sat` indicating that z3 found
a solution to the system and the decoded solution of the system with the flag:
`zer0pts{FLAG_by_Gr0v3r's_4lg0r1thm}`
{{< image src="/q-solved/flag.png" style="border-radius: 8px;" >}}
+3
View File
@@ -0,0 +1,3 @@
{{ $file := .Get "file" | readFile }}
{{ $lang := .Get "language" }}
{{ (print "```" $lang "\n" $file "\n```") | markdownify }}
@@ -0,0 +1,3 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */::-webkit-scrollbar{width:8px;height:8px;background:#212020}::-webkit-scrollbar-thumb{background:#888}::-webkit-scrollbar-thumb:hover{background:#dcdcdc}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:0.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace, monospace;font-display:auto;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace, monospace;font-display:auto;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-display:auto;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type="button"],[type="reset"],[type="submit"]{-webkit-appearance:button}button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:0.35em 0.75em 0.625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type="checkbox"],[type="radio"]{box-sizing:border-box;padding:0}[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button{height:auto}[type="search"]{-webkit-appearance:textfield;outline-offset:-2px}[type="search"]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}code[class*="language-"],pre[class*="language-"]{color:white;background:none;font-family:Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size:1em;text-align:left;text-shadow:0 -.1em .2em black;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre[class*="language-"],:not(pre)>code[class*="language-"]{background:#141414}pre[class*="language-"]{border-radius:.5em;border:0.3em solid #545454;box-shadow:1px 1px .5em black inset;margin:.5em 0;overflow:auto;padding:1em}pre[class*="language-"]::-moz-selection{background:#27292a}pre[class*="language-"]::selection{background:#27292a}pre[class*="language-"]::-moz-selection,pre[class*="language-"] ::-moz-selection,code[class*="language-"]::-moz-selection,code[class*="language-"] ::-moz-selection{text-shadow:none;background:rgba(237,237,237,0.15)}pre[class*="language-"]::selection,pre[class*="language-"] ::selection,code[class*="language-"]::selection,code[class*="language-"] ::selection{text-shadow:none;background:rgba(237,237,237,0.15)}:not(pre)>code[class*="language-"]{border-radius:.3em;border:0.13em solid #545454;box-shadow:1px 1px .3em -.1em black inset;padding:.15em .2em .05em;white-space:normal}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:#787878}.token.punctuation{opacity:.7}.token.namespace{opacity:.7}.token.tag,.token.boolean,.token.number,.token.deleted{color:#cf694a}.token.keyword,.token.property,.token.selector,.token.constant,.token.symbol,.token.builtin{color:#f9ee9a}.token.attr-name,.token.attr-value,.token.string,.token.char,.token.operator,.token.entity,.token.url,.language-css .token.string,.style .token.string,.token.variable,.token.inserted{color:#919e6b}.token.atrule{color:#7386a5}.token.regex,.token.important{color:#e9c163}.token.important,.token.bold{font-weight:bold}.token.italic{font-style:italic}.token.entity{cursor:help}pre[data-line]{padding:1em 0 1em 3em;position:relative}.language-markup .token.tag,.language-markup .token.attr-name,.language-markup .token.punctuation{color:#ad895c}.token{position:relative;z-index:1}.line-highlight{background:rgba(84,84,84,0.25);background:linear-gradient(to right, rgba(84,84,84,0.1) 70%, rgba(84,84,84,0));border-bottom:1px dashed #545454;border-top:1px dashed #545454;left:0;line-height:inherit;margin-top:0.75em;padding:inherit 0;pointer-events:none;position:absolute;right:0;white-space:pre;z-index:0}.line-highlight:before,.line-highlight[data-end]:after{background-color:#8794a6;border-radius:999px;box-shadow:0 1px white;color:#f5f2f0;content:attr(data-start);font:bold 65%/1.5 sans-serif;left:.6em;min-width:1em;padding:0 .5em;position:absolute;text-align:center;text-shadow:none;top:.4em;vertical-align:.3em}.line-highlight[data-end]:after{bottom:.4em;content:attr(data-end);top:auto}pre[data-line]{position:rLine truncated
/*# sourceMappingURL=main.css.map */
@@ -0,0 +1 @@
{"Target":"main.b78c3be9451dc4ca61ca377f3dc2cf2e6345a44c2bae46216a322ef366daa399.css","MediaType":"text/css","Data":{"Integrity":"sha256-t4w76UUdxMphyjd/PcLPLmNFpEwrrkYhajIu82bao5k="}}
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
import sys
import os
with open('./disk.img', 'rb') as f:
data = f.read()
blocks = [data[i * 0x1000:(i * 0x1000) + 0x1000] for i in range(len(data) // 0x1000)]
clear = bytearray()
for block in blocks:
x = 0
for b in block:
c = x ^ b
clear.append(c)
x = c
os.write(1, clear)
Binary file not shown.
@@ -0,0 +1,9 @@
int64_t encrypt_block(char* block, int64_t len)
{
int64_t i;
for (i = 0; i < len; i = (i + 1))
{
block[((len - i) - 1)] = (block[((len - i) - 1)] ^ block[((len - i) - 2)]);
}
return i;
}
+72
View File
@@ -0,0 +1,72 @@
int64_t encrypt_file(char* name)
{
return encrypt_file2(name);
}
int64_t encrypt_file2(char* name)
{
int32_t inode = 0;
int32_t len_read = 0;
uint64_t blocksize = ((uint64_t)fs->blocksize);
void* block = xcalloc(1, blocksize); // Allocate data for encrypted block
int64_t fd = get_size(name); // Get the file size
if (fd != 0)
{
fd = open(name, 2); // Open the file
int32_t fd = fd;
if (fd != 0xffffffff)
{
if (inode == 0)
// Create an inode for the encrypted file
ext2fs_new_inode(fs, 0, 0x41ed, 0, &inode);
ext2fs_inode_alloc_stats2(fs, ((uint64_t)inode), 1, 1);
char stop = 0;
int64_t nb_blocks = 1;
uint64_t* blocks = xcalloc(1, 0x10);
do
{
// Fill the block with file data
if (fill_block(fd, block, blocksize, &len_read) == 0)
break;
// Determine if another block is needed to encrypt the file
int32_t n_blocks = len_read / 0x1000;
if (len_read % 0x1000 != 0)
stop = 1;
// Encrypt the block
encrypt_block(block, ((int64_t)len_read));
// Write encrypted block to the filesystem
int64_t new_block = write_block(block, ((uint64_t)fs->blocksize), inode);
// Some stuff I did not bother to understand
// probably setting up recursive blocks for big files
// or preparing new empty blocks for the file that must be
// emptied
// but I do not know nor does it really matter for now
if (blocks[((nb_blocks - 1) * 2)] == 0)
{
blocks[((nb_blocks - 1) * 2)] = new_block;
blocks[(((nb_blocks - 1) * 2) + 1)] = new_block;
}
else if ((blocks[(((nb_blocks - 1) * 2) + 1)] + 1) != new_block)
{
nb_blocks = (nb_blocks + 1);
realloc(blocks, (nb_blocks << 4));
blocks[((nb_blocks - 1) * 2)] = new_block;
blocks[(((nb_blocks - 1) * 2) + 1)] = new_block;
}
else
blocks[(((nb_blocks - 1) * 2) + 1)] = new_block;
memset(block, 0, ((uint64_t)fs->blocksize));
} while ((stop & 1) == 0);
// Remove data from the original file
fd = delete_data(name, nb_blocks, blocks);
}
}
return fd;
}
@@ -0,0 +1,28 @@
DIR* encrypt_folder(char* path, void* callback)
{
DIR* dir = opendir(path);
if (dir != 0)
{
while (true)
{
struct dirent64* dirent = readdir(dir);
if (dirent == 0)
{
break;
}
if (((uint32_t)dirent->d_type) != 4)
{
callback(&dirent->d_name);
}
else if ((strcmp(&dirent->d_name, ".") != 0 && strcmp(&dirent->d_name, "..") != 0))
{
chdir(&dirent->d_name);
encrypt_folder(".", callback);
}
}
chdir("..");
dir = closedir(dir);
}
return dir;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 90 MiB

+41
View File
@@ -0,0 +1,41 @@
int32_t main(int32_t argc, char** argv, char** envp)
{
int32_t res;
if (argc != 2)
{
printf("Usage %s <device> \n", *(int64_t*)argv);
res = 1;
}
else if (check_fs_opened() != 0)
{
res = 1;
}
else
{
open_and_read(argv[1]);
if (fs == 0)
{
perror("Could not get handle on FS");
exit(1);
/* no return */
}
if (check_flag_clear() != 0)
{
res = 1;
}
else
{
if (fs->blocksize != 0x1000)
{
perror("FS blocksize is invalid");
exit(1);
/* no return */
}
encrypt_folder(".", encrypt_file);
ext2fs_flush(fs);
write_inode_bitmap();
res = 0;
}
}
return res;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 191 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
uint64_t check_serial(void* user_digest, int64_t serial, int32_t size)
{
void* buff = NULL;
int64_t res;
if (user_digest == NULL || serial == NULL)
return 0;
something_interesting(user_digest, user_digest, &buff, size);
res = memcmp(serial, buff, size * size) == 0;
free(buff);
return res;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+49
View File
@@ -0,0 +1,49 @@
uint64_t dot_product(char* A, char* B, char** out, int32_t size)
{
if (A == NULL || B == NULL)
{
return 0;
}
int32_t res = 1;
int64_t i = 0;
int32_t j = 0;
*out = calloc(size * size, 1);
while (size > j)
{
int64_t k = 0;
char* A_line = A + i;
do
{
char* B_col = B + k;
int64_t col = 0;
int32_t sum = 0;
do
{
char element;
element = A_line[col];
element *= B_col[0];
col += 1;
B_col += size;
sum += element;
} while (size > col);
((*out) + i)[k] = sum; // ith line, kth column
bool win;
if (j != k) // Check if on the diagonal
win = sum == 0; // if not check that it is 0
else
win = sum == 1; // if yes check it is 1
k += 1;
res &= win; // Bitwise and, every number must be correct
} while (size > k);
j += 1;
i += size;
}
return res;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+71
View File
@@ -0,0 +1,71 @@
int32_t main(int32_t argc, char** argv, char** envp) __noreturn
{
int32_t user_status;
int32_t serial_status;
int32_t status;
if (argc == 4)
{
int32_t user_width = 0;
int32_t user_height = 0;
void* username_img_data = NULL;
void* user_zbar_img = NULL;
int32_t serial_width = 0;
int32_t serial_height = 0;
void* serial_img_data = NULL;
void* serial_zbar_img = NULL;
char digest[0x40];
strcpy(&digest, argv[1]);
void sha512;
SHA512_Init(&sha512);
SHA512_Update(&sha512, &digest, strlen(argv[1]));
SHA512_Final(&digest, &sha512);
char qr_data_user[0x40];
user_status = get_qr_data(argv[2],
&username_img_data,
&user_width,
&user_height,
&user_zbar_img,
&qr_data_user,
0x40);
char qr_data_serial[0x40];
serial_status = get_qr_data(argv[3],
&serial_img_data,
&serial_width,
&serial_height,
&serial_zbar_img,
&qr_data_serial,
0x40);
if ((user_status != 0 && serial_status != 0))
{
char err = (serial_width != user_width)
| (serial_height != user_height)
| (user_width != user_height)
| (memcmp(&digest, &qr_data_user, 0x40) != 0)
| (check_serial(&qr_data_user, &qr_data_serial, 8) == 0);
void* an_interesting_output = NULL;
int32_t win = something_interesting(username_img_data, serial_img_data, &an_interesting_output, user_width);
free(username_img_data);
free(serial_img_data);
free(an_interesting_output);
status = err | (win == 0);
}
}
else
{
printf("Usage: %s <username> <username.p…", *argv);
}
if (argc != 4 || user_status == 0 || serial_status == 0)
{
status = 1;
}
exit(status);
/* no return */
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 438 B

+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
import hashlib
import qrcode
from PIL import Image
import numpy as np
import requests
def get_user():
r = requests.get("https://brachiosaure.france-cybersecurity-challenge.fr/")
name = r.text.split("text-warning\">")[1].split('<')[0]
return name
def get_digest(name):
m = hashlib.sha512()
m.update(name.encode())
digest = m.digest()
return digest
def linearize_serial(matrix_serial):
serial = bytearray()
for line in matrix_serial:
for b in line:
serial.append(b % 256)
return bytes(serial)
def img_to_matrix(img):
array = list(img.getdata())
width, height = img.size
matrix_img = [[array[i * width + j] for j in range(width)] for i in range(height)]
return matrix_img
def matrix_to_img(mat, path):
array = np.uint8(mat)
img = Image.fromarray(array)
img.save(path)
def gen_qrcode(data, path):
qr = qrcode.QRCode(version = 1, box_size = 2, border = 2)
qr.add_data(data)
qr.make()
qr_usr = qr.make_image()
qr_usr.save(path)
def identitymatrix(n):
return [[int(x == y) for x in range(0, n)] for y in range(0, n)]
def get_flag(name):
files = {
"upload1": open(f"{name}_usr.png", "rb"),
"upload2": open(f"{name}_serial.png", "rb")
}
r = requests.post("https://brachiosaure.france-cybersecurity-challenge.fr/login", files=files)
for line in r.text.split('\n'):
if "FCSC{" in line:
print(line)
name = get_user()
digest = get_digest(name)
matrix_usr = [[digest[i * 8 + j] for j in range(8)] for i in range(8)]
matrix_usr = np.array(matrix_usr)
matrix_serial = np.dot(matrix_usr, matrix_usr)
serial = linearize_serial(matrix_serial)
gen_qrcode(digest, "user.png")
gen_qrcode(serial, "serial.png")
img_usr = Image.open("./user.png", "r")
img_serial = Image.open("./serial.png", "r")
matrix_img_usr = img_to_matrix(img_usr)
matrix_img_serial = img_to_matrix(img_serial)
def invert(usr, serial):
# Add empty and identity matrices to make it invetible
usr = make_invertible(usr)
serial = make_invertible(serial)
n = len(usr)
# Total size after redimensionning
new_n = n * 2
# The magic inversion by swapping corners and computing matrix opposite
usr_inv = invert_magic(usr)
serial_inv = invert_magic(serial)
# Will hold the final user png
new_usr = []
# Will hold the final serial png
new_serial = []
# Create the new_usr
for i in range(new_n):
line = [0] * new_n
if i < n:
for j in range(n):
line[j] = usr[i][j]
if i >= n:
for j in range(n):
line[j + n] = int(serial_inv[i - n][j])
new_usr.append(line)
# Create the new_serial
for i in range(new_n):
line = [0] * new_n
if i < n:
for j in range(n):
line[j] = int(usr_inv[i][j])
if i >= n:
for j in range(n):
line[j + n] = serial[i - n][j]
new_serial.append(line)
return new_usr, new_serial
def make_invertible(mat):
res = []
n = len(mat)
ident = identitymatrix(n)
# Add the identity matrix below the original
for line in ident:
mat.append(line)
for i in range(len(mat)):
line = mat[i]
for j in range(n):
# Add the identity matrix at the right of the original
if i < n:
line.append(ident[i][j])
# Add the empty matrix at the bottom right corner
else:
line.append(0)
return mat
def invert_magic(mat):
n_tot = len(mat)
n = n_tot // 2
#Create a new empty matrix to hold the result
res = [[0 for _ in range(n)] for _ in range(n)]
ident = identitymatrix(n)
# Add the identity matrix below
for line in ident:
res.append(line)
for i in range(len(mat)):
line = res[i]
for j in range(n):
# Identity matrix on the right
if i < n:
line.append(ident[i][j])
# Oposite of the original in the bottom right corner
else:
el = -mat[i - n][j] % 256
line.append(el)
return res
res_usr, res_serial = invert(matrix_img_usr, matrix_img_serial)
matrix_to_img(res_usr, f"{name}_usr.png")
matrix_to_img(res_serial, f"{name}_serial.png")
get_flag(name)
Binary file not shown.

After

Width:  |  Height:  |  Size: 451 B

+35
View File
@@ -0,0 +1,35 @@
case 0:
{
int32_t count = 0;
for (int i = 0; i <= 0xb; ++i) // Refactorized SIMD instruction as loop
count += pop_count(context.visited[i]);
int32_t err = count != 0x90;
err = err | context.err;
context.err = err; // Set error
int128_t third_board_1 = context.third_board; // Trying to clean up SIMD
int128_t third_board_2 = *(((uint128_t *)&context.third_board) + 1);
int128_t third_board_3 = *(((uint128_t *)&context.third_board) + 2);
int128_t zmm0 = ((third_board_1 & third_board_2) & third_board_3);
zmm0 = (zmm0 & _mm_bsrli_si128(zmm0, 8)); // More SIMD magic
zmm0 = (zmm0 & _mm_bsrli_si128(zmm0, 4));
int32_t all_set = (zmm0 & 0xfff) != 0xfff;// Check that context.third_board
err = all_set | err; // is all set to 1
context.err = err;
uint32_t flag = 1; // Set error flag
if (context.bit_queue == 0) // Check that we emptied the bit queue
{
int32_t x = 0;
for (int i = 0; i <= 0xb; ++i) // SIMD refactor
x ^= context.board[i];
flag = x;
}
res = ((uint64_t)(err | flag));
break;
break;
}
+5
View File
@@ -0,0 +1,5 @@
case 1:
{
context.__offset0xa0_d = ((context.__offset0xa0_d + 1) & 3);
break;
}
+39
View File
@@ -0,0 +1,39 @@
case 2:
{
enum moves move = context.move; //__offset0xa0
int32_t j = context.j;
int32_t i = context.i;
if (move == 0)
{
j = (j + 1);
}
else if (move == 1)
{
i = (i - 1);
}
else if (move == 2)
{
j = (j - 1);
}
else
{
op = op == 3;
i = (i + ((uint32_t)op));
}
int32_t row;
if ((j <= 0xb && i <= 0xb))
{
row = context.visited[i];
}
if (((j > 0xb || (j <= 0xb && i > 0xb)) || ((j <= 0xb && i <= 0xb) && (TEST_BITD(row, j)))))
{
context.err = (context.err | 1);
}
if (((j <= 0xb && i <= 0xb) && (!(TEST_BITD(row, j)))))
{
context.i = i;
context.j = j;
context.visited[i] = (row | ((int32_t)(1 << j))); // set bit
}
break;
}
+16
View File
@@ -0,0 +1,16 @@
case 3:
{
int32_t bits_queue = context.bits_queue;
int64_t i = ((int64_t)context.i);
int32_t bits_cleared;
bits_cleared = bits_queue == 0;
int32_t new_flags = (bits_cleared | context.err);
uint64_t row = ((uint64_t)(((bits_queue & 1) << ((int8_t)context.j)) | context.board[i])); // set bit
context.bits_queue = (bits_queue >> 1); // pop bit queue
context.board[i] = row; // save new board with new bit
int32_t count;
count = pop_count(row);
count = count > 2;
context.err = (new_flags | ((uint32_t)count));
break;
}
+16
View File
@@ -0,0 +1,16 @@
case 3:
{
int32_t bits_queue = context.bits_queue; //offset0x8_q
int64_t i = ((int64_t)context.i);
int32_t bits_cleared;
bits_cleared = bits_queue == 0;
int32_t new_flags = (bits_cleared | context.err);
uint64_t row = ((uint64_t)(((bits_queue & 1) << ((int8_t)context.j)) | context.board[i])); // set bit
context.bits_queue = (bits_queue >> 1); // pop bit queue
context.board[i] = row; // save new board with new bit
int32_t sub_res;
sub_res = sub_1c60(row);
sub_res = sub_res > 2;
context.err = (new_flags | ((uint32_t)sub_res));
break;
}
+15
View File
@@ -0,0 +1,15 @@
case 4:
{
int32_t j = ((int32_t)cursor[1]);
int64_t i = ((int64_t)cursor[2]);
int32_t bits_set;
bits_set = context.bits_queue != 0;
context.err = (context.err | bits_set);
next = &cursor[3];
int32_t bit = sub_1570(j, i, context);
context.third_board[i] = (context.third_board[i] | (bit << j));
break;
}
+15
View File
@@ -0,0 +1,15 @@
case 4:
{
int32_t j = ((int32_t)cursor[1]);
int64_t i = ((int64_t)cursor[2]);
int32_t bits_set;
bits_set = context.bits_queue != 0;
context.err = (context.err | bits_set);
next = &cursor[3];
int32_t bit = sub_1570(j, i, context);
context.third_board[i] = (context.third_board[i] | (bit << j));
break;
}
+189
View File
@@ -0,0 +1,189 @@
uint64_t check(char* input, int64_t len)
{
int64_t i = 0x14;
char* cursor = input;
void* end = &cursor[len];
void* fsbase;
int64_t rax = *(int64_t*)((char*)fsbase + 0x28);
struct context context;
int64_t* context_ptr = &context;
for (; i != 0; i = (i - 1))
{
*(int64_t*)context_ptr = 0;
context_ptr = &context_ptr[1];
}
// bits = 0x00ffffff
// visited[0] = 1
context.bits_queue = 0x100ffffff;
*(int32_t*)context_ptr = 0;
uint64_t res;
if (cursor < end)
{
while (true)
{
char* next = &cursor[1];
if (*(int8_t*)cursor > 4)
{
res = ((uint64_t)(context.err | 1));
break;
}
int32_t i;
uint128_t zmm0;
int128_t arr3_5-9;
int128_t arr3_1-4;
switch (*(int8_t*)cursor)
{
case 0:
{
int128_t arr1_1-5 = context.visited[1];
arr3_1-4 = context.check_board[1];
int128_t arr1_5-9 = context.visited[5];
int128_t arr1_9-13 = context.visited[9];
arr3_5-9 = context.check_board[5];
int128_t arr2_1-5 = context.board[1];
int32_t r12 = context.visited[5];
int32_t rbp_1 = context.visited[9];
int128_t arr2_5-9 = context.board[5];
int128_t arr2_9-13 = context.board[9];
int32_t var_38_1 = context.move;
int32_t err1 = (pop_count(((uint64_t)*(int32_t*)((char*)context.j)[0xc])) + pop_count(((uint64_t)context.visited[1])));
int32_t err2 = ((err1 + pop_count(((uint64_t)*(int32_t*)((char*)arr1_1-5)[4]))) + pop_count(((uint64_t)*(int32_t*)((char*)arr1_1-5)[8])));
int32_t err3 = ((err2 + pop_count(((uint64_t)*(int32_t*)((char*)arr1_1-5)[0xc]))) + pop_count(((uint64_t)r12)));
int32_t err4 = ((err3 + pop_count(((uint64_t)*(int32_t*)((char*)arr1_5-9)[4]))) + pop_count(((uint64_t)*(int32_t*)((char*)arr1_5-9)[8])));
int32_t err5 = ((err4 + pop_count(((uint64_t)*(int32_t*)((char*)arr1_5-9)[0xc]))) + pop_count(((uint64_t)rbp_1)));
int32_t bits = context.bits_queue;
int32_t err6;
err6 = ((err5 + pop_count(((uint64_t)*(int32_t*)((char*)arr1_9-13)[4]))) + pop_count(((uint64_t)*(int32_t*)((char*)arr1_9-13)[8]))) != 0x90;
int32_t err = (err6 | context.err);
context.err = err;
int128_t var_48_1 = context.check_board[9];
zmm0 = ((arr2_9-13 & arr3_1-4) & arr3_5-9);
zmm0 = (zmm0 & _mm_bsrli_si128(zmm0, 8));
zmm0 = (zmm0 & _mm_bsrli_si128(zmm0, 4));
int32_t rax_23;
rax_23 = (zmm0 & 0xfff) != 0xfff;
int32_t err = (((uint32_t)rax_23) | err);
uint32_t flag = 1;
context.err = err;
if (bits == 0)
{
int128_t var_48_2 = context.check_board[9];
int32_t flag;
flag = *(int32_t*)((char*)arr2_9-13)[8] != ((((((((((*(int32_t*)((char*)arr1_9-13)[0xc] ^ arr2_1-5) ^ *(int32_t*)((char*)arr2_1-5)[4]) ^ *(int32_t*)((char*)arr2_1-5)[8]) ^ *(int32_t*)((char*)arr2_1-5)[0xc]) ^ arr2_5-9) ^ *(int32_t*)((char*)arr2_5-9)[4]) ^ *(int32_t*)((char*)arr2_5-9)[8]) ^ *(int32_t*)((char*)arr2_5-9)[0xc]) ^ arr2_9-13) ^ *(int32_t*)((char*)arr2_9-13)[4]);
flag = ((uint32_t)flag);
}
res = ((uint64_t)(err | flag));
break;
break;
}
case 1: // cycle through instructions
{
cursor = next;
context.move = ((context.move + 1) & 3);
break;
}
// change coordinates and set nth bit of ith element of arr
// error if bit is already set
case 2:
{
enum moves op = context.move;
int32_t j = context.j;
i = context.i;
if (op == 0)
{
j = (j + 1);
}
else if (op == 1)
{
i = (i - 1);
}
else if (op == 2)
{
j = (j - 1);
}
else
{
op = op == 3;
i = (i + ((uint32_t)op));
}
int32_t row; // get element
int64_t i_cpy;
if ((j <= 0xb && i <= 0xb))
{
i_cpy = ((int64_t)i);
row = context.visited[i_cpy];
}
if (((j > 0xb || (j <= 0xb && i > 0xb)) || ((j <= 0xb && i <= 0xb) && (TEST_BITD(row, j)))))
{
context.err = (context.err | 1);
cursor = next;
}
if (((j <= 0xb && i <= 0xb) && (!(TEST_BITD(row, j)))))
{
cursor = next;
context.j = _mm_unpacklo_epi32(j, i); // store new indexes
context.visited[i_cpy] = (row | ((int32_t)(1 << j))); // set bit
}
break;
}
// set the nth bit of the ith element of arr2 if lsb of bits is set
// error if bits is cleared or if bitwise_check(new_element) > 2
case 3:
{
int32_t bits_queue = context.bits_queue;
int64_t i = ((int64_t)context.i);
int32_t bits_cleared;
bits_cleared = bits_queue == 0;
int32_t new_flags = (bits_cleared | context.err);
uint64_t row = ((uint64_t)(((bits_queue & 1) << ((int8_t)context.j)) | context.board[i])); // set bit
context.bits_queue = (bits_queue >> 1); // rshift bits
context.board[i] = row; // save new element of arr2
int32_t sub_res;
sub_res = pop_count(row);
sub_res = sub_res > 2;
context.err = (new_flags | ((uint32_t)sub_res));
cursor = next;
break;
}
case 4:
{
int32_t j = ((int32_t)cursor[1]);
int64_t i = ((int64_t)cursor[2]);
int32_t bits_set;
bits_set = context.bits_queue != 0;
context.err = (context.err | bits_set);
cursor = &cursor[3];
int32_t var_198_1 = context.move;
int32_t rax_26;
uint128_t zmm1;
int128_t zmm3;
int128_t zmm4;
int128_t zmm5;
int128_t zmm6;
rax_26 = sub_1570(j, i, context.j, context.visited[1], context.visited[5], context.visited[9], context.board[1], context.board[5], context.board[9], context.check_board[1], context.check_board[5], context.check_board[9], i);
context.check_board[i] = (context.check_board[i] | (rax_26 << j));
break;
}
}
if ((((*(int8_t*)cursor == 3 || *(int8_t*)cursor == 1) || *(int8_t*)cursor == 4) || *(int8_t*)cursor == 2))
{
if (cursor >= end)
{
break;
}
}
}
}
if ((cursor >= end || (cursor < end && *(int8_t*)cursor <= 4)))
{
res = 1;
}
*(int64_t*)((char*)fsbase + 0x28);
if (rax != *(int64_t*)((char*)fsbase + 0x28))
{
__stack_chk_fail();
/* no return */
}
return res;
}
+87
View File
@@ -0,0 +1,87 @@
uint64_t sub_1570(int32_t j, int32_t i, struct context context)
{
int32_t res = 0;
int32_t *board = context.board;
int32_t res_flag = 0;
if ((j <= 0xb && i <= 0xb))
{
int32_t r12_1 = (i + 0x79); // ignore this
int32_t y = -0xb; // First increment
int32_t rbp_1 = (j + 0xb); // ignore this too
while (true)
{
int32_t y_cpy = (y + 1);
if (y != 0)
{
int32_t r8 = r12_1; // ignore for now
int32_t x = -0xb; // Second increment
int32_t neg = (y >> 0x1f); // Probably interesting
int32_t r11_2 = ((y_cpy * -0xb) + rbp_1); // but I can't seem
int32_t y_cpy_cpy = ((neg ^ y) - neg); // to care enough
while (true)
{
if (x != 0)
{
int32_t neg = (x >> 0x1f); // Abs value again or
int32_t x_cpy = ((neg ^ x) - neg); // something
int32_t y_cpy_cpy_cpy = y_cpy_cpy;
int32_t count;
while (true) // Euclidean algorithm
{
int32_t y_cpy_cpy;
int32_t _;
_ = HIGHW(((int64_t)y_cpy_cpy_cpy));
y_cpy_cpy = LOWW(((int64_t)y_cpy_cpy_cpy));
int32_t mod = (COMBINE(y_cpy_cpy, y_cpy_cpy) % x_cpy);
y_cpy_cpy_cpy = x_cpy;
count = mod;
if (mod == 0)
{
break;
}
x_cpy = mod;
}
if (x_cpy == 1) // Check if increments are coprime
{
int32_t row = r8; // Stuff we ignored but seems to
int32_t column = r11_2; // be the starting point
int32_t m = 0x17;
int32_t m_cpy;
do // Run through the board using coprime increments
{
// Check if we are inside the board
if ((column <= 0xb && row <= 0xb))
{
// Count the bits
count += (board[row] >> column) & 1;
}
column = (column + y);
row = (row + x);
m_cpy = m;
m = (m - 1);
} while (m_cpy != 1);
// STOP THE COUNT
int32_t too_much = count > 2;
res_flag = (res_flag | too_much);
}
if (x == 0xb) // End the while true loops and iterate
{
break;
}
}
x = (x + 1); // Update increment
r8 = (r8 - 0xb);
}
if (y_cpy == 0xc)
{
break;
}
}
y = y_cpy; // Update increment with the next one
}
res = res_flag == 0;
}
return ((uint64_t)res);
}
+18
View File
@@ -0,0 +1,18 @@
uint64_t check(char* input, int64_t len)
{
char* cursor = input;
void* end = &cursor[len];
void* fsbase;
struct context context;
int64_t* context_ptr = &context;
for (int64_t i = 0x14; i != 0; i = (i - 1))
{
*(int64_t*)context_ptr = 0;
context_ptr = &context_ptr[1];
}
context.__offset0x8_q = 0x100ffffff;
*(int32_t*)context_ptr = 0;
...
}
+51
View File
@@ -0,0 +1,51 @@
uint64_t check(char* input, int64_t len)
{
...
uint64_t res;
while (cursor < end)
{
char* next = &cursor[1];
if (*(int8_t*)cursor > 4)
{
res = ((uint64_t)(context.err | 1));
break;
}
switch (*(int8_t*)cursor)
{
case 0:
{
...
break;
break;
}
case 1:
{
...
break;
}
case 2:
{
...
break;
}
case 3:
{
...
break;
}
case 4:
{
...
break;
}
}
cursor = next;
}
if ((cursor >= end || (cursor < end && *(int8_t*)cursor <= 4)))
{
res = 1;
}
return res;
}
Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
int32_t main(int32_t argc, char** argv, char** envp)
{
char input[0x400];
ssize_t len = read(0, &input, 0x400);
if (len <= 0)
{
puts("Error.");
exit(1);
/* no return */
}
int32_t res = check(&input, len);
if (res == 0)
{
FILE* file = fopen("flag.txt", &r);
if (file == 0)
{
puts("Well done! You can submit your i…");
exit(1);
/* no return */
}
char flag[0x46];
if (fread(&flag, 1, 0x46, file) != 0)
{
__printf_chk(1, "Well done, the flag is %s\n", &flag);
}
fclose(file);
}
return res;
}
+8
View File
@@ -0,0 +1,8 @@
enum moves : uint32_t
{
NEXT_COL = 0x0,
PREV_ROW = 0x1,
PREV_COL = 0x2,
NEXT_ROW = 0x3
};
+6
View File
@@ -0,0 +1,6 @@
uint64_t pop_count(int64_t row)
{
int64_t rdi = (row - ((row >> 1) & 0x5555555555555555));
int64_t rdi_3 = (((rdi >> 2) & 0x3333333333333333) + (rdi & 0x3333333333333333));
return (((((rdi_3 >> 4) + rdi_3) & 0xf0f0f0f0f0f0f0f) * 0x101010101010101) >> 0x38);
}
+87
View File
@@ -0,0 +1,87 @@
10 8
5 6
0 4
| | | | |X| | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | |X| | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | |X| | | |
| | | | | | | | | | | | |
11 10
8 8
5 6
2 4
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | |X| | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | |X| | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | |X| | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | |X| |
7 10
6 8
5 6
4 4
3 2
2 0
| | | | | | | | | | | | |
| | | | | | | | | | | | |
|X| | | | | | | | | | | |
| | |X| | | | | | | | | |
| | | | |X| | | | | | | |
| | | | | | |X| | | | | |
| | | | | | | | |X| | | |
| | | | | | | | | | |X| |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
3 10
4 8
5 6
6 4
7 2
8 0
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | |X| |
| | | | | | | | |X| | | |
| | | | | | |X| | | | | |
| | | | |X| | | | | | | |
| | |X| | | | | | | | | |
|X| | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
2 8
5 6
8 4
11 2
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | |X| | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | | | |X| | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | | | |X| | | | | | | |
| | | | | | | | | | | | |
| | | | | | | | | | | | |
| | |X| | | | | | | | | |
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
import os
from math import gcd
def pretty_print(arr):
res = ""
for row in arr:
res += '|'
for el in row:
res += el + '|'
res += '\n'
return res
def count_alligned(i, j):
for y in range(-0xb, 0xc):
if y == 0:
continue
start_row = i + 0x79
start_column = (y + 1) * -0xb + j + 11
for x in range(-0xb, 0xc):
if x == 0:
start_row -= 0xb
continue
pgcd = gcd(y, x)
if pgcd == 1:
arr = [[' ' for _ in range(0xc)] for _ in range(0xc)]
row = start_row
column = start_column
for _ in range(0x17):
if column <= 0xb and row <= 0xb and column >= 0 and row >= 0:
print(row, column)
arr[row][column] = 'X'
column += y
row += x
print(pretty_print(arr))
start_row -= 0xb
count_alligned(5, 6)
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
import os
def check_align(i, j):
return b'\x04' + j.to_bytes(1, 'little') + i.to_bytes(1, 'little')
def cycle():
return b'\x01'
def done():
return b'\x00'
def move():
return b'\x02'
def place():
return b'\x03'
def fill_column(skip = True):
res = b''
for _ in range(0xb):
if not skip:
res += place()
res += move()
if not skip:
res += place()
return res
def fill():
res = b''
res += cycle() * 3
res += fill_column(False)
for _ in range(5):
res += cycle() + move() + cycle()
res += fill_column()
res += cycle() * 3 + move() + cycle() * 3
res += fill_column()
res += cycle() + move() + cycle()
res += fill_column(False)
for i in range(0xc):
for j in range(0xc):
res += check_align(i, j)
return res + done()
res = fill()
os.write(1, res)
Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 770 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

+15
View File
@@ -0,0 +1,15 @@
.PHONY: all run
all: ./solver
./simple: ./megalosaure.c simple.c
gcc -Wno-overflow simple.c megalosaure.c -o simple -O3 -march=native -fno-pie -no-pie
./megalosaure.c: ./disasm.py
./disasm.py
./solver: ./megalosaure.c main.c
gcc -Wno-overflow main.c megalosaure.c -o solver -O3 -march=native -fno-pie -no-pie
run: all
./solver
+437
View File
@@ -0,0 +1,437 @@
#!/usr/bin/env python3
import struct
from pwn import *
from typing import Optional, List
from Crypto.Util.number import inverse
#from z3 import *
opcodes = {
0x0: "pushread_i_f",
0x1: "push_m",
0x2: "push32_i_i",
0x3: "popwrite_i_f",
0x4: "pop_m",
0x5: "dup",
0x6: "add",
0x7: "sub",
0x8: "mul",
0x9: "mod",
0xa: "xor",
0xb: "and",
0xc: "or",
0xd: "shr",
0xe: "shl",
0xf: "not",
0x10: "neg",
0x11: "nop",
0x12: "exit",
}
registers = [
"ip",
"sp"
]
N = 2**32
class Stream:
i: int
buf: bytes
def __init__(self, buf) -> None:
self.pos = 0
self.buf = buf
def read_u16(self) -> Optional[int]:
try:
val = struct.unpack("<H", self.buf[self.pos:self.pos + 2])
self.pos += 2
return val[0]
except:
return None
def read_i16(self) -> Optional[int]:
try:
val = struct.unpack("<h", self.buf[self.pos:self.pos + 2])
self.pos += 2
return val[0]
except:
return None
def read_u32(self) -> Optional[int]:
try:
val = struct.unpack("<I", self.buf[self.pos:self.pos + 4])
self.pos += 4
return val[0]
except:
return None
def read_i32(self) -> Optional[int]:
try:
val = struct.unpack("<i", self.buf[self.pos:self.pos + 4])
self.pos += 4
return val[0]
except:
return None
class Operand:
pass
class Register(Operand):
index: int
name: str
def __init__(self, index: int) -> None:
self.index = index
self.name = f"r{hex(index)}"
class Mem(Operand):
index: int
name: str
def __init__(self, index: int) -> None:
self.index = index
self.name = f"m[{hex(index)}]"
class Imm(Operand):
value: int
unsigned: int
def __init__(self, value: int) -> None:
self.value = value
self.raw = struct.unpack("<I", struct.pack("<i", self.value))[0]
class Instruction:
opcode: int
operands: List[Operand]
addr: int
name: str
size: int
def __init__(self, opcode, operands, opcodes) -> None:
self.opcode = opcode
self.operands = operands
self.name = opcodes[self.opcode] if self.opcode in opcodes else "invalid"
self.size = 2 * (len(operands) + 1)
@staticmethod
def disassemble(data: bytes) -> 'Instruction':
stream = Stream(data)
opcode = stream.read_u16()
operands = []
if opcode not in opcodes:
return Instruction(opcode, [], addr, opcodes)
mnemonic = opcodes[opcode]
mnemonic_decomp = mnemonic.split('_')
mnemonic_decomp.pop(0)
for element in mnemonic_decomp:
if element == 'i':
value = stream.read_u16()
operand = Imm(value)
operands.append(operand)
elif element == 'm':
value = stream.read_u16()
operand = Mem(value)
operands.append(operand)
elif element == 'f':
n_regs = operands[-1].value
for i in range(n_regs):
index = stream.read_u16()
operand = Register(index)
operands.append(operand)
return Instruction(opcode, operands, opcodes)
def to_string(self):
asm = self.name
for op in self.operands:
asm += ' '
if isinstance(op, Register):
asm += op.name
elif isinstance(op, Mem):
asm += op.name
elif isinstance(op, Imm):
asm += f"{hex(op.value)}"
return asm
def transpile(self):
if self.name == "pop_m":
return ''
elif self.name == "push32_i_i":
val = (self.operands[1].value << 0x10) | self.operands[0].value
return f'{val}'
elif self.name == "push_m":
return f'm{self.operands[0].index}'
elif self.name == "add":
return '+'
elif self.name == "sub":
return '-'
elif self.name == "mul":
return '*'
elif self.name == "mod":
return '%'
elif self.name == "xor":
return '^'
elif self.name == "and":
return '&'
elif self.name == "or":
return '|'
elif self.name == "not":
return '~'
elif self.name == "neg":
return '-'
elif self.name == "shr":
return '>>'
elif self.name == "shl":
return '<<'
else:
raise
class Child:
def __init__(self, pod, index):
self.pod = pod
self.index = index
self.offset = (pod.offset + index) * self.pod.code_size
self.code = self.pod.megalosaure.elf.read(self.pod.code_base + self.offset * 2, self.pod.code_size * 2)
self.instructions = []
self.depends = []
self.unlocks = []
self.inputs = []
self.main_instr = None
while True:
instr = Instruction.disassemble(self.code)
self.code = self.code[instr.size:]
self.instructions.append(instr)
if instr.name == 'exit':
break
elif instr.name == 'pushread_i_f':
for reg in instr.operands[1:]:
self.depends.append(reg.index)
elif instr.name == 'popwrite_i_f':
for reg in instr.operands[1:]:
self.unlocks.append(reg.index)
else:
if self.main_instr != None:
raise
self.main_instr = instr
def to_string(self):
asm = ""
for instr in self.instructions:
asm += instr.to_string() + '\n'
return asm
def consume_locks(self, locks):
while self.depends != []:
dependency = self.depends[0]
if locks[dependency][0]:
return
self.inputs.append(locks[dependency][1])
locks[dependency] = (True, None)
self.depends.pop(0)
def is_schedulable(self, locks):
return len(self.depends) == 0
def mark_unlocks(self, locks):
for unlock in self.unlocks:
locks[unlock] = (False, self)
def transpile(self, indent=0):
code = "(\n"
indent += 4
code += ' ' * indent
instr = self.main_instr
op = instr.name
inputs = self.inputs
if len(inputs) == 0:
code += instr.transpile()
elif len(inputs) == 1:
inp = inputs[0]
code += instr.transpile() + inp.transpile(indent)
else:
code += inputs[1].transpile(indent)
code += instr.transpile()
code += inputs[0].transpile(indent)
code += '\n'
indent -= 4
code += ' ' * indent
code += ")"
return code
def z3(self, solver, memory):
instr = self.main_instr
op = instr.name
inputs = self.inputs
output = BitVec(f'{self.pod.index}_{self.index}', 32)
if len(inputs) == 0:
if op == 'push_m':
addr = instr.operands[0].index
mem = memory[addr]
solver.add(mem == output)
elif op == 'push32_i_i':
val = (instr.operands[1].value << 0x10) | instr.operands[0].value
output = BitVecVal(val, 32)
else:
print(op)
elif len(inputs) == 1:
inp = inputs[0]
value = inp.z3(solver, memory)
if op == "pop_m":
addr = instr.operands[0].index
mem = memory[addr]
solver.add(mem == value)
solver.add(mem == output)
elif op == "not":
solver.add(output == ~value)
else:
print(op)
else:
value0 = inputs[0].z3(solver, memory)
value1 = inputs[1].z3(solver, memory)
if op == "xor":
solver.add(output == (value0 ^ value1))
elif op == "or":
solver.add(output == (value0 | value1))
elif op == "and":
solver.add(output == (value0 & value1))
elif op == "add":
solver.add(output == (value0 + value1))
elif op == "sub":
solver.add(output == (value1 - value0))
elif op == "mul":
solver.add(output == (value1 * value0))
elif op == "shl":
solver.add(output == (value1 << value0))
elif op == "shr":
solver.add(output == (value1 >> value0))
else:
print(op)
return output
class Pod:
def __init__(self, n_childs, offset, megalosaure, i):
self.megalosaure = megalosaure
self.n_childs = n_childs
self.offset = offset
self.childs = []
self.code_size = 9
self.code_base = 0x50c0
self.stages = []
self.index = i
for i in range(n_childs):
self.childs.append(Child(self, i))
def build_ast(self):
locks = [(True, None) for _ in range(0x26c9)]
to_schedule = [child for child in self.childs]
next_stage_schedule = [1]
while next_stage_schedule != []:
current_stage = []
next_stage_schedule = []
while to_schedule != []:
child = to_schedule.pop(0)
child.consume_locks(locks)
if child.is_schedulable(locks):
current_stage.append(child)
child.mark_unlocks(locks)
else:
next_stage_schedule.append(child)
to_schedule = next_stage_schedule
self.stages.append(current_stage)
return self.stages
def transpile(self):
code = f"uint32_t m{self.index + 2} = {self.stages[-1][0].transpile()};\n"
return code
def z3(self, solver, memory):
self.stages[-1][0].z3(solver, memory)
class Megalosaure:
name = "megalosaure"
address_size = 2
default_int_size = 4
instr_aligment = 2
max_instr_length = 12
def __init__(self, path):
self.elf = ELF(path)
print('[+] Loading virtual machines')
self.podinfo_addresses = 0x444220
self.pods = []
for i in range(0x2c):
podinfo_b = self.elf.read(self.podinfo_addresses + i * 8, 8)
n_childs = struct.unpack('<L', podinfo_b[:4])[0]
offset = struct.unpack('<L', podinfo_b[4:])[0]
pod = Pod(n_childs, offset, self, i)
self.pods.append(pod)
def build_ast(self):
print('[+] Lifting AST')
for pod in self.pods:
pod.build_ast()
def transpile(self, path, depth):
print('[+] Transpiling to C')
code = "#include <stdint.h>\nuint64_t megalosaure(uint32_t m0, uint32_t m1) {\n"
for i in range(depth):
code += self.pods[i].transpile()
code += f"return (((uint64_t)m{depth + 1}) << 32) | m{depth};\n"
code += "}\n"
print(f'[+] Transpiled to {path}')
with open(path, 'w') as f:
f.write(code)
return code
def z3(self, depth, desired):
print('[+] Building z3 solver')
memory = [BitVec(f'm{i}', 32) for i in range(0x2e)]
memory[0] = BitVecVal(0x43534346, 32)
solver = Solver()
for i in range(depth):
self.pods[i].z3(solver, memory)
m44 = desired % (2**32)
m45 = desired >> 32
solver.add(memory[44] == m44)
solver.add(memory[45] == m45)
print('[+] Running solver')
print(solver.check())
m = solver.model()
print(m)
return code
meg = Megalosaure('./megalosaure')
meg.build_ast()
#meg.z3(0x2c, 0x9b07e7ce91a8a7b5)
meg.transpile('./megalosaure.c', 0x2c)
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
from Crypto.Util.number import inverse
import struct
import os
N = 2**32
def reverse(desired_out, mult):
return ((desired_out) * inverse(mult, N)) % N
first = reverse(0xa4e1a60a, 0x1337)
print(struct.pack('<L', first))
+88
View File
@@ -0,0 +1,88 @@
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
uint64_t megalosaure(uint32_t m0, uint32_t m1);
int block = 1;
int main(int argc, char **argv)
{
char charset[18] = "0123456789abcdef}";
const uint64_t ref[9] = { 0x9b07e7ce91a8a7b5, 0x9e819eac35e7e97c, 0xfd401d3317aa6b5f, 0xdf16a32fbd9d5587, 0x80c561ac0dab4fae, 0x9237d1ddd368e209, 0x07ebe4f6ee26882c, 0xb72ffd11e878303b, 0x99d2a7dc8267bf3f };
int charset_len = 16;
int pid = 0;
for (int i = 0; i < 7; ++i)
{
if (pid == 0)
{
pid = fork();
if (pid == 0)
{
block++;
}
}
}
char m0_c[8] = {'0', '0', '0', '0', '0', '0', '0', '0'};
uint32_t *m0 = (uint32_t *)(&m0_c);
uint32_t *m1 = (uint32_t *)(&m0_c[4]);
uint64_t res;
uint64_t x_int = ref[block - 1];
char *x = (char*)&x_int;
if (block == 8)
{
charset_len += 2;
}
for (int i0 = 0; i0 < 18; ++i0)
{
m0_c[0] = charset[i0] ^ x[0];
for (int i1 = 0; i1 < charset_len; ++i1)
{
m0_c[1] = charset[i1] ^ x[1];
for (int i2 = 0; i2 < charset_len; ++i2)
{
m0_c[2] = charset[i2] ^ x[2];
for (int i3 = 0; i3 < charset_len; ++i3)
{
m0_c[3] = charset[i3] ^ x[3];
for (int i4 = 0; i4 < charset_len; ++i4)
{
m0_c[4] = charset[i4] ^ x[4];
for (int i5 = 0; i5 < charset_len; ++i5)
{
m0_c[5] = charset[i5] ^ x[5];
for (int i6 = 0; i6 < charset_len; ++i6)
{
m0_c[6] = charset[i6] ^ x[6];
for (int i7 = 0; i7 < charset_len; ++i7)
{
m0_c[7] = charset[i7] ^ x[7];
res = megalosaure(*m0, *m1);
if (res == ref[block])
{
char flag[9];
flag[8] = 0;
uint64_t *flag_ptr = (uint64_t*)flag;
*flag_ptr = *m0 + (((uint64_t)*m1) << 32);
*flag_ptr ^= x_int;
printf("Block %d: %s\n", block, flag);
if (pid != 0)
waitpid(pid, NULL, 0);
return 0;
}
}
}
}
}
}
}
}
}
}
Binary file not shown.
@@ -0,0 +1,210 @@
import struct
from binaryninja import *
tI = lambda e: InstructionTextToken(InstructionTextTokenType.InstructionToken, e)
tt = lambda e: InstructionTextToken(InstructionTextTokenType.TextToken, e)
tr = lambda e: InstructionTextToken(InstructionTextTokenType.RegisterToken, e)
ti = lambda e: InstructionTextToken(InstructionTextTokenType.IntegerToken, e, int(e, 16))
ta = lambda e: InstructionTextToken(InstructionTextTokenType.PossibleAddressToken, e, int(e, 16))
ts = lambda e: InstructionTextToken(InstructionTextTokenType.OperandSeparatorToken, e)
opcodes = {
0x0: "pushread_i_f",
0x1: "push_m",
0x2: "push32_i_i",
0x3: "popwrite_i_f",
0x4: "pop_m",
0x5: "dup",
0x6: "add",
0x7: "sub",
0x8: "mul",
0x9: "mod",
0xa: "xor",
0xb: "and",
0xc: "or",
0xd: "shr",
0xe: "shl",
0xf: "not",
0x10: "neg",
0x11: "nop",
0x12: "exit",
}
registers = [
"ip",
"sp"
]
class Stream:
i: int
buf: bytes
def __init__(self, buf) -> None:
self.pos = 0
self.buf = buf
def read_u16(self) -> Optional[int]:
try:
val = struct.unpack("<H", self.buf[self.pos:self.pos + 2])
self.pos += 2
return val[0]
except:
return None
def read_i16(self) -> Optional[int]:
try:
val = struct.unpack("<h", self.buf[self.pos:self.pos + 2])
self.pos += 2
return val[0]
except:
return None
def read_u32(self) -> Optional[int]:
try:
val = struct.unpack("<I", self.buf[self.pos:self.pos + 4])
self.pos += 4
return val[0]
except:
return None
def read_i32(self) -> Optional[int]:
try:
val = struct.unpack("<i", self.buf[self.pos:self.pos + 4])
self.pos += 4
return val[0]
except:
return None
class Operand:
pass
class Register(Operand):
index: int
name: str
def __init__(self, index: int) -> None:
self.index = index
self.name = f"r{hex(index)}"
class Mem(Operand):
index: int
name: str
def __init__(self, index: int) -> None:
self.index = index
self.name = f"m[{hex(index)}]"
class Imm(Operand):
value: int
unsigned: int
def __init__(self, value: int) -> None:
self.value = value
self.raw = struct.unpack("<I", struct.pack("<i", self.value))[0]
class Instruction:
opcode: int
operands: List[Operand]
addr: int
name: str
size: int
def __init__(self, opcode, operands, addr, opcodes) -> None:
self.opcode = opcode
self.operands = operands
self.addr = addr
self.name = opcodes[self.opcode] if self.opcode in opcodes else "invalid"
self.size = 2 * (len(operands) + 1)
@staticmethod
def disassemble(data: bytes, addr: int, opcodes = opcodes, registers = registers) -> 'Instruction':
stream = Stream(data)
opcode = stream.read_u16()
operands = []
if opcode not in opcodes:
return Instruction(opcode, [], addr, opcodes)
mnemonic = opcodes[opcode]
mnemonic_decomp = mnemonic.split('_')
mnemonic_decomp.pop(0)
for element in mnemonic_decomp:
if element == 'i':
value = stream.read_i16()
operand = Imm(value)
operands.append(operand)
elif element == 'm':
value = stream.read_u16()
operand = Mem(value)
operands.append(operand)
elif element == 'f':
n_regs = operands[-1].value
for i in range(n_regs):
index = stream.read_u16()
operand = Register(index)
operands.append(operand)
return Instruction(opcode, operands, addr, opcodes)
def to_tokens(self) -> List[InstructionTextToken]:
tokens = [tI(self.name)]
for op in self.operands:
tokens.append(tt(" "))
if isinstance(op, Register):
tokens.append(tr(op.name))
elif isinstance(op, Mem):
tokens.append(tr(op.name))
elif isinstance(op, Imm):
if "rel" in self.name or self.name == "call_imm":
tokens.append(ta(str(hex(self.jmp_dest()))))
else:
tokens.append(ti(str(op.value)))
tokens.append(tt(" ("))
tokens.append(ti(str(hex(op.raw))))
tokens.append(tt(")"))
return tokens
def info(self) -> InstructionInfo:
info = InstructionInfo()
info.length = self.size
if "exit" in self.name or "stop" in self.name or self.name == "ret":
info.add_branch(BranchType.FunctionReturn)
return info
class Megalosaure(Architecture):
name = "megalosaure"
address_size = 2
default_int_size = 4
instr_aligment = 2
max_instr_length = 12
regs = {reg: RegisterInfo(reg, 4) for reg in registers}
stack_pointer = "sp"
def get_instruction_text(self, data, addr):
instruction = Instruction.disassemble(data, addr)
return instruction.to_tokens(), instruction.size
def get_instruction_info(self, data, addr):
instruction = Instruction.disassemble(data, addr)
return instruction.info()
def get_instruction_low_level_il(self, data, addr, il):
pass
Megalosaure.register()
arch = Architecture["megalosaure"]
+29
View File
@@ -0,0 +1,29 @@
#include <stdint.h>
#include <stdio.h>
uint64_t megalosaure(uint32_t m0, uint32_t m1);
int main(int argc, char **argv)
{
char m0_c[8] = {'F', 'C', 'S', 'C', '{', '0', '0', '0'};
uint32_t *m0 = (uint32_t *)(m0_c);
uint32_t *m1 = (uint32_t *)(&m0_c[4]);
for (int i = 30; i < 127; ++i)
{
m0_c[5] = i;
for (int j = 30; j < 127; ++j)
{
m0_c[6] = j;
for (int k = 30; k < 127; ++k)
{
m0_c[7] = k;
uint64_t res = megalosaure(*m0, *m1);
if (res == 0x9b07e7ce91a8a7b5)
{
printf("%s\n", m0_c);
return 0;
}
}
}
}
}
+131
View File
@@ -0,0 +1,131 @@
uint64_t allowed_moves[0x10][0x5] =
{
[0x0] =
{
[0x0] = 0x0100000000000000
[0x1] = 0x0000100000000000
[0x2] = 0x0000000000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x1] =
{
[0x0] = 0x1000000000000000
[0x1] = 0x0010000000000000
[0x2] = 0x0000010000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x2] =
{
[0x0] = 0x0100000000000000
[0x1] = 0x0001000000000000
[0x2] = 0x0000001000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x3] =
{
[0x0] = 0x0010000000000000
[0x1] = 0x0000000100000000
[0x2] = 0x0000000000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x4] =
{
[0x0] = 0x1000000000000000
[0x1] = 0x0000010000000000
[0x2] = 0x0000000010000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x5] =
{
[0x0] = 0x0100000000000000
[0x1] = 0x0000100000000000
[0x2] = 0x0000001000000000
[0x3] = 0x0000000001000000
[0x4] = 0x0000000000000000
}
[0x6] =
{
[0x0] = 0x0010000000000000
[0x1] = 0x0000010000000000
[0x2] = 0x0000000100000000
[0x3] = 0x0000000000100000
[0x4] = 0x0000000000000000
}
[0x7] =
{
[0x0] = 0x0001000000000000
[0x1] = 0x0000001000000000
[0x2] = 0x0000000000010000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x8] =
{
[0x0] = 0x0000100000000000
[0x1] = 0x0000000001000000
[0x2] = 0x0000000000001000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0x9] =
{
[0x0] = 0x0000010000000000
[0x1] = 0x0000000010000000
[0x2] = 0x0000000000100000
[0x3] = 0x0000000000000100
[0x4] = 0x0000000000000000
}
[0xa] =
{
[0x0] = 0x0000001000000000
[0x1] = 0x0000000001000000
[0x2] = 0x0000000000010000
[0x3] = 0x0000000000000010
[0x4] = 0x0000000000000000
}
[0xb] =
{
[0x0] = 0x0000000100000000
[0x1] = 0x0000000000100000
[0x2] = 0x0000000000000001
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0xc] =
{
[0x0] = 0x0000000010000000
[0x1] = 0x0000000000000100
[0x2] = 0x0000000000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0xd] =
{
[0x0] = 0x0000000001000000
[0x1] = 0x0000000000001000
[0x2] = 0x0000000000000010
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0xe] =
{
[0x0] = 0x0000000000100000
[0x1] = 0x0000000000000100
[0x2] = 0x0000000000000001
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
[0xf] =
{
[0x0] = 0x0000000000010000
[0x1] = 0x0000000000000010
[0x2] = 0x0000000000000000
[0x3] = 0x0000000000000000
[0x4] = 0x0000000000000000
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

+71
View File
@@ -0,0 +1,71 @@
char init_state[0x36] =
{
0x0d, 0x03, 0x02, 0x0e, 0x0f, 0x09, 0x07, 0x0e, 0x0d, 0x06, 0x03, 0x02, 0x07, 0x02, 0x08, 0x0e,
0x07, 0x04, 0x04, 0x03, 0x0d, 0x04, 0x0c, 0x03, 0x0f, 0x02, 0x0a, 0x05, 0x09, 0x01, 0x06, 0x0a,
0x0b, 0x02, 0x05, 0x0c, 0x0e, 0x0b, 0x0d, 0x01, 0x0a, 0x01, 0x05, 0x09, 0x01, 0x0f, 0x06, 0x0e,
0x04, 0x04, 0x0b, 0x04, 0x0b, 0x0f, 0x00
};
int32_t main(int32_t argc, char** argv, char** envp)
{
char* const init_state_ptr = &init_state;
char state[0x36];
char* state_ptr = &state;
for (int64_t size = 0x36; size != 0; size -= 1)
{
*state_ptr = *init_state_ptr;
state_ptr += 1;
init_state_ptr += 1;
}
printf("Password: ", init_state_ptr);
fflush(stdout);
char input[0x18];
scanf("%24s", &input);
int64_t state_index = 0;
while (true)
{
if (strlen(&input) <= state_index)
{
// Cutting everything that happens
...
if (check == OK)
{
puts("Win!");
FILE file = fopen("flag.txt", &rb);
if (file != NULL)
{
char flag[0x46];
fread(&flag, 1, 0x46, file);
fclose(file);
puts(flag);
return 0;
}
else
puts("Send your input on the remote se…");
}
else
puts("Nope!");
break;
}
else
{
char* pos_ptr = strchr("abcdefghjklmnpqrstuvwxyz", input[state_index]);
if (pos_ptr != NULL)
{
// Doing stuff while iterating on the input
...
state_index += 1;
continue;
}
}
puts("Nope!");
break;
}
exit(1);
/* no return */
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

+37
View File
@@ -0,0 +1,37 @@
else
{
char* pos_ptr = strchr("abcdefghjklmnpqrstuvwxyz", input[state_index]);
if (pos_ptr != NULL)
{
int64_t pos = pos_ptr - "abcdefghjklmnpqrstuvwxyz";
int32_t remainder = pos % 4;
char* permutation_array = &permutations[pos / 4];
while (true)
{
if (remainder < 1)
break;
remainder -= 1;
char state_copy[0x36];
char* state_copy_ptr = &state_copy;
char* state_ptr_1 = &state;
int64_t i = 0x36;
for (; i != 0; i -= 1)
{
*state_copy_ptr = *state_ptr_1;
state_copy_ptr += 1;
state_ptr_1 += 1;
}
do
{
char elem = state_copy[permutation_array[i]];
state[i] = elem;
i += 1
} while (i != 0x36);
}
state_index += 1;
continue;
}
}
@@ -0,0 +1,56 @@
char permutations[0x6][0x36] =
{
[0x0] =
{
[0x00] = 0x09
[0x01] = 0x01
[0x02] = 0x02
[0x03] = 0x0c
[0x04] = 0x04
[0x05] = 0x05
[0x06] = 0x0f
[0x07] = 0x07
[0x08] = 0x08
[0x09] = 0x2d
...
[0x34] = 0x34
[0x35] = 0x35
}
[0x1] =
{
[0x00] = 0x00
[0x01] = 0x01
[0x02] = 0x2a
[0x03] = 0x03
...
[0x34] = 0x34
[0x35] = 0x11
[0x2] =
{
[0x00] = 0x02
[0x01] = 0x05
...
[0x35] = 0x35
}
[0x3] =
{
[0x00] = 0x00
[0x01] = 0x01
...
[0x35] = 0x33
}
[0x4] =
{
[0x00] = 0x00
[0x01] = 0x01
...
[0x35] = 0x35
}
[0x5] =
{
[0x00] = 0x21
[0x01] = 0x1e
...
[0x35] = 0x14
}
}
BIN
View File
Binary file not shown.
+67
View File
@@ -0,0 +1,67 @@
if (strlen(&input) <= state_index)
{
int64_t board = 0x3da8e0915f2c4b67;
int64_t next_board;
int64_t i = 0;
uint64_t move;
while (true)
{
uint64_t c = state[i];
void* allowed_moves = &allowed_moves;
int32_t shifter = 0x3c;
do
{
if (c == ((board >> shifter) & 0xf))
{
uint64_t* moves = allowed_moves;
do
{
move = *moves;
if (move == 0)
break;
moves += 1;
} while (((move * 0xf) & board) != 0);
if (move != 0)
break;
}
shifter -= 4;
allowed_moves += 0x28;
} while (shifter != 0xfffffffc);
if (c != ((board >> shifter) & 0xf) || move == 0)
break;
int64_t swapper = ((c * move) ^ (c << shifter));
next_board = (board ^ swapper);
if (board == swapper)
break;
i += 1;
if (i == 0x36)
break;
board = next_board;
}
if (next_board == 0x123456789abcdef0)
{
puts("Win!");
FILE file = fopen("flag.txt", &rb);
if (file != NULL)
{
char flag[0x46];
fread(&flag, 1, 0x46, file);
fclose(file);
puts(flag);
return 0;
}
else
puts("Send your input on the remote se…");
}
else
puts("Nope!");
break;
}
+193
View File
@@ -0,0 +1,193 @@
use std::collections::HashMap;
struct Board {
board: [usize; 0x10],
moves: Vec<usize>,
max_moves: usize,
move_number: usize,
empt_idx: usize,
solved_grid: [usize; 0x10],
fixed_moves: HashMap<usize, usize>,
move_limit: [isize; 0x10]
}
impl Board {
pub fn new(board: [usize; 0x10]) -> Self {
let empt_idx: usize = board.iter().position(|&r| r == 0).unwrap().try_into().unwrap();
let all_moves: [usize; 0x36] = [
0x0d, 0x03, 0x02, 0x0e, 0x0f, 0x09, 0x07, 0x0e, 0x0d, 0x06, 0x03, 0x02, 0x07, 0x02, 0x08, 0x0e,
0x07, 0x04, 0x04, 0x03, 0x0d, 0x04, 0x0c, 0x03, 0x0f, 0x02, 0x0a, 0x05, 0x09, 0x01, 0x06, 0x0a,
0x0b, 0x02, 0x05, 0x0c, 0x0e, 0x0b, 0x0d, 0x01, 0x0a, 0x01, 0x05, 0x09, 0x01, 0x0f, 0x06, 0x0e,
0x04, 0x04, 0x0b, 0x04, 0x0b, 0x0f
];
let solved_grid: [usize; 0x10] = [1,2,3,4,5,6,7,8,9,0xa,0xb,0xc,0xd,0xe,0xf,0];
let mut fixed_moves: HashMap<usize, usize> = HashMap::new();
for i in vec![4, 0xd, 0x16, 0x1f, 0x28, 0x31] {
fixed_moves.insert(i, all_moves[i]);
}
let mut move_limit: [isize; 0x10] = [0; 0x10];
for mv in all_moves.iter() {
move_limit[*mv] += 1;
}
Board {
board: board,
moves: Vec::new(),
max_moves: 0x36,
move_number: 0,
empt_idx: empt_idx,
solved_grid: solved_grid,
fixed_moves: fixed_moves,
move_limit: move_limit,
}
}
pub fn solved(&self) -> bool {
self.board == self.solved_grid
}
pub fn get_move(&self, off: Vec<isize>) -> Option<usize> {
let empt_idx: isize = self.empt_idx.try_into().unwrap();
let empt_i: isize = empt_idx / 4;
let empt_j: isize = empt_idx % 4;
let src_i: isize = empt_i + off[0];
let src_j: isize = empt_j + off[1];
if src_i < 4 && src_i >= 0 && src_j < 4 && src_j >= 0 {
let idx: usize = (src_i * 4 + src_j).try_into().unwrap();
return Some(self.board[idx])
}
None
}
pub fn generate_moves(&self) -> Vec<usize> {
let mut moves: Vec<usize> = Vec::new();
for off in vec![vec![-1, 0], vec![1, 0], vec![0, -1], vec![0, 1]] {
let maybe_move = self.get_move(off);
if let Some(mv) = maybe_move {
moves.push(mv);
}
}
moves
}
pub fn apply_move(&mut self, mv: usize, undo: bool) {
let i: usize = self.board.iter().position(|&x| x == mv).unwrap();
let tmp: usize = self.board[i];
self.board[i] = self.board[self.empt_idx];
self.board[self.empt_idx] = tmp;
self.empt_idx = i;
if undo {
self.move_number -= 1;
self.moves.pop();
self.move_limit[mv] += 1;
}
else {
self.move_number += 1;
self.moves.push(mv);
self.move_limit[mv] -= 1;
}
}
pub fn manhattan_distance(&self, mv: usize) -> isize {
let mv_idx: isize = self.board.iter().position(|&x| x == mv).unwrap().try_into().unwrap();
let mv_i: isize = mv_idx / 4;
let mv_j: isize = mv_idx % 4;
let supposed_idx: isize = (mv - 1).try_into().unwrap();
let supposed_i: isize = supposed_idx / 4;
let supposed_j: isize = supposed_idx % 4;
let manhattan: isize = (supposed_j - mv_j).abs() + (supposed_i - mv_i).abs();
manhattan
}
pub fn solve(&mut self) -> bool {
// GG
if self.solved() {
return true;
}
// No more moves
if self.move_number >= self.max_moves {
return false;
}
// Last move need to be 0xc or 0xf
if self.move_limit[0xc] <= 0 && self.move_limit[0xf] <= 0 {
return false;
}
let last_move: Option<usize> = self.moves.last().copied();
if let Some(mv) = last_move {
// Tile cannot possibly go back to its supposed location
let man: isize = self.manhattan_distance(mv);
if self.move_limit[mv] < man {
return false
}
}
// Generate possible moves from current grid
let mut moves: Vec<usize> = self.generate_moves();
// Cannot apply same move twice
if let Some(mv) = last_move {
moves = moves.iter().filter(|&x| *x != mv).cloned().collect();
}
// Filter fixed moves from the cube center tiles
if self.fixed_moves.contains_key(&self.move_number) {
let mv: usize = *self.fixed_moves.get(&self.move_number).unwrap();
moves = moves.iter().filter(|&x| *x == mv).cloned().collect();
}
for mv in moves {
// Apply move
self.apply_move(mv, false);
// Recursive call
let solved: bool = self.solve();
// GG
if solved {
return true;
}
// Undo move
self.apply_move(mv, true);
}
false
}
}
fn solve() {
let arr: [usize; 0x10] = [
3, 0xd, 0xa, 8,
0xe, 0, 9, 1,
5, 0xf, 2, 0xc,
4, 0xb, 6, 7
];
let mut board: Board = Board::new(arr);
board.solve();
println!("{:x?}", board.moves);
}
fn main() {
solve()
}
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
import os
alphabet = b"abcdefghjklmnpqrstuvwxyz"
moves = [
('g', 2),
('o', 3),
('g', 3),
('b', 2),
('y', 2),
('g', 3),
('w', 1),
('o', 3),
('r', 3),
('y', 1),
('r', 3),
('w', 1),
('b', 1),
('o', 2),
('g', 1),
('y', 2),
('g', 1),
('y', 2),
('r', 2),
('g', 2),
('w', 2),
('o', 2),
]
sequence = b""
def face_id(face):
res = 0
if face == 'w':
res = 2
if face == 'b':
res = 4
if face == 'o':
res = 1
if face == 'r':
res = 0
if face == 'y':
res = 3
if face == 'g':
res = 5
return res
for move in moves:
i = face_id(move[0]) * 4 + move[1]
sequence += alphabet[i].to_bytes(1, "little")
os.write(1, sequence + b'\n')
Loaded 100 of 769 files, more files were not shown because too many files have changed in this diff. Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.