ARP Alert tool in C for Linux

Published by admin. 9. July 2019 No Comments

Introduction

A couple of days ago, my roommate’s laptop got hacked. Some of our neighbours managed to gain access to his camera (on a Windows 10 machine). I then tried to figure out if there is a simple possibility to get notified whenever a new device is connecting to your computer. I am going to write a simple tool in C for Linux, which is not going to solve my roommates problem. But I mostly do it for fun anyways. The goal is to display a message containing the MAC and IP address of a device, which is sending an ARP request to my computer. Basic C programming skills as well as a basic understanding of what ARP (Address Resolution Protocol) is, would be very helpful. This tutorial is based on my github project network_notifier.

Let’s get started

The following describes the steps to code a simple ARP alertion tool in C for Linux. Once running, this tool will notify the user of incoming ARP requests following certain criterias. We will use a white list of mac addresses, which are to be ignored and a black list of mac addresses, which will not receive an ARP reply. All other requests will be reported to the user.

The following describes the steps to code a simple ARP alertion tool in C for Linux. Once running, this tool will notify the user of incoming ARP requests following certain criterias. We will use a white list of mac addresses, which are to be ignored and a black list of mac addresses, which will not receive an ARP reply. All other requests will be reported to the user.

This tutorial will be divided into three parts:

  1. Writing a simple general purpose network sniffer library in C
  2. Writing a simple library to read from files containing the white and black list of mac addresses in C
  3. Putting everything together in a C program

Note: I am developing using Visual Studio Code, the gcc compiler and Ubuntu 19.10.

Part 1: Network Sniffer in C

In the following, I am using a tutorial from Binarytides on writing a simple package sniffer in C.

Every package received basically consists of two parts: A header and a payload. We are interested in retrieving both of them, which means we need to open a raw socket:

int sock_raw = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

Once the socket is opened, we can run a loop to receive data from it:

while(1)
{
    size = recv(sock_raw, buffer, IP_MAXPACKET, 0);
    //...
}

The next step is to assign the buffer to a suitable structure:

 struct ethhdr *header = (struct ethhdr *)buffer;
 int protocol = ntohs(header->h_proto);

Note: The byte order on network streams is reversed, meaning that before sending data we need to call htons() (host to network – short) on it. And when receiving data, we need to call ntohs().

Now, we can simply use a switch case statement to find out which protocol was used.

References

Leave a Reply

Your email address will not be published. Required fields are marked *