Advertisements
Home Automation Project
06 Jun

Home Automation Project

I love the idea of home automation. Ever since the early days of Star Trek when they could get back to their room and tell the computer what they want – lights, music … food! This idea was taken to another lever by S.A.R.A.H. (Self Actuated Residential Automated Habitat), the bunker home Jack and Zoe Carter live in on Eureka.

I ways knew I wanted an automated home, not only does it appeal to the geek in me but I’m also fairly lazy and like systems that make life easier. During a recent week off I spent almost the whole time setting up my smart house (which I’m calling GERTY from the 2009 movie Moon).

When I started my project I’d played and experimented with other systems, some worked better than others and some were killed off my the makers, but up till now I’ve been tinkering. There’s never been a fixed design or plan. Now I know what I want. I just don’t know how I’m getting there yet – and that’s the adventure.

At present I’m using OpenHAB. It’s not something I’ve ever played with before and so far I’m liking it. It’s doing what I want and giving me the power I’m looking for.

My plan is over the next few weeks to use this blog as my ‘grail diary’ recording my experiences with results. I found the OpenHAB learning curve was quite high and the examples didn’t always explain anything fully – just copy and paste – and I struggled to find many real world examples. My grail diary will consist of this blog and a git repository the house the working examples.

Thought out the journey I welcome you all to join in and let me know what you think and how you would or are solving the same problems. In my first article I will be looking at presence detection, since one of the most important things of a smart house is for it to know if you home or not.

Raspberry Pi Bitcoin Core 0.10.2 Installation
14 Jun

Raspberry Pi Bitcoin Core 0.10.2 Installation

This weekends project is setting up a Raspberry Pi as an online Bitcoin wallet.

As you might the first step has been installing Bitcoin Core. There is no binary Bitcoin available for the Raspberry Pi’s ARM process so I had to build it from source. Less I Forget here is my step-by-step guide:

Requirements

  • Raspberry Pi 2
  • A 2A power supply
  • External HD
  • Raspbian OS Image Downloaded from here
  • The blockchain – Optional but could save days of waiting

Installing a Clean OS

First thing to do now we have a Raspbian install image is copy it to a new microSD card.

Being a Linux user I just copy the image from the command line using dd:

dd is a Unix command so if your MacOSX user the same command will work for you as well. It takes a few minutes but gets the job done. For Windows users a program like Win32DiskImager can do the install for you – full instructions can be found here.

Raspi-Config / Updating

As normal with a new installation raspi-config will run during the first boot. What we need to do here is expand the file system to take up the whole sdcard – no point in empty space just sitting around looking prity.

Once that’s done enable the SSH server. The Pi will reboot after your exit raspi-config so just let it do its thing.

Once the Pi is back up and running you can now keep working working with an attached keyboard a mouse of fire up and SSH connection from another machine and work from there, the choice is yours.

If you do choose the SSH option make sure you start a screen session, since the commands we’re about to run could take a few hours on the Raspberry.

If you need a pointers, the quickest way to get the Raspberry’s IP address is running ifconfig from the command line. The default username is pi and – if you didn’t already change it – the password will be raspberry, but I would highly recommend changing it as your first step passwd will do the job.

Now that we have a running Raspberry Pi and we’ve logged into a terminal – ether thru the keyboard and monitor or over SSH – we’re going to quickly run an OS update:

Installing Bitcoin

Getting the dependencies

We’re going to have to build Bitcoin Core from the source code, and for that we need the build tools and dependent libraries installed:

We also need to install the BerkeleyDB 4.8, since its not available from apt-get we’ll need to build it from source as well. This will take a while so probably best grab a cup of coffee or something, but if your using a Raspberry Pi2 you can replace the make command with make -j4 to spread the load over the extra cores.

Getting the source

Now that the system is ready we can finally start on Bitcoin. First get the source code from the GitHub repository:

Building it

Next we’ll configure it for our system and get the build started. Again this will take ages, but you can speed it up on the Raspberry Pi2 by using the make -j4 command instead of just make – for reference I just used the make option and it was done in about 3 – 4 hours.

Up & running

… and we’re back. We now have Bitcoin Core 0.10.2 installed on our Raspberry. Before we run it for the first time we need to make sure we can download the blockchain. At present the blockchain is over 35Gb. Since we can’t feasible store it on our microSD card we need to put it on an external hard drive.

If you’ve never plug an external drive into a Raspberry Pi before, its worth pointing out the Pi doesn’t have enought power to support the drive directly. You must ether get a drive back with it own power or plug the drive into a powered usb hub.

Once your drive is ready you have a few options for telling Bitcoin Core where to put the blockchain. Ether mount the external drive to /home/pi/.bitcoin or create a symlink there. The final option is to pass the the new location to bitcoin over the command line bitcoin-qt -datadir=/path/to/harddisk/

One last thing before we fire up the Core. If you already have a copy of the blockchain copy this to the Raspberry Pi, it will save hours or even days of waiting. However, if like me you don’t you may run into the same problems I have.

When I started running bitcoin-qt it will crash. After Googling around the error message relates to a lack of memory. The Raspberry Pi2 has 1GB or ram but its appears that isn’t always enough. Since adding more RAM isn’t a practical option I’ve resorted to running this script:

This handy little one-liner will restart bitcoin-qt every time it closes – in my case crashes – and the download will resume where it left off.

I’m not sure if this problem is histochemic of the Raspberry Pi or just while the blockchain is downloading but once my downloads completed I’ll get a better idea and can give some more feedback.

Raspberry Pi Powered OpenVPN – Client Side
19 Apr

Raspberry Pi Powered OpenVPN – Client Side

This is part two of my series on creating your own, private, VPN server at home using a Raspberry Pi. If you have followed on from my Raspberry Pi Powered OpenVPN – Server post you will have a fully working OpenVPN server. You probably also noticed it took you a good portion of your afternoon, but with bugs and hacks being found in more and more Linux software and libraries it is well worth having a server you can trust.

You’ll have noticed though we’re missing a vital step before we can make use of our new server. In part three of my tutorial we created some access keys to allow our phones and laptops (from here on called clients) to access our server, but we haven’t told the clients.

OpenVPN software gets all the information about where your server is, how to connect, what keys to use and what connections to create from a configuration file called and .ovpn. Since you need a separate OVPN file for each client we’ll use a script to do our heavy lifting.

Eric Jodoin first created this script while at the SANS institute, and with some basic template files, it can create configuration files for all our clients.

As with the Raspberry Pi Powered OpenVPN – Server tutorial the following commands still need executed as root, so remember ether add sudo infront of them or make sure you still have root from the sudo -s command.

Setting the defaults

Eric’s script works by combining a default configuration file with the keys specific to client, so we need to create it first.

Create a new blank file:

nano /etc/openvpn/easy-rsa/keys/Default.txt

Then copy and past in this:


Remember to change the line remote to match your setup. Include the public IP address of your OpenVPN server and make sure the port and proto are correct. If in on page four you opted to use TCP or a non standard port, one other than 1194, you need to make sure this is correct here as well.

If you are not sure what your public IP address is you can ask Google.

Some ISPs will rotate your IP address regularly which causes a problem when trying to access your new server. There are however many services that offer dynamic domain names (DDNS). These give you a static domain name but make sure the IP address always points to your home PC. First thing I would do is check your router to see if it supports a DDNS provider. If it doesn’t then you can use a free service like DNS Dynamic, but you will have to setup and run the ddclient on the Pi to keep your IP address updated.

As in the previous tutorials use control+x and save the new file.

Creating the script

Now we’ll create a copy of the script Eric produced, the original PDF download of his research paper can be found online.

First create a new file in nano:

nano -w /etc/openvpn/easy-rsa/keys/ovpn_gen.sh

Get a copy of the script from my gitlab server and past it into this new file. Lastly control+x and save the new script.

By default new files created in nano are just text files, they do not have permission to execute commands. This command will give only the root user permission to read, write or execute our new file:

chmod 700 /etc/openvpn/easy-rsa/keys/ovpn_gen.sh

We can now run the script, but first make sure we are in the keys folder:


The first thing we’re asked for is the Client Name. This must be the same as we used in page three of the server side tutorial. I’ll continue using KEYNAME here, but if I was setting up the key for my Nexus 5 I would use stuart.nexus5.

If everything worked as expected you’ll see a message like this:


Now just rinse and repeat for as many clients as you have setup, but make sure to only run the command for keys you already created. If you need a new device go back to page three and create a new set of keys first.

Downloading the OVPN files

You now have to download your new OVPN file from the /etc/openvpn/easy-rsa/keys/ folder onto your clients. If you are on a link system I would use the scp command, but for Windows users WinSCP would work as well.

If you are using WinSCP you will not have permission to access the /etc/openvpn/easy-rsa/keys/, this is by design and adds additional protect to your server. So you can cp the file into the pi home directory first and download it from there, but make sure to delete it once you have it on the client.

cp /etc/openvpn/easy-rsa/keys/KEYNAME.ovpn /home/pi/

and then

rm /home/pi/KEYNAME.ovpn

In part two of this tutorial we’ll take a look at setting up our client and getting OpenVPN installed and running on your Android phone or tablet.

Raspberry Pi Powered OpenVPN – Server, Part 1
07 Feb

Raspberry Pi Powered OpenVPN – Server, Part 1

I mentioned in a previous post that I had a spare Raspberry Pi. It’s taken me a while to finish but I’ve managed to turn it into a portable OpenVPN server.

A VPN, or Virtual Private Network, is a way of extending your private network into the outside world all fully encrypted. Free and in most cases unencrypted WiFi is available almost everywhere from universities to coffee shops or hotels and even your dentists waiting room, but you have to be careful what you are doing on internet access points.

Most people are unaware but free WiFi from places like your local coffee shop or hotel are ot safe. Sending confidential email or even web browsing can be subject to interception, what is commonly known as a man-in-the-middle attack. Because of the way WiFi works its relatively easy for someone with the right tools to get between you and the internet. So however tempting it may be you really do not want to be logging into your bank and even something as simple as checking your GMail could leave your Google username and password out in the open.

The idea behind a VPN is to connect to the internet from a trusted source. Once VPN connection has been established all your communications to or from the VPN are encrypted and hidden from prying eyes. No one else at the coffee shop will have any idea what your doing online. All they will see is encrypted traffic to your VPN without being able to delve into that traffic to find out what your doing.

There is a multitude of online services which offer VPN access, in many cases allowing you to pick where you’d like access the internet from there by bypassing geographic restrictions on services like Netflix and BBC iPlayer, but these as in all things have upsides and downsides depending on the service and what charges they make. Since I really resent paying for something I can do myself I going to turn a inexpensive (£35) Raspberry Pi into my VPN server.

Doing it this way not only means I will save myself the ongoing payments of 3rd party VPN service, but I’ll also be able to access my home network as if I was there and still have full access to my Synology file storage.

What you’ll need

Hardware

Raspberry Pi: I’m using a model B but a B+ will work equally well.

SD Card: I would recommend an 8GB card. You shouldn’t need more if all your running on the Pi is OpenVPN.

Network cable: Cat5 or Cat6 depending on your network but you need something to connect the Pi to your router.

Software

OpenVPN: Which we will be installing onto your Raspberry Pi.

Some assumptions

  1. You already have installed Raspbian on your Raspberry Pi SD Card
  2. Your Raspberry Pi has a static IP address within your home network. You can ether do this from the Pi its self or like me setup your routers DHCP settings to issue the Raspberry Pi with static IP
  3. SSH is enabled. We need to access the Raspberry Pi to change settings and setup the OpenVPN server. Using SSH will make this simpler and means we don’t need to fuss with a keyboard or monitor attached to the Raspberry Pi
  4. You have forwarded both the UDP & TCP port 1194 to your Raspberry Pi’s static IP. Instructions for doing this will vary from router to router but if you search Google for your specific router you’ll find instructions

So if you’re ready I’ll get started on my how to guide.

House Cleaning

First thing we’ll do is setup the Raspberry Pi. Assuming your using a new Raspbian installation.

  1. Change your password: The default username and password for a clean Raspbian installation is pi and raspberry. Leaving this unchanged is generally a really bad idea, but not changing it on a Pi your connecting to the internet is begging for trouble. To change it first login over SSH and type sudo passwd this will change your root password then just use passwd to change the pi user password.
  2. Update: Always a good first step after a clean install. Updating the system will make sure you’re using the latest software and libraries, and any know bug or security flaws will have been patch. Raspbian OS being just a version of Debian system updates are handled by apt-get so to update the system run sudo apt-get update; sudo apt-get upgrade from the SSH terminal window.
  3. Install OpenVPN: OpenVPN is already in the repositories so installation is as easy as running sudo apt-get install openvpn

Now that our Raspberry Pi is ready we’ll move on to the setting up the installing and setting up OpenVPN on the Pi.

Raspberry Pi Powered OpenVPN – Server, Part 4
07 Feb

Raspberry Pi Powered OpenVPN – Server, Part 4

Time to put it all together

OpenVPN Configuration

So far we have setup and new Raspberry Pi, install OpenVPN, generated some server keys and at least one user/device key and created a Certificate Authority to sign them. We are still missing something though. OpenVPN doesn’t know any of the yet. We still have to tell it where to find these new files we’ve just create, what IP or port to listen for connections on, what type of connection to make or where to send the resulting traffic.

All these setting are held in OpenVPN’s configuration file, but non is installed with the OpenVPN package so we need to create a new one. Start by creating a file on the Pi nano /etc/openvpn/server.conf then fill it with this initial template:

I’ve marked some bits you will need to change yourself most importantly PI_IP_ADDRESS and YOUR_DNS_IP_ADDRESS but read thru the comments to make sure everything else is right for your setup. Once your done just control+x and save the file.

Port Forwarding

Now that OpenVPN knows what to do we need to tell the Pi to forward internet traffic. By default a Raspbian OS is designed to be a receiving client, internet traffic goes to or from it, but in this case we want it to forward traffic it receives on somewhere else – in this case your router.

To edit the system setting open up the system control file with nano /etc/sysctl.conf and find the line “#net.ipv4.ip_forward=1” and uncomment it by removing the # leaving “net.ipv4.ip_forward=1”. Once again use control+x to save the file. Lastly we have to tell the system we have changed the file. That’s done with the sysctl command, just type sysctl -p and your done.

Raspbian Firewall

We’re almost ready to restart the Raspberry Pi and have a functional server, but before we can there is one more thing we have to do. Raspbian comes with a built in firewall called iptables, found on most Linux systems, which is there to protect your computer from the dangers of the internet but we need to poke a hole through it while leaving the rest of it intact. This is done by issuing command directly to iptables, but we want these changes to still be in place next time we reboot the Raspberry Pi so we need to make the command something the Pi will run everything it connects to the router.

This is best done in two steps. First we’ll setup the script we want to run. Make a new file nano /etc/iptables-openvpn.sh and type in:

Make sure you change PI_IP_ADDRESS to your Raspberry Pi’s IP address. The hit control+x and save the file. We now need to make the file executable, but we also want normal users from changing it.

The first line means only the file owner can execute the file, no one else can even read it. The second line just makes sure the owner is root.

Now we have our supporting files we need to tell the Pi to run this file, and so poke the same hole, in our firewall every time a network connection is setup. Network setting for Linux are commonly stored in the /etc/network/interfaces file so we can start there.

nano /etc/network/interfaces

You can see a line that says “iface eth0 inet dhcp” that simply tells Linux to ask your router for an IP address for the ethernet plug. We can now inject out iptables-openvpn.sh file here by using the pre-up option.

…becomes…

Now before asking for an IP address from a connected router the Pi will run our iptables command and the firewall will be ready. control+x to save your work.

You can finally reboot your Raspberry Pi

Your Raspberry Pi is now a fully working OpenVPN server, in the next tutorial we’ll get started preparing our clients to connect to it.

Raspberry Pi Powered OpenVPN – Server, Part 3
07 Feb

Raspberry Pi Powered OpenVPN – Server, Part 3

Client Side

So we now have a working server, what we have to do now is create certificates for our users or our selves.

If you want to you can cheat here and create one certificate per user then they can use that everywhere, but as I talked about before, if they device is every lost or stolen you will have to setup all you other devices with the new key. So I have created a separate certificate for each device.

Since I am not the only person potentially going to use my VPiN service and I alone have four or five devices all needing access I’ve gone with a naming scheme USER.DEV. So for my Nexus 5 it’s be stuart.nexus5 and my laptop is stuart.redtop (If you’d ever seen my laptop you’d understand… o what the hell here it is)

To create a device key just type

./build-key-pass KEYNAME

… and more prompts

  • Enter PEM pass phrase – Make this something you will remember, depending on the client your running you may be asked to type this ever time you want to connect.
  • A challenge password? – You still have to leave this blank
  • Sign the certificate? [y/n] – The answer must be yes. You will be creating a ten year certificate

We now have an RSA key, but RSA keys have not been perfectly implemented everywhere and if you want to connect your Android or iOS device we need a Triple DES key. Triple DES is simple another encryption algorithm that applies its encryption three times for every block of data, making it harder for hackers to break by brute force. We can do this using the openssl command. All we need to do is input the old key and tell it what to produce:

openssl rsa -in keys/KEYNAME.key -des3 -out keys/KEYNAME.3des.key

OpenSSL will now prompt you for the password of the rsa/old key, which is just entered, and ask you for a new password for the 3des/new key. I just used the same password for both keys, there is no loss of security as long as it was a good password and no need for two separate password.

And that’s it. You’ve now created your first client side key. You will have to repeat these steps for each device but its simple enough just keep changing your KEYNAME as appropriate.

In the final part of this tutorial we need to put everything together and tell OpenVPN about our configuration.

Raspberry Pi Powered OpenVPN – Server, Part 2
07 Feb

Raspberry Pi Powered OpenVPN – Server, Part 2

Groundwork

Keypair

I mentioned before that a VPN encrypts traffic to and from your device. In much the same way as connecting to a site over HTTPS. This is done by public-key-cryptography. If any of you have ever heard me talk at Dundee Tech Talks you’ll have heard me go on at length about encryption and public key encryption is by far the coolest method of encryption. I’ll probably talk about it more in another post but at its simplest level you have two keys. One encrypts and one decrypts, you then can make the encryption key public. OpenVPN comes with a collection of helper scripts and config files called Easy_RSA which produce keys use the RSA encryption algorithms.

The next few commands are going to be run a root. You can ether stick sudo in-front of all the commands I’ll list bellow, or to save some time just type sudo -s and become root.

Now before we start setting up our certificates we must copy the default EasyRSA in a folder that makes sense:
cp -r /usr/share/doc/openvpn/examples/easy-rsa/2.0 /etc/openvpn/easy-rsa

Now before we can start using EasyRSA we have to tell it where to find our new directory. So edit the vars files nano /etc/openvpn/easy-rsa/vars find the line ‘export EASY_RSA’ and update the value, once your done it should look like export EASY_RSA="/etc/openvpn/easy-rsa"

Before we leave the vars file we’ll also want to adjust the level of encryption 1024 to 2048. In most cases 1024 is all you would ever need, but why settle for less when its as easy as typing three numbers to exponentially increase your VPNs security.

To exit nano simple type control+x, nano will prompt you to save the file before exiting.

The Authority

One thing that give OpenVPN its security is that it doesn’t use a username and password to authenticate its users. When asked for a password the majority of people will use a relatively simple password, or reuse a previous password and where someone picks a good/strong password it can easily be forgotten. Another risk to consider is where you’ll be using the VPN. Having the password stored on devices like phones and tablets which can be lost or stolen leading you to have to change your password then update all other devices with the new password – a pain if you happen to away from home.

Instead OpenVPN uses a OpenSSL keypair. Every device has its own private key signed by the OpenVPN server which is then used to authenticate each device separately. Now if a device is lost its as easy as revoking that devices key, no other device heeds changed or updated.

So we need to create a certificate authority on the Raspberry Pi to sign user keys – which we’ll do next. The following commands still need executed as root, so remember ether add sudo infront of them or make sure you still have root from the sudo -s command we used when setting up the keypair.

Step 1

Move into the EasyRSA folder we created earlier: cd /etc/openvpn/easy-rsa

Step 2 – A

Run source ./vars this will setup the all the environment variables we edited before.

Step 2 – B

As pointed out by Redrerick in the comments after the most recent update to OpenVPN available for the Raspbery Pi, openvpn armhf 2.2.1-8+deb7u3, you now have to run ./clean-all this will clear out any keys and certificates and give you a clean slate to start with.

Step 3

./build-ca this is where the magic happens. The Raspberry Pi is now going to hit you with a load of questions about where you are and organisation names. You can ether fill them in accurately or just accept the defaults.

Step 4

What you will need to pick a name for your server. I started by trying to use my normal naming scheme but, turns out its crap, settled for VPiN – clever right?

./build-key-server VPiN

The same as in step 3 you are going to be hit by a series of questions.

  • Common Name – This has to be the same as your server name, if it hasn’t already defaulted to that change it!
  • A challenge password? – You have to leave this blank
  • Sign the certificate? [y/n] – The answer must be yes, if you don’t sign the certificate then nothing else will work

You’re going to get a warning saying the certificate is valid for 3,650 days. So if you still using your Raspberry Pi VPN server in ten years you’ll need to come back and go through these steps again – so you’d better bookmark the page now.

Finally it’ll say “1 out of 1 certificate requests certified, commit? [y/n]” again type ‘y’

Diffie-Hellman

Now we’re going to create whats called a Diffie-Hellman key exchange. This is a fundamental element to creating a secure connection between two machine when all of the ‘handshaking’ is done before the encryption is setup, meaning any 3rd party can sit in and watch the full unencrypted ‘handshake’ conversation but still not know what the final encryption keys used are, so once the connection become encrypted that’s it – there out in the cold.

Make sure you are still in the /etc/openvpn/easy-rsa director and run

./build-dh

Now best to get a coffee or something cause this can take a while, especially if you followed the instructions and increased the level of encryption from 1024 to 2048.

DoS (Denial of Service)

A DoS (Denial of Service) or DDoS (Distributed Denial of Service) attack is where an attacker gets the IP address of a service online and starts issuing so many connection requests, some times in the range or a several thousand per second, that the server can not handle them all and eventually dies under the load.

OpenVPN has built in protection against these attacks called a HMAC (hash-based message authentication code). Kind of like a pre-shared secret. If the server doesn’t receive this secret it want even try to authenticate a device instead just ignoring the request. Now, while you don’t want this secret out in the wild its not a huge security risk since even with the secret a device will need a valid certificate as well.

Generating the secret is as easy as typing:

openvpn --genkey --secret keys/ta.key

OpenVPN is finally installed on our Raspberry Pi, but its fairly useless unless our devices can connect to it. So next we’ll look start creating some key for our phones and laptops.

Raspberry Pi Yearly Running Cost
29 Jan

Raspberry Pi Yearly Running Cost

I don’t know about you but I run a number or Raspberry Pi’s in my house all doing different jobs. I’ve often heard it said how inexpensive a Pi is to run but I never how inexpensive, and I wanted some real world figures.

After a little time with the good all Google I came across this form post by audigex from 2012 so I’ve used his calculations, just updated the figures.

In the same vane as audigex’s original post I’ve taken the worst case and a more average look. A Raspberry Pi uses 5W maximum, 5V x 1A = 5W, in theory but it should never go higher than 700mA which is only 3.5W.

I really had to search around but the most expensive unit price I could find at present, January 2015, was £0.24 per kWh. I won’t name and shame the company here, but believe me if you’re paying that much you will be hard pressed not to beat it!

Worst Case
Raspberry Pi Power (Watts) 5W
Hours to user 1kWh 200 h = 1000 / 5
Hours in year 8765.81 h
Raspberry Pi per year 43.83 kWh = 8765.81 / 200
Cost per kWh £0.24
Yearly Running Cost £10.52 = 43.83 * 0.24

For a more realistic look I down graded the total watt usage to 3.5W as discussed above and took the average unit cost straight off the UK Gov website, and The Department of Energy & Climate Change Quarterly Energy Prices published on the 18th December 2014. According to official Government statistics the average cost for a kWh unit is £0.15 pence, personally I’m paying slightly less than the average but the figure is still a valid one for this analysis.

Realistic Values
Raspberry Pi Power (Watts) 3.5W
Hours to user 1kWh 286 h = 1000 / 3.5
Hours in year 8765.81 h
Raspberry Pi per year 30.68 kWh = 8765.81 / 200
Cost per kWh £0.15
Yearly Running Cost £4.60 = 30.68 * 0.15

So based on, what I freely admit is back of the napkin math, a Raspberry Pi costs between £4.60 and £10.52 per year. Obvisoully this may be slightly higher if you are also running a USB hub or any external storage.

I hope this is of use to someone else. If you have noticed any flaws in my calculations please let me know in the comments bellow.