TCP Packets Syntax Error - python-3.x

I am having issues with a syntax error I can't seem to solve. I am trying to reassemble a tcp packet after a checksum.
def reassemble_tcp_feilds(self):
self.raw = struct.pack('!HHLLBBH',
self.tcp_src,
self.tcp_dst,
self.tcp_seq,
self.tcp_ack_seq,
self.tcp_hdr_len,
self.tcp_flags ,
self.tcp_wdw
)+
struct.pack("H",
self.tcp_chksum
)+
struct.pack('!H',
self.tcp_urg_ptr
)
return
The error occurs in the addition of the first struct.pack with the next struct.pack. Any suggestion will be appreciated.

In python, you can't end a line with an operator, the + needs to have something after it, not just a new line. This should work for you, however:
def reassemble_tcp_feilds(self):
self.raw = struct.pack('!HHLLBBH',
self.tcp_src,
self.tcp_dst,
self.tcp_seq,
self.tcp_ack_seq,
self.tcp_hdr_len,
self.tcp_flags ,
self.tcp_wdw
)+struct.pack("H",
self.tcp_chksum
)+struct.pack('!H',
self.tcp_urg_ptr
)
return

Related

Python : stripping, converting bytes type

Under Python 3.10, I do have an UDP socket that listens to a COM port.
I do get datas like this :
b'SENDPKT: "STN1" "" "SH/DX\r"\x98\x00'
The infos SH/DX before the "\n" can change and has a different length and I need to extract them.
.strip('b\r') doesn't work.
Using .decode() and str(), I tried to convert this bytes datas to a string for easier manipulation, but that doesn't work either.
I get an error "invalid start byte at position 27 for 0x98
Any guess, how I can solve this ?
Thanks,
For sophisticated input you can try ignoring errors while decoding:
b = b'SENDPKT: "STN1" "" "SH/DX\r"\x98\x00'
s = b.decode(errors='ignore')
res = s[20:s.find('\r')] # 'SH/DX'

Angr can't solve the googlectf beginner problem

I am a student studying angr, first time.
I'm watching the code in this url.
https://github.com/Dvd848/CTFs/blob/master/2020_GoogleCTF/Beginner.md
import angr
import claripy
FLAG_LEN = 15
STDIN_FD = 0
base_addr = 0x100000 # To match addresses to Ghidra
proj = angr.Project("./a.out", main_opts={'base_addr': base_addr})
flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(FLAG_LEN)]
flag = claripy.Concat( *flag_chars + [claripy.BVV(b'\n')]) # Add \n for scanf() to accept the input
state = proj.factory.full_init_state(
args=['./a.out'],
add_options=angr.options.unicorn,
stdin=flag,
)
# Add constraints that all characters are printable
for k in flag_chars:
state.solver.add(k >= ord('!'))
state.solver.add(k <= ord('~'))
simgr = proj.factory.simulation_manager(state)
find_addr = 0x101124 # SUCCESS
avoid_addr = 0x10110d # FAILURE
simgr.explore(find=find_addr, avoid=avoid_addr)
if (len(simgr.found) > 0):
for found in simgr.found:
print(found.posix.dumps(STDIN_FD))
https://github.com/google/google-ctf/tree/master/2020/quals/reversing-beginner/attachments
Which is the answer of googlectf beginner.
But, the above code does not work. It doesn't give me the answer.
I want to know why the code is not working.
When I execute this code, the output was empty.
I run the code with python3 in Ubuntu 20.04 in wsl2
Thank you.
I believe this script isn't printing anything because angr fails to find a solution and then exits. You can prove this by appending the following to your script:
else:
raise Exception('Could not find the solution')
If the exception raises, a valid solution was not found.
In terms of why it doesn't work, this code looks like copy & paste from a few different sources, and so it's fairly convoluted.
For example, the way the flag symbol is passed to stdin is not ideal. By default, stdin is a SimPackets, so it's best to keep it that way.
The following script solves the challenge, I have commented it to help you understand. You will notice that changing stdin=angr.SimPackets(name='stdin', content=[(flag, 15)]) to stdin=flag will cause the script to fail, due to the reason mentioned above.
import angr
import claripy
base = 0x400000 # Default angr base
project = angr.Project("./a.out")
flag = claripy.BVS("flag", 15 * 8) # length is expected in bits here
initial_state = project.factory.full_init_state(
stdin=angr.SimPackets(name='stdin', content=[(flag, 15)]), # provide symbol and length (in bytes)
add_options ={
angr.options.SYMBOL_FILL_UNCONSTRAINED_MEMORY,
angr.options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS
}
)
# constrain flag to common alphanumeric / punctuation characters
[initial_state.solver.add(byte >= 0x20, byte <= 0x7f) for byte in flag.chop(8)]
sim = project.factory.simgr(initial_state)
sim.explore(
find=lambda s: b"SUCCESS" in s.posix.dumps(1), # search for a state with this result
avoid=lambda s: b"FAILURE" in s.posix.dumps(1) # states that meet this constraint will be added to the avoid stash
)
if sim.found:
solution_state = sim.found[0]
print(f"[+] Success! Solution is: {solution_state.posix.dumps(0)}") # dump whatever was sent to stdin to reach this state
else:
raise Exception('Could not find the solution') # Tell us if angr failed to find a solution state
A bit of Trivia - there are actually multiple 'solutions' that the program would accept, I guess the CTF flag server only accepts one though.
❯ echo -ne 'CTF{\x00\xe0MD\x17\xd1\x93\x1b\x00n)' | ./a.out
Flag: SUCCESS

Why does my code stuck after speak function?

I try to create a Voice Assistant on python3
This is my function Speak (with pyttsx):
def speak(what):
print("Gosha: " + what)
speak_engine.say( what )
speak_engine.runAndWait()
speak_engine.stop()
in the main body it works fine, but in function execute_cmd, after Speak function my code stucks.
One part of execute_cmd:
def execute_cmd(cmd, voice):
global finished
finished = False
#import debug
if cmd == 'ctime':
now = datetime.datetime.now()
hours = str(now.hour)
minutes = str(now.minute)
if (now.minute < 10): minutes = '0' + minutes
speak("Now " + hours + ":" + minutes)
finished = True
finished will never True
This happens anywhere in the function
pls help me
(sorry for my eng, I'm from Russia)
UPD: I debugged my code and noticed, my code get stuck on speak_engine.runAndWait()
I know, many people have same problem, but their solutions didn't help me
I'm not sure I understand you problem. What exactly do you mean by your code getting "Stuck"? Since you said that your finished variable will never be False, I assume that the code runs through and doesn't get stuck. My best guess is that your code simply doesn't produce sound.
If that's the case, I could imagine it's due to the previous loop still being active. So maybe try adding the following to your speak() function:
ef speak(what):
print("Gosha: " + what)
try:
speak_engine.endLoop()
except Exception as e:
pass
speak_engine.say( what )
speak_engine.runAndWait()
speak_engine.stop()

Python- How to handle error for RTSP link

I've created a python script that checks muliple different urls and ports and detects if there is an RTSP stream on them - it is working fine, but it creates errors when the stream doesn't exist (which I'd obviously expect).
I'm getting [rtsp # 0x16745c0] method DESCRIBE failed: 451 ERROR
What I want to do it add a line to my script so if I get the above error, then I just display it in a message on screen. I've tried the following with no luck:
for x in feedList:
print("[INFO] Checking Link..." + x)
cap=cv2.VideoCapture(x)
try:
# Check if camera opened successfully
if (cap.isOpened()== True):
streamlink = x
print("[INFO] FOUND! Stream Link..." + x)
break
except socket.error:
print("[NO STREAM]" + x)
except:
print("[FAILED]" + x)
pass
The Except cases never get hit, I always just get [rtsp # 0x16745c0] method DESCRIBE failed: 451 ERROR
Any help would be appreciated.
Thanks
Chris
If the stream on the link does not exist, creating VideoCapture object on that link would still be successful but you will not be able to process on the object.
You code's control flow just might be going in and checking if (cap.isOpened()== True) but there is no else block to handle what would happen if if (cap.isOpened() != True). So just try adding an else block to display the error message.
for x in feedList:
print("[INFO] Checking Link..." + x)
cap=cv2.VideoCapture(x)
try:
# Check if camera opened successfully
if (cap.isOpened()== True):
streamlink = x
print("[INFO] FOUND! Stream Link..." + x)
break
# Else is important to display error message on the screen if can.isOpened returns false
else
print("[NO STREAM]" + x)
except socket.error:
print("[NO STREAM]" + x)
except:
print("[FAILED]" + x)
pass
If this doesn't work: following might solve the issue:
One of the main issues is that every camera manufacturer uses their
own protocol (RTSP URI formatting). Finding the correct URL for your
IP-camera can be frustrating and time-intensive. When found you can
try to open it with VLC, and afterwards with Kerberos.io.
Depending on the format of the RTSP URI things can go wrong, for
example when using a format like above. To solve the problem you'll
need to add an question mark "?" at the end of the url.
As example original link might be:
rtsp://192.168.2.109:554/user=admin&password=mammaloe&channel=1&stream=0.sdp
So with ? it would be:
rtsp://192.168.2.109:554/user=admin&password=mammaloe&channel=1&stream=0.sdp?
Source

EOL Error in Python

I am having the following error, can someone explain to me what can I do to fix it.
def increment(i):
request =("https://www.minsalud.gov.co/sites/rid/Paginas/freesearchresults.aspx?k=&k=Salud%20Mental%20Legislacion#k=%2CSalud%20Mental%20Legislacion=+ 1"+ i+")
EOL while scanning string literal
You are missing a closing " and ) at the end of your line
request =("https://www.minsalud.gov.co/sites/rid/Paginas/freesearchresults.aspx?k=&k=Salud%20Mental%20Legislacion#k=%2CSalud%20Mental%20Legislacion=+ 1"+ i+")")

Resources