Skip to content

Commit

Permalink
properly convert single-byte (unsigned) integer values to and from ne…
Browse files Browse the repository at this point in the history
…twork format
  • Loading branch information
michaelroland committed Oct 19, 2022
1 parent c2fa43c commit 0db0e19
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions socks.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,8 +394,8 @@ def recvfrom(self, bufsize, flags=0):

buf = BytesIO(super(socksocket, self).recv(bufsize + 1024, flags))
buf.seek(2, SEEK_CUR)
frag = buf.read(1)
if ord(frag):
frag = struct.unpack(">B", buf.read(1))[0]
if frag:
raise NotImplementedError("Received UDP packet fragment")
fromhost, fromport = self._read_SOCKS5_address(buf)

Expand Down Expand Up @@ -488,9 +488,10 @@ def _SOCKS5_request(self, conn, cmd, dst):
"Server requested username/password"
" authentication")

writer.write(b"\x01" + chr(len(username)).encode()
writer.write(b"\x01"
+ struct.pack(">B", len(username))
+ username
+ chr(len(password)).encode()
+ struct.pack(">B", len(password))
+ password)
writer.flush()
auth_status = self._readall(reader, 2)
Expand Down Expand Up @@ -526,7 +527,7 @@ def _SOCKS5_request(self, conn, cmd, dst):
raise GeneralProxyError(
"SOCKS5 proxy server sent invalid data")

status = ord(resp[1:2])
status = struct.unpack(">B", resp[1:2])[0]
if status != 0x00:
# Connection failed: server returned an error
error = SOCKS5_ERRORS.get(status, "Unknown error")
Expand Down Expand Up @@ -567,7 +568,7 @@ def _write_SOCKS5_address(self, addr, file):
if rdns:
# Resolve remotely
host_bytes = host.encode("idna")
file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
file.write(b"\x03" + struct.pack(">B", len(host_bytes)) + host_bytes)
else:
# Resolve locally
addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
Expand All @@ -592,7 +593,7 @@ def _read_SOCKS5_address(self, file):
addr = socket.inet_ntoa(self._readall(file, 4))
elif atyp == b"\x03":
length = self._readall(file, 1)
addr = self._readall(file, ord(length))
addr = self._readall(file, struct.unpack(">B", length)[0])
elif atyp == b"\x04":
addr = socket.inet_ntop(socket.AF_INET6, self._readall(file, 16))
else:
Expand Down Expand Up @@ -644,7 +645,7 @@ def _negotiate_SOCKS4(self, dest_addr, dest_port):
raise GeneralProxyError(
"SOCKS4 proxy server sent invalid data")

status = ord(resp[1:2])
status = struct.unpack(">B", resp[1:2])[0]
if status != 0x5A:
# Connection failed: server returned an error
error = SOCKS4_ERRORS.get(status, "Unknown error")
Expand Down

0 comments on commit 0db0e19

Please sign in to comment.