first commit

This commit is contained in:
2024-10-18 21:01:20 +08:00
commit 45b4fa172f
35 changed files with 1580 additions and 0 deletions

0
README.md Normal file
View File

BIN
input/dprintf Normal file

Binary file not shown.

BIN
input/dprintf.i64 Normal file

Binary file not shown.

BIN
input/edit Normal file

Binary file not shown.

BIN
input/edit.i64 Normal file

Binary file not shown.

BIN
input/recv Normal file

Binary file not shown.

BIN
input/recv.i64 Normal file

Binary file not shown.

BIN
output/dprintf_patch/dprintf Executable file

Binary file not shown.

BIN
output/edit_patch/edit Executable file

Binary file not shown.

BIN
output/recv_patch/recv Executable file

Binary file not shown.

1
src/Extract_code Submodule

Submodule src/Extract_code added at 9bd4f149a5

0
src/README.md Normal file
View File

Binary file not shown.

Binary file not shown.

287
src/agent.py Normal file
View File

@@ -0,0 +1,287 @@
import os
import re
import sys
import json
import warnings
import subprocess
from chat import QueryChatGPT, llm_configured, load_config
from typing import Optional, Dict, List, Tuple
from binary_patch import load_binary_file_information, patch_dprintf, patch_recv, patch_strcpy
DIR = os.path.dirname(os.path.abspath(__file__))
PROMPT_PATH = os.path.join(DIR, 'prompt.json')
DANGER_FUNC = os.path.join(DIR, 'danger_func.json')
IN_DIR = os.path.join(DIR, 'input')
OUT_DIR = os.path.join(DIR, 'output')
INIT_IN_DIR = os.path.join(os.path.dirname(DIR), 'input')
FINAL_OUT_DIR = os.path.join(os.path.dirname(DIR), 'output')
IDAT64_PATH = "/root/idapro-9.0/idat64"
def get_prompt(name: str, _type: str, prompt_path: str = PROMPT_PATH) -> Optional[Dict[str, str]]:
"""
Access the prompt
Args:
name: the name of the prompt
_type: the type of the prompt
prompt_path: the path of the prompt file
Returns:
a dict containing two keys: 'role' and 'content'
"""
prompts = None
with open(prompt_path, 'r') as f:
prompts = json.load(f)
assert(prompts)
for _p in prompts:
if _p['name'] == name and _p['type'] == _type:
return _p['prompt']
return None
def read_decompile_code(file_path: str) -> Optional[str]:
if not os.path.exists(file_path):
warnings.warn("Fail to find {file_path}!".format(file_path, file_path))
sys.exit(1)
with open(file_path, 'r') as r:
code_data = r.read()
return code_data
def read_struct_data(file_path: str) -> Optional[str]:
if not os.path.exists(file_path):
warnings.warn("Fail to find {file_path}!".format(file_path, file_path))
sys.exit(1)
with open(file_path, 'r') as r:
struct_data = r.read()
return struct_data
def handle_dprintf(file_name: str, code: str, elf_file: str, patch_dprintf_file: str = 'patch_dprintf.json'):
if 'dprintf' not in code:
return
print("begin to test dprintf in {file_name}.".format(file_name = file_name))
# generate output file
output_dir = OUT_DIR + '/' + file_name[:-2]
os.makedirs(output_dir, exist_ok=True)
output_file = output_dir + '/' + patch_dprintf_file
print("The dprintf info store into the " + output_file)
# get prompt from prompt.json
prompt = get_prompt('dprintf', 'attack')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(code = code))
print(response)
# judge whether the program exists dprintf format string vulnerability
print("response info : " + response[:4].lower())
if 'yes' not in response[:4].lower():
return
# store the relevant information into INPUT_DIR + "patch_dprintf.json"
data = {
"file_path": file_name,
"vul_info": response[4:] # set response[4:] to skip string "yes, "
}
if not os.path.exists(output_file):
with open(output_file, 'w') as w:
json.dump([], w, indent=4)
with open(output_file, 'r') as r:
log = json.load(r)
assert (isinstance(log, list))
# insert relevant vulnerability info into json file
log.append(data)
with open(output_file, 'w') as w:
json.dump(log, w, indent=4)
# invoke patch api here
output_dir = FINAL_OUT_DIR + '/' + elf_file + '_patch'
os.makedirs(output_dir, exist_ok=True)
lief_binary, pwn_binary = load_binary_file_information(INIT_IN_DIR + '/' + elf_file)
patch_dprintf(lief_binary, output_dir + '/' + elf_file)
def handle_recv(file_name: str, code: str, elf_file: str, patch_recv_file: str = 'patch_recv.json'):
if 'recv' not in code:
return
print("begin to test recv in {file_name}.".format(file_name = file_name))
# generate output file
output_dir = OUT_DIR + '/' + file_name[:-2]
os.makedirs(output_dir, exist_ok=True)
output_file = output_dir + '/' + patch_recv_file
print("The recv info store into the " + output_file)
# get prompt from prompt.json
prompt = get_prompt('recv', 'attack')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(code = code))
print(response)
# judge whether the program exists buffer overflow vulnerability due to recv func
print("response info : " + response[:4].lower())
if 'yes' not in response[:4].lower():
return
# store the relevant information into INPUT_DIR + "patch_recv.json"
data = {
"file_name": file_name,
"vul_info": response[4:] # set response[4:] to skip string "yes, "
}
# determine the specific size to fix recv func
# get patch prompt for recv
prompt = get_prompt('recv', 'patch')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(code = code))
print(response)
# record modified size
match = re.search(r'size=(\d+)', response)
data['fix_size'] = int(match.group(1))
match = re.search(r',\s*(.*)', response)
data['patch_info'] = match.group(1)
if not os.path.exists(output_file):
with open(output_file, 'w') as w:
json.dump([], w, indent=4)
with open(output_file, 'r') as r:
log = json.load(r)
assert (isinstance(log, list))
# insert relevant vulnerability info into json file
log.append(data)
with open(output_file, 'w') as w:
json.dump(log, w, indent=4)
# invoke patch api here
output_dir = FINAL_OUT_DIR + '/' + elf_file + '_patch'
os.makedirs(output_dir, exist_ok=True)
lief_binary, pwn_binary = load_binary_file_information(INIT_IN_DIR + '/' + elf_file)
patch_recv(lief_binary, data['fix_size'], output_dir + '/' + elf_file)
def handle_strcpy(file_name: str, code: str, elf_file: str, struct_data: str, patch_strcpy_file: str = 'patch_strcpy.json'):
if 'strcpy' not in code:
return
print("begin to test strcpy in {file_name}.".format(file_name = file_name))
# generate output file
output_dir = OUT_DIR + '/' + file_name[:-2]
os.makedirs(output_dir, exist_ok=True)
output_file = output_dir + '/' + patch_strcpy_file
print("The recv info store into the " + output_file)
# get prompt from prompt.json
prompt = get_prompt('strcpy', 'attack')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(code = code))
print(response)
# judge whether the program exists buffer overflow vulnerability due to strcpy func
print("response info : " + response[:4].lower())
if 'yes' not in response[:4].lower():
return
# store the relevant information into INPUT_DIR + "strcpy.json"
data = {
"file_name": file_name,
"vul_info": response[4:] # set response[4:] to skip string "yes, "
}
# determine the specific size to fix strcpy func
# get patch prompt for strcpy
prompt = get_prompt('strcpy', 'struct')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(struct_data = struct_data))
print(response)
prompt = get_prompt('strcpy', 'patch')
assert (prompt)
q = QueryChatGPT()
response = q.query(prompt['content'].format(code = code))
print(response)
# record modified size
match = re.search(r'size=(\d+)', response)
data['fix_size'] = int(match.group(1))
match = re.search(r',\s*(.*)', response)
data['patch_info'] = match.group(1)
if not os.path.exists(output_file):
with open(output_file, 'w') as w:
json.dump([], w, indent=4)
with open(output_file, 'r') as r:
log = json.load(r)
assert (isinstance(log, list))
# insert relevant vulnerability info into json file
log.append(data)
with open(output_file, 'w') as w:
json.dump(log, w, indent=4)
# invoke patch api here
output_dir = FINAL_OUT_DIR + '/' + elf_file + '_patch'
os.makedirs(output_dir, exist_ok=True)
lief_binary, pwn_binary = load_binary_file_information(INIT_IN_DIR + '/' + elf_file)
patch_strcpy(lief_binary, data['fix_size'], output_dir + '/' + elf_file)
def exp():
print("Trying to test function normally")
# print arguments
print(sys.argv)
elf_file = sys.argv[1]
extract_args = ["python3", "test.py", "-e"]
extract_args.append(IDAT64_PATH)
extract_args.append(INIT_IN_DIR + '/' + elf_file)
print(extract_args)
# extract c_code & struct_info for patch elf file
os.chdir("./Extract_code")
subprocess.run(extract_args, text=True)
os.chdir(os.pardir)
code_file = elf_file + '_extract.c'
struct_file = elf_file + '_struct.json'
# # read code which will be used to analyze by LLM
code = read_decompile_code(IN_DIR + "/" + code_file)
struct_data = read_struct_data(IN_DIR + "/" + struct_file)
# read danger_func.json to determine the scope of the func checked
with open(DANGER_FUNC, 'r') as f:
d_func = json.load(f)
assert(d_func)
for _d in d_func:
if _d['name'] == 'recv':
handle_recv(code_file, code, elf_file)
elif _d['name'] == 'dprintf':
handle_dprintf(code_file, code, elf_file)
elif _d['name'] == 'strcpy':
handle_strcpy(code_file, code, elf_file, struct_data)
if __name__ == '__main__':
if not llm_configured():
print('please complete llm access setup first...')
exit()
exp()

179
src/binary_patch.py Normal file
View File

@@ -0,0 +1,179 @@
#!/usr/bin/python3
import lief
from pwn import *
import os
import sys
global lief_ELF_ALLOC
lief_ELF_ALLOC = 2
global lief_ELF_EXCLUDE
lief_ELF_EXECINSTR = 4
def get_binary_file_CLASS(binary, output_info=True):
CLASS = CLASS = binary.header.identity_class
str_CLASS = ""
if CLASS == binary.header.CLASS.ELF32:
str_CLASS = "ELF32"
elif CLASS == binary.header.CLASS.ELF64:
str_CLASS = "ELF64"
else:
str_CLASS = "UNKNOWN"
if output_info:
print("[\033[1;34m*\033[0m] CLASS is %s" % (str_CLASS))
return (CLASS, str_CLASS)
def get_binary_file_machine_type(binary, output_info=True):
machine_type = binary.header.machine_type
str_machine_type = ""
arch = ""
if machine_type == lief._lief.ELF.ARCH.X86_64:
str_machine_type = "x86_64"
arch = "amd64"
else:
str_machine_type = "UNKNOWN"
arch = "UNKNOWN"
print('[\033[1;34m*\033[0m] machine type is %s ==> ARCH : %s' % (str_machine_type, arch))
return (str_machine_type, arch)
def load_binary_file_information(path):
lief_binary = lief.parse(path)
CLASS, str_CLASS = get_binary_file_CLASS(lief_binary)
str_machine_type, arch = get_binary_file_machine_type(lief_binary)
pwn_binary = ''
context.arch = arch
if "ELF" in str_CLASS:
context.os = "linux"
pwn_binary = ELF(path)
return (lief_binary, pwn_binary)
# flag : lief.ELF.SEGMENT_FLAGS.PF_R | lief.ELF.SEGMENT_FLAGS.PF_W | lief.ELF.SEGMENT_FLAGS.PF_X
def add_segment(lief_binary, content, types, flags, base=0x405000):
segment = lief.ELF.Segment()
segment.type = types
segment.FLAGS.from_value(flags)
segment.content = list(content)
segment.alignment = 8
segment.add(lief._lief.ELF.Segment.FLAGS.R | lief._lief.ELF.Segment.FLAGS.X)
segment = lief_binary.add(segment, base=base)
print(segment.FLAGS.value)
return segment
'''
def patch_by_call(start_address_of_call, target_function_address):
# caculate the offset
jmp_offset = target_function_address - (start_address_of_call + 5)
# call + p32(jmp_offset)
'''
def patch_strcpy(lief_binary, nbytes, save_path, output=True):
print("[\033[1;34m*\033[0m] get the length of buffer is 0x%x(%d)" % (nbytes, nbytes))
patch_strcpy_code = f"""
save_register:
push rax;
push rcx;
push rdx;
xor rcx, rcx;
loop:
mov rdx, {nbytes-1};
mov al, [rcx + rsi];
cmp rcx, rdx;
jge ret_code;
test al, al;
je ret_code;
mov [rdi + rcx], al;
inc rcx;
jmp loop;
ret_code:
mov [rsi + rcx], al;
pop rdx;
pop rcx;
pop rax;
ret;
"""
patch_code = asm(patch_strcpy_code)
if output:
print("the assmebly code :\n %s" % patch_strcpy_code)
print("the machine code :\n %s" % patch_code)
new_segment = add_segment(lief_binary, types = lief._lief.ELF.Segment.TYPE.LOAD, flags = 5, content=patch_code)
lief_binary.patch_pltgot("strcpy", new_segment.virtual_address)
lief_binary.write(save_path)
os.system("chmod +x " + save_path)
# to do
def patch_dprintf(lief_binary, save_path, output=True):
patch_dprintf_code = f"""
save_register:
push rdx;
push rcx;
init_register:
push rsi;
pop rcx;
xor rdx, rdx;
get_the_buffer_len:
mov al, [rsi+rdx];
inc rdx;
test al, al;
jnz get_the_buffer_len;
xor rax, rax;
mov al, 1;
syscall;
ret_code:
pop rcx;
pop rdx;
ret;
"""
patch_code = asm(patch_dprintf_code)
if output:
print("the assmebly code :\n %s" % patch_dprintf_code)
print("the machine code :\n %s" % patch_code)
new_segment = add_segment(lief_binary, types = lief._lief.ELF.Segment.TYPE.LOAD, flags = 5, content=patch_code)
lief_binary.patch_pltgot("dprintf", new_segment.virtual_address)
lief_binary.write(save_path)
os.system("chmod +x " + save_path)
def patch_recv(lief_binary, nbytes, save_path, output=True):
patch_recv_code = f"""
mov rdx, {nbytes}
mov r10, rcx;
xor r8, r8;
xor r9, r9;
push 45;
pop rax;
syscall;
ret;
"""
patch_code = asm(patch_recv_code)
if output:
print("the assmebly code :\n %s" % patch_recv_code)
print("the machine code :\n %s" % patch_code)
new_segment = add_segment(lief_binary, types = lief._lief.ELF.Segment.TYPE.LOAD, flags = 5, content=patch_code)
lief_binary.patch_pltgot("recv", new_segment.virtual_address)
print(save_path)
lief_binary.write(save_path)
os.system("chmod +x " + save_path)
'''
designed for console command
'''
# if __name__ == '__main__':
# # # argv = sys.argv
# # # argc = len(sys.argv)
# lief_binary, pwn_binary = load_binary_file_information("../input/edit")
# print(lief_binary)
# print(pwn_binary)
# patch_strcpy(lief_binary, 256, "../output/edit_patch/edit")

106
src/chat.py Normal file
View File

@@ -0,0 +1,106 @@
"""
Interfaces to interact with various LLMs
"""
import json
import os
import atexit
import configparser
from typing import Dict, Optional, List
from openai import OpenAI
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG = os.path.join(CUR_DIR, 'config.ini')
def load_config(field: str, value: str) -> str:
config = configparser.ConfigParser()
config.read(CONFIG)
return config[field][value]
def llm_configured() -> bool:
model = load_config('LLM', 'model')
api_key = load_config('LLM', 'api_key')
api_base = load_config('LLM', 'api_base')
return bool(len(model) and len(api_key) and len(api_base))
class QueryChatGPT():
""" Interface for interacting with ChatGPT
"""
def __init__(self) -> None:
self.chat_context: List[Dict[str, str]] = []
self.chat_history: List[Dict[str, str]] = []
self.temperature:float = 0.2
self.use_history = False
self.system_prompt: Optional[str] = None
atexit.register(self.log_history)
def clear(self):
self.chat_context = []
def set_history(self, open: bool) -> None:
self.use_history = open
def insert_system_prompt(self, system_prompt: str) -> None:
""" add system_prompt in self.chat_context """
if self.chat_context and self.chat_context[0]["role"] == "system":
self.chat_context[0]['content'] = system_prompt
else:
self.chat_context.insert(0, {
"role": "system",
"content": system_prompt
})
def log_history(self, log_file: str = 'chat_log.json'):
if not os.path.exists(log_file):
with open(log_file, 'w') as w:
json.dump([], w, indent=4)
with open(log_file, 'r') as r:
log = json.load(r)
assert (isinstance(log, list))
log.append(self.chat_history)
with open(log_file, 'w') as w:
json.dump(log, w, indent=4)
def __query(self, prompt: str, model: str) -> Optional[str]:
self.chat_context.append({"role": "user", "content": prompt})
self.chat_history.append({"role": "user", "content": prompt})
client = OpenAI(api_key=load_config('LLM', 'api_key'), base_url=load_config('LLM', 'api_base'))
response = client.chat.completions.create(
messages=self.chat_context, # type: ignore
model=model,
temperature=self.temperature,
)
response_content = str(response.choices[0].message.content)
self.chat_context.append({
"role": "assistant",
"content": response_content
})
self.chat_history.append({
"role": "assistant",
"content": response_content
})
return response_content
def query(self,
prompt: str,
*,
model: str = load_config('LLM', 'model')) -> Optional[str]:
response = self.__query(prompt, model)
if not self.use_history:
self.clear()
return response

174
src/chat_log.json Normal file

File diff suppressed because one or more lines are too long

7
src/config.ini Normal file
View File

@@ -0,0 +1,7 @@
[LLM]
model = gpt-3.5-turbo
api_key = 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
api_base = https://api.openai.com/v1/
; For openai online LLMs, the default api_base is https://api.openai.com/v1/
; For local LLMs, the api_base is usually like http://ip:port/v1/

14
src/danger_func.json Normal file
View File

@@ -0,0 +1,14 @@
[
{
"type": "buffer_overflow",
"name": "strcpy"
},
{
"type": "buffer_overflow",
"name": "recv"
},
{
"type": "format_string",
"name": "dprintf"
}
]

View File

@@ -0,0 +1,81 @@
//Function: echo_handler ->0x4199190 7 perm->5
int __cdecl echo_handler(int sock)
{
char buffer[256]; // [rsp+10h] [rbp-100h] BYREF
memset(buffer, 0, sizeof(buffer));
return recv(sock, buffer, 0x100uLL, 0) > 0 && dprintf(sock, buffer) > 0;
}
//Function: main ->0x4199603 7 perm->5
int __fastcall main(int argc, const char **argv, const char **envp)
{
uint16_t v3; // ax
char client_addr_str[24]; // [rsp+0h] [rbp-40h] BYREF
int addrlen; // [rsp+18h] [rbp-28h] BYREF
int opt; // [rsp+1Ch] [rbp-24h] BYREF
sockaddr_in address; // [rsp+20h] [rbp-20h] BYREF
int new_socket; // [rsp+38h] [rbp-8h]
int server_fd; // [rsp+3Ch] [rbp-4h]
opt = 1;
addrlen = 16;
server_fd = socket(2, 1, 0);
if ( !server_fd )
{
perror("socket failed");
exit(1);
}
if ( setsockopt(server_fd, 1, 15, &opt, 4u) )
{
perror("setsockopt");
exit(1);
}
address.sin_family = 2;
address.sin_addr.s_addr = 0;
address.sin_port = htons(0x2B00u);
if ( bind(server_fd, (const struct sockaddr *)&address, 0x10u) < 0 )
{
perror("bind failed");
exit(1);
}
if ( listen(server_fd, 3) < 0 )
{
perror("listen");
exit(1);
}
printf("TCP server listening on port %d\n", 11008);
new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
if ( new_socket < 0 )
{
perror("accept");
exit(1);
}
inet_ntop(2, &address.sin_addr, client_addr_str, 0x10u);
v3 = ntohs(address.sin_port);
printf("Accept %s:%d\n", client_addr_str, v3);
while ( echo_handler(new_socket) )
;
close(new_socket);
return 0;
}
//Function: backdoor ->0x4200059 7 perm->5
int __cdecl backdoor()
{
char *new_envp[2]; // [rsp+0h] [rbp-20h] BYREF
char *new_argv[2]; // [rsp+10h] [rbp-10h] BYREF
new_argv[1] = 0LL;
new_envp[0] = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
new_envp[1] = 0LL;
dup2(4, 0);
dup2(4, 1);
dup2(4, 2);
execve("/bin/sh", new_argv, new_envp);
return 0;
}

View File

@@ -0,0 +1,27 @@
[
{
"name": "in6_addr",
"size": "0x10",
"info": "struct {in6_addr::$B80A5568EDCB3DEA112C17957211D170 __in6_u;}"
},
{
"name": "in_addr",
"size": "0x4",
"info": "struct {in_addr_t s_addr;}"
},
{
"name": "sockaddr_in6",
"size": "0x1c",
"info": "struct {sa_family_t sin6_family;in_port_t sin6_port;uint32_t sin6_flowinfo;in6_addr sin6_addr;uint32_t sin6_scope_id;}"
},
{
"name": "sockaddr_in",
"size": "0x10",
"info": "struct {sa_family_t sin_family;in_port_t sin_port;in_addr sin_addr;unsigned __int8 sin_zero[8];}"
},
{
"name": "sockaddr",
"size": "0x10",
"info": "struct {sa_family_t sa_family;char sa_data[14];}"
}
]

188
src/input/edit_extract.c Normal file
View File

@@ -0,0 +1,188 @@
//Function: add ->0x4199478 7 perm->5
void __cdecl add(char *str)
{
Node *newNode; // [rsp+18h] [rbp-8h]
newNode = (Node *)malloc(0x108uLL);
strcpy(newNode->data, str);
newNode->next = head;
head = newNode;
}
//Function: delete ->0x4199559 7 perm->5
void __cdecl delete(char *str)
{
Node *entry; // [rsp+10h] [rbp-10h]
Node **current; // [rsp+18h] [rbp-8h]
for ( current = &head; *current; current = &entry->next )
{
entry = *current;
if ( !strcmp((*current)->data, str) )
{
*current = entry->next;
free(entry);
return;
}
}
}
//Function: edit ->0x4199684 7 perm->5
void __cdecl edit(char *oldStr, char *newStr)
{
Node *current; // [rsp+18h] [rbp-8h]
for ( current = head; current; current = current->next )
{
if ( !strcmp(current->data, oldStr) )
{
strcpy(current->data, newStr);
return;
}
}
}
//Function: show ->0x4199787 7 perm->5
void __cdecl show(int client_sock)
{
size_t v1; // rax
char buffer[1032]; // [rsp+10h] [rbp-410h] BYREF
Node *current; // [rsp+418h] [rbp-8h]
for ( current = head; current; current = current->next )
{
snprintf(buffer, 0x400uLL, "%s\n", current->data);
v1 = strlen(buffer);
send(client_sock, buffer, v1, 0);
}
}
//Function: main ->0x4199929 7 perm->5
int __fastcall __noreturn main(int argc, const char **argv, const char **envp)
{
int opt; // [rsp+Ch] [rbp-C44h] BYREF
char arg2[1024]; // [rsp+10h] [rbp-C40h] BYREF
char arg1[1035]; // [rsp+410h] [rbp-840h] BYREF
char command[5]; // [rsp+81Bh] [rbp-435h] BYREF
char buffer[1024]; // [rsp+820h] [rbp-430h] BYREF
int addrlen; // [rsp+C2Ch] [rbp-24h] BYREF
sockaddr_in address; // [rsp+C30h] [rbp-20h] BYREF
int new_socket; // [rsp+C48h] [rbp-8h]
int server_fd; // [rsp+C4Ch] [rbp-4h]
addrlen = 16;
memset(buffer, 0, sizeof(buffer));
opt = 1;
server_fd = socket(2, 1, 0);
if ( !server_fd )
{
perror("socket failed");
exit(1);
}
if ( setsockopt(server_fd, 1, 15, &opt, 4u) )
{
perror("setsockopt");
exit(1);
}
address.sin_family = 2;
address.sin_addr.s_addr = 0;
address.sin_port = htons(0x2B04u);
if ( bind(server_fd, (const struct sockaddr *)&address, 0x10u) < 0 )
{
perror("bind failed");
exit(1);
}
if ( listen(server_fd, 3) < 0 )
{
perror("listen");
exit(1);
}
printf("Server listening on port %d\n", 11012);
while ( 1 )
{
new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
if ( new_socket < 0 )
break;
read(new_socket, buffer, 0x400uLL);
memset(command, 0, sizeof(command));
memset(arg1, 0, 0x400uLL);
memset(arg2, 0, sizeof(arg2));
__isoc99_sscanf(buffer, "%4s %1023s %1023s", command, arg1, arg2);
if ( !strcmp(command, "ADD") )
{
add(arg1);
}
else if ( !strcmp(command, "DEL") )
{
delete(arg1);
}
else if ( !strcmp(command, "EDIT") )
{
edit(arg1, arg2);
}
else if ( !strcmp(command, "SHOW") )
{
show(new_socket);
}
else
{
puts("Unknown command.");
}
close(new_socket);
}
perror("accept");
exit(1);
}
//Function: backdoor ->0x4200706 7 perm->5
int __cdecl backdoor()
{
char *new_envp[2]; // [rsp+0h] [rbp-40h] BYREF
char *new_argv[2]; // [rsp+10h] [rbp-30h] BYREF
sockaddr_in serv_addr; // [rsp+20h] [rbp-20h] BYREF
int sock; // [rsp+3Ch] [rbp-4h]
new_argv[0] = "/bin/sh";
new_argv[1] = 0LL;
new_envp[0] = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
new_envp[1] = 0LL;
sock = socket(2, 1, 0);
if ( sock >= 0 )
{
serv_addr.sin_family = 2;
serv_addr.sin_port = htons(0x2EECu);
if ( inet_pton(2, "127.0.0.1", &serv_addr.sin_addr) > 0 )
{
if ( connect(sock, (const struct sockaddr *)&serv_addr, 0x10u) >= 0 )
{
dup2(sock, 0);
dup2(sock, 1);
dup2(sock, 2);
execve(new_argv[0], new_argv, new_envp);
return 0;
}
else
{
puts("\nConnection Failed ");
return -1;
}
}
else
{
puts("\nInvalid address/ Address not supported ");
return -1;
}
}
else
{
puts("\n Socket creation error ");
return -1;
}
}

View File

@@ -0,0 +1,32 @@
[
{
"name": "in6_addr",
"size": "0x10",
"info": "struct {in6_addr::$B80A5568EDCB3DEA112C17957211D170 __in6_u;}"
},
{
"name": "in_addr",
"size": "0x4",
"info": "struct {in_addr_t s_addr;}"
},
{
"name": "sockaddr_in6",
"size": "0x1c",
"info": "struct {sa_family_t sin6_family;in_port_t sin6_port;uint32_t sin6_flowinfo;in6_addr sin6_addr;uint32_t sin6_scope_id;}"
},
{
"name": "sockaddr_in",
"size": "0x10",
"info": "struct {sa_family_t sin_family;in_port_t sin_port;in_addr sin_addr;unsigned __int8 sin_zero[8];}"
},
{
"name": "sockaddr",
"size": "0x10",
"info": "struct {sa_family_t sa_family;char sa_data[14];}"
},
{
"name": "Node",
"size": "0x108",
"info": "struct {char data[256];Node *next;}"
}
]

87
src/input/recv_extract.c Normal file
View File

@@ -0,0 +1,87 @@
//Function: echo_handler ->0x4199222 7 perm->5
int __cdecl echo_handler(int sock)
{
char buffer[256]; // [rsp+10h] [rbp-100h] BYREF
memset(buffer, 0, sizeof(buffer));
if ( recv(sock, buffer, 0x400uLL, 0) <= 0 )
return 0;
printf("Message from client: %s\n", buffer);
if ( send(sock, "Hello from server\n", 0x12uLL, 0) <= 0 )
return 0;
puts("Hello message sent");
return 1;
}
//Function: main ->0x4199683 7 perm->5
int __fastcall main(int argc, const char **argv, const char **envp)
{
uint16_t v3; // ax
char client_addr_str[24]; // [rsp+0h] [rbp-40h] BYREF
int addrlen; // [rsp+18h] [rbp-28h] BYREF
int opt; // [rsp+1Ch] [rbp-24h] BYREF
sockaddr_in address; // [rsp+20h] [rbp-20h] BYREF
int new_socket; // [rsp+38h] [rbp-8h]
int server_fd; // [rsp+3Ch] [rbp-4h]
opt = 1;
addrlen = 16;
server_fd = socket(2, 1, 0);
if ( !server_fd )
{
perror("socket failed");
exit(1);
}
if ( setsockopt(server_fd, 1, 15, &opt, 4u) )
{
perror("setsockopt");
exit(1);
}
address.sin_family = 2;
address.sin_addr.s_addr = 0;
address.sin_port = htons(0x2AFFu);
if ( bind(server_fd, (const struct sockaddr *)&address, 0x10u) < 0 )
{
perror("bind failed");
exit(1);
}
if ( listen(server_fd, 3) < 0 )
{
perror("listen");
exit(1);
}
printf("TCP server listening on port %d\n", 11007);
new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen);
if ( new_socket < 0 )
{
perror("accept");
exit(1);
}
inet_ntop(2, &address.sin_addr, client_addr_str, 0x10u);
v3 = ntohs(address.sin_port);
printf("Accept %s:%d\n", client_addr_str, v3);
while ( echo_handler(new_socket) )
;
close(new_socket);
return 0;
}
//Function: backdoor ->0x4200139 7 perm->5
int __cdecl backdoor()
{
char *new_envp[2]; // [rsp+0h] [rbp-20h] BYREF
char *new_argv[2]; // [rsp+10h] [rbp-10h] BYREF
new_argv[1] = 0LL;
new_envp[0] = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
new_envp[1] = 0LL;
dup2(4, 0);
dup2(4, 1);
dup2(4, 2);
execve("/bin/sh", new_argv, new_envp);
return 0;
}

View File

@@ -0,0 +1,27 @@
[
{
"name": "in6_addr",
"size": "0x10",
"info": "struct {in6_addr::$B80A5568EDCB3DEA112C17957211D170 __in6_u;}"
},
{
"name": "in_addr",
"size": "0x4",
"info": "struct {in_addr_t s_addr;}"
},
{
"name": "sockaddr_in6",
"size": "0x1c",
"info": "struct {sa_family_t sin6_family;in_port_t sin6_port;uint32_t sin6_flowinfo;in6_addr sin6_addr;uint32_t sin6_scope_id;}"
},
{
"name": "sockaddr_in",
"size": "0x10",
"info": "struct {sa_family_t sin_family;in_port_t sin_port;in_addr sin_addr;unsigned __int8 sin_zero[8];}"
},
{
"name": "sockaddr",
"size": "0x10",
"info": "struct {sa_family_t sa_family;char sa_data[14];}"
}
]

4
src/my.log Normal file
View File

@@ -0,0 +1,4 @@
Extract_Functions /root/Program/input/dprintf-> Command '/root/idapro-9.0/idat64 -A -B -S"interface_extract.py" /root/Program/input/dprintf
' returned non-zero exit status 1.
Extract_Functions /root/Program/input/dprintf-> Command '/root/idapro-9.0/idat64 -A -B -S"interface_extract.py" /root/Program/input/dprintf
' returned non-zero exit status 1.

View File

@@ -0,0 +1,46 @@
[
{
"file_path": "/root/LLM_prompt/output//dprintf_extract/patch_dprintf.json",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is being passed as the format string to the dprintf function without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is being passed as the format string to dprintf without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is passed as the format string to the dprintf function without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is being passed as the format string to dprintf without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is directly passed as the format string to the dprintf function without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is passed as the format string to the dprintf function without proper formatting. This can lead to a format string vulnerability, allowing an attacker to potentially read or write arbitrary memory locations."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is passed as the format string to dprintf without proper formatting. This can potentially lead to a format string attack."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is being passed as the format string to the dprintf function without proper formatting. This can potentially lead to a format string vulnerability."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " there is a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer variable is directly passed as the format string to the dprintf function without any format specifier. This can potentially lead to a format string vulnerability if an attacker controls the input in the buffer variable."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " the program contains a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer variable is directly passed as the format string to the dprintf function without proper formatting. This can allow an attacker to exploit the format string vulnerability and potentially execute arbitrary code."
},
{
"file_path": "dprintf_extract.c",
"vul_info": " the program contains a dprintf format string vulnerability in the echo_handler function. The vulnerability lies in the line `dprintf(sock, buffer)`, where the buffer is directly passed as the format string to the dprintf function without proper formatting. This can potentially lead to a format string vulnerability if an attacker can control the contents of the buffer."
}
]

View File

@@ -0,0 +1,80 @@
[
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before writing data to it. The buffer size is 256 bytes, but the recv function is writing up to 0x100 bytes (256 bytes) to the buffer, which can lead to a buffer overflow vulnerability.",
"fix_size": 248,
"patch_info": "In the echo_handler function, the buffer size is 256 bytes, but only 248 bytes are being used for the recv function (starting from buffer[8]). This leaves 8 bytes unused, which could potentially lead to a buffer overflow if the recv function receives more than 248 bytes of data. To ensure the program works safely, the recv function should be prepared to receive a maximum of 248 bytes of data."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before writing data to it. This can lead to a buffer overflow vulnerability if the data received is larger than the size of the buffer (256 bytes). An attacker could potentially exploit this vulnerability to overwrite memory beyond the buffer and execute arbitrary code.",
"fix_size": 248,
"patch_info": "In the echo_handler function, the buffer size is 256 bytes. However, only 248 bytes are being used for the recv function (buffer[8] to buffer[255]). This leaves 8 bytes at the beginning of the buffer unused, which could potentially lead to a buffer overflow if the recv function receives more than 248 bytes of data."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being used. It receives data into the buffer starting from index 8, which could potentially lead to a buffer overflow if the received data is larger than the allocated buffer size.",
"fix_size": 248,
"patch_info": "The buffer size should be 248 bytes to account for the 8 bytes offset in the buffer index (&buffer[8]) in the recv function call. This will prevent buffer overflow and ensure the program works safely."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being passed to it. It receives data into the buffer starting from index 8, which could potentially lead to a buffer overflow if more data than the allocated buffer size is received.",
"fix_size": 248,
"patch_info": "The buffer size should be 248 bytes to account for the 8 bytes offset in the buffer array. This will prevent buffer overflow when using recv."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being passed to it, which can lead to a buffer overflow if the data received is larger than the buffer size of 256 bytes. This can potentially overwrite adjacent memory locations and lead to security vulnerabilities.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space for the received data and to prevent buffer overflow. The buffer size is set to 256 in the code, but since strings in C are null-terminated, the last byte should be reserved for the null terminator."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function reads up to 256 bytes into the buffer array, which is only 256 bytes in size. If more than 256 bytes are received, a buffer overflow could occur, leading to potential security vulnerabilities.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space for the received data and to prevent buffer overflow. The buffer size is set to 256 in the code, but since strings in C are null-terminated, the last byte should be reserved for the null terminator."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function reads data into the buffer array without checking the size of the data being received. This can lead to a buffer overflow if the data received is larger than the size of the buffer (256 bytes).",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space for the received data and to prevent buffer overflow. The buffer size is set to 256 in the code, but since strings in C are null-terminated, the last byte should be reserved for the null terminator."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " the program contains a risk of buffer overflow in the recv function. \n\nThe recv function is called with the buffer array as the second argument and a size of 0x100uLL (256 in decimal) as the third argument. However, the buffer array is only 256 bytes in size, which means that if more than 256 bytes are received from the socket, a buffer overflow could occur.\n\nTo mitigate this risk, the size of the buffer should be increased to accommodate the maximum amount of data that could be received from the socket.",
"fix_size": 255,
"patch_info": "The buffer size is declared as 256 bytes, so the maximum size for recv should be 255 to prevent buffer overflow. This leaves one byte for the null terminator."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function reads up to 256 bytes into the buffer variable, which is only allocated 256 bytes of space. This means that if more than 256 bytes are received, a buffer overflow could occur.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to account for the null terminator at the end of the buffer. This ensures that there is enough space to store the received data without causing a buffer overflow."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the input buffer before reading data into it, which can lead to a buffer overflow vulnerability. The buffer size is defined as 256 bytes, but the recv function reads up to 0x100 bytes (256 bytes) into the buffer without checking if the input data exceeds the buffer size. This can potentially overwrite adjacent memory locations and lead to a buffer overflow.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space to store the received data from the socket without causing a buffer overflow. The buffer size of 256 in the code snippet leaves only 1 byte for the null terminator, which may not be sufficient to prevent buffer overflow."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " the program contains the risk of buffer overflow in the recv function. The recv function is used to receive data from a socket into the buffer array, but the size of the buffer is fixed at 256 bytes. If the data received from the socket is larger than 256 bytes, it can lead to a buffer overflow vulnerability.",
"fix_size": 255,
"patch_info": "The buffer size in the echo_handler function is 256 bytes, so the maximum size for recv should be 255 bytes to prevent buffer overflow. This leaves one byte for the null terminator."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function reads up to 256 bytes into the buffer array, which is only allocated 256 bytes. This means that if more than 256 bytes are received, a buffer overflow can occur.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space for the received data as recv function reads up to the specified size - 1 bytes and adds a null terminator at the end. This prevents buffer overflow and ensures the program works safely."
},
{
"file_name": "dprintf_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being passed to it, which can lead to a buffer overflow if the data received is larger than the buffer size of 256 bytes.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space to store the received data without causing a buffer overflow. The buffer size is set to 256 in the code, but since strings in C are null-terminated, only 255 characters can be safely stored in the buffer to prevent overflow."
}
]

View File

@@ -0,0 +1,68 @@
[
{
"file_name": "edit_extract.c",
"vul_info": " strcpy used in the add function poses a risk of buffer overflow. The strcpy function is copying the input string 'str' into the 'data' field of the 'Node' structure without checking the length of the input string. This can lead to a buffer overflow if the input string is larger than the allocated size of 'data' in the 'Node' structure.",
"fix_size": 0,
"patch_info": "The size should be set to 0x107 because the Node struct contains a data field of size 0x108, and strncpy should only copy up to the specified size minus 1 to ensure that the null terminator is included."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the 'add' and 'edit' functions without checking the length of the input string 'str' against the size of the destination buffer 'newNode->data'. This can lead to buffer overflow if the input string is larger than the size of the destination buffer.",
"fix_size": 4131,
"patch_info": "The size of strncpy should be set to 1023 because the maximum length of the input string in the add function is 1023 characters. This ensures that the strncpy function does not exceed the allocated memory for the data field in the Node structure."
},
{
"file_name": "edit_extract.c",
"vul_info": " strcpy used in the add function poses a risk of buffer overflow. The strcpy function is copying the input string 'str' into the 'data' field of the 'newNode' structure without checking the length of the input string. This can lead to a buffer overflow if the input string is larger than the allocated memory for 'data' in the 'newNode' structure.",
"fix_size": 598,
"patch_info": "The size of strncpy should be set to 256 because the maximum length of the data in the Node struct is 256 bytes (0x100uLL). This ensures that the strncpy function does not exceed the allocated memory for the data field in the Node struct."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the 'add' function without checking the length of the input string 'str' before copying it into 'newNode->data'. This can lead to a buffer overflow if the input string is larger than the allocated memory for 'newNode->data'.",
"fix_size": 256,
"patch_info": "Reason: The maximum length of the data field in the Node struct is 256 bytes (0x100uLL), so the size for strncpy should be set to 256 to ensure that the data is properly copied without exceeding the allocated memory space."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the 'add' and 'edit' functions without checking the length of the input string 'str' against the size of the destination buffer 'newNode->data'. This can lead to buffer overflow if the input string is larger than the destination buffer size.",
"fix_size": 256,
"patch_info": "The maximum size of the data field in the Node struct is 256 bytes (0x100uLL), so the strncpy should be set to this size to ensure that the data is not truncated or overwritten."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function used in the 'add' function can potentially lead to a buffer overflow if the input string 'str' is larger than the allocated size of 'newNode->data'. This can result in overwriting adjacent memory locations and potentially lead to a security vulnerability.",
"fix_size": 256,
"patch_info": "The size for strncpy should be set to 256 because the maximum length of the data field in the Node struct is 256 bytes (0x100uLL). Using strncpy with a size of 256 ensures that the data is copied correctly without exceeding the allocated memory for the data field in the Node struct."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the \"add\" function without checking the length of the input string 'str' before copying it into the 'data' field of the 'newNode' struct. This can lead to a buffer overflow if the input string is larger than the allocated memory for 'data'.",
"fix_size": 0,
"patch_info": "The size should be set to 0x107 because the data field in the Node struct is of size 0x108, and strncpy should not copy the null terminator. Therefore, setting the size to 0x107 ensures that the entire data field is copied without including the null terminator."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the \"add\" function to copy the input string into the \"data\" field of the Node struct without checking the length of the input string. This can lead to a buffer overflow if the input string is longer than the allocated space for the \"data\" field.",
"fix_size": 1023,
"patch_info": "The size of strncpy should be set to 1023 because the maximum length of the input string 'arg1' in the main function is 1023 characters. This ensures that the strncpy function does not exceed the allocated buffer size and prevents buffer overflow vulnerabilities."
},
{
"file_name": "edit_extract.c",
"vul_info": " strcpy used in the add function poses a risk of buffer overflow. The strcpy function is copying the input string 'str' into the 'data' field of the 'newNode' struct without checking the length of the input string. This can lead to a buffer overflow if the input string is larger than the allocated memory for 'data' in the 'newNode' struct.",
"fix_size": 0,
"patch_info": "The size should be set to 0x107(decimal) for strncpy in order to replace strcpy. This is because the size of the data field in the Node struct is 0x108uLL, and strncpy should copy up to one less byte than the total size of the data field to prevent buffer overflow."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the \"add\" function without checking the length of the input string \"str\" before copying it into the \"data\" field of the \"newNode\" struct. This can lead to a buffer overflow if the input string is larger than the allocated memory for \"data\".",
"fix_size": 1023,
"patch_info": "The maximum length of the string that can be passed to the add function is 1023 characters based on the buffer size of arg1 in the main function. Therefore, the size for strncpy should be set to 1023 to ensure that the entire string is copied without exceeding the buffer size."
},
{
"file_name": "edit_extract.c",
"vul_info": " there is a strcpy vulnerability in the code. The strcpy function is used in the \"add\" function without checking the length of the input string \"str\" before copying it into the \"newNode->data\" buffer. This can lead to a buffer overflow if the input string is longer than the buffer size allocated for \"newNode->data\".",
"fix_size": 1023,
"patch_info": "The maximum size of the input string for the add function is 1023 characters, so the size for strncpy should be set to 1023 to ensure that the entire input string is copied without exceeding the buffer size."
}
]

View File

@@ -0,0 +1,44 @@
[
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before writing data to it, which can lead to a buffer overflow vulnerability. The buffer size is 256 bytes, but the recv function is writing data starting from buffer[8], potentially allowing for more data to be written than the buffer can hold.",
"fix_size": 256,
"patch_info": "In the echo_handler function, the buffer size is set to 256 bytes. Therefore, when using recv to receive data from the socket, the program should be prepared to handle up to 256 bytes of data to prevent buffer overflow."
},
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being passed to it. It receives data into the buffer starting from index 8, which could potentially lead to a buffer overflow if the received data is larger than the allocated buffer size.",
"fix_size": 256,
"patch_info": "In the echo_handler function, the buffer size is set to 256 bytes. Therefore, when using recv to receive data from the socket, the program should be prepared to handle up to 256 bytes of data to prevent buffer overflow."
},
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before copying data into it, which can lead to a buffer overflow vulnerability. The buffer size is 256 bytes, but the recv function is copying data into buffer starting from index 8, potentially allowing more data to be copied than the buffer can hold.",
"fix_size": 256,
"patch_info": "In the echo_handler function, the buffer size is set to 256 bytes. Therefore, when using recv to receive data from the socket, the program should be prepared to handle up to 256 bytes of data to avoid buffer overflow."
},
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before copying data into it. This can lead to a buffer overflow vulnerability if the data received is larger than the size of the buffer (256 bytes). An attacker could potentially exploit this vulnerability to overwrite memory beyond the buffer and execute malicious code.",
"fix_size": 248,
"patch_info": "The buffer size should be reduced by 8 to account for the offset used in recv to prevent buffer overflow."
},
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before copying data into it, which can lead to a buffer overflow vulnerability. The buffer size is 256 bytes, but the recv function is copying up to 0x400 bytes into the buffer starting from index 8, potentially overwriting memory beyond the buffer boundaries.",
"fix_size": 248,
"patch_info": "The buffer size should be reduced by 8 bytes to account for the offset of 8 in the recv function call. This will prevent buffer overflow and ensure the program works safely."
},
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer being passed to it, which can lead to a buffer overflow vulnerability if the data received is larger than the buffer size of 256 bytes.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space to store the received data from the client without causing a buffer overflow. The buffer size should always be one less than the actual size to account for the null terminator."
},
{
"file_name": "recv_extract.c",
"vul_info": " the program contains a risk of buffer overflow in the recv function. The recv function is called with a buffer size of 0x400 (1024 bytes), but the buffer allocated in the echo_handler function is only 256 bytes. This means that if the recv function receives more than 256 bytes of data, it will overflow the buffer and potentially overwrite other memory areas.",
"fix_size": 255,
"patch_info": "The buffer size should be set to 255 to ensure that there is enough space for the received data plus a null terminator. This will prevent buffer overflow and ensure the program works safely."
}
]

View File

@@ -0,0 +1,8 @@
[
{
"file_name": "recv_extract.c",
"vul_info": " reason: The recv function in the echo_handler function does not check the size of the buffer before writing data to it, which can lead to a buffer overflow vulnerability. The buffer size is 256 bytes, but the recv function is writing data starting from buffer[8], potentially allowing for more data to be written than the buffer can hold.",
"fix_size": 248,
"patch_info": "The buffer size should be reduced by 8 bytes to account for the offset used in recv function (&buffer[8]). This will prevent buffer overflow and ensure the program works safely."
}
]

50
src/prompt.json Normal file
View File

@@ -0,0 +1,50 @@
[
{
"type": "attack",
"name": "dprintf",
"prompt": {
"role": "user",
"content": "Please analyze whether the following program contains a dprintf format string vulnerability. If you find dprintf format string vulnerability please answer with 'yes, reason here'.\n{code}"
}
},
{
"type": "attack",
"name": "strcpy",
"prompt": {
"role": "user",
"content": "Please analyze the following code to determine if the strcpy used in the program poses a risk of buffer overflow. If it actually exists then answer with 'yes, reason here', or else output 'no strcpy vulnerability'.\n{code}"
}
},
{
"type": "struct",
"name": "strcpy",
"prompt": {
"role": "user",
"content": "Here are some specific struct information that may be useful for my later questions. It should be noted that the pointer next size is 8 bytes.\n{struct_data}"
}
},
{
"type": "patch",
"name": "strcpy",
"prompt": {
"role": "user",
"content": "According to struct Node info determine how many size should I set for strncpy which will be used to replace strcpy and only consider add function. Answer with 'size=value(decimal), ', and then give me the reason.\n{code}"
}
},
{
"type": "attack",
"name": "recv",
"prompt": {
"role": "user",
"content": "Please analyze whether the following program contains the risk of buffer overflow and only check recv function. If it actually exists then answer with 'yes, reason here', or else output 'no recv vulnerability'.\n{code}"
}
},
{
"type": "patch",
"name": "recv",
"prompt": {
"role": "user",
"content": "There is a risk of buffer overflow when using recv in the program. Please tell me the specific size be prepared for recv to ensure the program work safely. Answer with 'size=value, ', and then give me the reason.\n{code}"
}
}
]

69
src/prompt.py Normal file
View File

@@ -0,0 +1,69 @@
"""
This script is designed for editing the bare query
bare query - questions or information that inspire
ChatGPT to understand the program deeply instead of
caring about the response of ChatGPT
{
'type': 'bare_query',
'name': 'XXX',
'prompt': {
'role': 'user',
'content': 'You should provide programming advice.',
}
}
"""
import os
import json
BPATH = os.path.dirname(os.path.abspath(__file__))
BPATH = os.path.join(BPATH, 'prompt.json')
print(BPATH)
assert(os.path.exists(BPATH))
with open(BPATH, 'r') as r:
lst = json.load(r)
while True:
choice = input('1. list 2. add new 3. keyword-based search 4. delete 5. exit: ')
if choice == '1':
print('\n-----------------')
for _id, _query in enumerate(lst):
_type = _query['type']
_name = _type
if 'name' in _query.keys():
_name = _query['name']
print(_id, f': ({_type}) ({_name})', repr(_query['prompt']['content']))
elif choice == '2':
_type = input('Input your query type:')
_name = input('Input your query name (use type as default):')
if not _name:
_name = _typeprompt
_query = input('Input your query content:')
new_entry = {
'type': _type,
'name': _name,
'prompt': {
'role': 'user',
'content': _query,
}
}
lst.append(new_entry)
elif choice == '3':
k = input('Input your keyword:')
for _id, _query in enumerate(lst):
_c = _query['prompt']['content']
if k in _c:
print(_id, ':', _c)
elif choice == '4':
i = input('Input the id of deleted enetry:')
lst.pop(int(i))
elif choice == '5':
with open(BPATH, 'w') as w:
json.dump(lst, w, indent=4)
exit(0)
else:
pass

1
src/tmp.txt Normal file
View File

@@ -0,0 +1 @@
/root/Program/input/dprintf