## A Basic Install of a Raspberry Pi System

With a brand new Raspberry Pi comes the challenge of how to set it up. For some uses, such as a desktop (full Raspbian with PIXEL) or media centre (e.g. LibreELEC) it can be as simple as downloading an image, plugging in a screen, keyboard, and mouse, and going from there. When you want to do something else with your Raspberry Pi, especially in a headless setting (i.e. without screen), then setting everything up can be a bit more tricky. This guide helps to simplify the process of setting up a basic, secure Raspberry Pi headless installation.

# Creating and setting up the microSD card

First things first, you need to prepare a microSD with Raspbian. To do so, head over to the Raspberry Pi Downloads section and download Raspbian (Jessie) Lite. This is a basic installation of Raspbian that works particularly well for headless systems where you don’t need the extra software for a GUI. Once downloaded, you have to get the image onto a microSD card. To do that, you can follow their excellent guide. Once that is done, regardless of whether you use Linux/MacOS/Windows, you should see a boot drive. This boot drive allows you to change a few settings before you let the Raspberry Pi do the actual install. Depending on the Raspberry Pi you have, there are 1-2 steps you want to do:

• enable SSH so that you can easily access your Raspberry Pi from another device;

To enable SSH on the Raspberry Pi you need to create an empty document titled ssh on the boot drive. If you are using Linux or MacOS you can use the touch command for this. All you have to do is navigate to the boot drive from terminal, and touch the ssh file. On MacOS, you would do:

touch /Volumes/boot/ssh


On Windows you can simply open your favourite text editor and create an empty file ssh file. Do be careful that the file does not automatically get an extension. You don’t want the file to be title ssh.txt, you want it to be called ssh.

To provide your Wi-Fi credentials, create a file titled wpa_supplicant.conf on the boot drive. The contents of this file should be as follows:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB

network={
ssid="YourNetwork"
key_mgmt=WPA-PSK
}


Here you replace YourNetwork and YourPassword with the name and password of your Wi-Fi network. For example, if the name of your network is BTHub4, then the ssid line would have to be changed to ssid="BTHub4". The country code also needs to be set to the country you reside it. This is to ensure the broadcast is in accordance with local regulations. To do this, you need to provide the ISO/IEC alpha2 country code for the country you are in. GB is used for the United Kingdom, but if you live somewhere else you can use this list to find the code for your country. For example, if you live In Norway – which has code NO – you would change country=GB to country=NO.

You can now plug the microSD into your Raspberry Pi. This is also the time to connect your Raspberry Pi to your network using an ethernet cable if you are not using Wi-Fi. If all goes well your Pi will now perform the setup, and after a minute or so will be ready to use.

# Setting locale, updating, and using fs2ram for microSD longevity

If all went well, your Raspberry Pi should now be accessible in your network. To verify that it is, fire up your terminal and type:

ping raspberrypi.local -c 1


which will send a single ping to your Raspberry Pi 1. If all goes well, you should see a couple of lines of output including

1 packets transmitted, 1 packets received


If things don’t go as planned, you might see

ping: cannot resolve raspberrypi.local: Unknown host


In this case your Raspberry Pi is not (yet) connected to the network. Give it a few more minutes to set itself up. In the meantime, if you are using an Ethernet cable, verify that you have plugged in the Ethernet cable correctly and that the green and orange light on the Ethernet port of the Raspberry Pi are on (and flashing). If you are using Wi-Fi, then check that all the information you provided in wpa_supplicant.conf is correct.

Try Ethernet if Wi-Fi fails.

Setting up Wi-Fi is a tad more finicky. If you have a Raspberry Pi with both Ethernet and Wi-Fi, and you can’t seem to get it connected to the Wi-Fi, then it might be worthwhile to see if you can access the Raspberry Pi when it is connected using a good old fashioned Ethernet cable.

If the ping worked, you can login to your Raspberry Pi using:

ssh raspberrypi.local -l pi


If all goes well, you will be connected to your Raspberry Pi and it will prompt for your password. It can happen that your SSH client keeps a list of known hosts. In that case, you may get the question:

The authenticity of host 'openvpn.local (---)' can't be established.
ECDSA key fingerprint is SHA256:---/---.


Simply type yes to accept. After you accept, the password prompt will appear. The password for the pi user is raspberry, so go ahead and type that one in.

Problem connecting to SSH?

If you have a problem connecting to the SSH, then first of all give it a few minutes. The first time around your Raspberry Pi needs to create the SSH keys and this can take some time. If after a few minutes you are still not able to connect with SSH, but the ping you tried before is working, then repeat the earlier steps to create the ssh file on the boot drive – make sure you don’t use any extension!

## Setting locales and your timezone

Once you are in, the first thing to do is change the locale. To do that, type:

sudo dpkg-reconfigure locales


A menu will appear from which you can select all of the applicable locales. Locales can be selected by going up and down with the arrow keys and pressing spacebar to select the ones you want. It’s a good choice to select the UTF8 option for your language/region. So, if you are in the UK, you would choose en_GB UTF8. Once you selected all the ones of interest, simply press enter and you will see a final confirmation screen. If all is fine, hit enter again.

Generating each locale takes quite some time.

While tempting, it probably isn’t a good idea to generate all locales. Instead, select at least one English locale (such as en_GB or en_US) and all the local locales you are interested in.

The next step is to select your timezone. To do that, type:

sudo dpkg-reconfigure tzdata


You will be presented with a menu such as with the previous command, but this time you have to select the city closest to you with the same timezone (you can only select one). If you are in UK mainland, you would choose Europe followed by London.

With your locales and timezone set, it is now time to fully update your system. To do that, type:

sudo apt-get -qq update && sudo apt-get -qq upgrade && sudo apt-get -qq dist-upgrade && sudo apt-get -qq autoclean && echo "done"


This single statements combines a number of commands. The first command will update the list of available packages and their versions. The next command will do the actual upgrading of out-of-date software. The following command also upgrades the software you already have, but is a bit more clever about it and may actually remove some packages if you may no longer need them. The final command clears out the local repository of retrieved package files. When all of this is done, the message done will appear at the bottom of the screen and you will be returned to the prompt.

## Using RAMTMP and fs2ram for microSD longevity

Before you restart to apply all the updates, you will also enable some features that will help ensure the longevity of your microSD card. Any microSD only has a finite number of times data can be written to it, and Linux/Raspbian can be a bit wasteful in the number of files they write every minute. Instead, you will use memory to store temporary files and logs. As an added bonus, corruption to your system often happens due to a power interruption while a write is in process. With less writes, you not only ensure the longevity of the microSD card but also – hopefully – prevent system corruption.

First of all, let’s enable RAMTMP. To do this, type:

sudo nano /etc/default/tmpfs


As you scroll down, you will find a line that currently reads:

#RAMTMP=no


Change that one line to:

RAMTMP=yes


and then press CTRL+X, followed by y, and finally an enter to conclude. Be careful to change both the no to a yes and to remove the # at the start of the line. Changing this line will ensure temporary files are kept in memory rather than written to the microSD. Next, lets install fs2ram which will help to keep even more things in RAM. Type:

sudo apt-get install fs2ram


After a few seconds, a menu will appear asking you the particular setup for fs2ram. Choose the first option: Content-preserving.

Once installation is done and you are returned to the prompt, there are some settings to update. To do this, type:

sudo nano /etc/fs2ram/fs2ram.conf


and delete the penultimate line, which reads:

tmpfs            /var/cache      keep_file_content       -               tmpfs


The end result should look like:

#
# In case you want to make /var/lock or /tmp available as ram
# filesystems, it is preferable to set the variables RAMTMP, RAMLOCK
# from /etc/default/tmpfs.
#
#<file system>  <mount point>   <script>                <script option> <type>  <options>
tmpfs            /var/log        keep_file_content       -               tmpfs
tmpfs            /var/tmp        keep_file_content       -               tmpfs


As before you can save the changes to the file by pressing CTRL+X, followed by y, and finally an enter to conclude.

Finally, lets also disable swap files. To do this, type:

sudo swapoff --all


and then followed by

sudo apt-get remove dphys-swapfile


where you confirm the change by typing Y.

One last thing before you restart. You also want to change the hostname. Remember how you were able to connect to the Raspberry Pi by using ssh raspberrypi.local? This worked1 because raspberrypi is the default hostname used by a newly installed Pi. Let’s change this to something more personal.

Type:

sudo raspi-config


Once you hit enter, a menu will appear as below.

Use the arrow keys to move around in this menu and choose option 2 Hostname by hitting enter when that option is selected. The next menu will give you information on which names qualify as valid hostnames. A valid hostname must be between 1–63 characters long, and the only allowed characters are ASCII letters ‘a’ through ‘z’ (in a case-insensitive manner), the digits ‘0’ through ‘9’, and the hyphen (‘-‘):

Confirm you have read this by pressing enter.

As you can see, the current hostname is raspberrypi. Change this to something more descriptive and appropriate for this host. Say that you want to use this Raspberry Pi as an OpenVPN server, then you would change the name to openvpn:

Once you have picked a good name, hit enter to confirm. You are now back in the main menu. Use the tab key to move to the buttons at the button and select Finish.

Since you changed the hostname, the tool will ask you if you want to restart. Confirm that you indeed want to restart at this time by choosing Yes.

## Performance, convenience, and security

ssh openvpn.local -l pi


This time though, you have to replace openvpn in the above command with the hostname you chose earlier. If SSH asked you to verify a known host before, then it will do so again now. As before, you can confirm by typing yes. The password is still the same as before, so on the password prompt type raspberry.

You are now going to install a number of packages doing various things, from improving performance, to adding security. Type:

sudo apt-get -qq install cpufrequtils apt-utils raspi-copies-and-fills rng-tools vim curl fail2ban rsync


The package cpufrequtils will allow you to check and change the CPU speed. The package apt-utils will install some esoteric utilities that will be needed to successfully install other packages. Better memory management and a hardware based random number generator (which is much, much faster) are enabled thanks to raspi-copies-and-fills and rng-tools. Both vi and curl are commonly used tools on Raspbian/Linux and are handy to have. The package fail2ban is there to protect you. It will scan failed login attempts, and will automatically block computers that try to log in too often without success. Finally, rsync is a very popular – and capable! – utility for transferring files in a variety of ways.

Most of these packages work out of the box, but you need to load the module for the hardware random number generator. To do this, type:

sudo sh -c 'echo "bcm2708-rng" >> /etc/modules'


# Changing the default user

You have done a lot so far, but our Raspberry Pi is still unsafe due to the default user/password pi/raspberry. Furthermore, all of the commands you used so far that were preceded by sudo are executed with root privileges. This means that they can change anything on the system. That’s a lot of things that you can do with the system, all of which is possible if you only know that the user/password is pi/raspberry.

You are now going to fix that. What you will do is create a new user, and delete the original pi user. There are three options to consider, from weakest to safest, to create a new user:

• protected by a password (easiest to set up, but least secure);
• with SSH keys (great tradeoff between security/convenience);
• with SSH keys and a passphrase (best security).

The first option is the easiest, but generally the least secure. It requires you to enter the password whenever you try to connect to your Raspberry Pi. This can be solved by using SSH keys. With SSH keys, you store a private part of the key on your own computer, and a public part of the key on the Raspberry Pi. As long as you are connecting from your own computer, you won’t need a password at all. This option is also safer, as a key can be much larger than a password, and is guaranteed to be random. The small downside of this approach is that you need to keep your (private/public) key safe. If you lose it, you also lose access (but in return there is no password for you to forget). The final option combines both ideas. It uses a private/public key pair, but also requires a passphrase to unlock the key. The last option is the safest, but also the most cumbersome. The choice really is yours, and all three options are discussed below.

## A user with a password

To create a new user (e.g. kim) with a password, it suffices to type:

sudo adduser kim


Simply follow the instructions to add the new user. It will first asks you to enter and confirm the password, followed by some personal information. How much of the personal information you fill in is really up to you, and if you leave it blank it doesn’t really matter. Once you are done with that, the system will ask you if all personal information is correct and you can confirm by pressing Y or n if you want to change any of the personal information.

You are done and can skip the next section. Immediately go to the section titled “sudo privileges and deleting pi”? This section explains the next steps on how to gain sudo privileges, test them, and finally delete the standard pi user.

## A user with SSH keys – generating the SSH keys

Creating a user with SSH keys is a bit more involved because you first need to generate the keys. The following steps will guide you through that process and make it as simple as possible. If you already have SSH keys, you can immediately go to the next section – adding the user. Do note that these instructions only apply to Linux and MacOS. To start, on your own computer, open a terminal and type in:

ssh-keygen -t rsa -C kim@openvpn


You can change kim@openvpn to whatever you want, as this is just a comment. It can be handy to add a comment in the format username@hostname to make it easier for you to later on remember what the key was for. It is not mandatory though, and if you don’t want a comment you can just enter ssh-keygen -t rsa.

You will now have to answer a number of questions. First, it will ask you where to store the key. Simply press enter to store the key in the default location. Next, it will ask you for a passphrase. If you want SSH keys with a passphrase, this is where you have to add your passphrase. If you don’t want a passphrase, simply hit enter and confirm by hitting enter again. The process will complete by telling you where your public key is saved, what your key fingerprint is, and give you a randomart image that can be used to recognise your key.

Once your key is generated, type

cat ~/.ssh/id_rsa.pub


What you see here is your public key. It will be of a form similar to this:2

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC5YJDS4o+BAj0gE2Lu+JMh+4hLnGfZ4ECavF7i9PgG8phbUOlOqa5mmyHW88K6tGYg/UICUbaszBeLeSTdGc2raSwGqGSH3dBVjiDio2I1y7Ru8/yNnai6Bieje5f5yclZX+ORpXehS29pPZ7HRxoW1cl8GfT93CbTbknDweHsrQsFTPu4xxKLUH3etHSTqyMe7ITiGsbxSTHZdRN76YqO00uephpX9j3peYztYjqKh+2IQEBTXrFpZ6hFT1FEle8n03wLVY8pyk4q+54ZKHuVw3RpUyKmfxHtREYtNrxWERgwp5Ujoo6ei2Fu/L4mk02hwRUk62PUuLpGt7uiaBah kim@openvpn


Keep that window open, as you will need your public key in one of the next steps.

You really should make a backup of your private key. If you used the default location, you will find the private key in ~/.ssh/id_rsa. You can see the contents of the file by typing cat ~/.ssh/id_rsa. If you do so, you will see that the file has a -----BEGIN RSA PRIVATE KEY----- header and a -----END RSA PRIVATE KEY----- footer. Copy the entire block (including the header and footer) to a safe location, such as a USB stick that you leave in a safe place or as an entry in a password manager of your choice.

Generating SSH keys on Windows.

If you are using Windows, then things are just a bit more complicated. Have a look at this excellent tutorial from DigitalOcean on how to generate SSH keys on Windows. Once you have generated the SSH keys, you can continue with the instructions on this page.

## A user with SSH keys – adding the user

Now that you have the SSH keys you can proceed with creating the user. In all commands that follow, remember to always replace kim with your desired username. First, let’s add the user to the system:

sudo adduser --disabled-password kim


Simply follow the instructions to add the new user without a password. It will ask you to enter some personal information associated with this new user. How much of the personal information you fill in is really up to you, and if you leave it blank it doesn’t really matter. Next, you need to add the public SSH key to the list of authorised keys for this user. To do so, type (where you replace kim with your chosen username; do this for each command):

sudo mkdir /home/kim/.ssh
sudo nano /home/kim/.ssh/authorized_keys


You now need to copy your public SSH key into this file. Simply copy your public key (the one that starts with ssh-rsa and ends with your comment) and paste it into this file. As before, save and close by pressing CTRL+X, followed by y, and an enter to conclude.

They public key is now in place, and all that is left is some bookkeeping. The problem is that so far you used sudo, so the files you created have as owner the user root. Instead, you want to make kim the owner (or, for your case, the username you chose).

First, let’s change the owner (replace all three occurrences of kim with your chosen username):

sudo chown -R kim:kim /home/kim/.ssh


The final step is to set the correct permissions for the directory and file you created. To do that, first execute:

sudo chmod 700 /home/kim/.ssh


Followed by:

sudo chmod 600 /home/kim/.ssh/authorized_keys


Remember: in both cases you have to replace kim with the username you chose.

## sudo privileges and deleting pi

With the user created, the final step is to give the user sudo privileges. Otherwise, the new user will not be able to run commands preceded by sudo to gain elevated privileges. Do to this, type:

sudo sh -c "echo 'kim ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers.d/kim-passwd"


where you replace two occurrences of kim with the username you chose.

Before you delete the user pi, you need to confirm that all settings are working well. To do so, get out of the Raspberry Pi system by typing:

exit


Now reconnect with the newly created username:

ssh openvpn.local -l kim


Remember: you have to replace openvpn with the hostname you chose earlier, and replace kim with the username you chose.

If all goes well, you should be able to login without a problem. If you do run into errors, then log back in with the user pi by typing ssh openvpn.local -l pi and where you replace openvpn with your chosen hostname. Then retrace your steps and make sure you performed all of the commands correctly.

Finally, you are ready to delete the default pi user. This is the final test to see whether everything is set up properly, as you need to use sudo to delete a user:

sudo userdel pi


If it doesn’t work, or if it asks for a password even though you are using SSH keys, then you need to log out by typing exit and log back in using the user pi (see a few paragraphs above). This typically means that you did not set the sudo privileges correctly – did you replace every occurrence of kim with your newly chosen username?

A final step to batten down the hatches is to automatically install security updates. This will ensure your software remains up-to-date, even if you don’t log in yourself to check that everything is in working order. To make this possible, all you need to do is:

sudo apt-get install unattended-upgrades -y


This will install the unattended-upgrades package and all its dependencies. To activate it, type:

sudo dpkg-reconfigure -plow unattended-upgrades


You will be presented with a menu, where you should choose Yes to enable the automatic installation of stable updates. To enable it to update all stable packages from Raspbian, you also need to execute:

sudo sed -E -i 's/\/\/([[:space:]]*"o=Raspbian,a=stable")/  \1/g' /etc/apt/apt.conf.d/50unattended-upgrades


This will change the update file and signal that all stable packages from Raspbian can be updated if possible. The next day, or whenever you want to see what has been going on, you can type:

cat /var/log/unattended-upgrades/unattended-upgrades.log


to see that all is working well, as well as get an overview of all upgrades that have been performed in an unattended way.

And … that’s it, all done.

# Conclusion

After following these steps, you now have a fully set up Raspberry Pi system with good performance, a hopefully long life for the microSD card, and a secure new user. Remember that at any time you can log into your Raspberry Pi from your computer by opening a terminal and typing:

ssh hostname.local -l username


where you replace hostname with the chosen hostname and username with the chosen username.

1. Using raspberrypi.local as the address only works reliably if this is the only Raspberry Pi in your network, or if all your other Raspberry Pis have been assigned hostnames other than raspberrypi

2. Of course this is not my actual key. But even if it was, it would be of no use to you as this is only the public key, which is useless without the private key.