Thursday, August 7, 2014

The Pie, The Only Programmer With A Life: My Highly Opinionated Thoughts On Learning Program...

The Pie, The Only Programmer With A Life: My Highly Opinionated Thoughts On Learning Program...: This is gonna be a rather long and highly opinionated post on mastering programming so I advice you grab a cup of coffee and sip slowly as y...

Friday, June 6, 2014

Setting up a Node Server and Securing it with SSL on RaspberryPi

It's Friday, and as usual it's #FridayHacks: learning and experimenting with my kits, arduino & Raspberry Pi. Today, I'm only exploring projects of others, no experimentation. Here' s what I discovered whiles gathering knowledge (PS: I have not tried it out yet): A how-to on setting up a Node server with SSL on RaspberryPi by Sirar Salih. Have a good read and have fun trying it out.
RaspberryPis are awesome little things that you can do a lot of cool stuff with. Basically, a RaspberryPi (RasPi) is a 35 dollar, mini computer. It has LAN, USB, audio, RCA, HDMI and power ports as well as an SD card input. The A model has a 700 MHz processor and 256 MB of RAM. An SD card is flashed with an operating system and used on the device, there are lots of operating systems to choose from, I personally prefer Debian Wheezy. I purchased my RasPi some time last year and have had quite some fun with it since. When I first got it, I set up XBMC on it and used it as a humble HTPC or at least as a video media outlet in my apartment.
WP_20140531_19_52_36_Pro
Recently, I decided to use my RasPi for something far more awesome. I decided to set up a publicly secure node server on it and have it control an AR Drone in my apartment through REST calls (I don’t have any drone just yet though). In the following tutorial, I will show you how to set up a secure node server on your own RasPi and make it accessible from anywhere in the world.
First things first: Install Node
The first step is to install node on your RasPi. Power up your RasPi, log in as root user and then simply type the following commands:
wget http://nodejs.org/dist/v0.10.2/node-v0.10.2-linux-arm-pi.tar.gz
tar -xvzf node-v0.10.2-linux-arm-pi.tar.gz
This will download node and unzip it for you. If you then typels you’ll see that node-v0.10.2-linux-arm-pi was unzipped successfully in your current folder. The next step is to set node in your global path so you can start it from anywhere. Type the following:
NODE_JS_HOME=/home/pi/node-v0.10.2-linux-arm-pi 
PATH=$PATH:$NODE_JS_HOME/bin
The node packet manager (npm) comes bundled with node, we will use that to install external modules. Node and npm should now be accessible from any location in your RasPi.
Install External Node Modules
You may need to install node’s native build tool for future use, to do that, simply type:
npm install -g node-gyp
The node-gyp build tool is now installed and located at:
%HOME%/node-v0.10.2-linux-arm-pi/lib/node_modules
You will find all future installed modules located in this folder. Next up is to install express (we will use this module to create our secure node server later on):
npm install -g express
It may be a good idea to install the socket.io module as well for future use:
npm install -g socket.io
We now have all the external modules that are needed.
Change from Dynamic to Static Local IP for the RaspberryPi
Since the aim is getting the RasPi accessible from the outside world, you need to have a static IP for it. Chances are you are using a router, and thus a dynamic IP is provided to your RasPi by the router. In this case, you need to make the dynamic IP static. You can start by typing the following command:
ifconfig
Note the fields inet addrBcast and Mask. Here is an example:
inet addr:192.168.1.110  
Bcast:192.168.1.255  
Mask:255.255.255.0
Now type the following command:
route -nee
Note the field Gateway, which is the IP of your router:
Gateway: 192.168.1.1
Now type the following command:
nano /etc/network/interfaces
Change the line iface eth0 inet dhcp to iface eth0 inetstatic. Now, change the information to include the following:
iface eth0 inet static
address 192.168.1.110
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
Save changes made to this file and then exit (CTRL+XY andEnter). Now reboot your RasPi in order for the changes to take effect:
reboot
Log in as root user. That’s it, your RasPi now has a static local IP. In this example, the IP is 192.168.1.110. The next step is to port forward your global IP to this IP.
Port Forward Global IP to the RaspberryPi Static Local IP
In order to access the RasPi from the outside, we need to port forward our global IP to the RasPi static local IP. I prefer to use the router UI for this, I use a Linksys WRT54G router, here is a screenshot of how I do the port forwarding using this router:
Capture
Once you’ve done port forwarding, the RasPi should now be accessible from the outside.
Generate a Certificate Signing Request (CSR) for SSL
We need to generate a Certificate Signing Request (CSR) to sign the SSL certificate that we will use for the RasPi node server. We will use *cough* OpenSSL *cough* to generate the CSR, if OpenSSL is not already installed in your RasPi then simply install it by typing the following command:
apt-get install openssl
Now generate the CSR like so:
openssl req -nodes -newkey rsa:2048 -keyout private.key -out server.csr
Note: private.key is the private key which is for your eyes only, make sure to move it to a secure location. We will use this key later along with the SSL certificate to create the node server.
You will now get some questions that you need to answer, here is an example:
Country Name (2 letter code) [AU]: NO
State or Province Name (full name) [Some-State]: Oslo
Locality Name (eg, city) []: Oslo
Organization Name (eg, company) [Internet Widgits Pty Ltd]: Salih AS
Organizational Unit Name (eg, section) []: IT
Common Name (eg, YOUR name) []: mysubdomain.mydomain.com
Email Address []:
Please enter the following 'extra' attributes to be sent with your certificate request

A challenge password []: 
An optional company name []:
Note: Email addresschallenge password and optional company name can be left blank. The most important field here is Common Name, you need to type in the domain that you want to use for your RasPi. Setting up SSL requires a domain (unless you’re going for a mighty expensive and special SSL certificate), therefore you need to have one (in my case, I usehttps://raspi.sirars.com). You can purchase a domain at a good price from providers such as GoDaddy.
Generate the SSL Certificate
We will now generate an SSL certificate using the CSR we got in the previous step. An SSL certificate costs money. I personally prefer SSLs.com for their cheap price range, fast delivery and good documentation. I recommend that you order your SSL certificate from them. Once you’ve done that, edit the server.csr by typing the following command:
nano server.csr
Copy the entire content. Now go to this link and follow the steps thoroughly. When you’re done, you’ll get an e-mail fromSSLs.com containing your SSL certificate (which has the name format mysubdomain_mydomain_com.crt).
Point Your Domain to the Global IP of the RaspberryPi
The next step is to point your domain to the global IP. Say that you own the domain http://raspi.domain.com, in that case you need to point this domain to the now global IP of your RasPi. I purchased my domain from GoDaddy, here is a screenshot showing how I pointed my subdomain to the global IP address of my RasPi using GoDaddy’s domain management panel:
Capture
@ points the whole domain, while subdomain raspi points to a specific IP. For security reasons, my IP addresses are censored in the screenshot. Once you’ve pointed either your domain or subdomain to the global IP of the RasPi, it will take around 10 hours or so to take effect depending on the domain provider.
Create Node Server Using the SSL Certificate
The last step, is to create the node server itself with the generated SSL certificate. Start editing the JavaScript file by typing:
nano node_server.js
Now create the secure server by inserting the following JavaScript code (make sure to use absolute file paths):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var fs = require('fs');
var https = require('https');
var privateKey = fs.readFileSync('private.key', 'utf8');
var certificate = fs.readFileSync('mysubdomain_mydomain_com.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var express = require('%HOME%/node-v0.10.2-linux-arm-pi/lib/node_modules/express');
var app = express();
var ip = "192.168.1.110";
var port = 443;          //HTTPS
app.get('/', function(request, response){
    response.send("Welcome to my RaspberryPi Node Server!");
});
var httpsServer = https.createServer(credentials, app);
httpsServer.listen(port, ip);
console.log('Node express server started on port %s', port);
This code simply creates the node server for you using the SSL certificate that was generated earlier. Note the usage of the static local IP. We also created here a simple GET request on “/” that returns a welcome a message to the user, so when the user types your domain name in the browser (which is basically doing a GET request, using HTTPS) he/she will be greeted by this message.
To start the node server, simply type the command:
node node_server.js
Test out your secure node server by visiting your domain using HTTPS, it should work by returning a welcome message. You can find my own server here.
Create a Script to Automatically Start Node Server on Boot (optional)
This step is optional but highly recommendable. Once you’ve finished setting up your secure node server, the next thing you want to do is to create a simple script that will automatically start up the server every time your RasPi is rebooted. Start editing the script file by typing the command:
nano startup_script.sh
Insert the following lines in the script:
NODE_JS_HOME=/home/pi/node-v0.10.2-linux-arm-pi
PATH=$PATH:$NODE_JS_HOME/bin
node /home/pi/node_server.js
Save the file and then exit. Make the file executable by typing the following command:
chmod +x startup_script.sh
Now, you need to move this script to the /etc/init.d folder:
mv startup_script.sh /etc/init.d
Reboot your RasPi, and the node server should now start automatically.
Hope you enjoyed it!