<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dharmil Chhadva on Medium]]></title>
        <description><![CDATA[Stories by Dharmil Chhadva on Medium]]></description>
        <link>https://medium.com/@dharmilch18?source=rss-9a0050c16170------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6XvMbENO5RuYgiox71YcQA.jpeg</url>
            <title>Stories by Dharmil Chhadva on Medium</title>
            <link>https://medium.com/@dharmilch18?source=rss-9a0050c16170------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 19:06:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dharmilch18/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Man In The Middle Attack (MITM) Part 2 — Packet Sniffer]]></title>
            <link>https://levelup.gitconnected.com/man-in-the-middle-attack-mitm-part-2-packet-sniffer-82f0a121c58d?source=rss-9a0050c16170------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f0a121c58d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[packet-sniffing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[man-in-the-middle-attack]]></category>
            <dc:creator><![CDATA[Dharmil Chhadva]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 02:42:46 GMT</pubDate>
            <atom:updated>2020-08-13T02:42:46.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Man In The Middle Attack (MITM) Part 2 — Packet Sniffer</h3><p>Building a packet sniffer using Python 🐍 that extracts visited URLs and user credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyDEtK2L28GK1XGGW4JkVw.jpeg" /></figure><blockquote>This is part 2 of Man In The Middle (MITM) attack. If you haven’t read part 1 then I strongly suggest you read that before reading part 2. You can find the link to Part 1 in the next section.</blockquote><h3>What is a Packet Sniffer?</h3><p>A packet sniffer is a tool that is used to monitor networks and to diagnose any network problems. It is commonly used by network technicians. Hackers often use this to spy on user’s network traffic and for extracting passwords.</p><p>Packet sniffers log network traffic on a network <strong>interface</strong> that they have access to. It can see every <a href="https://computer.howstuffworks.com/question525.htm#pt0">packet</a> that flows to and from an interface.</p><p>You’d be wondering that we are designing a packet sniffer but the title says Man In The Middle Attack. This is because in <a href="https://levelup.gitconnected.com/man-in-the-middle-attack-part-1-arp-spoofing-6f5b174dec59">Part 1</a> we wrote a Python script (ARP Spoofing) that allows us to become a Man In The Middle. The purpose of the packet sniffer is to capture the victim’s (the user which has been attacked using ARP Spoofing) network traffic and extract visited URLs and credentials.</p><p><a href="https://levelup.gitconnected.com/man-in-the-middle-attack-part-1-arp-spoofing-6f5b174dec59">Man In The Middle Attack (MITM) Part 1 — ARP Spoofing</a></p><h3>Modules Used:</h3><ol><li><a href="https://docs.python.org/3.4/library/subprocess.html">argparse</a>: To understand what this does read my first article <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563">here</a>.</li><li><a href="https://scapy.readthedocs.io/en/latest/extending.html">Scapy</a>: Enables the user to send, sniff and dissect and forge network packets. This capability allows the development of tools that can probe, scan, or attack networks. It can forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It easily handles most tasks like scanning, tracerouting, probing, unit tests, attacks, or network discovery.</li><li><a href="https://docs.python.org/3/library/time.html">time</a>: We only use the time module to generate a delay of 2 seconds. To learn more about this module read the docs.</li></ol><h3>What functionality the Python 🐍 script must have?</h3><ul><li>get_args() — A function to get command-line arguments. In this case, we need an input value from the user for the <strong>interface </strong>on which we want to sniff the packets.</li><li>sniffer(interface) — A function that takes the <strong>interface </strong>value as an input and sniffs the packets on that interface.</li><li>process_packet(packet) — A function that is called by the sniffer function for every new packet that is sniffed. This checks whether the packet is of type HTTP Request or not. For this use case, we only need the packets which are of the HTTP Request type because the information we want is sent in this packet. It then uses get_url(https://medium.com/packet) and get_credentials(packet) functions.</li><li>get_url(https://medium.com/packet) — A function that extracts the URL from the packet that was passed to it.</li><li>get_credentials(packet) — A function that also takes packet as input and extracts credentials such as username and password.</li></ul><p>Without further ado, let’s start writing the script in Python.</p><h3>Python Script for Packet Sniffer</h3><p>In this section, we’ll build the script step by step. I’ll explain everything in each step, so read carefully.</p><p><strong>Step 1: Importing Necessary Modules</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469a4d00cab773d76ed753c9a6186f9d/href">https://medium.com/media/469a4d00cab773d76ed753c9a6186f9d/href</a></iframe><p><strong>Step 2: Writing the </strong>get_args()<strong> function</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a06ac3c28e5049e4f05b407a00fe0bed/href">https://medium.com/media/a06ac3c28e5049e4f05b407a00fe0bed/href</a></iframe><p>The above function adds functionality which allows the user to pass user input values as the command-line arguments. After the addition of the above code, the user will be able to pass the name of the interface on which the packets are supposed to be sniffed in the same instruction that is used to run the script. For example,</p><pre>root@kali:~# python3 sniffer.py -i interface_name</pre><p>OR</p><pre>root@kali:~# python3 sniffer.py --interface interface_name</pre><p>To learn how exactly this function works, read the entire <strong>Step 2</strong> from the article on how to <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563">change MAC Address of a device</a>.</p><p><strong>Step 3: Writing the </strong>sniffer(interface)<strong> function</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f539036f164c1231e87d8895ba9d80e/href">https://medium.com/media/1f539036f164c1231e87d8895ba9d80e/href</a></iframe><p>The above gist contains the definition of the sniffer(interface) function. It takes an <strong>interface</strong> name as an input that is used inside it. It uses a method called sniff provided by the scapy module. The methodsniff requires an interface name iface as an input. The next argument, store tells scapy whether to store the packets in memory or not. store = False tells scapy not to store the packets. The last argument is prn, it tells scapy which function to be called each time a new packet is sniffed. In this case, process_packet function is called for every new packet.</p><p><strong>Step 4: Writing the</strong> process_packet(packet) <strong>function</strong></p><p>Before jumping into the function, let’s take a look at how a scapy packet looks like.</p><pre>###[ Ethernet ]###<br>dst       = 52:54:00:12:35:00<br>src       = 08:00:27:35:21:2e<br>type      = IPv4<br>###[ IP ]###<br>version   = 4<br>ihl       = 5<br>tos       = 0x0<br>len       = 441<br>id        = 22651<br>flags     = DF<br>frag      = 0<br>ttl       = 64<br>proto     = tcp<br>chksum    = 0xf1f9<br>src       = 10.0.2.9<br>dst       = 176.28.50.165<br>\options   \<br>###[ TCP ]###<br>sport     = 48556<br>dport     = http<br>seq       = 790303956<br>ack       = 327206<br>dataofs   = 5<br>reserved  = 0<br>flags     = PA<br>window    = 64240<br>chksum    = 0xf075<br>urgptr    = 0<br>options   = []<br>###[ HTTP 1 ]###<br>###[ HTTP Request ]###<br>Method    = &#39;GET&#39;<br>Path      = &#39;/login.php&#39;<br>Http_Version= &#39;HTTP/1.1&#39;<br>A_IM      = None<br>Accept    = &#39;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&#39;<br>Accept_Charset= None<br>Accept_Datetime= None<br>Accept_Encoding= &#39;gzip, deflate&#39;<br>Accept_Language= &#39;en-US,en;q=0.5&#39;<br>Access_Control_Request_Headers= None<br>Access_Control_Request_Method= None<br>Authorization= None<br>Cache_Control= &#39;max-age=0&#39;<br>Connection= &#39;keep-alive&#39;<br>Content_Length= None<br>Content_MD5= None<br>Content_Type= None<br>Cookie    = None<br>DNT       = None<br>Date      = None<br>Expect    = None<br>Forwarded = None<br>From      = Non<br>Front_End_Https= None<br>HTTP2_Settings= None<br>Host      = &#39;testphp.vulnweb.com&#39;<br>If_Match  = None<br>If_Modified_Since= None<br>If_None_Match= None<br>If_Range  = None<br>If_Unmodified_Since= None<br>Keep_Alive= None<br>Max_Forwards= None<br>Origin    = None<br>Permanent = None<br>Pragma    = None<br>Proxy_Authorization= None<br>Proxy_Connection= None<br>Range     = None<br>Referer   = &#39;<a href="http://testphp.vulnweb.com/login.php&#39;">http://testphp.vulnweb.com/login.php</a></pre><p>The above block shows the contents of the packet. The line that starts with ###[text]### is called a layer. The lines after that are the fields that come under that layer until the next layer is encountered. For instance, from the above block, ###[ Ethernet ]### is a layer and the following lines are the fields under the Ethernet. These fields contain information about Ethernet. Similarly, ###[ TCP ]###, ###[ HTTP Request ]###, etc. are layer. Now, let&#39;s jump to the <strong>process_packet</strong> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e20c62cf6714f6740b69002dd454571a/href">https://medium.com/media/e20c62cf6714f6740b69002dd454571a/href</a></iframe><p>This function needs the sniffed packet as an input. In this function, we are first checking if the packet has a HTTP Request layer. This is done by using a method provided by scapy called haslayer(). If the packet does not has the layer then it is not processed.</p><p>If it has the HTTP Request layer then, we perform two operations:</p><ol><li>Call get_url(https://medium.com/packet) function to extract URL from the packet. It takes the packet as an input. This function returns a URL, we store this is in a variable called url and then we print the value of url.</li><li>Then we call another function called get_credentials(packet). It also takes packet as an input. It checks the packet for possible credentials and if found any then it returns those credentials. We store it in a variable named cred and then we print its value.</li></ol><blockquote>I’ll explain get_url(https://medium.com/packet) and get_credentials(packet) functions in the later steps.</blockquote><p><strong>Step 5: Writing the</strong> get_url(https://medium.com/packet) <strong>function</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/883320d55f44df1829144bf4476582c0/href">https://medium.com/media/883320d55f44df1829144bf4476582c0/href</a></iframe><p>The get_url(https://medium.com/packet) function also needs a packet as an input to extract the URL within the packet. The function extracts the contents of theHost and Path subfields of the HTTPRequest layer of the packet. We then join both the parts and return the URL extracted from the packet. The following is an example of the contents present in Host and Path subfields.</p><pre>Path      = &#39;/login.php&#39;<br>Host      = &#39;testphp.vulnweb.com&#39;</pre><p>The code packet[http.HTTPRequest] allows us to access the layers and is possible because of Scapy.</p><p><strong>Step 6: Writing the </strong>get_credentials(packet)<strong> function</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14b625b44afb57e3dcec942a0f949ec/href">https://medium.com/media/c14b625b44afb57e3dcec942a0f949ec/href</a></iframe><p>In the above code, you can see a Python tuple named keywords . Before understanding why it is required let&#39;s understand the function itself.</p><p>This function also needs a packet to work with. Now, when we looked at the contents of the packet at the beginning of step 4, there was no such layer called Raw . This layer is crucial for what we are trying to achieve because the additional information such as credentials is added to the Raw layer. The below code block shows the Raw layer. It also shows that the credentials are stored inside a subfield called load.</p><pre>###[ Raw ]###<br>load = &#39;uname=hdhd&amp;pass=hshs&#39;</pre><p>Now back to the function. At first, the function checks whether the packet has the Raw layer. If the packet has the layer, then it extracts the value of the load subfield and stores it in a variable called <strong>field_load</strong>.</p><p>The next step is using a for loop to loop over the tuple we discussed earlier. The tuple contains the keywords that are potential names of the form fields used at the time of making an HTML Form. These keywords are derived by guessing common names given to HTML Form elements that are used to design HTML Signup and Login forms.</p><p>The for loop loops over each element in the tuple and checks whether any of the keywords is present the <strong>field_load </strong>variable. If anyone keyword matched then the <strong>field_load</strong> is returned to the process_packet(packet) function to display potential credentials.</p><p><strong>Step 7: Final Step</strong></p><p>Now, all that&#39;s left to do is call get_args() and sniffer(interface) function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a1422eb9995490cfad9f6713f8277f0/href">https://medium.com/media/1a1422eb9995490cfad9f6713f8277f0/href</a></iframe><p>With this, we complete the entire script and all that&#39;s left to do is test it.</p><h3>Entire Script</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ddbeb0cabc41cc1588d48c8ad88ef5/href">https://medium.com/media/f3ddbeb0cabc41cc1588d48c8ad88ef5/href</a></iframe><h3>Working Demo</h3><p>Okay, before jumping to writing the code in Python I’ll tell you about the setup that I have: I am currently on Windows 10 and I have <a href="https://www.virtualbox.org/">Virtualbox </a>running with two VMs (1. Kali Linux and 2. Windows 10). I will execute the python script that we made in Part 1 — ARP Spoofing on my Kali Linux machine and attack my Windows 10 VM to become Man In The Middle. Then, I’ll execute the packet sniffer script from this part on my Kali Linux Machine. After that, I’ll log in to a website and see whether the sniffer script is able to extract the credentials or not.</p><p>Note: The VMs are configured to use <strong>NatNetwork</strong> in Virtualbox. When the VMs are set to use <strong>NatNetwork, </strong>the VMs thinks the host as the router (access point). To know more about NatNetwork and how to configure a VM to use it, read <a href="https://www.techrepublic.com/article/how-to-create-multiple-nat-networks-in-virtualbox/">this</a>.</p><p>Note: The packet sniffer only works on websites using the HTTP protocol. It does not work with HTTPS. To test, use this website — <a href="http://testphp.vulnweb.com/login.php">Test Vuln Login</a>.</p><h4>Kali Linux Machine</h4><ul><li>IP Address = <strong>10.0.2.9</strong></li><li>MAC Address = <strong>08:00:27:35:21:2e</strong></li></ul><h4>Windows 10</h4><ul><li>IP Address = <strong>10.0.2.15</strong></li><li>MAC Address = <strong>08:00:27:e6:e5:59</strong></li></ul><h4>Access Point or Default Gateway</h4><ul><li>IP Address = <strong>10.0.2.1</strong></li><li>MAC Address = <strong>52:54:00:12:35:00</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*MhXoV7VA7Q2Xu5CvbEnkvw.png" /><figcaption><strong>Becoming Man In The Middle using ARP Spoofing</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*DJ9TmYiF-82G3fu2WR4FUA.png" /><figcaption><strong>Proof that we are the MITM</strong></figcaption></figure><p>MITM — Man In The Middle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*OyWMAQm_Q21HX-wwZfcUbQ.png" /><figcaption><strong>Executing Packet Sniffer Script</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*9UVcQytOQvBuZauigh8jFg.png" /><figcaption><strong>Testing Form</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*5UcVFqtMFSVFeAGufbW8mA.png" /><figcaption><strong>Testing Form with credentials</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Exhwo9fgveHL1hJG8zS-w.png" /><figcaption><strong>Extracted URLs</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruKdfc3R8sd-6XtMbtTIvA.png" /><figcaption><strong>Extracted Credentials</strong></figcaption></figure><p>In the above image, you can see that we have extracted the captured username and password from the packet that was sniffed. In the testing form, we entered username = test_user and password = test_user123 and in the above image, you can see that we are getting the same username and password value in the output.</p><h3>Conclusion</h3><p>We successfully wrote a Python 🐍 script to capture packets. We also tested it with Man In The Middle Attack — ARP Spoofing. The script works perfectly as we wanted it to.</p><p>You can find the entire script on my <a href="https://github.com/dharmil18/Packet-Sniffer">Github Repository</a>. Thank You 😃 for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f0a121c58d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/man-in-the-middle-attack-mitm-part-2-packet-sniffer-82f0a121c58d">Man In The Middle Attack (MITM) Part 2 — Packet Sniffer</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Man In The Middle Attack (MITM) Part 1 — ARP Spoofing]]></title>
            <link>https://levelup.gitconnected.com/man-in-the-middle-attack-part-1-arp-spoofing-6f5b174dec59?source=rss-9a0050c16170------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f5b174dec59</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[arp-spoofing]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[man-in-the-middle-attack]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Dharmil Chhadva]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 02:00:02 GMT</pubDate>
            <atom:updated>2020-08-05T02:00:02.477Z</atom:updated>
            <content:encoded><![CDATA[<h3>Man In The Middle Attack (MITM) Part 1 — ARP Spoofing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zz0ztGgICt0z192EqInOWg.jpeg" /><figcaption>Image by <a href="https://www.pexels.com/@pixabay">Pixabay</a> on <a href="https://www.pexels.com/">Pexels</a></figcaption></figure><h3>What is Address Resolution Protocol (ARP)?</h3><p>In a network, computers use the <strong>IP Address</strong> to communicate with other devices, however, in reality, the communication happens over the <strong>MAC Address. ARP is used to find out the MAC Address of a particular device whose IP address is known.</strong> For instance, a device wants to communicate with the other device on the network, then the sending device uses ARP to find the MAC Address of the device that it wants to communicate with. ARP involves two steps to find the MAC address:</p><ol><li>The sending device sends an <strong>ARP Request</strong> containing the IP Address of the device it wants to communicate with. This request is broadcasted meaning every device in the network will receive this but only the device with the intended IP address will respond.</li><li>After receiving the broadcast message, the device with the IP address equal to the IP address in the message will send an <strong>ARP Response</strong> containing its MAC Adress to the sender.</li></ol><p>If it is still not clear what ARP is and how it works then refer to the images below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mda_kqjm4ONDM7jQnKZ7TQ.jpeg" /><figcaption><strong>Fig 1. ARP Request</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTdIvgRjXx9XewTRZVeAyg.jpeg" /><figcaption><strong>Fig 2. ARP Response</strong></figcaption></figure><h3>What is ARP Spoofing?</h3><p>ARP spoofing is a <strong>Man In The Middle (MITM)</strong> attack in which the attacker (hacker) sends forged ARP Messages. This allows the attacker to pretend as a legitimate user as it links the attacker machine’s MAC Address to the legitimate IP Address. Once the MAC Address has been linked the attacker will now receive the messages intended for the legitimate IP Address. Furthermore, ARP Spoofing allows the attacker can intercept, modify, and drop the incoming messages.</p><p>ARP Spoofing is only possible on 32-bit IP Addresses (IPv4) and not on IPv6.However, it is widely used because most of the internet still works on IPv4.</p><p>Let’s understand ARP Spoofing more clearly with the help of diagrams 😃.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WJ1yUmr9tOEW5S6mzraQQ.jpeg" /><figcaption><strong>Fig 3. Normal Network</strong></figcaption></figure><p>Fig 3. demonstrates the working of a normal network (no malicious activity) and how a device (hacker or victim) access the Internet with the help of an access point. All the messages pass through the access point. For instance, a device (hacker or victim) sends requests to access the resources on the Internet and in turn, receives responses. These <strong>requests </strong>and <strong>responses </strong>always pass through the access point and therefore the access point is called the <strong>Gateway</strong> to the Internet.</p><blockquote>Note: In this article, the words <strong>“Gateway”</strong>, <strong>“Access Point”, “Router”</strong> and <strong>“Default Gateway” </strong>are used interchangeably. Also the words <strong>“attacker”</strong> and <strong>“hacker” </strong>are used similarly. The words <strong>“target”</strong> and <strong>“victim”</strong> means the same.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nz1e4AfW6HGcgXde_eIwUg.jpeg" /><figcaption><strong>Fig 4. Overview of ARP Spoofing</strong></figcaption></figure><p>Fig 4. illustrates how the ARP Spoofing affects the normal flow of <strong>requests</strong> and <strong>responses </strong>in a network. In ARP Spoofing, the hacker simply fools the <strong>access point</strong> and the <strong>victim </strong>by pretending as the <strong>access point</strong> in front of the <strong>victim</strong> and as the <strong>victim</strong> in front of the <strong>access point</strong>. Now, let’s see how the hacker manages to pretend and fool the access point and the victim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgmPwYZR7cw0NaIHSO2YtA.jpeg" /><figcaption><strong>Fig 5. ARP Spoofing</strong></figcaption></figure><p>With the help of Fig 5. we can understand how the attacker is able to fool both the access point as well as the victim. The figure shows the IP Address and MAC Address of every device present in the network. To understand how ARP Spoofing works you must completely understand the figure first. In order to carry out ARP spoofing the attacker/hacker sends an ARP Response to the access point and the victim.</p><p>Before we dive deeper into Fig 5., let’s first understand ARP Response and what different fields it contains. We already covered what ARP Response is and when it is used. Now, let’s take a look inside an ARP Response to understand what kind of information it holds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*0-kCRo73fZ333N_i6rTTNA.png" /><figcaption><strong>Fig 6. ARP Response Example</strong></figcaption></figure><p>Fig 6. displays an ARP Response packet captured in <a href="https://www.wireshark.org/">Wireshark</a>. There are several fields inside of it using which it communicates with other devices in the network. Out of all the fields, the most important ones for us are:</p><ul><li>Opcode — When its value is <strong>2 </strong>it means its an ARP Response and when it is <strong>1 </strong>it means its an ARP Request. In the figure above the value of Opcode is <strong>2 </strong>which means its an ARP Response.</li><li>Sender MAC Address</li><li>Sender IP Address</li><li>Target MAC Address</li><li>Target IP Address</li></ul><p>Now, to pretend as the victim in front of the Access Point, the attacker/hacker uses ARP Response to its advantage. The attacker sends an ARP Response message to the Access Point with the following information:</p><ul><li>Opcode = <strong>2</strong></li><li>Sender MAC Address = <strong>08:00:11:1a:25:ff </strong>(Attacker’s MAC Address)</li><li>Sender IP Address = <strong>10.0.2.15</strong></li><li>Target MAC Address = <strong>08:22:55:2a:ab:35</strong></li><li>Target IP Address = <strong>10.0.2.1</strong></li></ul><p>This shows that the attacker is forging an ARP Response message by setting the <strong>victim’s IP Address as the Sender’s IP Address</strong>. This <strong>fools the access point in thinking that the ARP Response was sent by the victim (a legitimate device), however, in reality, it was sent by the attacker.</strong> The attacker also<strong> sets its own machine’s MAC Address</strong> <strong>as the Sender MAC Address</strong>. Due to this, the access point updates the MAC Address of the IP Address <strong>10.0.2.15</strong> to the MAC Address of the attacker in its ARP table and therefore linking the attacker’s machine with a legitimate IP Address. With this, any message intended for <strong>10.0.2.15 </strong>will now be sent to the attacker’s machine. This is what <strong>“10.0.2.15 is at 08:00:11:1a:25:ff” </strong>means in Figure 5.</p><p>Read about ARP Table <a href="https://www.javatpoint.com/arp-table">here</a>.</p><p>Similarly, to pretend as the Access Point in front of the victim, the attacker again uses ARP Response and sends it to the victim machine using the following information in it:</p><ul><li>Opcode = 2</li><li>Sender MAC Address = <strong>08:00:11:1a:25:ff </strong>(Attacker’s MAC Address)</li><li>Sender IP Address = <strong>10.0.2.1</strong></li><li>Target MAC Address = <strong>00:22:11:55:33:aa</strong></li><li>Target IP Address = <strong>10.0.2.15</strong></li></ul><p>This ARP Response is received by the victim and thinks that this was sent by the Access point, and thus, updates the MAC Address of the access point’s IP Address with the attacker’s MAC Address in its ARP table. This fools the victim and the attacker successfully pretends to be the access point. This means that any message intended for the access point is now being sent to the attacker.</p><p>Now, as the only way to access the resources on the internet is through the Access Point itself, the victim’s requests now pass through the attacker’s machine instead of the actual access point. This gives a chance to the attacker to intercept, modify, or stop the data transit. The attacker can also relay the requests and responses to and from the victim and the access point without any changes.</p><p>After this, the communication between the victim and the access point happens through the attacker’s machine just as it is shown in Figure 4.</p><p>At this moment, I assume that you have understood how ARP Spoofing is carried out, so let’s jump on to the coding part.</p><h3>Why is ARP Spoofing possible?</h3><p>ARP was designed for security. There are two reasons why ARP spoofing is possible.</p><ol><li>The machines in a network accept ARP Responses even if they haven’t sent an ARP Request.</li><li>The machines trust these ARP Responses without any verification.</li></ol><h3>Modules Used:</h3><ol><li><a href="https://docs.python.org/3.4/library/subprocess.html">argparse</a>: To understand what this does read my first article <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563">here</a>.</li><li><a href="https://scapy.readthedocs.io/en/latest/extending.html">Scapy</a>: Enables the user to send, sniff and dissect and forge network packets. This capability allows the development of tools that can probe, scan, or attack networks. It can forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It easily handles most tasks like scanning, tracerouting, probing, unit tests, attacks, or network discovery.</li><li><a href="https://docs.python.org/3/library/time.html">time</a>: We only use the time module to generate a delay of 2 seconds. To learn more about this module read the docs.</li></ol><blockquote>Okay, before jumping to writing the code in Python I’ll tell you about the setup that I have: I am currently on Windows 10 and I have <a href="https://www.virtualbox.org/">Virtualbox </a>running with two VMs (1. Kali Linux and 2. Windows 10). I will execute the python script on my Kali Linux machine and try to attack my Windows 10 VM. Note: The VMs are configured to use <strong>NatNetwork</strong> in Virtualbox. When the VMs are set to use <strong>NatNetwork, </strong>the VMs thinks the host as the router (access point). To know more about NatNetwork and how to configure a VM to use it, read <a href="https://www.techrepublic.com/article/how-to-create-multiple-nat-networks-in-virtualbox/">this</a>.</blockquote><h3>Python Script for ARP Spoofing</h3><p>In this section, we’ll build the entire script from scratch that will enable us to carry out an ARP spoofing attack.</p><h4>Step 1: Import the modules discussed above.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5737068148a545e736e093ef5f38fe/href">https://medium.com/media/2a5737068148a545e736e093ef5f38fe/href</a></iframe><h4>Step 2: Implementing the functionality to allow the users to pass command line arguments.</h4><p>To add this feature to our script, we’ll need to make use of the <strong>argparse</strong> module that we imported in Step 1. The script needs the IP Address of the victim(target) as well as the access point(gateway).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7d18f8eca3364b25980cc506ab17aa6/href">https://medium.com/media/c7d18f8eca3364b25980cc506ab17aa6/href</a></iframe><p>To know more about how argparse works and what does the above part of the script does and what functionality it adds to the script, read the entire <strong>Step 2</strong> from my previous article on how to <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563">change MAC Address of a device</a></p><p>The above code allows the user to provide the input values for <strong>target</strong> and <strong>gateway</strong> IP Address to be used in the script and it does this as follows:</p><pre>root@kali:~# python3 arp_spoofer.py -t target_ip -g gateway_ip</pre><p><strong>OR</strong></p><pre>root@kali:~# python3 arp_spoofer.py --target target_ip --gateway gateway_ip</pre><p>target_ip = IP Address of the victim (target). In our example above, it’s <strong>10.0.2.15</strong></p><p>gateway_ip = IP Address of the access point (gateway). In our example above, it’s <strong>10.0.2.1</strong></p><p>These values of <strong>target_ip</strong> and <strong>gateway_ip</strong> are used by another function that fools the victim and the access point. We’ll discuss that function in the later steps.</p><h4>Step 3: Writing a function to get the current MAC Address</h4><p>This function takes the IP Address as an input and returns its MAC Address. We need this function to get the MAC Address of the victim and the access point.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a265f7322627a08804a3c6f31a9a4e1/href">https://medium.com/media/6a265f7322627a08804a3c6f31a9a4e1/href</a></iframe><p>Still, now we are not using this function anywhere in our code but we’ll use it inside another function that fools both the victim and the access point. To know technical details about the <strong>get_mac(IP) </strong>function, read the entire step 3 of this <a href="https://medium.com/@dharmilch18/writing-a-network-scanner-using-python-a41273baf1e2#29e2">article</a>. The only difference is that the function name in the linked article is <strong>scan(ip)</strong> instead of <strong>get_mac(ip).</strong></p><h4>Step 4: Writing the spoof function that fools both the access point and the victim.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca9d96a0718e173bfd5cec49cf25baf/href">https://medium.com/media/1ca9d96a0718e173bfd5cec49cf25baf/href</a></iframe><p>Now, there’s a lot going on in this function so let’s break it down line by line so that we understand it completely.</p><p>The <strong>spoof(target_ip, spoof_ip) </strong>accepts two IP Addresses as an input, the <strong>target_ip </strong>is the IP Address of the machine that we want to fool and the <strong>spoof_ip </strong>is the IP Address of the machine whose IP Address we’ll use to fool the other (target) machine.</p><p>The first line, inside the <strong>spoof(target_ip, spoof_ip) </strong>function definition, is where we make use of the <strong>get_mac(ip)</strong> function that we wrote in step 3.</p><pre>target_mac = get_mac(target_ip)</pre><p>This returns the MAC Address of the target_ip and stores it inside the <strong>target_mac</strong> variable.</p><p>In the next line, we create an ARP Response packet using scapy’s ARP class. We achieve this using the following line of code.</p><pre>spoof_packet = scapy.ARP(op = 2, pdst = target_ip, hwdst = target_mac, psrc = spoof_ip)</pre><p>The above line of code creates an ARP Response with the field values as:</p><ul><li>Opcode (op) = 2 — which means its an ARP Response. We’ve already covered this above.</li><li>Destination IP Address (pdst) — Target’s IP Address is set to <strong>target_ip </strong>that the function accepts as an input.</li><li>Destination Hardware Address (hwdst) — Target’s MAC Address is set to the target_mac variable that was used to store the value returned by the get_mac(ip) function in the previous line.</li><li>Source IP Address (psrc) — Sender’s IP Address is set to <strong>spoof_ip.</strong></li></ul><p>I know all of these do not make sense but if we consider the following:</p><ul><li>target_ip = <strong>10.0.2.1</strong></li><li>spoof_ip = <strong>10.0.2.15</strong></li><li>target_mac = get_mac(target_ip)</li></ul><p>Then, the ARP Response that we are created in the 2nd line of the function has the following information:</p><ul><li>Opcode = <strong>2</strong></li><li>Sender MAC Address = Unknown</li><li>Sender IP Address = spoof_ip = <strong>10.0.2.15</strong></li><li>Target MAC Address = target_mac = <strong>08:22:55:2a:ab:35</strong></li><li>Target IP Address = target_ip = <strong>10.0.2.1</strong></li></ul><p>Now, you would be wondering why we are not setting our MAC Address to fool the access point and pretend as the victim in this ARP Response? This is because the Scapy module adds the MAC Address of the machine where the ARP Response packet is created. In our case, the attacker would be us and therefore the Scapy packet is created on our machine so scapy will automatically add our MAC Address in the ARP Response message.</p><p>Also, note that the sender’s IP Address is set to <strong>spoof_ip </strong>so upon receiving, the access point thinks that the ARP Response is from the victim and this is how the attacker sends an ARP Response to the access point pretending to be the victim (legitimate machine).</p><p>Similarly, we can also fool the victim to think that the attacker is the access point.</p><p>Now, the third line of the function sends the ARP Response packet that we created on the second line.</p><pre>scapy.send(spoof_packet, verbose = False)</pre><p>The scapy.send() function requires the packet to be sent as a mandatory argument. The <strong>verbose = False</strong> argument tells the scapy to not print any output of its own.</p><p>This marks the end of the spoof function, all that’s left to do is call the function to start fooling both (victim and access point) machines.</p><p>Next, after the <strong>spoof </strong>function, the next three lines give us the input values of target_ip and the gateway_ip that are passed using the command line arguments in Step 2.</p><pre>options = get_args()<br>target_ip = options.target_ip<br>gateway_ip = options.gateway_ip</pre><p>After these lines, there is a <strong>“try ” </strong>block where we put a block of code that we think would generate an error. In this case, the script will generate an error when we press Control + C to end the execution of the script. We do this because when we want to quit the script execution we still need to restore the changes (fooling) that we did in the network.</p><p>In the try block, we start a while loop that will loop indefinitely as we want to continue to fool both the machines until we stop the execution.</p><pre>try:<br>    while True:<br>        spoof(target_ip, gateway_ip)<br>        spoof(gateway_ip, target_ip)<br>        packets_sent += 2<br>        print(&quot;\r[+] Packets Sent: {}&quot;.format(packets_sent), end = &quot;&quot;)<br>        time.sleep(2)</pre><p>Inside the while loop, the first <strong>spoof()</strong> function call will <strong>fool</strong> the <strong>victim</strong> to <strong>think</strong> that the <strong>attacker</strong> is the <strong>access point</strong> and the second <strong>spoof()</strong> function call will fool the <strong>access point</strong> to<strong> think</strong> that the <strong>attacker</strong> is the <strong>victim</strong>.</p><pre>packets_sent += 2</pre><p>The above line simply calculates the number of packets sent in every iteration. As we call the <strong>spoof()</strong> function twice for every iteration, we send two packets every iteration and therefore we increment packets_sent by 2.</p><pre>time.sleep(2)</pre><p>The time.sleep(2) line, generates a delay of 2 seconds before executing the next iteration.</p><h4>Step 5: Writing the restore function.</h4><p>In this step, we create a <strong>restore </strong>function that would restore the state of the network that was before the ARP Spoofing attack as soon as we encounter an error on KeyboardInterrupt Control + C .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e88dbb8e6c47714aad92e2fddf2184a/href">https://medium.com/media/9e88dbb8e6c47714aad92e2fddf2184a/href</a></iframe><p><strong>What is Restore Function?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbiRHJak_yXfsuMhQ-HVbQ.jpeg" /><figcaption><strong>Fig 7. Restoring</strong></figcaption></figure><p>In Fig 7., we can see that the attacker sends ARP Requests to both the machines (victim and access point) in order to restore the network into a normal state. The attacker sends the ARP requests with genuine information inside it.</p><p><strong>With Restore Function</strong></p><pre>def restore(source_ip, destination_ip):<br>    source_mac = get_mac(source_ip)<br>    destination_mac = get_mac(destination_ip)<br>    restore_packet = scapy.ARP(op = 2, pdst = destination_ip, hwdst = destination_mac, psrc = source_ip, hwsrc = source_mac)<br>    scapy.send(restore_packet, count =1, verbose = False)</pre><p>The restore function accepts two IP Addresses i.e. source_ip and destination_ip. Similarly to <strong>spoof() </strong>function, the <strong>restore() </strong>function also creates an ARP Response but instead of forging information, it creates the Request with genuine information.</p><p>You can see that the values of the pdst, hwdst, psrc and hwsrc is legitimate values as we want to restore the state. Also, note that in this function, online the <strong>spoof()</strong> function, we explicitly set the MAC Address of the sender.</p><p>In this function, we use <strong>get_mac() </strong>function to get the MAC Address of the Source IP Address and the Destination IP Address. We store these values in two variables in order to access them later. Then, we create a <strong>restore_packet </strong>with genuine IP and MAC Addresses. After that, we send the <strong>restore_packet </strong>with <strong>scapy.send()</strong>.</p><p>Remember that we called the spoof() function in the try block and we did not mention the code block in except. We’ll use this <strong>restore() </strong>function inside the except block when we encounter a <strong>KeyboardInterrupt </strong>Control + C error. We call the <strong>restore() </strong>twice because we need to restore the normal state on both sides i.e. the access point and the victim as shown in Fig 7.</p><pre>except KeyboardInterrupt:<br>    print(&quot;\n[-] Detected Ctrl + C..... Restoring the ARP Tables..... Be Patient&quot;)<br>    restore(target_ip, gateway_ip)<br>    restore(gateway_ip, target_ip)</pre><p>The above code executes as soon as it encounters KeyboardInterrupt and restores the state on both the sides by calling the <strong>restore() </strong>function twice.</p><p>This is where the Python script ends and we have successfully implemented an ARP Spoofing attack. Now, all that’s left to do is to test the script by executing it.</p><h3>Working Demo</h3><p>Okay, before jumping to writing the code in Python I’ll tell you about the setup that I have: I am currently on Windows 10 and I have <a href="https://www.virtualbox.org/">Virtualbox </a>running with two VMs (1. Kali Linux and 2. Windows 10). I will execute the python script on my Kali Linux machine and try to attack my Windows 10 VM. Note: The VMs are configured to use <strong>NatNetwork</strong> in Virtualbox. When the VMs are set to use <strong>NatNetwork, </strong>the VMs thinks the host as the router (access point). To know more about NatNetwork and how to configure a VM to use it, read <a href="https://www.techrepublic.com/article/how-to-create-multiple-nat-networks-in-virtualbox/">this</a>.</p><h4>Kali Linux Machine</h4><ul><li>IP Address = <strong>10.0.2.9</strong></li><li>MAC Address = <strong>08:00:27:35:21:2e</strong></li></ul><h4>Windows 10</h4><ul><li>IP Address = <strong>10.0.2.15</strong></li><li>MAC Address = <strong>08:00:27:e6:e5:59</strong></li></ul><h4>Access Point or Default Gateway</h4><ul><li>IP Address = <strong>10.0.2.1</strong></li><li>MAC Address = <strong>52:54:00:12:35:00</strong></li></ul><ol><li>Obtaining IP Address and the MAC Address of the target and the access point using a Network Scanner. If you haven’t read my article on how to build a network scanner then read <a href="https://medium.com/@dharmilch18/writing-a-network-scanner-using-python-a41273baf1e2">Writing a Network Scanner using Python</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*3BZqNm6n6GfHpy6DD3LxnQ.png" /><figcaption><strong>Fig 8. Finding IP and MAC Addresses using Network Scanner</strong></figcaption></figure><p>2. Access Point or Default Gateway of Windows 10 before attacking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yYMZTIOjnsHMMQyHYLpuw.png" /><figcaption><strong>Fig 9. Before the Attack</strong></figcaption></figure><p>You can see that, before the ARP Spoofing attack, the access point with the IP Address <strong>10.0.2.1</strong> has a MAC Address <strong>52:54:00:12:35:00, </strong>which is the normal network flow.</p><p>3. Attacking the Windows 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*WcHwGCCX56Rbfiz743LqWw.png" /><figcaption><strong>Fig 10. ARP Packet</strong></figcaption></figure><p>In this step, we have started our ARP Spoofing attack by specifying the IP Addresses of the target (victim) and the access point (gateway) as the command line argument.</p><p>4. ARP Table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zb4tVKrBwO6H30My4SEvkg.png" /><figcaption><strong>Fig 11. ARP Table</strong></figcaption></figure><p>In Fig 11., you can see that after carrying out the attack, the access point or the gateway’s MAC Address is the MAC Address of the Kali Linux Machine i.e. <strong>08:00:27:35:21:2e. </strong>As soon as this happens all the messages intended for the access point from Windows 10 will pass to the attacker (Kali Linux).</p><p>5. Restoring to the normal state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OK3wPN6dEhePQ23Ic5HDg.png" /><figcaption><strong>Fig 12. Restoring to the normal state</strong></figcaption></figure><p>6. ARP Table after Restoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0vs--aTaZRgHBbEFJ3ZJcQ.png" /><figcaption><strong>Fig 13. ARP Table After Restoring</strong></figcaption></figure><p>Fig 13. displays the ARP Table after the attack was stopped and the network was restored to the normal state. See the second table where the access point’s MAC Address is the original IP Address.</p><p><strong>Note: When the Windows 10 machine is being ARP spoofed, you cannot use the Internet (as shown in Fig 4.) unless you run a special command in your Kali Linux Machine.</strong></p><pre><strong>echo 1 &gt; /proc/sys/net/ipv4/ip_forward</strong></pre><p><strong>The above command will make sure that the Internet works completely fine in Windows 10. The command enables IP Forwarding in Kali Linux which effectively says Kali Linux to forward the packets to the access point.</strong></p><p>This is where Part 1 of the Man In The Middle (MITM) attack ends. Stay tuned for more parts in this series where we will intercept credentials, modify network traffic, replacing downloading files, etc. You can find the entire code for this tutorial on my <a href="https://github.com/dharmil18/ARP-Spoofer">Github Repository</a>.</p><p>Thank you for reading. For any queries, you can ask me and any constructive feedback is always appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f5b174dec59" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/man-in-the-middle-attack-part-1-arp-spoofing-6f5b174dec59">Man In The Middle Attack (MITM) Part 1 — ARP Spoofing</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Network Scanner using Python]]></title>
            <link>https://levelup.gitconnected.com/writing-a-network-scanner-using-python-a41273baf1e2?source=rss-9a0050c16170------2</link>
            <guid isPermaLink="false">https://medium.com/p/a41273baf1e2</guid>
            <category><![CDATA[network-scanner]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kali-linux]]></category>
            <dc:creator><![CDATA[Dharmil Chhadva]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 12:54:44 GMT</pubDate>
            <atom:updated>2020-08-04T02:13:48.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQFOoc5KSXa795XwvxT0DA.jpeg" /></figure><blockquote><strong>Note:</strong> The following tutorial works on any Linux Distributions, provided you have the root access i.e. you’ll have to execute this script using the root user.</blockquote><h3>What is a Network Scanner?</h3><p>A network scanner is a software tool that scans the network for connected devices. It is also used for diagnostic and investigative purposes to find and categorize what devices are running on a network. This tool takes an IP address or a range of IP addresses as input and then scans each IP Addresses sequentially and determines whether a device is present on that particular IP address or not. It scans the network and returns an IP address and it’s corresponding MAC address if the device is present. A popular tool that’s commonly used CyberSecurity professionals is <a href="https://nmap.org/"><strong>nmap</strong></a>.</p><h3>How does it work?</h3><p>To understand how the Network Scanner scans the entire network we need to first understand what is <strong>ARP (Address Resolution Protocol)</strong>.</p><p>In a network, most of the computers use the <strong>IP Address</strong> to communicate with other devices, however, in reality, the communication happens over the <strong>MAC Address. ARP is used to find out the MAC Address of a particular device whose IP address is known.</strong> For instance, a device wants to communicate with the other device on the network, then the sending device uses ARP to find the MAC Address of the device that it wants to communicate with. ARP involves two steps to find the MAC address:</p><ol><li>The sending device sends an <strong>ARP Request</strong> containing the IP Address of the device it wants to communicate with. This request is broadcasted meaning every device in the network will receive this but only the device with the intended IP address will respond.</li><li>After receiving the broadcast message, the device with the IP address equal to the IP address in the message will send an <strong>ARP Response</strong> containing its MAC Adress to the sender.</li></ol><p>Network Scanner uses ARP Request and Response to scan the entire network to find active devices on the network and also to find their MAC Addresses.</p><p>If it is still not clear what ARP is and how it works then refer to the images below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mda_kqjm4ONDM7jQnKZ7TQ.jpeg" /><figcaption><strong>Fig 1. ARP Request</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTdIvgRjXx9XewTRZVeAyg.jpeg" /><figcaption><strong>Fig 2. ARP Response</strong></figcaption></figure><p>Now that we know how does the network scanner works internally, let’s start writing it in Python.</p><h3>Modules Used:</h3><ol><li><a href="https://docs.python.org/3.4/library/subprocess.html">argparse</a>: To understand what this does read my first article <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563#f878">here</a>.</li><li><a href="https://scapy.readthedocs.io/en/latest/extending.html">Scapy</a>: Enables the user to send, sniff and dissect and forge network packets. This capability allows the development of tools that can probe, scan, or attack networks. It can forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It easily handles most tasks like scanning, tracerouting, probing, unit tests, attacks, or network discovery.</li></ol><blockquote>Okay, before jumping to writing the code in Python I’ll tell you about the setup that I have: I am currently on Windows 10 and I have <a href="https://www.virtualbox.org/">Virtualbox </a>running with two VMs (1. Kali Linux and 2. Windows 10). I will execute the python script on my Kali Linux machine and try to scan the entire network. Note: The VMs are configured to use <strong>NatNetwork</strong> in Virtualbox. To know more about NatNetwork and how to configure a VM to use it, read <a href="https://www.techrepublic.com/article/how-to-create-multiple-nat-networks-in-virtualbox/">this</a>.</blockquote><h3>Writing the Network Scanner</h3><p>As we know what modules are required, let’s start writing the script.</p><h4><strong>Step 1: Import the modules discussed above.</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/528f0d9c3697861bfcabc9a782c3dd4a/href">https://medium.com/media/528f0d9c3697861bfcabc9a782c3dd4a/href</a></iframe><h4><strong>Step 2:</strong> <strong>Implementing the functionality to allow the users to pass command line arguments.</strong></h4><p>To add this feature to our script, we’ll need to make use of the <strong>argparse</strong> module that we imported in Step 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7190c2b108fe4986e0c3fd08b241713e/href">https://medium.com/media/7190c2b108fe4986e0c3fd08b241713e/href</a></iframe><p>To know more about how argparse works and what does the above part of the script does and what functionality it adds to the script, read the entire <strong>Step 2</strong> from my previous article of how to <a href="https://medium.com/@dharmilch18/changing-mac-address-using-python-8a16fc4a3563#03c5">change MAC Address of a device</a>.</p><p>The above code allows the user to provide the input for <strong>interface</strong> value as follows:</p><pre>root@kali:~# python3 network_scanner.py -t IP_Address/IP_Addresses</pre><p><strong>OR</strong></p><pre>root@kali:~# python3 network_scanner.py --target IP_Address/IP_Addresses</pre><p><strong>IP_Address</strong> = Specific IP Address that you want to scan to check whether there is a device that’s using this IP Address or not.</p><p><strong>IP_Addresses</strong> = Range of IP Addresses that you want to scan.</p><h4><strong>Step 3: Writing function that scans the network</strong></h4><p>In this function, we’ll have to do the following things to be able to scan the network:</p><ul><li>Create an ARP Request.</li><li>Create an Ethernet Frame.</li><li>Place the ARP Request inside the Ethernet Frame.</li><li>Send the combined frame and receive responses.</li><li>Parse the responses and print the results.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed89e06bd3ac3eb6faa8b748fe704a6/href">https://medium.com/media/8ed89e06bd3ac3eb6faa8b748fe704a6/href</a></iframe><p>Note that the function <strong>scan </strong>takes an IP Address as an argument. Now, let&#39;s break down the above code line by line.</p><pre>def scan(ip):<br>    .....<br>    .....</pre><pre>scan(&#39;10.0.2.15&#39;)</pre><p>Now the first thing that we want to do is to create an ARP Request (See Fig 1.) frame using <strong>scapy</strong>.</p><pre>arp_req_frame = scapy.ARP(pdst = ip)</pre><p>The above line of code creates an ARP Request frame using scapy’s ARP Class with the destination IP Address <strong>(pdst)</strong> provided as an argument to the function. The destination IP Address is set to the IP Address passed to the function because we want to direct the ARP Request frame to the IP Address we want. For instance, if <strong>ip = ‘10.0.2.15’</strong> then the ARP Request is targetted for that IP Address only.</p><p>Now, the question is how did I come to know that destination IP Address is represented as <strong>pdst </strong>in ARP class? For this, scapy has a built-in function that we can use to find what member variables (variables) or fields a class has.</p><pre>arp_req_frame = scapy.ARP(pdst = ip)<br>print(scapy.ls(scapy.ARP()))</pre><pre><strong>OUTPUT<br></strong>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.1/24</pre><pre>hwtype : XShortField        = 1               (1)<br>ptype  : XShortEnumField    = 2048            (2048)<br>hwlen  : FieldLenField      = None            (None)<br>plen   : FieldLenField      = None            (None)<br>op     : ShortEnumField     = 1               (1)<br>hwsrc  : MultipleTypeField  = <strong>&#39;08:00:27:35:21:2e&#39;</strong> (None)<br>psrc   : MultipleTypeField  = <strong>&#39;10.0.2.9&#39;</strong>      (None)<br>hwdst  : MultipleTypeField  = &#39;00:00:00:00:00:00&#39; (None)<br>pdst   : MultipleTypeField  = &#39;0.0.0.0&#39;       (None)</pre><blockquote><strong>Note: 10.0.2.1/24 means IP Addresses from 10.0.2.1 to 10.0.2.254</strong></blockquote><p>The <strong>scapy.ls()</strong> function returns the fields a particular class has. It works for every class that scapy provides. We just have to pass the class name as <strong>scapy.class_name()</strong> to it. In the example above, we wanted to know about the fields or member variables the ARP class has and so we used the scapy.ls(scapy.ARP()). This function then gave us the response as shown in the output above. This function provides the name of the fields, a small description of that field, and the default value that each field holds.</p><p>The main fields to know are:</p><ul><li><strong>hwsrc </strong>= Source MAC Address.</li><li><strong>psrc </strong>= Source IP Address.</li><li><strong>hwdst </strong>= Destination MAC Address.</li><li><strong>pdst </strong>= Destination IP Address.</li></ul><p>Note: The <strong>hwsrc</strong> and <strong>psrc</strong> will always have the default value of the machine on which the ARP Request packet was created. In our case, the IP Address of my Kali machine is <strong>‘10.0.2.9’</strong> and MAC Address is <strong>‘08:00:27:35:21:2e’</strong> and therefore the field <strong>psrc</strong> and <strong>hwsrc</strong> has these values in them. Also, the default value for <strong>hwdst </strong>and <strong>pdst </strong>will <strong>‘00:00:00:00:00:00’</strong> and <strong>‘0.0.0.0’ </strong>respectively.</p><p>So, this is how we can change any field’s value as we want while creating an instance of the class. Additionally, we can also view the ARP Request itself by another function that scapy provides.</p><pre>arp_req_frame = scapy.ARP(pdst = ip)<br>print(arp_req_frame.summary())</pre><p>Upon execution of the above code, we get the following output. You can see that it says ‘<strong>who has 10.0.2.3 says 10.0.2.9’, </strong>this means the packet is a request packet and it’s asking everyone that who has the IP Address of <strong>10.0.2.3</strong>. The second part i.e <strong>says 10.0.2.9 </strong>provides information about the source or sender of the ARP Request to all the receiving devices and thus the receiving device with the IP Address <strong>10.0.2.3 </strong>will know whom to send the ARP Response. You can see that the output generated below is the same as what Fig 1 illustrates.</p><pre>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.3</pre><pre><strong>OUTPUT<br></strong>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.3</pre><pre><strong>ARP who has 10.0.2.3 says 10.0.2.9</strong></pre><p>Another useful function that scapy provides is <strong>show().</strong></p><pre>arp_req_frame = scapy.ARP(pdst = ip)<br>print(arp_req_frame.show())</pre><p>After the execution, it generates the following output.</p><pre>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.3</pre><pre><strong>OUTPUT</strong><br>###[ ARP ]###<br>hwtype    = 0x1<br>ptype     = IPv4<br>hwlen     = None<br>plen      = None<br>op        = who-has<br>hwsrc     = 08:00:27:35:21:2e<br>psrc      = 10.0.2.9<br>hwdst     = 00:00:00:00:00:00<br>pdst      = 10.0.2.3</pre><p>The above output shows the various fields of an ARP Request packet and its corresponding values. Note that the <strong>pdst (destination IP Address) </strong>has a value of <strong>10.0.2.3 </strong>because when executing the code we provide a command-line argument for which IP Address to scan and this IP Address is then set to pdst. This is because at the time of creating an instance of the ARP class we provided the IP Address of the destination device using <strong>scapy.ARP(pdst = ip) </strong>where <strong>ip</strong> is a variable name and its value is taken from the command-line argument that was passed at the time of execution. We already covered how to add command-line argument functionality that accepts input in <strong>Step 2</strong>.</p><p>After creating the ARP Request packet we need to now create an <a href="https://en.wikipedia.org/wiki/Ethernet_frame">Ethernet</a> Frame. The Ethernet frame contains fields such as Source and Destination Hardware (MAC) among others. Now, as the communication inside a network is carried out using the MAC Address, we can set the value of destination hardware address field to theMAC Address to which we want to communicate. Learn more about <a href="https://www.geeksforgeeks.org/ethernet-frame-format/">Ethernet Frame here</a>.</p><p>The ARP Request is supposed to be broadcasted (transmitted to every IP Address in a network). Therefore, to broadcast the ARP Request we set the <strong>Destination Address</strong> field of Ethernet field to <strong>‘ff:ff:ff:ff:ff:ff’ </strong>as this is a broadcast MAC Address. We now do this using scapy.</p><pre>broadcast_ether_frame = scapy.Ether(dst = &quot;ff:ff:ff:ff:ff:ff&quot;)</pre><p>The above line of code creates an Ethernet Frame with <strong>dst (Destination Address)</strong> is set to <strong>‘ff:ff:ff:ff:ff:ff’. </strong>Note, we can use scapy.ls() and show() function on Ethernet class. The fields of the Ethernet frame can be viewed using scapy.ls() function similarly to how we did it on ARP Class. The show() function can also be used similarly as we did for ARP Class. Output for both the function can be seen below.</p><pre>print(scapy.ls(scapy.Ether()))</pre><pre><strong>OUTPUT<br></strong>dst  : DestMACField     = &#39;ff:ff:ff:ff:ff:ff&#39; (None)<br>src  : SourceMACField   = &#39;08:00:27:35:21:2e&#39; (None)<br>type : XShortEnumField  = 36864           (36864)</pre><pre>--------------------------------------------------------------------</pre><pre>print(broadcast_ether_frame.show())</pre><pre><strong>OUTPUT<br></strong>###[ Ethernet ]###<br>dst       = ff:ff:ff:ff:ff:ff<br>src       = 08:00:27:35:21:2e<br>type      = 0x9000</pre><p>The next step is to combine the ARP Request and the Ethernet Frame. We did this using scapy because it allows a very convenient way to combine frames. We do it by the following line of code.</p><pre>broadcast_ether_arp_req_frame = broadcast_ether_frame/arp_req_frame</pre><p>The above code creates a new frame by combining the ARP Request and Ethernet Frame using the <strong>‘/’ </strong>sign. This is because scapy allows us to combine frames using this.</p><p>Now if we call the <strong>show()</strong> function we can see that the final combined frame consists of both Ethernet and ARP Request.</p><pre>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.3</pre><pre><strong>OUTPUT<br></strong>###[ Ethernet ]###<br>dst       = ff:ff:ff:ff:ff:ff<br>src       = 08:00:27:35:21:2e<br>type      = ARP</pre><pre>###[ ARP ]###<br>hwtype    = 0x1<br>ptype     = IPv4<br>hwlen     = None<br>plen      = None<br>op        = who-has<br>hwsrc     = 08:00:27:35:21:2e<br>psrc      = 10.0.2.9<br>hwdst     = 00:00:00:00:00:00<br>pdst      = 10.0.2.3</pre><p>We can see that the type field of Ethernet Frame now holds ARP as its type. Also, the ARP part of the frame is identified as <strong>ARP Request </strong>by the value of the <strong>op </strong>field. If <strong>op = who-has</strong> then it means its an <strong>ARP Request</strong> and if <strong>op = is-at</strong> then it is <strong>ARP Response</strong>.</p><p>Now the only thing that is remaining is to sent the combined frame and to receive the responses. To send the requests and receive the responses we will use a function provided by scapy that not only sends the requests but also returns the responses.</p><p>This function returns the captured responses as a python tuple out of which the first element of the tuple has the <strong>answered</strong> responses where the devices responded and the second element has the responses which were <strong>unanswered</strong>. The responses which are in the unanswered list mean that there are no devices that use those IP Addresses.</p><p>The function that scapy provides to do the above tasks is called <strong>scapy.srp(). </strong>This function takes the actual frame to be transmitted as an argument. You can see that we have passed <strong>broadcast_ether_arp_req_frame (our final combined frame) </strong>is passed to the function below. It also takes a <strong>timeout </strong>input which tells the scapy for how much time period it should wait to receive a response before moving further. What this means is, from the below example <strong>timeout = 1</strong> means the scapy will wait for 1 second for the response and if the response is not received it will move further to send the packet to the next IP Address. The argument <strong>verbose = False</strong> is not important and it only stops the scapy from printing its own messages on the screen.</p><pre>answered_list= scapy.srp(broadcast_ether_arp_req_frame, timeout = 1, verbose = False)<br>    print(&#39;Total Number of Responses -&gt;&#39;, len(answered_list))<br>    print(&#39;\n-----------Answered Responses---------&#39;)<br>    print(&#39;Number of Answered Responsed -&gt;&#39;, len(answered_list[0]))<br>    print(&#39;\n&#39;)<br>    for i in range(0,len(answered_list[0])):<br>        print(answered_list[0][i])<br>        print(&#39;\n&#39;)<br>    print(&#39;\n-----------UnAnswered Responses---------&#39;)<br>    print(&#39;Number of UnAnswered Responsed -&gt;&#39;, len(answered_list[1]))<br>    print(&#39;\n&#39;)<br>    for i in range(0,len(answered_list[1])):<br>        print(answered_list[1][i])<br>        print(&#39;\n&#39;)</pre><p>The above code displays the total number of answered (responded) responses and the actual responses itself. It also displays the total number of unanswered (not responded) responses and the actual responses.</p><p>Note: This code is not used in the final script and is just for understanding the output returned by <strong>scapy.srp()</strong> function. The above code generates the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ok3M83G4Ujj79XkY87hoqQ.png" /><figcaption>scapy.srp() function’s Output</figcaption></figure><p>From the above image, we can see that the total number of responses received was <strong>two. </strong>This is because the tuple consists of two elements <strong>answered</strong> and <strong>unanswered</strong>. Furthermore, we can see that the total answered responses are <strong>three</strong> which means that only <strong>three</strong> devices responded with ARP Response. Below this, we can also see the actual responses itself. After this, we see that the total unanswered responses are <strong>253 </strong>which means <strong>253 </strong>devices did not respond. We can also see some of the responses that scapy recorded for unanswered responses.</p><p>The main aim of showing the above output was to make you understand that we only need the answered responses and not the unanswered one. Therefore, we can access only the answered responses using the following line of code.</p><pre>answered_list = scapy.srp(broadcast_ether_arp_req_frame, timeout = 1, verbose = False)[0]</pre><p>As the <strong>answered_list</strong> is a tuple we can extract the individual elements by providing the index in square brackets. The above code will only store answered responses.</p><p>Now, all that is left is to extract the IP Address and the MAC Address from each of the answered responses. We’ll use Python dictionaries inside of a list for that purpose.</p><pre>result = []<br>    for i in range(0,len(answered_list)):<br>        client_dict = {&quot;ip&quot; : answered_list[i][1].psrc, &quot;mac&quot; : answered_list[i][1].hwsrc}<br>        result.append(client_dict)</pre><pre>print(result)</pre><p>The above code creates an empty list called <strong>result </strong>and then creates a dictionary called <strong>client_dict </strong>for each response and then appends it to the <strong>result</strong> list. The <strong>client_dict </strong>has two keys <strong>‘ip’</strong> and <strong>‘mac’</strong> which stores the IP Address and MAC Address respectively. The output of the above code for our case will be:</p><pre>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.1/24</pre><pre>[{&#39;ip&#39;: &#39;10.0.2.1&#39;, &#39;mac&#39;: &#39;52:54:00:12:35:00&#39;}, {&#39;ip&#39;: &#39;10.0.2.2&#39;, &#39;mac&#39;: &#39;52:54:00:12:35:00&#39;}, {&#39;ip&#39;: &#39;10.0.2.3&#39;, &#39;mac&#39;: &#39;08:00:27:22:d8:10&#39;}]</pre><p>The next step in the <strong>scan()</strong> function is to return the <strong>result</strong> list. We’ll use the result list in another function to print the results in a certain format.</p><h4>Step 4: Writing function to print the results in a certain format.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5350aa127d58e168dde8710e96bc169f/href">https://medium.com/media/5350aa127d58e168dde8710e96bc169f/href</a></iframe><p>The above display() function takes the result list as an input and displays the result in a certain format. It produces the output shown below.</p><pre>root@kali:~/Desktop/Network Scanner# python3 network_scanner.py -t 10.0.2.1/24<br>-----------------------------------<br>IP Address     MAC Address<br>-----------------------------------<br>10.0.2.1       52:54:00:12:35:00<br>10.0.2.2       52:54:00:12:35:00<br>10.0.2.3       08:00:27:22:d8:10</pre><p>This is where the script is complete and we have created a network scanner using Python successfully.</p><h4>Working Example</h4><p>I am using a Virtualbox setup with two VMs (Kali Linux and Windows 10). I’ll show you that the scanner that we created works perfectly fine. I’ll execute the script in Kali Linux and I will also start Windows 10 VM. The expectation is that the output should contain the IP Address and MAC Address of the Windows 10 VM also.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*s7JrqxS0JWCTefI0tyH__w.png" /><figcaption>Windows 10 VM</figcaption></figure><p>From the above image, we can note two things about the Windows 10 VM:</p><ol><li>IP Address = 10.0.2.15</li><li>MAC Address = 08-00-27-e6-e5-59 (represented as Physical Address in the image below the Description field)</li></ol><p>Now, the output generated by the script on the Kali Linux machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JI3MNlVOdmBJd9ki-crvpw.png" /><figcaption>Script Output on Kali Linux VM</figcaption></figure><p>From the above image, we can see that the network scanner script that we created scans the entire network including the Windows 10 VM which is in the same network.</p><p>Thank You for reading. The entire code can found in my <a href="https://github.com/dharmil18/Network-Scanner">Github Repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a41273baf1e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/writing-a-network-scanner-using-python-a41273baf1e2">Writing a Network Scanner using Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changing the MAC Address using Python]]></title>
            <link>https://levelup.gitconnected.com/changing-mac-address-using-python-8a16fc4a3563?source=rss-9a0050c16170------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a16fc4a3563</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kali-linux]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Dharmil Chhadva]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 13:51:18 GMT</pubDate>
            <atom:updated>2020-08-05T12:12:07.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*OzLQY2lUIx_r6ZI2v6ZBew.jpeg" /><figcaption>Media Access Control (MAC) Address</figcaption></figure><blockquote><strong>Note:</strong> The following tutorial works on any Linux Distributions, but you will need the root access to execute the system commands necessary in order to change the MAC Address successfully.</blockquote><h4>What is MAC Address?</h4><p>To learn how to change the MAC Address, it is essential to learn about what a MAC Address is. We all use various electronic gadgets such as smartphones, desktops, laptops, tablets, and many more to browse the internet, for entertainment, among other tasks. Each of these electronic gadgets has its own MAC Address. <strong>MAC</strong> stands for <strong>Media Access Control</strong> Address. Every device needs a MAC Address to be uniquely identified by others on the network. For instance, when you watch a video on Youtube, you send a request for the video via your device, and this request is transmitted through your default gateway (usually through a router for a private home network). The router then sends this request to the World Wide Web and receives a response. Now, the <strong>World Wide Web (which is public)</strong> does not know who you are because your device has a <strong>private IP Address</strong> that is only recognized by your router, so the response received by the router is then given to you because the router knows your MAC Address associated with the private IP Address of your device.</p><p>MAC Address is a 48-bits hardware address that is hardcoded on the <strong>Network Interface Card (NIC)</strong> at the time of manufacturing. MAC Address is also known as the <strong>Physical Address</strong> of a device. MAC Addresses are used to transmit packets within the network.</p><p>For example, <strong>00:1A:3F:F1:4C:C6</strong> is a MAC Address. The first three octets (00:1A:3F) of the address identifies the manufacturer and is known as <strong>OUI (Organizational Unique Identifier). </strong>The last three octets are <strong>Network Interface Controller Specific</strong>.</p><p>Read more about <strong>NIC</strong> <a href="https://www.tutorialspoint.com/what-is-network-interface-card-nic">here</a>.</p><h4>Why do we need to change the MAC Address?</h4><p>There are several reasons why you would want to change the MAC Address of your device. Let’s look at them one by one:</p><ul><li><strong>Increase Anonymity:</strong> When on a public network, you might want to change the MAC Address to stay anonymous, if you don’t then there are chances that the network you are on might log your MAC Address and thus leaving behind a trail.</li><li><strong>Impersonate other devices:</strong> When you want to carry out an attack (for testing purposes), changing the MAC Address can be useful to impersonate any legitimate device.</li><li><strong>Bypassing filters:</strong> If a MAC Address is blacklisted to use the network, and to overcome this is to change the MAC Address and fool the filters.</li></ul><h4>How to change the MAC Address?</h4><p>To change the MAC Address, we need to execute a few system commands. The first step is to identify the interface whose MAC Address you want to change and you can do this using the following command in Linux.</p><pre>dcode@dcode-pop-os:~$ ifconfig</pre><p>The above command produces the following output.</p><pre><strong>enp0s3:</strong> flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt;  mtu 1500<br>        inet 10.0.2.5  netmask 255.255.255.0  broadcast 10.0.2.255<br>        <strong>ether 08:00:27:35:21:ff</strong>  txqueuelen 1000  (Ethernet)<br>        RX packets 13962  bytes 17732985 (17.7 MB)<br>        RX errors 0  dropped 0  overruns 0  frame 0<br>        TX packets 7969  bytes 975852 (975.8 KB)<br>        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0</pre><p>First of all, to change the MAC Address we need to know the <strong>interface name</strong> and the existing <strong>MAC Address. </strong>This information can be obtained by executing the <strong>ifconfig</strong> command. We can get the interface name and the existing MAC Address from the output produced by <strong>ifconfig</strong>. For instance, from the above output, <strong>enp0s3 </strong>is the name of the <strong>interface </strong>and the <strong>ether</strong> field on the third line has the MAC Address (<strong>08:00:27:35:21:ff</strong> in our case).</p><p>Now that we know the interface name whose MAC Address we want to change, we can move to the next command.</p><pre>dcode@dcode-pop-os:~$ sudo ifconfig enp0s3 down</pre><p>The above command when executed, takes the interface down. What that means is you will no longer be able to connect to the internet. We need to take the interface down <strong>(disabling it)</strong> first if we need to change the MAC Address. After this, the next command to be executed will change the MAC Address.</p><pre>dcode@dcode-pop-os:~$ sudo ifconfig enps03 hw ether 00:11:22:33:44:55</pre><p>The above command changes the existing MAC Address <strong>(08:00:27:35:21:FF)</strong> to a new MAC Address <strong>(00:11:22:33:44:55)</strong> specified in the command itself. Now the MAC Address of the interface enp0s3 has been changed but to use it, we need to enable the interface again using the following command.</p><pre>dcode@dcode-pop-os:~$ sudo ifconfig enp0s3 up</pre><p>After executing the above command, you enable the interface again so that you can access the internet. To check whether the MAC Address was changed to what we specified, execute the <strong>ifconfig</strong> command.</p><pre>dcode@dcode-pop-os:~$ ifconfig<br><strong>enp0s3:</strong> flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt;  mtu 1500<br>        inet 10.0.2.5  netmask 255.255.255.0  broadcast 10.0.2.255<br>        <strong>ether 00:11:22:33:44:55</strong>  txqueuelen 1000  (Ethernet)<br>        RX packets 13997  bytes 17737735 (17.7 MB)<br>        RX errors 0  dropped 0  overruns 0  frame 0<br>        TX packets 8892  bytes 1059117 (1.0 MB)<br>        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0</pre><p>From the output, we can see that the MAC Address was changed to <strong>00:11:22:33:44:55</strong> from <strong>08:00:27:35:21:ff</strong>.</p><h4>Using Python to change the MAC Address</h4><p>Up until now, we manually typed the commands and executed them but we can automate the entire process using Python so that we just have to provide the script with the interface name and the new MAC Address.</p><p><strong>Modules Used:</strong></p><ul><li><a href="https://docs.python.org/3.4/library/subprocess.html">subprocess</a></li><li><a href="https://docs.python.org/3/library/argparse.html">argparse</a></li><li><a href="https://docs.python.org/3/library/re.html">re</a></li></ul><p>The <strong>subprocess</strong> module is used to execute system commands using Python. It contains several functions that can be used. We are going to focus on one particular function that is used to execute the system commands. It is called the <strong>call() </strong>function.</p><p><strong>Usage</strong></p><pre>subprocess.call([‘ifconfig’])</pre><p>This instruction executes the ifconfig command using Python.</p><p>The <strong>argparse </strong>module makes it convenient to write user-friendly command-line interfaces. The program defines the arguments it requires and <strong>argparse </strong>will figure out how to parse these arguments. It also generates help and usage messages and issues errors when the user enters any invalid arguments.</p><p><strong>Usage</strong></p><pre>dcode@dcode-pop-os:~$ python3 programs_name.py -op1 option -op2 option</pre><p>With the help of argparse we can provide the user with the ability to pass the input values using command-line arguments. Even if you don’t understand now, it will be clear once we start coding 😃.</p><p>Next, the <strong>re </strong>module provides <strong>Regular Expression</strong> matching operations. You’ll know for what we use the <strong>re</strong> module as we progress ahead.</p><h4>Python Script Coding</h4><p>This is where we start coding in Python.</p><p><strong>Step 1:</strong> <strong>Import the modules discussed above.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14fbbe72c9ca4694ff56a2f04fb865bb/href">https://medium.com/media/14fbbe72c9ca4694ff56a2f04fb865bb/href</a></iframe><p><strong>Step 2:</strong> <strong>Implementing the functionality to allow the users to pass command line arguments.</strong></p><p>To add this feature to our script, we’ll need to make use of the <strong>argparse</strong> module that we imported in Step 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d3a1ef4715b8a619edde0ddcffbbfff/href">https://medium.com/media/9d3a1ef4715b8a619edde0ddcffbbfff/href</a></iframe><p>The above code allows the user to provide the input for <strong>interface</strong> value and <strong>new MAC Address</strong> as follows:</p><pre>dcode@dcode-pop-os:~$ python3 mac_changer.py -i interface_name -m new_mac_address</pre><p><strong>OR</strong></p><pre>dcode@dcode-pop-os:~$ python3 mac_changer.py --interface interface_name --mac new_mac_address</pre><p>interface_name = Name of the interface whose MAC Address you want to change.</p><p>new_mac_address = MAC Address that you want to replace in place of the old one.</p><p>The <strong>options </strong>stores the values provided by the user. When you print it the output is as follow:</p><pre>print(options)</pre><pre><strong>Output:</strong> <br>Namespace(interface=&#39;enp0s3&#39;, new_mac=&#39;00:55:22:33:44:11&#39;)</pre><p>Individually accessing the <strong>two </strong>arguments is done as follows:</p><pre>print(options.interface)<br>print(options.new_mac)</pre><pre><strong>Output:</strong> <br>enp0s3<br>00:11:22:33:44:55</pre><blockquote>Note: The <strong>dest </strong>argument in the <strong>add_argument() </strong>method provides the name according to which the <strong>parse_args()</strong> stores its corresponding values in the <strong>options </strong>variable.</blockquote><p>The last thing in Step 2 is we created a variable <strong>command_args </strong>and invoked the function <strong>get_args()</strong>.</p><pre>command_args = get_args()</pre><p>The above statement will store the <strong>options </strong>returned by the<strong> get_args() </strong>hence giving us access to the argument values outside of the scope of the function.</p><p><strong>Step 3: Writing a function that changes the MAC Address.</strong></p><p>Now that we have the two values that we require to change the MAC Address <strong>(interface and new MAC Address), </strong>we’ll write a function that changes the MAC Address using system commands.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bccd76722b0b49a676bf7a881de5f44/href">https://medium.com/media/0bccd76722b0b49a676bf7a881de5f44/href</a></iframe><p>Look at the function that we just wrote, it accepts <strong>two </strong>arguments <strong>(interface and new_mac). </strong>The two values are provided to <strong>change_mac()</strong> function by <strong>command_args</strong> variable. It also checks whether the MAC Address provided is valid or not. After that, using the <strong>subprocess </strong>module we execute the system commands. Note: You require root access to execute these commands.</p><p>Now, at this point, we have completed a Python script that changes the MAC Address, but we still need to be sure that the new MAC Address was applied. And for that, we need a write another function that returns the current MAC Address of the interface.</p><p><strong>Step 4: Writing a function to get the current MAC Address</strong></p><p>This function takes interface as an input and returns the current MAC Address of that interface. We are writing this function to check whether the new MAC address was applied or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21ad851121bfcd69a5da5ffcb3ca1e38/href">https://medium.com/media/21ad851121bfcd69a5da5ffcb3ca1e38/href</a></iframe><p>So, the <strong>get_current_mac()</strong> function extracts the current MAC Address of the interface provided. Now, let’s break down this function.</p><pre>output = sub.check_output([&#39;ifconfig&#39;, interface], universal_newllines = True)</pre><p>The above statement is similar to <strong>sub.call()</strong> in the <strong>change_mac()</strong> function but there is one difference. The <strong>sub.check_output()</strong> functions returns the output of the command whereas <strong>sub.call()</strong> does not return anything. The returned output is stored in the variable <strong>output.</strong></p><p>Also, the argument <strong>universal_newlines = True </strong>is used because if this value is set to <strong>False</strong> then the output returned is in <strong>bytes.</strong></p><blockquote>Official Docs -&gt; By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behavior may be overridden by setting <em>universal_newlines</em> to True</blockquote><p>The next statement is,</p><pre>search_mac = re.search(r&quot;\w\w:\w\w:\w\w:\w\w:\w\w:\w\w&quot;, output)</pre><p>This is where the <strong>re</strong> module is being used.<strong> re</strong> stands for Regular Expressions and these are often used in string matching applications. The <strong>re.search()</strong> function accepts the <strong>regular expression</strong> and the <strong>string</strong> in which the pattern is supposed to be matched. In our case, the string is stored inside the variable <strong>output. </strong>The <strong>\w\w:\w\w:\w\w:\w\w:\w\w:\w\w </strong>expression matches the MAC Address in the output variable which has the output of the <strong>ifconfig</strong> command. See the image below to understand it better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6kJTE176C7GJTuPsi2A8AA.png" /><figcaption>Regex Demonstration</figcaption></figure><p>As you can see that the regular expression matches the MAC Address perfectly (Highlighted in green in the Match result box). <a href="https://pythex.org/">Regular Expression Cheatsheet</a></p><p>Furthermore, there are chances that <strong>re.search()</strong> might find more than one string that matches the regex (regular expression). Therefore, the below statement will make sure to return the first matched element only. What if it matches more than one string and returns the string which is not desired? In the output returned by <strong>ifconfig,</strong> the chances of a getting string other than the desired one is next to zero.</p><pre>search_mac.group(0)</pre><p>This sums up the <strong>get_current_mac()</strong> function.</p><p>Now, the only thing remaining is to check whether the MAC Address provided by the user was applied. For this, you can see that we have called <strong>get_current_mac()</strong> function twice, once before calling <strong>change_mac()</strong> function and once after calling the <strong>change_mac()</strong> function. This ensures that we capture both the MAC Addresses (before and after change). We then compare <strong>changed_mac</strong> and <strong>command_args.new_mac </strong>and if both matches then the MAC Address has been changed successfully.</p><pre>if changed_mac == command_args.new_mac:<br>    print(&#39;Successfully Changed the MAC Address&#39;)<br>else:<br>    print(&#39;Could not change the MAC Address&#39;)</pre><p>This where the script ends and to execute the script do the following: This was covered in <strong>Step 2.</strong></p><pre>dcode@dcode-pop-os:~$ python3 mac_changer.py -i interface_name -m new_mac_address</pre><pre><strong>OR</strong></pre><pre>dcode@dcode-pop-os:~$ python3 mac_changer.py --interface interface_name --mac new_mac_address</pre><p>The entire code can be found on my <a href="https://github.com/dharmil18/MAChanger">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a16fc4a3563" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/changing-mac-address-using-python-8a16fc4a3563">Changing the MAC Address using Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>