Book Image

Learning Raspberry Pi

By : Samarth Shah, Serge Schneider
Book Image

Learning Raspberry Pi

By: Samarth Shah, Serge Schneider

Overview of this book

Table of Contents (14 chapters)
Learning Raspberry Pi
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Remotely accessing Raspberry Pi


Once the Raspberry Pi is up and running, it may be necessary to access it remotely, and there are several ways of going about it.

The SSH remote server

SSH can be used for the vast majority of remote administration tasks. It gives us full access to a remote terminal just like it is local. Because the Raspberry Pi makes a good headless server, SSH is installed and enabled by default in Raspbian. Within Linux, connecting to an SSH server is done with the ssh command:

ssh user@IP:port

Tip

If you don't know how to get the IP address of Raspberry Pi, refer to Chapter 7, Troubleshooting, Tips/Tricks, and Resources for Advanced Users, Tips and tricks section.

The user and port parameters are optional. The username defaults to the currently logged-in user and the default port is 22.

On Windows, an SSH connection can be established using PuTTY, which you can download from http://www.chiark.greenend.org.uk/~sgtatham/putty/.

Securing SSH

If you want to make the Raspberry Pi accessible from outside of the local network, extra precautions should be taken to protect it from bots and hackers. Most bots simply attempt to connect on port 22 as root and brute force the password. Assuming that the password is relatively secure, this isn't a big problem, but it will eventually start filling up the logs with failed login attempts.

Changing the port number and forbidding root login over SSH is the simplest way of stopping the vast majority of automated login attempts. This can be done by editing /etc/ssh/sshd_config and setting the following options:

Port 1286 #Any unused port number is fine
PermitRootLogin no

Note

To keep things simple for the rest of the instructions, please leave the port at the default 22 for now.

However, changing the port number is not always desirable and will not stop someone from scanning for open ports. Ideally, you would disable password logins altogether and use keys. This is how it works—you generate a private and public key. The public key can be sent to a remote server. The private key, as the name implies, is kept private and is used instead of the password.

Windows users can generate the keys using the PuTTYgen tool, which is available on the PuTTY website:

  1. Copy the public key to the ~/.ssh/authorized_keys file on the Raspberry Pi (you may have to create it) and save the private key onto your PC.

  2. After this, change the permissions of the authorized_keys file in order to protect it:

    # chmod 600 ~/.ssh/authorized_keys
    
  3. Once this is done, you can use Save private key in PuTTY.

  4. The following PuTTY Key Generator screenshot annotations show the public key to be copied and how to save the private key:

  5. The highlighted area of the preceding screenshot shows how the private key can be used within PuTTY.

  6. Within Linux, the keys can be generated as follows:

    # ssh-keygen -t rsa
    
  7. When prompted, accept the default save location and enter a passphrase. The content of id_rsa.pub should then be pasted into the ~/.ssh/authorized_keys file on the Raspberry Pi. This can be done with a single command:

    # ssh-copy-id user@IP –p PORTNUMBER
    

    You should now be able to connect to the Raspberry Pi by using our private key.

  8. Once you have confirmed that this works, come back to /etc/ssh/sshd_config and disable password logins:

    PasswordAuthentication no
    
  9. You can add as many public keys to the authorized_keys file as necessary. For example, you may wish to allow someone else to access your Raspberry Pi. To do this, you would ask for their public keys and add it to the authorized_keys file of the desired user account.

    Note

    In the case the private key is stolen, it cannot be used without the passphrase. If someone knows the passphrase, it is useless without the SSH key. The combination prevents brute force connection attempts and secures the key itself.

  10. The final thing to do is to install fail2ban. This program monitors connection attempts and bans malicious IPs. This is a very powerful tool that can be used to fight a variety of different attacks and SSH is supported by default. This can be installed by running the following command:

    # apt-get install fail2ban
    

Open the configuration file to edit with Sudo nano /etc/fail2ban/jail.local and paste the following content (assuming your private IP addresses are in the range 192.168.0.*):

# SSH
# 3 failed retry: Ban for 10 minutes
[ssh]
enabled = true
port = ssh
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
mail-whois-lines[name=%(__name__)s, dest=%(destemail)s, logpath=%(logpath)s]
logpath = /var/log/auth.log
maxretry = 3
bantime = 600
ignoreip = 192.168.0.0/10

[ssh-ddos]
enabled = true
port = ssh
filter = sshd-ddos
action = iptables[name=SSH, port=ssh, protocol=tcp]
logpath = /var/log/auth.log
maxretry = 10
ignoreip = 192.168.0.0/10

Restart the fail2ban service:

sudo /etc/init.d/fail2ban restart

Transferring files

Besides executing commands remotely, SSH also allows us to transfer files. The scp command is similar to cp, but can copy files to and from SSH servers with the following command:

$ scp /path/to/src user@IP:/path/to/dst

This works great for a simple file transfer, but there is a more powerful command, which is as follows:

$ rsync /path/to/src user@IP:/path/to/dst -av

Rsync will only copy files that differ. By default, it does this by checking the file size and timestamp of the file, but a -c option can also be passed to use a checksum. This is very useful when making backups or updating source code, for example. It can also be used with a local source and destination, making it a very useful tool to get familiar with.

Windows users can use WinSCP, which is available at http://winscp.net. It has an excellent GUI that can use PuTTY private keys, and offers a way to move files between your PC and Raspberry Pi.

X11 Forwarding

So, you can run commands and transfer files, but what about the GUI? The X Windowing System was designed with the ability to use a remote display in mind. SSH can be used to forward remote GUI programs to the local X server. For Linux users, it's only a matter of launching SSH as before, but with the addition of a -Y option. When you have a SSH session ready, try launching leafpad. It should show up on your display.

Windows users will require an X server running. Some options are listed here:

Maintaining remote session using screen

While screen is not related to SSH directly, it is an incredibly powerful combination. Under normal conditions, if our connection drops and the SSH session is lost, everything that was running inside of it is terminated. This may result in a lot of hard work being lost. The screen allows us to create a session, which you can detach and re-attach as required. While detached, everything will continue to run as normal. If the connection drops, you can simply re-attach to the screen session and continue where you left off. Unfortunately, Raspbian does not come with screen preinstalled, so run the following command to install it:

# apt-get install screen

Once installed, it can be launched by running the following command:

# screen

You will receive a welcome screen, which can be dismissed by pressing Enter or disabling it in ~/.screenrc.

First, you'll need to learn a few key bindings to get started with screen. The default key bindings are initiated by pressing Ctrl + a and are completed by another key. For example, the screen session can be detached by pressing Ctrl + a and then d. Once detached, you can return back to the screen session by running the following command:

# screen -x

What if you want to run multiple applications? On a local machine, you have multiple ttyS commands or you can open many terminals windows and tabs. Starting a new SSH session for every application would be a little inconvenient. Screen has us covered here as well. Ctrl + a+ c will create a new window. The first window (0) is now replaced by the new window (1). To return to the first windows, the Ctrl + a + 0 binding will work. You can have as many windows as needed and navigate them using the Ctrl + a + 0-9 keys. Alternatively, Ctrl + a will bring up a list of all windows and let us switch between them using the arrows and the Enter key.

This short introduction only scratches the surface of what is possible with screen. It can display multiple windows at once in a split view, allowing you to have a file browser, a media player, and a network monitor running and making them visible all at once within the screen session. Multiple users can connect to the same screen session, if remote assistance is required. Screen can be configured to display a status bar with all of the windows listed and a clock, for example. It also supports start-up scripts, which can be very useful for power users.

The reverse SSH

Your Raspberry Pi could be behind a firewall with no access to port forwarding. In such a case, you can't connect directly. However, if the computer you wish to connect from is not behind a firewall and also has an SSH server running, reverse SSH can be used. From the Raspberry Pi, start SSH with the following command:

$ ssh -N -R 2222:localhost:22 user@IP

In this case, the user and IP parameters are for the computer you wish to connect from. -N means that you do not wish to run any commands. -R 2222:localhost:22 means that port 22 on localhost is going to be tunneled to port 2222 on the remote computer.

Then, from the remote computer, you can connect to localhost on port 2222 and that will redirect to port 22 on the Raspberry Pi launching SSH as follows:

$ ssh user@localhost –p 2222

The disadvantage is that this needs to be prepared in advance and will only last as long as both computers are on. This can be circumvented by preparing a script that runs every 15 minutes and creates the tunnel if it's not already established.

The other problem is that one computer must not be behind a firewall. The solution is to use a middleman server, which the Raspberry Pi will establish a tunnel with. Then, you can connect to this server and be tunneled through to the Raspberry Pi. However, the fundamental problem still remains, as now you require yet another server that is not behind a firewall. If such a server is not available, a third-party solution such as Hamachi, may be an option.

Virtual display using VNC

VNC is quite different from the other options and comes in two flavors. The first allows for the display that is attached to the Raspberry Pi to be mirrored remotely and is called x11vnc. One example of where this is handy is remote assistance. The other option is a virtual display, which is not shown on the Raspberry Pi's monitor itself. The virtual display approach is useful when you would like to be able to launch multiple, independent VNC sessions. In order to connect to a VNC server, you will need a VNC client. There are clients and servers available for all major operating systems, from Windows to Android. TightVNC is one example. The installation package differs from other distributions, but once installed, it can be launched using VNC Viewer.

In order to use the real display, you need to install x11vnc on the Raspberry Pi by running this:

# apt-get install x11vnc

If the X server is running, x11vnc can be launched directly by running x11vnc. By default, x11vnc will exit once the client disconnects. This can be prevented by adding the -forever option.

In order to use a virtual display, install a TightVNC server on the Raspberry Pi by running the following command:

# apt-get install tightvncserver

When running vncserver for the first time, you will be taken through a quick set up procedure.

Pay attention to the output, as it will say which display the server is running on. When connecting, specify this display as the port number.

In order to stop a running virtual VNC display, the -kill option can be used. The following command will kill the VNC server using display :1:

$ vncserver -kill :1

Share the keyboard and mouse using Synergy

Synergy is used to share the keyboard and mouse across multiple systems. For example, you can have a display connected to the Raspberry Pi and control it from the keyboard and mouse on your PC. This will be useful if you would like to use the full desktop environment without VNC, but don't have a spare keyboard, or if you would like to have a dual-display setup with one of the displays dedicated to the Raspberry Pi.

  1. On the PC, download and install the synergy server, either from the official website (http://synergy-foss.org) or from your distribution's repository. Running it will guide you through a setup procedure, which will prepare it for use.

    Note

    The version of synergy in the Raspbian repository is not supported by newer servers. It is possible to download an older server (1.3.8) or compile the client for Raspbian, which will not be covered here.

  2. Install Synergy on the Raspberry Pi by running this:

    # apt-get install synergy
    
  3. Finally, from the Raspberry Pi's desktop, launch the Synergy client with the following command:

    # synergyc IP