Categories
Raspberry Pi

PiAlert – V1

I had a bit of an idea, and the PiAlert was the result. A video is the best demonstration but in short, different coloured lights light up when certain things are triggered, and a counter is kept for each light. My primary trigger is access attempts on port 22 (SSH) on my servers. Its usually all automated attempts, but after 24 Hours one of my VPS’s where I have normal login enabled recorded 1633 attempts, and another where I have SSH set to only allow password-less logins via SSH Keys recorded 9 attempts. Similarly, automated WordPress logins were detected once. The video shows it being manually triggered prior to it being exposed to the outside world.

And some photos of it in action

I won’t lie. This is at best an alpha level item. I’ve uploaded all the code and design files in the hope that someone finds it interesting and possible wants to help improve it for others.

I haven’t been able to share this post in the Raspberry_Pi subreddit as I was banned over 4 months ago for asking about the Pi HQ Camera (boring story). I’ve tried for the last 4 months to at least appeal the ban but no one replies to the mod mail. If anyone wants to help rectify that by speaking to the mods I’d be over the moon so I can get my project posted there!

The Project

I’m a bit late for the whole “lockdown project movement”, and seeing as I worked through any lock downs that happened I didn’t get the time to sit and tinker like I would have. That changed recently thanks to surgery where I’m now sat up in the house with very little to do.

After the recent incident with one of my servers I realised I quite enjoyed watching the logs scroll past showing what was happening. I usually run

tail -n 80 -f /var/log/apache2/error.log
tail -n 80 -f /var/log/apache2/access.log
tail -n 80 -f /var/log/auth.log

and it’s interesting seeing what pages random bots are trying to access, or what accounts they attempt to login to SSH via. It’s also got that same look as hacker movies do. I figured I could create a more visually appealing system and thats where this project came from.

Watching SSH logins have changed recently for me since I implemented a more strict login procedure – the number of failed attempts have dropped dramatically and this is evident after running this for 24 hours – as detailed above.

This post will be split into three sections, Hardware, Server Software Configuration and Pi Software.

Hardware

This device is made up of a Raspberry Pi Zero W, a Pimoroni Blinkt! and a cheap 4 Digit 7 segment display (in white) from AliExpress, and is hooked up like so

A simple diagram – please forgive the slightly-better-than-MSPaint attempt.

The Blinkt! has been attached using DuPont wires which have been cut at one end and soldered direct onto the same 40-PIN GPIO connector on the Blinkt!, because I had to use the Pi’s GPIO pins to also hook up the 4 digit display.

Getting the Blinkt! to work this way turned out to be a bit tricker than I first thought. I thought my Blinkt! just had some poor mechanical connections in the connector and the amount of trial and error it took to get it working was more than I want to admit to. It turns out, after reaching out to Pimoroni on twitter that early versions of the Blinkt! used Pin 2 for 5V, instead of Pin 4, as shown on pinout.xyz. In my haste I ordered a second Blinkt! in case my one was faulty – but now I have to think of another project to use the second one for!

All these components were then put into a case I designed in Tinkercad and 3D Printed on my Ender 3 Pro, which to an extent worked, but I could not get my head around how to create a case that clips together for a friction/clip fit. I ended up throwing two large columns that an M5 Screw would fit into to hold it all together. These columns are off centre to all room for the Pi to fit.

It was printed in some cheap no-brand PLA at 217°C, 10% infill, and regular settings that I’ve tweaked over time watching various YouTube channels.

This took 9 iterations of printing, measuring and tweaking before I got the front part of the case looking pretty decent. Each time I printed it something else could just be moved a bit over, or it could just be adjusted ever so slightly, and because I’m using Tinkercad a few times I ended up moving a key part or two and had to almost start over again. During my iterations I ended up getting rid of my attempt at clamps to keep the Blinkt! in place, and resorted to a hot glue gun (a first for me!). I ended up using that on the 4 digit display, and to keep the Pi Zero set. One of the last iterations was the mounting for the Pi Zero itself. I had initially left it floating in the case but plugging the usb cable was a bit of an adventure with it moving about so much. My final revision, if there ever is one, is to remove the screw posts and holes for M5 screws, and figure out how to get the case to snap-fit together. If anyone wants to take a bash at remixing it, please, feel free! My only other issue is I wouldn’t mind a piece of opaque glass or acrylic to sit over the front. On the one hand it hides the obvious parts that look very tech-y, and two, it should diffuse the light somewhat.

The Pi Zero W I used was used previously in another project that needed the 40 Pin GPIO connecter mounted backwards. This actually turned out to be a bonus, and as it was being popped in a case and this will more than likely be its final project, I decided to bend some of the pins to help it fit a bit better.

A final design idea is that I really should have included a button or two, even just hidden around the case somewhere. One for cycling through the detected hits so I don’t have to wait on a specific hit to see that number, and one to switch off the display with a short press, and gracefully shut the Pi down with a long press. If needed, its always accessible via SSH and if absolutely needed I could write a URL route that calls

sudo halt

Server Software Configuration

As part of the process of securing and monitoring my servers after my last incident I verified that fail2ban was actually installed on them. fail2ban is an amazing piece of FOSS software that, in summary, watches logs on your sever, takes a note if anything is happening that shouldn’t be like multiple failed login attempts to the SSH Service, and bans that IP Address from reaching your server if the issue is severe or repeated for a predetermined time. By default it watches SSH traffic, but it can also be extended to monitor other things like the amount of 404 errors, or incorrect login attempts to WordPress etc.

Part of fail2ban allows you to create custom actions when various triggers happen. This ended up being more difficult than just plonking a curl request in and I ended up reaching out and asking on GitHub because no matter what I tried it wasn’t working. For ease of reference – this is how I made custom actions for fail2ban on a debian based server –

Create a jail.local file and add the following

[sshd]
enabled = true
port = ssh
banaction = pinotifyred[myhost="SCRIPTHOSTSERVER"]
Replacing SCRIPTHOSTSERVER with a suitable URL (i.e dev.testing:8080) - no protocol at the start, no path at the end, and no trailing slash. 

This inherits all the actions for SSHD, so it will continue to ban as normal, but it allows us to define additional actions. Unfortunately, you can’t just define a command to run here (and this was my issue), but instead tell it what action you would like to run, which gets called from the action.d folder. In the action.d folder create a file named after the ban action, in this case pinotifyred.conf, and have the following code in there

[Definition]
# sends get request like "http://example.com/red"

actionban = curl --fail "http://<my-host>/red" >> /dev/null

[Init]
# overwrite this in jail as action parameter:
my-host = SCRIPTHOSTSERVER
Again, replacing SCRIPTHOSTSERVER with a suitable URL (i.e dev.testing:8080) - no protocol at the start, no path at the end, and no trailing slash. You can see that the actual address and protocol are set here in the actionban section.

This code calls the action ban, and replaces the <my-host> variable with what it has been defined as. I couldn’t get it to work without having that as a variable.

This code performs the command required, and also defines some variables that are needed for fail2ban to work. As a bonus feature, the way this is set up means that you can send a curl or wget request with various parameters including what IP has been banned, time and date it was banned etc, so if you’re after a more data-rich solution this could also be used. To do that, you could have a file in your action.d folder containing something similar to

[Definition]
#sends get request like "http://example.com/ban.php?jail=sshd&amp;ip=192.0.2.100":

actionban = curl -G --data-urlencode "jail=%(name)s" --data-urlencode "ip=" --fail "http://<my-host>/ban.php"

[Init]
overwrite this in jail as action parameter:
my-host = SCRIPTHOSTSERVER

As a small side note – I think theres a bug here in that the ban action is being called when an IP is unbanned. It’s something I’ll look into later as it’s possibly double counting.

Pi Software

I’ll be completely honest. The code is an absolute mess. It’s written in Python 3 by someone (me) who doesn’t know python, but knows how to search for and get answers on Stack Exchange, and with a grasp of basic programming fundamentals, managed to create the python program.

I’m not going to go over the process for formatting and getting you Pi to a headless and login-able state via SSH as that been done a thousand times before. The code below is hosted at GitHub, with only two files, the main

pialert.py

script to be run at startup, and a

tm1637.py

library, gracefully used from RaspberryTips.

You can see the code in its entirety at my GitHub page.

Dark Mode

PiAlert (this link opens in a new window) by nickwebcouk (this link opens in a new window)

A small script used in conjunction with a Raspberry Pi and other services to alert the user

This Python program just simply sets itself up to act as a HTTP server (and I know its not meant for production, but this is one of those “quick and easy” projects) and listen for any requests. Its single threaded, so if it gets a lot of attention it’ll more than likely fall down. It simply waits for a URL, if its defined, it runs an action. The action is to light up the Blinkt! in a Larson style scanner and then increment the counter. Depending on the URL means different colours LED’s illuminate. Theres no real error checking, theres no check to make sure the counter won’t overflow, and the program has the added benefit of showing me that even my home network is constantly under attack by malformed URL’s looking to gain access via any vulnerability they can find (which also throws up an exception error but doesn’t crash the program).

The penultimate piece of the puzzle is setting up the Pi so that as soon as it boots, it loads this script, and then just sits and runs. This is accomplished by editing

/etc/rc.local

in vi by adding the command thats usually used to run the program –

python3 /home/pi/PiAlert/pialert.py &

The last piece of this whole puzzle is making sure the Pi, which is sitting behind a firewall on a home network with a Dynamic IP, will always be able to be reached by my VPS’s. I could use Dynamic DNS or any of the other myriad of services out there, however someone on the self hosted subreddit created a free service called freemyip.com which does exactly what I need it to do, and does it well. The service doesn’t seem popular yet and with the phenomenal price of free I’m sure that won’t be the same for long — but given how simple it is I would gladly kick a few quid their way. I also noticed that a second service has been set up by someone else on the sub, sliceport.com which I’ll have to give a bash at some point.

This isn’t meant to be one of those mission-critical pieces of kit that you see in every action movie. It’s meant just as a small reminder that every day, there are thousands of bots in the ether attempting to gain access to something they’re not meant to. This device just brings those attempts into the physical world, reminds you about them, and it looks quite nice.

My code has 4 coloured lights set, and I have them set up as follows:

  1. Blue for failed WordPress attempts on this site
  2. Red for failed SSH attempts on Server A
  3. Purple for failed SSH attempts on Server B
  4. Green for failed URL’s from Server C

I’ll probably extend and change this as time goes on but this is a good indicator of what’s happening without having to log in to any server.

The best part? The design is somewhat neutral and is very, very flexible. If I decide I don’t want this anymore I can rewrite the code and turn it into a clock, or a counter for page hits, or any other number of things. Theres 8 RGB Leds and 4 7-Segment displays. Its also very portable. I have it sitting at my desk where I write my code, and its a nice reminder that bad people are trying bad things. But because of the low power requirements it can be ran from a battery pack – I could plug it in anywhere in the house where it will get a WiFi signal and it’ll happily run the code, and if a different network is needed all I have to do is SSH in, or create a new

wpa_supplicant.conf

file on the

/boot 

partition.

So in summary — the codes a mess and could really be refactored. If I ever learn python it’ll be one of the first things I do. The enclosure could do with some love, and again, if I ever learn a 3D Modelling program I’ll get to that as well. But apart from that? I’m happy.

Categories
Electronics PiDashCam Raspberry Pi

PiDashCam – Issues

Well. That didn’t go to plan. I managed to hook the PiDashCam up to the car. It powered on fine, and has recorded, however I forgot to change the settings and it recorded in 10 second blocks. I also mounted it incorrectly, so it sort of sat at an angle. I also went out when it was a bit dark so the images are really not great. The worst part, however, is that the Raspberry Pi Zero didn’t seem to grab the time from the RTC Module. I’ll need to do some digging and figure out exactly where its all went wrong…

Very cropped side by side

The camera, although a lower resolution, appears to capture more of the image. Its a shame it appears very hard to see properly, but I’m hoping thats to do with the camera_mode, or possibly the sensor. More tinkering required!

I’ve also been thinking about having a simple way to change the camera_mode when recording. I think I’m going too implement a 3 LED system, using Binary counting, so show which camera_mode I’m using. I’ve have a (very) quick look at Alex Eames code for button presses here and think I can change this so that a quick press is camera_mode, a longer press is stop recording (useful for when I have it hooked up in the house to view files instead of running pkill every time I log in), and a long press is shutdown. Ultimately the first press can be used as a “protect” marker on files should it be required, but I’m getting ahead of myself!

# The following Python code has been copied from https://github.com/raspitv/bikedashcam/blob/master/dashcamcorder.py - Alex Eames and Raspi.tv


try:
    while True:
          # this will run until button on GPIO13 is pressed, then
          #   if pressed short,     stop recording
          #   if pressed long,      close program
          #   if pressed very long, shutdown Pi gracefully
        print "Waiting for button press"
        GPIO.wait_for_edge(13, GPIO.FALLING)
        print "Stop button pressed"
        stop_recording()

          # poll GPIO 13 bottom button at 20 Hz for 3 seconds
          # if still pressed at the end of that time period, shut down
          # if released at all, break
        for i in range(60):
            if GPIO.input(13):
                break
            sleep(0.05)

        if 25 <= i < 58:              # if released between 1.25 & 3s close prog
            print "Closing program"
            GPIO.cleanup()
            sys.exit()

        if not GPIO.input(13):
            if i >= 59:
                shutdown()
Categories
Electronics GitHub PiDashCam Raspberry Pi

An Update…

So, after being alerted by the Raspberry Pi Weekly mailing list to a liveblog by Alex Eames detailing his process for building a biking “dash cam” I thought I better start detailing what I’ve done, what I’m currently doing, and what I plan to do with my PiDashCam project which has taken a back seat for a number of months years. I’ve watched the videos Alex has made, but not yet looked at the code. My first post was using an Original Raspberry Pi with no camera attached, hooked up to a GPS module to ensure I got valid GPS data, and a small SPI screen so I could view the data

The Before

Unfortunately work and life took over and apart from spending a few odd minutes here and there over a number of months, no real advances were made apart from this update in which I was now testing with the Raspberry Pi Zero W, and figuring out how to get it talking to the GPS module, with the accelerometer, button and RGB LED all hooked up (but still no camera).

The After

I’m now going to try and update here with that I’ve decided upon, some new design goals and design directions, and the code needed to run my PiDashCam, in addition to stripping back to the bare essentials (you know, like being a camera).

I’ve remained with the Raspberry Pi Zero Wireless and I have an RTC Module hooked up, in addition to the camera, and one button. At present, the Pi boots, and automatically runs two scripts.

The new, updated, lesser qualified PiDashCam

The first, record.py, grabs the date and time, starts the camera, and starts recording, updating the annotated text on the screen. It then outputs a new file named after the current year, month, day, hour, minute and second (YYMMDDHHMMSS) every pre-determined number of seconds (roughly). You will be able to view this source code on GitHub as soon as I get round to uploading it. It also annotates the current date and time, and the current camera_mode.

The second, start.py, simply waits for the button press. At present it only detects an on push, nothing fancy like a multiple second hold. It then gracefully pkills the Python Process that is controlling the camera and after a few seconds delay, initiates a shut down of the Pi.

As its a bit unwieldily at present, I’ve stuck and blu-tacked it to a cheap dash camera I bought from eBay or AliExpress at some point or another. 

The camera works when testing in my house. I’ve still to take it a road test and make sure it works. I have a second, cheap Dash Cam that was another eBay or AliExpress special that does what it needs to do, but the quality is pretty poor. I plan on keeping both cameras connected and comparing the output. If I cant at least match the quality of a sub £20 Dash Cam then there’s no real point in continuing this one.

My Plan is as follows

  1. Test the camera, make sure it works in the car
  2. QUALITY CHECK
  3. Test multiple camera modes with the First Edition Raspberry Pi Camera
  4. Test multiple camera modes with the Second Edition Raspberry Pi Camera
  5. Test multiple camera modes with a cheap FishEye Pi Camera
  6. QUALITY CHECK
  7. Add in GPS Logging
  8. Add second button for marking of emergency record
  9. Add in G-Sensor for additional annotation and Emergency Record Function
  10. QUALITY CHECK
  11. Create a settings style file where all user-selectable settings are set
  12. Put it all in a nice case
  13. Work out a way to convert the raw h264 files to a usable mp4 format
  14. Build a nice web-based interface with an API so that apps can access the files/settings via Wi-fi
  15. Integrate with the CAN-Bus to take car data for better analysis of driving etc.

After each quality check, if the quality is not something that is useful then it could be a cancellation of the project. I’m trying to provide a more organised, and focused attempt this time and having these Design Goals will ensure that I focus on what’s required without jumping ahead. As always, I’m a great started and terrible finisher, but hopefully that will change!

In addition to the PiDashCam, I’m Aldo going to try my had again at small electronics. I’ve had a plate of 100 of these WS8211B RGB LED’s, and due to the way I stored them, they managed to snap. Playing about with the layout meant I could resonable build a Binary Clock, which I’ve wanted to do for quite a while. Given how many I had though, I figured I could extend this out and make it alternate between a Binary and Regular clock, and seeing as I have an ESP8266 spare, this could all be controlled wirelessly, with the time updated from an NTP server. But, there will be a separate blog post about that!


Updated 20/02/2019 with correct links to Alex Eames blog and minor technical details.

Categories
Electronics GitHub PiDashCam Raspberry Pi

Pi Zero W – PiDashCam Part 2

There will be a longer post about the newly released Pi Zero W, however suffice to say as soon as I saw it was available it was ordered, and I now have one!

There has been a few changes to the PiDashCam project, which has included moving to the Pi Zero when v1.3 was released (As it had a camera connector on the board). I missed my opportunity to write about those updates!

The Pi Zero W uses a similar set up to the Pi 3, in that the built-in bluetooth capabilities use the hardware UART, which means that my UART GPS receiver wont work.

As it is so similar to the Pi 3 (excluding the memory and processor) the current Device Tree for disabling bluetooth on the Pi 3 works for the Pi Zero W.

I’ve included some code below. This starts from a fresh install and allows you to use the hardware UART of the Pi Zero W and disables bluetooth on that board.

I hope it helps someone! (Also, feel free to replace vi with nano – I’m trying to teach myself Vim).

sudo vi /boot/cmdline.txt

in this file, remove the following text:

console=serial0,115200

Save and close the file. Next up,

sudo vi /boot/config.txt

and add the following to the end of the file:

enable_uart=1
dtoverlay=pi3-disable-bt

Next, it’s these three quick commands which includes a reboot of the Pi Zero W, which enables hardware UART:

sudo systemctl stop serial-getty@ttyAMA0.service
sudo systemctl disable serial-getty@ttyAMA0.service
sudo reboot

To complete the GPS side of things however, continue with the following:

sudo apt-get install gpsd gpsd-clients python-gps
sudo systemctl stop gpsd.socket
sudo systemctl disable gpsd.socket

and finally,

sudo killall gpsd
sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock
cgps

which should see you getting data from the GPS Receiver.

Thanks to Adafruit for their existing tutorial, and the Raspberry Pi github/forums and IRC for the Device Tree information.

Categories
Electronics Raspberry Pi

The Raspberry Pi Dash Cam Project – Post 1

I’ve been toying with the idea of building a dash cam using a Raspberry Pi for a while. Every now and then I’ll buy something I think I’ll need for the project, hoping that I would get some time to work on it.

I’ve had a few days holiday, and one of my aims was to at least build a prototype in the days I had off.

I haven’t built a prototype, but I have the majority of parts together and verified that they worked! And it was surprisingly easy, apart from a 1.8″ Display (more on that later!).

Firstly, why not just buy one? Because I think I can build this, and I think I can enhance it and add to it, especially if I splash out and buy a Raspberry Pi 2! Also, why not?

My plan is to have the Raspberry Pi Camera Module recording as soon as the Pi boots to an acceptable state. A GPS receiver should then log the current GPS Position, heading and speed to a text file, and hopefully output some of that to a display. Likewise, an accelerometer and gyroscope should hopefully offer some additional readings to show the standard of driving.I plan to power the Pi via the cars 12v source (the accessory port or cigarette lighter). I will also have to create a safe power circuit so that once the vehicle has been switched off, the Pi shutdown gracefully. I will also have to make sure that when the vehicle starts there won’t be any sharp spikes in electricity which could fry the Pi.

So far I have:
The Raspberry Pi (Model B – Model B Rev 2 if required)
Raspberry Pi Camera Module
A DS3231 RTC (i2c)
A GPS Receiver (UART)
1.8″ Display (SPI).

I have backed a BerryIMU, which has an accelerometer, gyroscope and magnetometer, which will connect over i2c, but that has still to be delivered.

To mount the camera to the window, I purchased some suction pads (the ones with nuts) and I’ll create a custom camera mount to use them with.

Yesterday and today I spent some time with the equipment I have to make sure it all works together, which, excluding the camera, it does! I’ve excluded the camera during this round of testing I want to get everything else working first. Heres the equipment, breadboard style. Please excuse the dust! The Pi was stuck behind my TV.

Heres a quick video of the Pi being powered up in my car, using the equipment I already had to hand. Sorry about the black box, but this GPS Receiver is pretty accurate!

Just now I’m running stock Raspbian, but I have also been playing with buildroot, specifically gamaral’s pre-built image.

It really does boot that quick. Once I have everything set up in Raspbian, i’m hoping a few more days of compiling will get me a full featured Dash Cam that boots that quickly using buildroot. I’m hoping that the recording will start within 5 seconds of power being applied.

All my goals for the system as pretty much listed above. I just have to start learning Python! Good think I backed another Kickstarter project!

With regards to the 1.8″ Display, that was a bit harder to set up.

I was under the impression the Display I had used a ST7735 driver, as everywhere online said thats what the display used. It doesn’t. It actually uses a HX8353 driver.

There is some commands below. Each command is on a separate line and should be executed separately.

I had to install a custom version of the Raspberry Pi’s firmware, developed by notro using this command:

sudo REPO_URI=https://github.com/notro/rpi-firmware rpi-update

and then

sudo reboot

This custom firmware contains all the drivers needed to use the screen on the Pi. I could compile the software myself, but this is a proof-of-concept to make sure everything works. I then shut down the Pi, and hooked up the display as per this wiring diagram (please excuse the rubbish 5 minute job):

hx8353d

One thing to note is that I hooked the Backlight directly to 5v, so the backlight is always on when power is applied to the screen.

I then fired the Pi up, and typed the following commands:

sudo modprobe fbtft dma
sudo modprobe fbtft_device custom name=fb_hx8353d  gpios=reset:25,dc:24 speed=16000000 rotate=270 bgr=1
con2fbmap 1 1

This gave me the console on the screen. I then modified /etc/modules  (using sudo nano /etc/modules), and inserted the following lines at the end

fbtft dma
fbtft_device custom name=fb_hx8353d  gpios=reset:25,dc:24 speed=16000000 rotate=270 bgr=1

It’s as easy as that!

Now, to learn Python!

Categories
Electronics Equipment Raspberry Pi

A case for my Raspberry Pi!

Heres a quick 7 minute video about a case I purchased for the Raspberry Pi that only cost £4 from eBay!