Bytes, Encodings, Hex and Base64
Everything a security tool reads arrives as bytes: packets, files, log lines, HTTP bodies, registry values. Text is an interpretation of those bytes, and attackers live in the gap between the bytes and the interpretation. A filter that blocks the string <script> misses %3Cscript%3E; a log search for Invoke-WebRequest misses the same command hidden in a Base64 -EncodedCommand; a user name that looks like admin may contain a Cyrillic а. To see what is really there, a tool has to work with bytes on purpose and decode them on purpose.
Definitions
bytes: an immutable sequence of integers 0–255.b"GET /"is bytes;"GET /"is astr(Unicode code points).- Encoding: the rule that turns code points into bytes. UTF-8 uses 1 byte for ASCII and 2–4 bytes for everything else; UTF-16LE (Windows' internal encoding) uses 2 or 4.
- Decoding error policy: what
bytes.decode()does with invalid input:"strict"raises,"replace"puts in U+FFFD (�),"backslashreplace"keeps the byte visible as\xff. - Hex: two characters per byte,
bytes.hex()andbytes.fromhex(). Lossless and easy to read in a report. - Base64 (RFC 4648): 3 bytes become 4 characters from
A–Z a–z 0–9 + /, with=padding. Base64url replaces+ /with- _, as in JWTs and URLs. - Percent-encoding (RFC 3986):
%3Cis the byte 0x3C (<), used in URLs and form bodies.
Seeing the bytes
s = "admin"
look = "аdmin" # the first letter is CYRILLIC SMALL LETTER A
print(s == look, len(s), len(look))
print(s.encode("utf-8").hex(" "))
print(look.encode("utf-8").hex(" "))
raw = b"user=alice\xff\xfe&pw=x" # two bytes that are not valid UTF-8
for policy in ["replace", "backslashreplace"]:
print(policy, "->", raw.decode("utf-8", policy))
try:
raw.decode("utf-8")
except UnicodeDecodeError as e:
print("strict ->", type(e).__name__, "at byte", e.start)False 5 5
61 64 6d 69 6e
d0 b0 64 6d 69 6e
replace -> user=alice��&pw=x
backslashreplace -> user=alice\xff\xfe&pw=x
strict -> UnicodeDecodeError at byte 10
The two names print the same on most screens but are different strings: the look-alike starts with the two bytes d0 b0. backslashreplace is the right policy for a security report, because it keeps the evidence visible instead of hiding it behind a �.
Hex, Base64 and percent-encoding
Attackers and ordinary software both wrap data in encodings. A log line from a lab Windows host (synthetic) shows a PowerShell process started with -EncodedCommand, which takes Base64 of UTF-16LE text. Decoding it is the first step of every triage:
import base64, binascii, urllib.parse
logline = ("powershell.exe -NoProfile -EncodedCommand "
"VwByAGkAdABlAC0ATwB1AHQAcAB1AHQAIAAnAGgAZQBsAGwAbwAgAGwAYQBiACcA")
blob = logline.split()[-1]
raw = base64.b64decode(blob, validate=True)
print(raw[:12].hex(" "), "...")
print("decoded:", raw.decode("utf-16-le"))
print(base64.b64encode(b"\xfb\xff"), base64.urlsafe_b64encode(b"\xfb\xff"))
try:
base64.b64decode("aGVsbG8", validate=True) # missing padding
except binascii.Error as e:
print("bad base64:", e)
path = "/download?file=..%2F..%2Fetc%2Fpasswd"
print(urllib.parse.unquote(path))
print(urllib.parse.quote("<script>", safe=""))57 00 72 00 69 00 74 00 65 00 2d 00 ...
decoded: Write-Output 'hello lab'
b'+/8=' b'-_8='
bad base64: Incorrect padding
/download?file=../../etc/passwd
%3Cscript%3E
Three habits are visible here. validate=True makes b64decode reject characters outside the alphabet instead of silently dropping them. The Base64url variant changes only two characters, so a decoder for the wrong variant fails on exactly the strings that contain them. And a URL has to be decoded before it is checked: the encoded path hides a ../ traversal that a filter on the raw string would miss.
How hidden content is detected
- Look for encoded blobs, not just keywords: long runs of
[A-Za-z0-9+/]{40,}={0,2},-EncodedCommand/-enc,FromBase64String, many%xxescapes in a URL. Decode them and search the result. - Measure, don't eyeball: print
.hex()orascii()of suspicious strings.ascii("аdmin")shows'\u0430dmin'. - Count code points from unexpected scripts in identifiers (user names, domain names, package names). A Latin name with one Cyrillic letter is a classic look-alike.
How it is fixed or prevented
- Canonicalise, then validate. Decode percent-encoding (once, and reject input that still contains
%afterwards if double encoding is not expected), normalise Unicode withunicodedata.normalize("NFKC", s), then apply the check. Never check the raw form and use the decoded one. - Restrict identifiers to an allowlist such as
[a-z0-9_.-]when you control the format, or use the Unicode identifier rules (UTS #39 confusable detection) when you must accept other scripts. - Keep bytes as bytes until you know the encoding:
open(path, "rb"),sys.stdout.buffer, and an explicitdecode(..., "backslashreplace")at the edge. - Store evidence losslessly: hex or Base64 in reports, never the "replace"-decoded text.
Pitfalls
- Mixing
strandbytes.b"abc" == "abc"isFalsewithout an error. Decide at the boundary. - Decoding twice.
%253Cdecodes to%3C, then to<. If your checker decodes once and the application decodes twice, the check is bypassed. - NFKC changes meaning. It turns
fiintofiand full-widthaintoa, which is right for comparison and wrong for storage. Normalise a copy. - Assuming Base64 means malicious. E-mail attachments, certificates and JWTs are Base64 too; decode before judging.
Practice
1. Decode the Base64url string eyJhbGciOiJub25lIn0 (no padding). What is it, and what must you add before Python's decoder accepts it?
Its length is 19, so add one = to reach a multiple of 4: base64.urlsafe_b64decode("eyJhbGciOiJub25lIn0=") gives b'{"alg":"none"}', a JWT header that disables signature checking, which a verifier must reject.
2. Write a one-line check that a user name contains only ASCII letters, digits, dot, dash and underscore. Does аdmin pass?
re.fullmatch(r"[A-Za-z0-9._-]+", name) is not None. The Cyrillic а is outside the class, so it fails, as it should. (Note that str.isalnum() would accept it: it is Unicode-aware.)
3. A filter blocks requests whose raw path contains ../. Give two encodings of ../ that pass it, and the fix.
..%2F and %2E%2E/ (also ..%252F if the server decodes twice, and ..\ on Windows). Fix: decode and normalise the path first (posixpath.normpath of the decoded path), then check that the result stays inside the allowed directory.
Practice problem in 21 languages: Base64 and Base64url Encoding.
Test yourself
Which decode error policy keeps invalid bytes visible as \xff in a report?
- strict
- ignore
- replace
- backslashreplace
PowerShell's -EncodedCommand takes Base64 of which encoding?
- UTF-8
- UTF-16LE
- ASCII
- Latin-1
Why must a URL path be decoded before a traversal check?
- Decoding makes it shorter
..%2Fcontains no../until it is decoded, so a raw check is bypassed- Encoded paths are always malicious
- Browsers never encode paths
"admin" == "аdmin" (second with a Cyrillic а) is False. What is the first byte of the Cyrillic letter in UTF-8?
- 0x61
- 0xd0
- 0xff
- 0x00