Creating a Real-time HoneyPot Attack Map

Every device connected to the internet is open for cyber attacks. It takes less than one minute before a system is attacked once it is connected to the internet. Recently, I worked on a hackathon project to visualize honeypot attacks on a map in real-time.

A honeypot is a computer system that mimics a target for hackers. It tries to fool hackers into thinking it is a real computer system, distracting them from other targets.

Initial Setup

There are many honeypot systems around but for this project I used T-Pot created by Deutsche Telekom Security. It consists of many honeypot daemons and tools out-of-the-box and is easy to setup.

To create a live map, we need to have the following:

  • Running T-Pot instance
  • Small server with a webserver (nginx) and Node.js/NPM

Follow the instructions to install T-Pot. Confirm your T-Pot instance is running and you see attacks appearing in the dashboards.

There are many instructions on how to install a server with Nginx and Node.js (one example can be found here).

Node.js Application to Receive Logs

On the webserver, we create a small Node.js application that will do two simple tasks:

  • Receive data from the T-Pot installation (logstash)
  • Run a small websocket server to broadcast the received data to connected clients

Install required packages
In our Node.js application we use two packages: `express` and `ws`. First install both packages:

npm install ws express

Now we create a small application called `server.js`:

vi server.js

Insert the following code into the file:

#!/usr/bin/env nodejs
const http = require('http');
const WebSocket = require('ws');
const express = require('express');
const app = express();

const PORT = 8080;
const WS_PORT = 8081;

app.use(express.json());

// Create a WebSocket Server so clients can connect to it
const wss = new WebSocket.Server({ port: WS_PORT })
wss.on('connection', function connection(ws) {
});

// Now we create a simple HTTP server which receives a message
// and forwards the message to the connected WebSocket clients
app.get('/', (req, res) => {
  res.send('Hello');
});

app.post('/', (req, res) => {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(req.body));
    }
  });
  res.sendStatus(200);
});

app.listen(PORT, () => {
   console.log('The server is running at port 8080!');
});

This small Node.js application simply listens on port 8080 to receive a POST message. WebSockets can connect to port 8081. Once a message is received on port 8080, it is sent to all connected WebSocket clients.

Test Application

To test your application, make it executable:

chmod +x server.js

Now run the application:

./server.js

The output will be:

The server is running at port 8080!

You can use a process manager like PM2 to daemonize your application:

sudo npm install -g pm2
pm2 start server.js

PM2 will restart applications automatically if the application crashed or is killed. In order to have your application to run after a system (re)boot, you will need to execute another command:

pm2 startup systemd

This command output might include a command which needs to be run with superuser privileges:

sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u your_user — hp /home/your_user

Webpage Showing the Map

Now we will create a small webpage, and add some Javascript code. This code will open a websocket to receive updates and plot them on a map. To create a world map, I used Mapbox GL JS. You will need to create a (free) account in order to create an API key that will be used to create a map.

If you have a server running default Nginx, create a new `index.html` in the web-root folder:

cd /var/www/html
vi index.html

Insert the following HTML code into the file:

<!DOCTYPE HTML>
<html>
   <head> 
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
   <script src='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.js'></script>
    <link href='https://api.mapbox.com/mapbox-gl-js/v2.0.1/mapbox-gl.css' rel='stylesheet' />  
    <style>
        @import url(https://fonts.googleapis.com/css?family=Inconsolata:400,500);

        body { background-color: black }
        #map { height: calc(100vh - 275px);; width: ; z-index: 1; }
        .table { color: #fff; font-family: Inconsolata,sans-serif; font-size: 15px; border-color: #525252;}    
        .thead { font-weight: 700; color: #525252; }            
        
        @-webkit-keyframes flashrow {
           from { background-color: #525252; }
           to { background-color: var(--bs-table-bg); }
         }
         @-moz-keyframes flashrow {
           from { background-color: #525252; }
           to { background-color: var(--bs-table-bg); }
         }
         @-o-keyframes flashrow {
           from { background-color: #525252; }
           to { background-color: var(--bs-table-bg); }
         }
         @keyframes flashrow {
           from { background-color: #525252; }
           to { background-color: var(--bs-table-bg); }
         }
         .flashrow {
           -webkit-animation: flashrow 1.5s; /* Safari 4+ */
           -moz-animation:    flashrow 1.5s; /* Fx 5+ */
           -o-animation:      flashrow 1.5s; /* Opera 12+ */
           animation:         flashrow 1.5s; /* IE 10+ */
         }
    </style>   
   </head>   
   <body>
   <div class="container">   
    <div class="row">
      <div class="col">
         <div id="map"></div>
      </div>
   </div>
   <div class="row">
      <div class="col" id="ticker">
         <table id="tickettable" class="table table-black ticker">
            <thead class="text-uppercase thead">
               <tr>
                  <th class="col-lg-1 thead">Time</th>
                  <th class="col-lg-2 thead">Country</th>
                  <th class="col-lg-3 thead">AS Organisation</th>
                  <th class="col-lg-6 thead">TYPE</th>
               </tr>
            </thead>
            <tbody>            
            </tbody>
         </table>         
      </div>
   </div>
</div>
<script src='map.js'></script>
</html>

This page simple loads Mapbox GL Javascript libraries and some styles. It also loads another Javascript file (at the bottom) which will open the Websocket and update the map.
Let’s create this Javascript file:

vi map.js

and insert the following code into the file:

// Set the IP to your webserver IP
const WEBSOCKET_SERVER = 'ws://<YOUR_WEBSERVERIP:8081>';
// Set your mapboxGL AccessToken
const MAPBOX_TOKEN = 'YOUR_ACCESS_TOKEN';

// Remove points from map after x-seconds
var displayTime = 300;

// Set some defaults for the map

var framesPerSecond = 15; 
var initialOpacity = 1;
var opacity = initialOpacity;
var initialRadius = 3;
var radius = initialRadius;
var maxRadius = 15;
let points = new Map();
var timers = [];

//Set your accessToken here
mapboxgl.accessToken = MAPBOX_TOKEN;

//Create new mapboxGl Map. Set your used style
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/leaseweb/ckkiepmg40ds717ry6l0htwag',
    center: [0, 0],
    zoom: 1.75
});

// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
   closeButton: false,
   closeOnClick: false
});

// Once the map is loaded, we open the Websockets
map.on('load', function () {   
   openWebSockets(map); 
});

function openWebSockets(map) { 
   if ("WebSocket" in window) {
      // Let us open a web socket
      var ws = new WebSocket( WEBSOCKET_SERVER); 

      ws.onopen = function() {
         // Web Socket is connected, send data using send()         
         console.log("WS Open...");
      };
   
      ws.onmessage = function (event) { 
         var received_msg = JSON.parse(event.data);             
         addPoint(received_msg);            
      };

      ws.onerror = function(error) {
         console.log('Websocket error: ');
         console.log(error);
      }

      ws.onclose = function() { 
         // websocket is closed.
         console.log("Connection is closed..."); 
      };

   } else {
      // The browser doesn't support WebSocket
      alert("WebSocket NOT supported by your Browser!");
   }    
}

function animateMarker(timestamp, pointId) {
   if(!(pointId === undefined)) {
      if (points.has(pointId)) {         
        timers[pointId] = setTimeout(function() {
            requestAnimationFrame(function(timestamp) {
              animateMarker(timestamp, pointId);
            });
            

            radius = points.get(pointId)[0];
            opacity = points.get(pointId)[1];
            
            radius += (maxRadius - radius) / framesPerSecond;            
            opacity -= ( .9 / framesPerSecond );
            if (opacity < 0) {
               opacity = 0;
            }

            map.setPaintProperty('point-'+pointId, 'circle-radius', radius);
            map.setPaintProperty('point-'+pointId, 'circle-opacity', opacity);
         
            if (opacity <= 0) {
                radius = initialRadius;
                opacity = initialOpacity;
            } 
            points.set(pointId,[radius, opacity ]);        
        }, 1000 / framesPerSecond);
     } else {
      //The point is removed, we don't do anything at this moment
     }
  }
}

function addPoint(msg) {
   geo = JSON.parse(msg.geoip);     
   var ip = geo.ip;
   //Create a geohash based on the lat/lon of the IP. We used factor 7 to prevent overlapping point animations
   var geohash = encodeGeoHash(geo.latitude, geo.longitude, 7);
   //Get the AS Organisation name (or unknown)
   var ASORG = (geo.as_org === undefined ? 'Unknown' : geo.as_org);

   //Remove the flashrow style from last added row
   var flashrows = document.getElementById("tickettable").getElementsByClassName('flashrow');
   while (flashrows[0]) {
      flashrows[0].classList.remove('flashrow');
   }
   
   //Get table to add the newly added point information
   var tbody = document.getElementById("tickettable").getElementsByTagName('tbody')[0];
   
   tbody.insertRow().innerHTML = '<tr><td class="flashrow">' + new Date().toLocaleTimeString() + '</td>' +
         '<td class="flashrow">' + geo.country_name + '</td>' +
         '<td class="flashrow">' + ASORG + '</td>' +
         '<td class="flashrow">' + msg.protocol.toUpperCase() + ' Attack on port ' + msg.dest_port +'</td>' +    
         '</tr>';
   
   //If we have more than 5 items in the list, remove the first one
   if (tbody.rows.length > 5) {
      tbody.deleteRow(0);
   }

   //Add the point to the map if it is not already on the map
   if (!(geohash === undefined)) {               
      if (!(points.has(geohash))) {
         
         //Add the point to hash to keep of all active points and prevent duplicate points.
         points.set(geohash, [initialRadius, initialOpacity ]);               

         //Set a timer to remove the poinrt after 5minutes
         setTimeout(function() { removePoint(geohash) }, displayTime * 1000);            

         map.addSource('points-'+geohash, {
           "type": "geojson",
           "data": {
               "type": "Feature",
               "geometry": {
                  "type": "Point",
                  "coordinates": [ geo.longitude, geo.latitude]
               },
               "properties": {
                  "description": "<strong>" + ASORG + " (AS " + geo.asn +")</strong><p>IP: " + ip + "<BR>City: " + (geo.city_name === undefined ? 'Unknown' : geo.city_name) + 
                     "<BR>Region: " + (geo.region_name === undefined ? 'Unknown' : geo.region_name) + "<BR>Country: " + (geo.country_name === undefined ? 'Unknown' : geo.country_name) + "</P>"
               }
           }
         });
         
         map.addLayer({
           "id": "point-"+geohash,
           "source": "points-"+geohash,
           "type": "circle",
           "paint": {
               "circle-radius": initialRadius,
               "circle-radius-transition": {duration: 0},
               "circle-opacity-transition": {duration: 0},
               "circle-color": "#dd7cbf"
           }
         });  

         map.on('mouseenter', 'point-'+geohash, function (e) {
            // Change the cursor style as a UI indicator.
            map.getCanvas().style.cursor = 'pointer';
             
            var coordinates = e.features[0].geometry.coordinates.slice();
            var description = e.features[0].properties.description;
             
            // Ensure that if the map is zoomed out such that multiple
            // copies of the feature are visible, the popup appears
            // over the copy being pointed to.
            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
               coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }
             
            // Populate the popup and set its coordinates
            // based on the feature found.
            popup.setLngLat(coordinates).setHTML(description).addTo(map);
         });
             
         map.on('mouseleave', 'point-'+geohash, function () {
            map.getCanvas().style.cursor = '';
            popup.remove();
         });

         //Animate the added point.
         animateMarker(0, geohash);               
      }
   }
}

function removePoint(ip) {
   clearTimeout(timers[ip]);
   points.delete(ip);
   map.removeLayer('point-'+ip);
   map.removeSource('points-'+ip);         
}

function encodeGeoHash(latitude, longitude, precision) {
  var BITS = [16, 8, 4, 2, 1];

  var BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
  var isEven = 1;
  var lat = [-90.0, 90.0];
  var lon = [-180.0, 180.0];
  var bit = 0;
  var ch = 0;
  precision = precision || 12;

  var geohash = "";
  while (geohash.length < precision) {
    var mid;
    if (isEven) {
      mid = (lon[0] + lon[1]) / 2;
      if (longitude > mid) {
        ch |= BITS[bit];
        lon[0] = mid;
      } else {
        lon[1] = mid;
      }
    } else {
      mid = (lat[0] + lat[1]) / 2;
      if (latitude > mid) {
        ch |= BITS[bit];
        lat[0] = mid;
      } else {
        lat[1] = mid;
      }
    }

    isEven = !isEven;
    if (bit < 4) {
      bit++;
    } else {
      geohash += BASE32[ch];
      bit = 0;
      ch = 0;
    }
  }
  return geohash;
}; 

You will need to make two small modification at the top of the file:

  • Set the IP of your webserver
  • Set your Mapbox access token

Once you have done this, open the page in your browser and a map should appear. NOTE: nothing will happen at this moment 🙂

Configure Logstash

Now we are all set for the last part: configuring Logstash to also forward (some) logs to our Node-application.
On your T-Pot server, we need to get the Logstash configuration as described on the T-Pot Wiki:

docker exec -it logstash ash
cd /etc/logstash/conf.d/
cp logstash.conf /data/elk/logstash.conf
exit

Open the Logstash configuration and add the following lines to the output section, after the Elasticsearch output:

if [type] == "ConPot" and [dest_port] and [event_type] == "NEW_CONNECTION" and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
         "type" => "%{type}"
         "protocol" => "Elastic"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Ciscoasa" and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "Ciscoasa"
         "source" => "%{src_ip}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Mailoney" and [dest_port] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "Mail"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "ElasticPot" and [dest_port] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "Elastic"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Adbhoney" and [dest_port] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "ADB"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Dionaea" and [dest_port] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "%{[connection][transport]}"
         "service" => "%{[connection][protocol]}"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Fatt" and [protocol] != "ssh" and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "%{protocol}"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "Cowrie" and [dest_port] and [protocol] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "%{protocol}"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}
if [type] == "HoneyTrap" and [dest_port] and [src_ip] != "${MY_INTIP}" {
   http {
     url => "http://${HTTP_LOGIP}"
     http_method => "post"
     mapping => {
          "type" => "%{type}"
         "protocol" => "%{[attack_connection][protocol]}"
         "source" => "%{src_ip}"
         "dest_port" => "%{dest_port}"
         "geoip" => "%{geoip}"
     }
   }
}

We need to add a new variable to the docker environment:

vi /opt/tpot/etc/compose/elk_environment

Then add the following line to the file, to exclude the T-Pot server in the Logstash messages:

HTTP_LOGIP=<YOUR_TPOTSERVER_IP>:8080

Now add a new docker volume for the Logstash service:

vi /opt/tpot/etc/tpot.yml

Go to the Logstash service section and add the following line:

- /data/elk/logstash.conf:/etc/logstash/conf.d/logstash.conf

Now we are all set and it’s time to restart your T-port service:

systemctl start tpot

That’s It!

Now take a look at your map. If there are attacks on your server, they should appear on the map and in the listing below.

You can trigger an event by, for example, opening a regular SSH session to your T-Pot server:

ssh <TPOT_SERVER>

Simply close the connection once it is established, and your location should appear on the map.

Daily figures

Almost immediately when you start running a honeypot you will see attacks. Within one day, I saw over 200.000 attacks, mostly on common ports like HTTP(S), SSH and SMTP. You can use this data to make your environments more safe, or just use them for some fun projects.

Some notes
As this was a quick project in limited time, there are definitely some optimisations or better coding that can take place 🙂 The Javascript will give a few errors after some time, probably due to points being removed from the map while a call to update the same point happens at the same time.
In addition, some points on the map will suddenly run on steroids, animating at higher frames than they did initially. The Node.js application was made quick and dirty but is suitable for this demo.

Technical Careers at Leaseweb

We are searching for the next generation of engineers and developers to help us build the infrastructure to automate our global hosting services! If you are interested in finding out more, check out our Careers at Leaseweb.

Share

Leave a Reply

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