To write a script, it doesn't matter if the programming is bad

1. The role of scripts in CTF competitions

CTF夺旗赛中往往分为杂项(MISC)、密码(CRYPTO)、WEB、逆向(REVERSE)和PWN。

In the current game, the role played by various tools is constantly declining, and it is rare to get the flag with one hit. It is often necessary to temporarily compile scripts according to the topic, debug, blast, and crack the algorithm to solve the problem smoothly.
To participate in CTF competitions, you must have the ability to write your own scripts.

2. What should I do if my programming skills are not good?

Often many students will say 编程技术不好whether it is necessary to learn development again. In fact, it is unnecessary. Scripts are not web development or network programming, and do not require such high requirements.
Just like your English is not good, but what should you do when you are abroad? Do you want to learn English from scratch? Of course not, try your best, as long as you can let the other party get what you mean. Work hard to talk and communicate, and it will take time. 脚本编制也依然,需要用到什么,就搞懂哪里,多写多练,慢慢就能上手. It is not too late to learn programming systematically by then.

Below I will briefly give an example to introduce how the script is written step by step according to the topic. Students with programming foundation may be able to see it at a glance, and students with weak foundation, it doesn't matter, the most important thing is to get the idea and practice frequently. In CTF, it is most important to find problem-solving ideas and practical ability based on clues and source code.

Mainly based on python scripts

What should I do if I don’t know the function in the code? After searching on Baidu, I can quickly grasp the usage of this function. That’s all. Applying what you have learned is the key to the script.

3. Simple example of scripting

3.1 Miscellaneous topic: a TXT file full of 0, 1

When I got the title, it was a txt file filled with 0 and 1.
Please add a picture description

I have some ideas, right? QR codes are often tested in miscellaneous items, and everyone is used to using tools to analyze them. Could it be that there is another way for this question, instead of directly providing the QR code, you need to build it yourself? With CTF's various anti-human questioning methods, the possibility is very high. But how to build it, let's analyze it step by step, and the script will come out after analyzing it.

  1. First of all, to build a QR code, you need to know the side length of the QR code (square), sopython脚本就要读取txt文件,获取文件的大小,再开方不就得到了边长吗?
import math

# 1.判断二维码数据是否可用
f = open('txt文件路径', 'r')
s = f.read()
print(len(s))
# 开平方根,如果二进制大小能整除,证明是正方形,得出宽、高  x=y=260
print(math.sqrt(len(s)))

# 结果是260,解题思路正确的概率飙升到80%
  1. Regardless of the title, is drawing a QR code essentially on a canvas with a side length of 260 画图? This requires the use of python's famous library PIL.

Remember the code routine of PIL library to create the canvas, it will always be like this, just remember the following lines of code, the routine is the same.

from PIL import Image
x = 260
y = 260
image_new = Image.new('RGB', (x,y), (0,0,0)) # RGB模式,边长均为260,黑色(0,0,0)\白色(255,255,255)
image_new.show()

insert image description here
3. What is the next step, 结合题目the clue is 0,1. That's simple, (it won't be complicated anyway, haha) the QR code has two colors, white and black, random, the core logic is to judge whether it is 0 or 1, and 0 will put black on the rubber (0,0,0 ), 1 is white (255,255,255)

It's still the same, how does the PIL library color different pixels, use the function putpixel, and code the routine. Where there is no way, just Baidu. Loop statements and file reading syntax, if you are really a novice, you can learn python-related content on Baidu, and the self-study time is 3 hours. Don't learn too deeply, just be able to understand the script.

# 3. 区分0或1分别上色黑或白,修复完整二维码
idx = 0    # idx表示txt文件中数据序号,第一个数据为0号,对应坐标点(0,0)  下一个1号对用坐标点(1,0)
for y in range(0, 260):   # 就是平面坐标(x,y)初中几何的知识,只不过用代码写出来
    for x in range(0, 260):
        data = s[idx]  
        if data == '0': # 假如txt中第一个数据为0,对应坐标点(0,0),就给他上黑丝(黑色)
            img_new.putpixel((x,y),(0,0,0)) 
        elif data == '1':
            img_new.putpixel((x,y),(255,255,255))
        idx += 1
img_new.show()
  1. Summarizing the above 3 steps, the complete script and results are as follows.
import math
from PIL import Image

# 1.判断二维码数据是否可用
f = open('txt文件路径', 'r')
s = f.read()
print(len(s))
# 开平方根,如果二进制大小能整除,证明是长方形,得出宽、高  x=y=260
print(math.sqrt(len(s)))

# 2. 测试每个像素点上色(全白、全黑)
x = 260
y = 260
img_new = Image.new('RGB', (x,y), (0,0,0)) # RGB模式,边长均为260,黑色(0,0,0)\白色(255,255,255)
# image_new.show()

# 3. 区分0或1分别上色黑或白,修复完整二维码
idx = 0
for y in range(0, 260):
    for x in range(0, 260):
        data = s[idx]
        if data == '0':
            img_new.putpixel((x,y),(0,0,0))
        elif data == '1':
            img_new.putpixel((x,y),(255,255,255))
        idx += 1
img_new.show()

Please add a picture description
Don't worry, scan the QR code, it's not my payment code~

3.2 Encryption topic: Standard Caesar blasting script

Basic knowledge: Caesar cipher is one of the simplest and most well-known encryption techniques. It belongs to substitution encryption. All letters in the plaintext are shifted backward (or forward) by a fixed number on the alphabet and then replaced with ciphertext.
An example is as follows:
the original alphabet ABCDEFGHIGKLMNOPQRSTUVWXYZ key=3 Each letter is shifted to the right by 3 digits. The
new alphabet DEFGHIGKLMNOPQRSTUVWXYZABC
If the plaintext M=“HEASON”,
then the ciphertext C = “KHDVRQ”. Decryption is similarly shifted to the left by 3 digits to obtain the
so-called key It is the key above, he has only 25 possibilities (key=1 means to remove this by himself). So write a script to traverse all the results, and see that the field is meaningful, and the cracking is actually completed.

from string import ascii_letters
str1 = 'ComeChina'
str2 = str1.lower()
num = 1
table = ascii_letters
for i in range(26):
    print("{}:  ".format(num), end='')
    for temp in str2:
        if temp not in table:
            print(chr(ord(temp)), end="")
        elif ((ord(temp)+num)>ord('z')):
            print(chr((ord(temp)+num)-26), end='')
        else:
            print(chr((ord(temp)+num)), end='')
    num += 1
    print("")
# 结果会输出26种全部结果,其中有个flag

If you can't understand this code, I don't think the script is so difficult, but

  1. You may not know that the relevant knowledge of ascii code is the ord function in the script. In essence, it is to convert a character into a unique decimal number, which is convenient for operation. Each character corresponds to a decimal number. The following chr is the reverse, converting the decimal number to the corresponding character. You can understand it by searching ascii on the Internet. It takes 20 minutes for self-study.
  2. As mentioned above, the loop structure needs to be learned. If you don't know the function, you will understand it in an instant.

3.3 Encryption Topic: Mutated Caesar Script

With the foreshadowing of the above question, this question is easy to understand. Mutated Kaiser is not a fixed key, but a key that changes regularly. For example, in this example, the first character is encrypted with key=5. For each subsequent character, the key is increased by 1 and then encrypted, and so on.
The script is as follows, set an initial key=5, and then in the loop, after processing a character, just increase it by 1.

key = 5  # 初始key值
result = ""
content = "afZ_r9VYfScOeO_UL^RWUc"  # 密文
for i in range(len(content)):
    ori = ord(content[i]) + key
    result += chr(ori)
    key += 1
print(result)

# 输出结果 flag{Caesar_variation}

3.4 Reverse topic

This article does not care about the reverse problem-solving method, only the script. Therefore, the reverse script is the simplest. The algorithm in the original pseudocode is written, and the script can be written in reverse.
Omit the preliminary analysis of the reverse topic, and directly upload the pseudocode
insert image description here
. Note that line 32 is the algorithm of the pseudocode. The script we compiled is very simple. Since we want to crack it, we need to reverse the algorithm, isn’t it all right?

# 1.原始24位字符串
key1 = 'xIrCj~<r|2tWsv3PtIzndka'
flag = ""

# 2. 获取每位的ascii值,(x^6)-1  注意异或运算优先级低于加减
for i in range(0, len(key1)):
    flag += chr((ord(key1[i])^6) - 1) # 注意:异或运算优先级低于加减,所以要写成(ord()^6)-1

#3. 倒序输出
print(flag)
print(flag[::-1]) # 逆序输出

# }NsDkw9sy3qPto4UqNx{galf
# flag{xNqU4otPq3ys9wkDsN}

The script is very simple, so simple that it is outrageous.

4. Summary

Therefore, the compilation of scripts in the CTF competition is not as difficult as everyone imagined.真正难得地方是思路,是找到破题点。

If the foundation is weak, in daily CTF learning, if you encounter a function you don’t understand, just learn as you encounter it, and just memorize the usage of routines. Keep practicing the scripts you already understand, keep reviewing the newly learned functions, and write a lot, and you will naturally get started. When you really have time, you can systematically learn a programming language.
个人经验,为了学习而学习,永远学不好。为了一个目标,用“偷懒”的办法,学以致用,不断巩固练习,效果反而好。

Guess you like

Origin blog.csdn.net/eason612/article/details/126202413