PiWall, how to build a game-changing, flexible, low-level network firewall

firewall-29940_640You may be surprised with how frequently, modern Internet devices such as mobiles, laptops or computers continuously send and receive data on our behalf that were we are not aware of their existence. When a person decides to know the content of the information that is being shared or limit and profile some data he may come across the idea of installing a firewall in his computer. So, is installing software firewalls in computers enough to counter the situation? When a software firewall is used it is probably aiming to control the higher network level and therefore it may be good at limiting other software applications exchanging data. On the other hand, have you considered the possibility that your own device might send the information which needs to be monitored? In this point, a software firewall on top of the device is not the best case scenario as the software might never be in a position to detect the exchanged low-lever system data or may not be legally allowed from the Operating System’s manufacturer and other factors to tamper with them. Finally, as the saying goes, one system is based on another, so if an attacker could use another vulnerability in your system to tamper with its firewall, since its software, you might never knew it was affected. On the other hand, as compared to software firewalls, someone could use a hardware standalone network firewall as these devices may control the network traffic from more than one hosts and they are dedicated to a single task wich makes them harder to be penetrated. The solution of using standalone network devices as firewalls makes more sence in the security field, however, their negative aspects lie in other factors as: that they are difficult to be found in the consumer market, they may cost something extra and may not be tailored according to a user’s needs.

For quite some time I was occupied to solve this situation wondering whether a person could use a firewall solution within reach to define his network policies, be 100% confident for their effect in play, eliminate the possibility of breach through software, and be informed as well, in real-time, for the exchanged network data. To fit in the above requirements, the solution had to be an independent network device for the afore mentioned benefits, not cost a fortune and to have enough processing speed to control the exchanging data. In order to match these expectations, the raspberry pi B was ideal as it is built for low-power consumption and may run Linux and Python over a quad-core ARM cpu. The next question in hand, was how to monitor the exchanging traffic. The solution, was given to me by the network itself as at the end it’s all about data in a cable that come and go. I had to let the hosts be and focus my attention on the medium, the cable where everyone is connected! What if you could control which kind of data arrive and which kind of data leave from the medium towards the Internet? There is no other way for the data to go right? and that would be something really game-changing as with one device you could control multiple hosts! In order to achieve this, I had to somehow split the network wire between the internal hosts that were in need to be defended and the Internet and to install the device in between them to act as the firewall.

In order to approach the solution, I had to ask how does someone split a network wire in two?! For this task, a bridge was in need to be formed as it is called in networks. A bridge is simply a device with two network cards which may exchange data from/to another and therefore the hosts from the one or the other side of the cable are not aware of the device’s existence since it does not have a network presence. Furthermore, in order to be informed for the network traffic from the device and change its rules you would need to use a third network interface to access the device, this time as a network host. These make up to three network interfaces, however, as you may have noticed a raspberry pi has only one. The other two interfaces would be usb to ethernet adapters since the pi has 4 USB ports available. In the project,  Apple’s ethernet to usb adapters were used as they demonstrate good performance, low power consumption and the raspbian os has the necessary drivers to support them. If you decide to make a device of your own, watch out for the adapters from the ebay and other online stores as the pi might not support their drivers. Finally in order to understand the device you may observe the following diagram.

firewall

Introducing the device

This is PiWall, a game-changing, flexible, low-level network firewall!

Do it yourself!

in order to replicate the device you are going to need:

  • one Raspberry Pi model B (2 or 3) url1, url2
  • one micro sd card 8gb or more
  • two Apple USB Ethernet Adapter
  • one power cable for the raspberry pi
  • a case for the raspberry pi (optional)
  • heat sinks for the pi (optional)
  • two new ethernet cables

Setting up the device

Write the latest linux/raspbian to the sd card as described in the official raspberry pi guide:

https://www.raspberrypi.org/documentation/installation/installing-images/

Insert the sd card and connect your device to a monitor, keyboard and power. As soon as you have a command prompt set up a new user password with:

passwd

edit the system’s settings with:

sudo raspi-config

select to:

expand filesystem
Internationalization options:
change time locale, timezone and keyboard layout
Advanced Options:
Hostname: change hostname to PiWall
SSH: enable sshd

Source code

The source code for the project is written in Python (3.4) as from the one hand, it is really easy and fun to control low-level traffic with a high-level programming language and from the other, Python is easy to write and thus to set your firewall, monitor and modify rules the way you need them.

The source code may:

  • Monitor your traffic on the fly
  • Firewall your traffic on the fly
  • Modify your traffic on the fly
  • Provide live information for all the above

Keeps internal and external host whitelist and has the necessary policies to handle ARP, IPv4, IPv6, ICMP, DHCP network protocols. You may view the project’s source code from here and learn how to install and run it:

https://github.com/kostiskag/PiWall

Last but not least, if something is not in the code the main idea is to define it yourself. Moreover the overall project, the programming language and the source code demonstrate a good background to apply various other algorithms for AI or big data. You may start by collecting frequencies from the various send and received protocols, you may modify your internal hosts mac addresses to keep them private, monitor DNS traffic, monitor peak hours and much more.

Final thoughts

You may know that these kind of solutions could be used for malicious acts like collecting network traffic, however, as a scientist, I believe in knowledge sharing and decided to publish this article as its development was meant to help individuals apply one extra measure of security in their home or work networks and thus try to reach a state of equilibrium towards the extensive network trafficking and profiling which is done on their behalf. On the other hand, this article and device were meant to let individuals be introduced into network traffic and control as network trafficking has become a part of our digital lives. Finally, the overall installation is not very expensive as the hardware costs around 110€£$ and may be used for research purposes, home or work environments.

As a room of after-thought, It may be a good practice to avoid connecting to unknown WiFis in airports, hotels or cafes as a similar and not so friendly Man-In-The-Middle (MITM) solution may be installed there. If you still need to connect from public places and can not avoid it you may use an encrypted VPN solution such as openVPN towards a trusted VPN server and thus be defended against a close MITM host.

Finally, have fun with your device and watch out for project updates!

You can view this project along with other three raspberry pi projects developed for 2017 in the following video

 

How to build a highly resilient raspberry pi GPS tracker and visualize your data real time on Google Maps.

gps_avdou_presentHello guys! In this article I am going to present one of my newest projects, a fully functional GPS tracker which may stream its location over 3g and visualize gps data on Google maps in real time.

To begin with, and in order to understand the significance of this project let me explain what a GPS tracker is and why someone might use it for. Normally when we use a car GPS or a mobile GPS app it shows our location on a map and demonstrates the best path related to distance or other factors from our spot to a selected destination. As opposed to a GPS tracker we may not use it to find the best route to our destination but it may be used to track objects or people who carry it. It is noteworthy that, in contrast with a gps we may not need to be physically near to it in order to receive data as it may stream those over the internet. As an example case, someone like me may not remember where he parked his car last night, with a tracker in his car he may receive its last known location. Similarly, the use of tracking moving objects is handy in other cases as when we need to know the location of other important stuff, or  even to track pets!

Another cool use trackers may have is to let you record your walks. Similarly with how you record video with a camera you might just do the same with GPS co-ordinates. This feature comes to be really useful for mountain climbing, daily walks or exploration as when you return to your place you may study/observe your followed track or, you know, collect and share your tracks like you take pictures or videos! In my implementation, in order to enhance this feature I have made the routes to be stored as independent html files and open in your browser with a double click.

In the remainder of this article, the device and its uses may be observed at first glance. Afterwards,  the device, its source code and scripts are going to be analyzed in order for you to learn more stuff and, if you decide, to be able to replicate the device!

Introducing the device!

In more detail, the parts which were used are:

PI: 1x raspberry pi model B url1, url2 One micro sd card 8gb or more. One micro USB to USB cable for the power. One USB power charger of (5V 1A), one usb keyboard, one monitor with hdmi input and an HDMI cable.

GPS: 1x adafruit hat for raspberry pi similarly with my implementation. You may also use the gps breakout without the hat were you should have some jumper wires in order to attach it. If you decide, you may use another USB gps. The other two gps components which were used were: an SMA to UFL adapter url1 , url2 and a SMA gps antenna url1, url2

Networks: 1x 3G usb adapter: url1 . For the case that you may wish to stream  the tracker’s location to a selected server. Otherwise, if you do not wish to stream the tracker’s location you may “record” your routes and view the results when you reach to your computer. Make sure that the adapter’s specifications are compatible with your region. In order to use your adapter you will require a SIM card and a mobile plan to send and receive internet data.

1x WiFi adapter: url1  Makes things easier when on a LAN environment to access the pi’s content, services and for setting up and debugging purposes. In the case that you may not wish to buy a wifi adapter you may use the pi’s ethernet socket.

Some USB extension cables or USB mounts. To connect those to the pi in order to be able to conveniently plug in/out the USB WiFi and 3G adapters.

Power: 1x witty pi 2 hat A very good implementation in order to manage your pi’s energy. It stabilizes the power input, there is a power on button and more importantly it may power on/off you pi based on a scheduled time plan. The main idea is to, let’s say, open tracker every day for 30 min or similarly with another plan in order to save the battery’s energy and use our tracker for a bigger time duration.

One powerbank most preferably with a large capacity and a USB output of 1A.

Case: A case capable to contain all the above equipment and to be able to withstand some real world shocks.

Do it yourself!

Assembling the device

The device’s assembly is not so hard to achieve. To begin with, the first task to do is to solder the adafruit gps hat. In the witty pi you should move Halt by GP4 to custom as the gps hat uses that port to send the PPS pulse. In addition, you should move the jumper to the right to Dummy Load On in order to not let the external powerbank switch off when it is left alone. Afterwards, you may create a stack with the gps hat and the witti pi 2. It does not matter which HAT is on top, however, witty pi comes by default with a stacked header and you may need to move the gps antenna sometimes so it is much more convenient for the witty pi to go first in the stack and the gps to go on top of it. You may power the device on from the button on the witty pi.

Configuring the device

For the first part of the device’s configuration we may wish to set up the raspberry pi for the first time, the I2C interface, the wifi and network, the ssh service and time in order to be let the devices work, to be able to control our device from a remote shell and to display the proper system time when sending email events. This process is already explained in another one of my articles about the tampering device which you may view from here. From this article you should follow “Phase 1 – pi configuration”.

Setting up the GPS

In order to set up your gps hat you should study adafruit’s given setup guide found here: https://learn.adafruit.com/adafruit-ultimate-gps-hat-for-raspberry-pi/. What I did was slightly different from the default setup as I provided gpsd’s settings in a different way and used the service command to stop and start gpsd. What I did was:

sudo apt-get update
sudo apt-get install gpsd gpsd-clients

GPSD is sometimes buggy and if you decided its time to reinstall it you should do that with the purge option:

sudo apt-get purge gpsd

In my case where I used Raspbian Jessie and as described in adafruit’s blog I had to run the following commands:

sudo systemctl stop gpsd.socket
sudo systemctl disable gpsd.socket

When all of this is done, restart your pi, there is a fix led on top of the gps hat which may indicate a fix when it blinks with large time gaps. Your next task to do is to power it on, leave it outside with the gps antenna facing the sky and run either from there or from ssh:

sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock
gpsmon

With those commands you may observe if you gps operated similarly with the pictures shown below. You may need to let it for some time in order to receive a gps FIX.

In order to close gpsd:

sudo service gpsd stop
#or
sudo killall gpsd

GPSD permission error FIX

If you can not open gpsmon or other gpsd clients as in my case, the gpsd may have changed the permissions of the gps device it is using. From what I have seen on the Internet posts the gpsd and the raspberry pi have some co-operation issues as this happens frequently. In order to overcome it you may use the following fix:

sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock
( while : ; do sudo chmod 777 /dev/ttyAMA0; sleep 20; done ) &
gpsmon

When you have decided that everything is alright it is time you registered gpsd on system’s start. In order to learn about startup scripts you may study this guide: https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/.

The following script is a startup one, the bulky header is being used for letting the os know in which order to start the startup scripts. The “while” code is a bit dirty however, as mentioned, the gpsd changes the permissions on the gps device and does not allow the pi user to open any gpsd clients. The while code lets the user to be able to open any gps clients. Finally, the last line executes a bundle of services for the gps from the pi’s home directory. You should keep that in mind as we may return later to that.

sudo nano /etc/init.d/init_gps

#!/bin/bash
### BEGIN INIT INFO
# Provides: init_gps
# Required-Start: $all
# Required-Stop:
# Default-Start: 4
# Default-Stop:
# Short-Description: Initialises gpsd and python services.
# Description: This file initts all gps related stuff.
### END INIT INFO
(
sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock
(
while : ; do
chmod 777 /dev/ttyAMA0
sleep 20
done
) &
# this file may open our source code services and  is explained in detail later in the article in the project’s git
sudo -u pi /home/pi/gps_bundle_services start
) > /home/pi/gpsout

sudo chmod +x /etc/init.d/init_gps
sudo update-rc.d init_gps defaults

Should you ever wish to remove the script from start you may do with:

sudo update-rc.d init_gps remove

Setting up 3G

In order to setup the 3g please consider the guide shown here as well: https://www.thefanclub.co.za/how-to/how-setup-usb-3g-modem-raspberry-pi-using-usbmodeswitch-and-wvdial

For the 3g what you have to do is:

Plug in the 3g usb but do not remove wifi or etherner as you may use ssh.

sudo apt-get update
sudo apt-get install ppp wvdial usb-modeswitch

First, as the above article suggests you should make sure that the usb 3g modem is on modem mode and not storage mode every time and before wvdial attempts to connect. When you have your setup ready you may proceed with setting wvdial.

Wvdial needs a config file in order to properly work and connect to network. If you did not have your 3g usb plugged in, the config file may not be auto generated but you may still want to auto generate it by running sudo wvdialconf. The auto-generated config file is halfway to connect and you are going to need more attributes as shown below. It might be a good strategy to save the auto generated file’s differences like the Init2 or Modem lines, copy the file from here and then replace these lines.

sudo nano /etc/wvdial.conf

[Dialer Defaults]
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0 +FCLASS=0
Init3 = AT+CGDCONT=1,”IP”,”internet”
Modem Type = Analog Modem
Baud = 9600
New PPPD = yes
Modem = /dev/ttyUSB0
ISDN = 0
Phone = *99#
Password = { }
Username = { }

In my case I had to connect to a cosmote 3g network in Greece and gave the above settings which did the trick. In your case you may have to variate a bit and search for your APN name or login credentials to match your carrier’s settings and save the file. Finally, shutdown the system and remove any LAN wifi usb or ethernet cable. We are going to need a keyboard and monitor for this one as we can’t use the ssh.  restart the system, then, use Ctrl + Alt + [F1 – F12] in order to switch between different terminals. Then in one terminal run:

sudo usb_modeswitch -c /etc/usb_modeswitch.conf
sudo wvdial 3gconnect

When wvdial connects, switch to another terminal to test your connection. You may also include an ampersand to the command and use the same terminal, however, you may have a lot of verbose in order to easily understand the messages. As soon as you observe the adapter’s led blinking vividly you are probably connected and you may run ifconfig to collect your public IP address from the ppp0 interface. To test your network run something like:

wget –spider http://www.google.com

Once your implementation is working make the 3G to connect at startup. I have developed this script to drop when there is an already active network interface like a wifi. Finally the session’s information is stored on /home/pi/3gout

sudo nano /etc/init.d/init_3g

#!/bin/bash
### BEGIN INIT INFO
# Provides: init_3g
# Required-Start: $all
# Required-Stop:
# Default-Start: 4
# Default-Stop:
# Short-Description: Initialises 3g
# Description: This file initts 3g
### END INIT INFO
(
sleep 60
#Allow this block when you have installed the project’s source code
#python3 /home/pi/gps_tracker/is_there_internet.py
#if [ $? = “1” ]; then
#echo “Script drops for this one.”
#exit
#fi
usb_modeswitch -c /etc/usb_modeswitch.conf
while : ; do
echo “3g connect”
date
wvdial 3gconnect
echo “3g hangup”
date
sleep 10
done
) > /home/pi/3gout &

sudo chmod +x /etc/init.d/init_3g
sudo update-rc.d init_3g defaults

Witty Pi 2

Witty pi’s setup can be studied from the given project guides:

http://www.uugear.com/product/wittypi2/
http://www.uugear.com/doc/WittyPi2_UserManual.pdf

Since everything is starting on system’s power on, our task with this hat is to set up a script for the pi to open every 4 hours for 40 min in order to collect GPS data,stream them back to us and thus extend the battery’s power for longer.

In order to install witty pi’s source code please run:

wget http://www.uugear.com/repo/WittyPi2/installWittyPi.sh
sudo sh installWittyPi.sh

Compatibility towards the gps hat

Remember that we had to put halt on GPIO4 to custom in order to not interfere with the gps hat since it is using the same port? It looks like we have to do the same thing in witty pi’s scripts or otherwise the device may switch off unexpectedly by misinterpreting the PPS pulse for a halt signal. In order to fix that go ahead and edit /home/pi/wittyPi/daemon.sh .

nano /home/pi/wittyPi/daemon.sh

Change the below variable from 7 to 10 in order to solve it.


# halt by GPIO-4 (wiringPi pin 7)
halt_pin=7 #should go to anything except 7(gps) and 1(the led) let’s say 10

You may find more information about this setup from here: http://www.uugear.com/portfolio/change-the-pin-that-used-by-witty-pi/ . When you are done save the file and restart your pi. Next, you may start making the schedule file in order to switch on and off automatically your device:

cd /home/pi/wittyPi/schedules
nano 40min_every_3hours.wpi

BEGIN   2016-02-24 00:00:00
END     2020-02-24 23:59:59
ON      M40   # keep ON state for 40 minutes
OFF     H3     # keep OFF state for 3 hours

Save the file and move on to synchronize time and activate the script.

cd /home/pi/wittyPi
sudo ./wittyPi.sh
Select:
Option 3 – To synchronize time
Option 6 – To activate a startup script
And select the script’s number from the given list
Option 8 – To exit

In case you need to reset the script:

sudo ./wittyPi.sh
Select:
Option 7 – to reset
Option 3 – to remove script
Option 8 – To exit

The project’s Source Code

Finally we have an assembled and configured device! The only thing we are still in need is the necessary logic in source code in order to fulfill more sophisticated tasks with our setup. For this reason, the project has a git repository with all the necessary source code for it written in python3 and all the above init scripts ready. The repository can be accessed from here:

https://github.com/kostiskag/gps_tracker

Now, this would be the proper time to switch over to the git’s readme in order to learn how to download, install and use the project’s source code and therefore to reach the device’s full potential. From this point, the setup is complete and after you have everything working it may be a good practice to take a backup from your sd card with all of the setup.

Final thoughts

After all of the code is packed together, the device becomes really reliable, useful and you do not need to make new tweaks or write source code anymore. You just open it, wait for it to connect and establish a FIX. After each event you receive your device ok emails through your mobile email client. By this point you know the device works, everything if fine so you start walking! Furthermore, you may let one of your friends sit in your computer and track you in real time with the auto-generated maps! From my part, I hope I have explained everything but if there is still something missing please let me know by sending me an email in order to update the article. You should keep in mind that this article and the articles I am making were meant to be of help so if you think that you were helped in one of your projects please attribute the article in it. If you do not have a particular project to work on but this article gave you insight or new knowledge, you might suggest this article to your friends or colleagues.  Finally, watch out for project updates and happy tracking!

You can view this project together with other three raspberry pi projects developed for 2017 in the following video

 

Monitor your stuff when you are away with a raspberry pi based tampering device

bagAll of us have some stuff we want to keep private, maybe something personal, or important ideas and concepts that we may not want to fall into the wrong hands. So how should we keep them safe in a house or work environment? One answer would be to lock them up! Obviously, but it is not so convenient and timely to lock stuff all the time and it’s not possible to know whether someone has passed the lock to begin with. This is why this device was made! To keep track of your personal stuff by sending real time email events about their state!

The Tampering device is a raspberry pi based device which is able to detect physical movement and motion, object rotation as well as the ability to detect whether a physical lock is being opened or closed. When an event is detected it sends an email to the user stating the event along with its detailed data and a timestamp so that he may know about it in real-time. Which are the good news? I have made this device in a way to be replicable so that fellow enthusiasts, scientists and engineers may re-assemble the device! In the remaining of this article the device is presented and there is a guide, resources and source code in order to replicate it.

Introducing the device

This is the tampering device! The user has to simply plug the pi into the powerbank to get it started. After power-up the user may take the device and place it in his bag as shown below or in another kind of space like a drawer. When the device is placed, the user has to attach the the lock sensors to the bag’s zip heads and connect those to the device.

As soon as the zip is closed the device is going to send the first email stating that the bag is now locked. From this point and on the device may send an event emal for every motion or rotation which was detected in the bag and whether the zip was opened or closed.

Do it yourself

In order for someone to replicate the device he should have some basic experience with the linux command line, python, computer networks and a basic knowledge of soldering.

Hardware:

You are going to need:

Phase 1 – pi configuration:

Write the latest version of rasbian to your sd card as described in the official raspberry guide here:

https://www.raspberrypi.org/documentation/installation/installing-images/

Insert the sd card into your pi, plug in a usb keyboard and the wifi usb antenna into your pi. After that, connect the pi’s HDMI output to your monitor’s or TV’s HDMI input. Finally, give to your pi some power either by plugging it to a mobile phone charger, a powerbank or into your computer.

The first thing we should do is to setup the wifi and enable the sshd on the pi in order to be able to directly access it through the computer and get rid of the keyboard and monitor interface.

WiFi setup: To setup your wifi follow the guide as shown here: https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md

In addition you may setup multiple wifi networks with priorities as demonstrated below in order to allow it to be operational under multiple areas:

to do this:

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

and define multiple wifi networks as shown below:

network={
ssid=”xyz-net1″
psk=”a_password”
priority=1
}
network={
ssid=”xyz-net2″
psk=”a_psw”
priority=2
}

finally save it and restart the interface…

sudo ifdown wlan0
sudo ifup wlan0

wait for it… and…

ifconfig wlan0

to collect your ip address and write it down. Make sure the ip address stays the same (it’s static) each time when the pi connects into your wifi. If not, then you should make it static through your router’s DHCP known hosts – interface or by defining it into /etc/network/interfaces as static. You should keep in mind that if the pi connects on a different wifi it may get a new ip address. Moreover make sure that in the interfaces file there are the lines which allow your wifi to accept the above configurations and start when the device starts. By default these lines are already there.

allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

After you have set up your wifi it is time to set up your pi’s behaviour. For that run:

sudo raspi-config

select from the menu:

Expand Filesystem

Advanced options:

Enable SSHD

Enable I2C

Internationalization Options:

Change the timezone to your local timezone. You are going to need that later in order for the device to send proper timestamps with the correct time for the events.

Change your keyboard layout in order to be able to type what you see over your buttons as by default pi has a GB keyboard layout.

You can also view the tutorials below to get you going:

https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-gpio

https://learn.adafruit.com/adafruits-raspberry-pi-lesson-4-gpio-setup/configuring-i2c

Now you should shutdown your pi and take a break! As soon as you are done, remove the usb keyboard and monitor, power it up, wait for the wifi. You can now start using the ssh client from your computer so that you may not need to keep a monitor and a keyboard plugged into your pi in order to use it and let it take a more compact form. If you are using windows as an OS you may use putty.

login with username: pi

and password: raspberry

Since the device is going to be monitoring your stuff it is a good practice to change the default password. In order to do that run:

passwd

and follow the on-screen guide

Phase 2 – hardware assembly:

Now it is time to install all the essential packages, From your ssh client run:

sudo apt-get update
sudo apt-get install i2c-tools python-pip python-smbus python-numpy python-dev python-rpi.gpio git

sudo pip install adafruit-lsm303

and wait for the packages to be installed. After the install process is finished you should shutdown the pi and assemble the hardware as shown in the diagram below:

schematic

You may solder the cables directly on the sensor boards or you may use a breadboard similar to my implementation in order to be able to separate the sensors and use them in other future projects. Even if you decided to solder them it may be a good practice to test them out in a breadboard in the beginning. Take care to power the sensors from the 3Volt output as shown in the diagram and do not use the 5Volt or you may burn them. Do not mix the SDA signals with the SCL signals. The two green pinouts in the diagram are used for the lock sensor and may be extended to any kind of conductive wires and materials like jumpers that may trigger an event when connected/disconnected and the circuit is closed/opened accordingly. Finally for the assembly part, this is the proper time to find a nice box for your project to protect your hardware and include a powerbank in order to make it portable.

To test your hardware power up your pi and run:

sudo i2cdetect -y 1

Normally if all the sensors were installed correctly you should be able to view a response similar to this:

i2c

(where there are not dashes everywhere in all the lines)

Phase 3 – source code:

Are you tired? Now it’s time for some source code!!!! In order to stop this endless torture I have prepared a git repository with all the necessary source code written in python in order to use both of the sensors under the same script. You may view the project’s repository on github from here: https://github.com/kostiskag/tamper_dev

In order to download the project’s source code run:

cd ~
git clone https://github.com/kostiskag/tamper_dev.git
cd tamper_dev
ls

Once you have downloaded the code you should test whether your sensors and the device are working properly. There is a set of standalone scripts in order to let you test your setup. The only thing that you may need is nano or python “a script” in the directory to either edit or run it. Remember python is already installed in phase 2 so we are clear from that. Finally, you may use the commands below:

python L3GD20test.py
-> to test your gyroscope
python LSM303test.py
-> to test your accelerometer and magnetometer
python LSMdiff.py
-> to test whether the device is moved
python GPIOTriggertest.py
-> to test whether your GPIO lock properly works

Phase 4 – configuring your email

Next, you should register your email in order to let your device send email events. The scripts are already configured for SMTP over SSL for a gmail email account. The only thing you should do is to allow less secure applications to send emails from your account as described here:

https://support.google.com/accounts/answer/6010255

http://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python

In my case I have created a separate email account responsible for the event notification that may send email events to my original email address. Once you have either made a new account or have an already existing and in both cases you have allowed less safe applications to be used, then you may send a hello world email to test your setup. Run the below commands to provide your email credentials and to test whether you may receive a Hello World email on your email box from the tampering device.

nano GMAILtest.py
python GMAILtest.py

As soon as you have a Hello World in your mailbox, provide your credentials to tamper_dev.py as well and move on to the next and final phase.

nano tamper_dev.py
python tamper_dev.py

Phase 5 – Finalise your device and deploy for use

Last but not least, you should register tamper_dev.py to be executed on system’s start so that the only thing that you may have to do is to power up the device. In order to do that:

sudo nano /etc/init.d/tamper_dev_init

let the os know about your python script by writing the commands below in the opened file:

#!/bin/bash
cd /home/pi/tamper_dev
python tamper_dev.py

save the file, and with the commands shown below, give it execution permissions and notify rc.d which is responsible to start your script at the os start.

sudo chmod +x /etc/init.d/tamper_dev_init
sudo update-rc.d tamper_dev_init defaults
sudo shutdown -h now

if you decide to remove the init script you may use the command shown below:

sudo update-rc.d tamper_dev_init remove

For a more detailed description of startup scripts you may study this guide: https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

Your device is ready! Now every time it is powered up it starts functioning automatically and once you close that zip it keeps you notified by sending email events over your mailbox!

Future work

The device described here may fail to respond properly under some specific cases as described below. There may be the case where someone might switch off your wifi router. If you think that this might happen and if you are not in control of your wifi’s state, you may choose to use a 3G usb adapter instead. In order to set the 3g adapter you may view the gps_tracker article under the section Setting up 3G. Moreover, there is the case that the device may shut down from a drained battery and there is no way to detect whether the device is off. In that case you may keep track of your battery’s life by measuring the battery’s life duration in order to be notified with an email fro low battery.

Finally watch out for project updates and stay safe, you and your projects!

You can view this project together with other three raspberry pi projects developed for 2017 in the following video