Raspberry Pi — Passwordless SSH Access on Win10
Using A Public-Private Keys Pair to Get To You PI Quickly! — RaspSeries # Episode 03
Greetings All!!!
[updated 2024] 09: #AllInOneStep
Hello Hobbyists! Welcome to the third raspiSeries episode!
We will demonstrate how to access your pi via ssh using public-private keys cryptography.
It is possible to configure your Raspberry Pi to allow your computer to security access it without providing a password each time you try to connect to it. To do this you need to generate SSH keys. It provides much better security than passwords alone. We will deal with it in a logical order.
A striking means of secure access to your Raspberry Pi in a very secure method, as said, is to use a public-private keys pair. A public key is placed on the server and a private key is placed on your local Windows workstation. thus it is almost impossible to log in to your Raspberry Pi just by typing password as long as you set up SSH to deny password-based authentication.
We will go deepen in this topic SSH to address even more secure shell access that you can set up in your own future Raspberry Pi’s projects.
And how do we intend to do it all?
Instead of using the official user pi and password raspberry, we chose to create a new user and use public-private key pairs. So we avoid us from having ever to use login-password, after all, we are going to the cloud (or distributed computing, if you prefer…) soon when we’ll deal with IoT projects, right?!
Here is this Post’s content:
- First, enable SSH, then we will change the interface from eth0 to wlan0; This is an arduous process at console, but you get it all step-by-step for your convenience;- We will give a new address to our Pi, static, this time. Thus avoid accepting the address provided by DHCP, giving more certainty in our access's code;- We will reveal a secret that will save you debug-time (it was hard to find it). Do not waste time too; Please, keep the pace until the final countdown; keep on reading ;)- We will generate a public-private key using PuTTYgen App;- We will put all the step-by-step in a logical and ordered sequence, so you will reference it easily and replicate it in your own platform at your home (#stayathome);- Come on, it will be exciting journey for sure!!! Be welcome!!!
Hardware needed:
- Raspberry Pi (any, mine is P1 - 2011.12);
- Micro SD Card with the OS loaded; See this post to get yours:)
- WiFi Dongle (and RJ-45 Cable) connected to internet;
- USB Type‑A to Micro‑USB lead (power supply)
List of programs:
1 - PuTTY;
2 - PuTTYGen;
3 - Advanced IP Scanner;
4 - Windows Explorer
Let’s get it on!
Motivation
But first, why we bother with SSH and typing stuff at the command line at all when Raspbian comes with a perfectly nice graphical desktop environment and a whole repository of GUI applications?
1. the first reason is that the desktop eats up too much of the Pi’s resources and the CPU is more concerned with redrawing fancy windows than with running our mischievous apps;
2. Stealth and secrecy are everything in embedded systems. Electronics components are often left with scarce space, resources, memory… Controlling and triggering it from a remote location via console gives your upcoming projects more freedom to work with, mainly in this era of pandemic home-office jobs, right? :/
Step-By-Step
Here are 9 step-by-steps needed to access your Pi passwordless:
00: Enable SSH on Your PI and Changing to WiFi interface, rather than Ethernet one (previous episode) by setting it up via the command line and set up the Raspberry Pi to have a fixed IP address;01: Confirming WiFi PuTTY’s Session by discovering our SSID;02: Confirming Your Raspberry Pi Is Serving SSH Via wlan0;03: Give Your Raspberry Pi A Static IP Address;04: Create A New User On Pi And Give It Sudo Privileges;05: Download PuTTYgen App;06: Generate RSA Keys With SSH By Using PuTTYgen;07: Copy Your Public Key to Your Raspberry Pi by Creating The Authorized Keys Directory and give due permissions;08: Log In To Pi With The Private Key & celebrate \o/[updated 2024] 09: To access your Raspberry Pi remotely using a public-private key pair and VNC technology
00: Enable SSH on Your PI and Changing to WiFi interface, rather than Ethernet one by setting it up via the command line and set up the Raspberry Pi to have a fixed IP address ;
If you want to access the Pi from Windows computers, you need 2 things: Enable SSH on your PI (we did this on our Episode 1 when we copy ssh to Raspberry Pi image; See Step 5 there or Note 1 below) and an SSH client (and one of the best is PuTTY). PuTTY’s a very small program that you do not even have to install; Let`s get it on:
1 — Download the executable Putty from putty.org;
PS: by default, your router’s DHCP (Dynamic Host Configuration Protocol) will assign an IP address to the Raspberry Pi; however, next time you power the Raspberry Pi up, the router may allocate a different IP address for it. This is a problem because in order to connect through SSH we need to know the Raspberry Pi’s IP address on your local network, and we can’t see this if we don’t have a monitor attached to it. There are two ways of solving this:
One, set up the Raspberry Pi to have a fixed IP address (we will treat this first case in this tutorial)
And two, scan the network to find the IP address of the Raspberry Pi every time we need to access it; it’s not an elegant option, right?
2 — Configure it: ip <192.168.0.21> or any offered by Dynamic Host Configuration Protocol (DHCP); you’ll need to scan your network to get it; again, refer to this previous Episode;
3 — Let’s access Raspberry Pi via Ethernet cable;
On PuTTY, Click the Open button;
4 — Access as pi and password raspberry, like usual;
5 — Then you’ll see the Pi’s regular login prompt;
Ok, now let’s access Raspberry Pi via WiFi. To make this happens follows these next steps.
You will need to run Advanced Scanner to get the wlan0 address (refers to this post, please:)
Now that you know the wlan0 interface address number, let’s try to change eth0 to wlan0 interface; Type:
sudo shutdown -h now
And connect the WiFi dongle; do not remove the ethernet cable yet!
01: Confirming WiFi PuTTY’s Session by discovering our SSID;
Please do these procedures:
Get the power to your Raspberry Pi board. Access via ssh with Putty client;
1 — Inside PuTTY session, type:
sudo iwlist wlan0 scan
This will list all available WiFi networks at your disposal. Look for ESSID name and see if that matches yours and if it is using WPA2 Version 1; If positive, you are good to go! If not, go here;
2 — Use the utility app called wpa-password to generate an encrypted psk (pre-shared-key):
wpa_passphrase "EAGLE" (use your SSID instead)
Please enter your WiFi credential and the output will be (in my case, obviously):
network={
ssid="EAGLE"
#psk="********"
psk=38fdfa1bd3e51699579c4429a95b32fd3f30f10df982bb6a4aa7ab24f88026d5
}
Note: delete the commented line when you transfer it to Raspberry Pi; that is your WiFi credential; Do not expose your passwords: security is our major endeavor, right?
3 — Open notepad++ (or notepad) and copy this snipped code there to use as follow;
4 — Execute this command:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Go to the bottom of the file and add this code snippet:
country=BR
network={
ssid="<YOUR CREDENTAL WIFI NAME>"
psk=<YOUR PSK GENERATED>
}
and CTRL + X, then Y, and hit <ENTER>;
5 — Now to enable WiFi type:
wpa_cli -i wlan0 reconfigure
If the inet addr
the field has an address beside it, the Raspberry Pi has connected to the network. You’ll see WiFi Dongle light flashes \o/;
Fine, now we are good to go ahead!
sudo shutdown -h now
Disconnect your Ethernet RJ-45 cable now :) and maintain plugged the USB WiFi adapter into one of the free USB ports on the Raspberry Pi and reconnect your Raspberry Pi to the power again, this time use 192.168.0.20 WiFi port.
Now that we are accessing Raspberry Pi via WiFi (in contrast we did in the previous episode) let’s just confirmed if it is true: Do we really go to WiFi?
02: Confirming Your Raspberry Pi is Serving SSH via wlan0:
Type this command:
sudo ip addr | grep ‘inet.*wlan0’
>Returns:
inet 192.168.0.20/24 brd 192.168.0.255 scope global dynamic noprefixroute wlan0
03: Give Your Raspberry Pi A Static IP Address.
Let’s give the Pi a Static IP Address; that way you avoid having to scan interfaces every time to find out what WiFi IP PI makes with DHCP. Just Do this:
1- Start by editing the dhcpcd.conf file
sudo nano /etc/dhcpcd.conf
2- Scroll all the way to the bottom of the file and add the following snippets (change the bold numbers accordingly with your own Ethernet (eth0)/ WiFi (wlan0) interfaces addresses):
interface eth0static ip_address=192.168.0.21/24
static routers=192.168.0.21
static domain_name_servers=192.168.0.21interface wlan0static ip_address=192.168.0.20/24
static routers=192.168.0.20
static domain_name_servers=192.168.0.20
3 — To exit the nano editor, press ctrl+x;
4 — To save your changes press the letter Y then hit <ENTER>;
5 — Now all you need to do is to reboot, and everything should be set (hope for the best ), type:
reboot
6 — Reset your PI; Disconnect your Pi from the USB and Power it Up again (the rise of WiFi interface is more time consuming; be patient!); You can verify whether it has successfully connected to WiFi using ifconfig wlan0:
ifconfig wlan0
If the inet addr
field has an address beside it, the Raspberry Pi has connected to the network. If not, check that your password and ESSID are correct.
04: Create A New User On Pi And Give It Sudo Privileges
1 -The easiest way to do this is from the command line:
sudo adduser <username>
Where username is the name you give your new user; then you will be asked to key in a password twice; enter it twice; then the system will ask you for further information about the user.
You can leave these fields blank if you want — just press <ENTER>;
Adduser will also create a home directory for the new user at /home/j3;
2 — After that, you can give them sudo privileges by editing the sudoers file:
sudo visudo
Use the cursor keys to navigate to the line below the entry for pi and copy it exactly, but use your new username instead of pi:
%j3 ALL=(ALL) NOPASSWD: ALL
3 — Once done, you need to save the sudoers file. This is done with:
CTRL+O
<ENTER>
CTRL+X
4 — Let’s prepare to test your new username, so now:
logout
or maintaining PuTTY session:
su - j3 (<ENTER> password)
5 — Then log in again using your new username and password
login
6 — One way to test if your new account j3 has sudo access is to attempt to edit the sudoers file again:
sudo visudo
7 — Then you have the same permissions as a pi user;
Congratulations! now, Type:
CTRL+X (to exit)
05: Download PuTTYgen App;
At this stage, we provide steps for generating RSA keys by using PuTTYgen on Windows for secure SSH authentication with OpenSSH.
Download PuTTYgen from PuTTY download page get PuTTYgen App, start it,
06: Generate RSA Keys With SSH By Using PuTTYgen.
Remember, if you have to access your Pi via SSH often, it might get tedious to always enter the password when you log in. A more convenient way is to use the public-private key mechanism.
To do that, you have to:
1 — Generate RSA Keys With SSH By Using PuTTYgen;
2 — Create A Directory Of Authorized Keys Entries;
3 — Log in to PuTTY With The Private Key.
In Windows, use PuTTYgen to generate your public and private keys.
1 — Launch the program, and then click the Generate button.
2 — Hover your mouse over the white space for seed generation; The program generates the keys for you;
3 — Enter a unique key passphrase in the Key passphrase and Confirm passphrase fields — although I have not used it. Having a password-protected key file would get in the way of SSH starting automatically as we would have to enter the password every time the service restarts. You may be prompted for that passphrase whenever you log in to your Pi with this key; We strongly suggest keeping the default settings as they are, so when you’re prompted to Enter a file in which to save the key
just press <ENTER>
to continue.
4 — Save the private keys by clicking the Save private key buttons; Name the file j3_key or any name you want; This file we’ll keep it in Windows; It is our private key; wait for next command (Create The Authorized Keys Directory — Item 6). I separated a dedicated directory called key.
5 —***Important***
Copy the public key to clipboard; This will be used in the next step (item 7.6).
07: Copy Your Public Key to Your Raspberry Pi by Creating The Authorized Keys Directory and give due permissions;
To copy your public key to your Raspberry Pi, use the following procedures.
Logged as j3:
1- Check if there is already a directory ~/ssh:
ls ~/.ssh
2 — If not create a new directory .ssh:
mkdir ~/.ssh
3 — Set the permissions; This step is very important; do not forget it!
chmod 700 ~/.ssh
4 — Open the authorized_keys file on the Linux server:
vi ~/.ssh/authorized_keys2
5 — Press the ‘i’ key to insert in vi;
i
6 — Go to the bottom of the file and right-click on the putty screen; This should insert the public key generated with PuTTYgen (see: previous Item 6.5)
7 — Press the scape
key to get out of insert mode in vi.
8 — Press :
to enter command mode in vi
9 — Type wq
and <ENTER> to write and quit vi
10 — Again, set the permissions; This step is very important; do not forget it!
chmod 644 ~/.ssh/authorized_keys2
Secret — The hash code of the primary key must always start with “ssh-rsa “ plus space. When using copy/paste without type i (insert command for vi) this piece may be omitted, generating Server Refused Our Key Error. Return to step 6.4 and enter this on start. There, everything will work perfectly !!!
08: Log In To Pi With The Private Key.
To make use of your newly generated RSA key pair, you must tell PuTTY to use it when connecting to your Pi;
1 — Open PuTTY, access as j3, and go to the SSH > Auth section;
2 — Browse to the location of the key file, and load the private key;
3 — Go to Connection > Data and enter, change the auto-login username as j3 (or whatever you configure);
4 — Go to the Session page, and save the session. This saves the configuration so that PuTTY uses the key every time that you connect to your PI.
Your public key is now ready to be recognized by the ssh service.
Open PuTTY and just click open (select the 192.168.0.20 interface) and boom, there you have it!
That’s It!!! Your Pi is a full-fledged member of your network now with pub-private keys. Cool, uh???
To deny password-based authentication read Topic 11
below.
Notes:
1 — If you see the message ssh: connect to host <IP-ADDRESS> port 22: Connection refused
and you know the IP-ADDRESS
is correct, then you probably haven't enabled SSH on your Pi. Run sudo raspi-config
in the Pi's terminal window, enable SSH, and then try to copy the files again;
2 — You should always have a reserved disk for disaster cases. Going forward, always have an SDCard image equal to the current reserved; how frustrating it can be when it crashes and corrupts your SD card. Here’s a little trick to making that a little less painful — lifehacker;
3 — To remove the /home/pi directory as well, use(It is not necessary. It depends on your project):
sudo deluser -remove-home pi
This will remove nearly all traces of the Pi user from the system, which will make it much harder for anyone to break into your Pi from outside if it’s connected.
4- The Pi has 256MB of RAM. If you use this, you found your configuration:
free -m
5- You will see that apparently the Pi has much less than 256MB of RAM. How can that be? Don’t worry: everything is OK with your hardware, and your Pi has 256MB of RAM. It just splits it between the CPU and the GPU (the device responsible for processing graphics). By default, the CPU gets 192MB of RAM, while the GPU gets 64MB. For most use cases, this is reasonable, but for some cases, a different setup might make more sense. If you use the Pi as a server, for example, you won’t need much graphics power but more RAM for the CPU.
6 — You can change the memory configuration by using a different GPU firmware. Raspbian comes with a few pre-configured firmware files, and you can find them in the /boot directory.
ls -l /boot/*.elf
-rwxr-xr-x 1 root root 2053456 Jul 19 06:47 /boot/arm128_start.elf
-rwxr-xr-x 1 root root 2053456 Jul 19 06:47 /boot/arm192_start.elf
-rwxr-xr-x 1 root root 2053456 Jul 19 06:47 /boot/arm224_start.elf
-rwxr-xr-x 1 root root 2053456 Jul 19 06:47 /boot/start.elf
The files starting with arm contain firmware images. The number after arm is the amount of main memory allocated for the CPU.
7 — For example, arm128_start.elf allocates 128MB for the CPU and 128MB for the GPU. The file start.elf contains the current firmware. To activate a new one, you have to copy it to start.elf and reboot the Pi (alternatively, you can use the memory_split menu in Raspi-config to change the memory layout).
sudo cp /boot/arm224_start.elf /boot/start.elf
8— Then:
sudo reboot
9 — Now check whether the Pi uses the new memory layout.
free -m
total used free shared buffers cached
Mem: 218 36 182 0 4 19
-/+ buffers/cache: 12 205
Swap: 127 0 127
10 — To remember the characteristics of Linux editors see this special hints:
nano — nanoEYE(crtEx+Y+Enter) = crtl + X ; Y ; Enter
vi — viesc:Wq (VW) = i ; esc ; : ; wq
visudo — visudoOX(VOX) = crtl + 0 + crtl + X
Excellent! The CPU now has plenty of RAM, so the current setup is perfect to run the Pi as a server for our future projects with Arduino and Raspberry Pi.
11— How to Disable root login and password-based login:
Make this change to sshd_config file, and save your options (CTRL+X, Y):
$ sudo nano /etc/ssh/sshd_config
Find ChallengeResponseAuthentication and set to no:
ChallengeResponseAuthentication no
Find PasswordAuthentication set to no
PasswordAuthentication no
Find UsePAM and set to no:
UsePAM no
Find PermitRootLogin and set to no (maintain the default setting):
PermitRootLogin prohibit-password
Now the only method to login is by your user j3 using your public-private key pair.
Congratulations!
Well done!
Thank you!
Next Steps:
Logging into the Pi using SSH is convenient and opens a new world of possibilities. For example, you can access the Pi’s file system, start and stop processes, and monitor what’s happening on the Pi at the moment. The biggest disadvantage of the SSH solution so far is that it works only in a text terminal.
You can easily overcome this limitation and control the Pi’s desktop, keyboard, and mouse using another computer. The solution is Virtual Network Computing VNC ©, a technology that transmits the whole screen and all mouse and keyboard events from one computer to another. This issue is for the next video (page).
VNC is a phenomenal technology; it is used in a home-office-work solution in this time of coronavirus COVID-19 pandemic. Be tuned!
“When Raspberry Pi was first announced a lot of people asked if this was an Arduino-killer. It turns out the two platforms are complementary. Raspberry Pi makes a great host for Arduino”
Related Posts
01Episode #RaspSeries — Raspberry Pi — How to Set Up a Headless Raspberry Pi — Without Ever Attaching a Monitor!
02Episode #RaspSeries — Raspberry Pi — First Boot — Configuring & Get Acquainted of your Pi
03 Episode #RaspSeries — Raspberry Pi — Passwordless SSH Access on Win10 — Using Open SSH Keys to Get to Your Pi Quickly!
04Episode #RaspSeries — Raspberry Pi Meets AlaMode® — An Arduino compatible board for the Raspberry-Pi
05Episode #RaspSeries — Mosquitto Meets Raspberry Pi — Part 1 — IoT Project Initialization — Join Our Knowledge About Mosquito & Raspberry PI
Inspirations & Credits:
Passwordless SSH access by www.raspberrypi.org
BLINDHOG.NET — Linux SSH — Passwordless Login With Putty:
Creating a new user with Sudo privileges in Debian on raspberry pi:
Dynamic Host Configuration Protocol:
[Edited on Jun 2024:]
09 — Detailed Steps Updated
To access your Raspberry Pi remotely using a public-private key pair and VNC technology, follow these steps:
1. SSH Access with Public-Private Key Pair
- Open a Terminal on Your Local Machine Open a terminal window on your local machine (Linux, macOS, or Windows with a tool like Git Bash).
- Generate SSH Key Pair (if needed) If you haven’t already created an SSH key pair, run:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Follow the prompts to save the key to the default location and enter a passphrase if desired.
3. Copy the Public Key to the Raspberry Pi Use the ssh-copy-id
command:
ssh-copy-id pi@raspberrypi
When you run this command, you will be prompted to enter the password for the pi
user on the Raspberry Pi.
Once authenticated, the command will copy your public key (~/.ssh/id_rsa.pub
) to the ~/.ssh/authorized_keys
file on the Raspberry Pi.
4. Verify Passwordless SSH Login After copying the key, test the SSH login:
ssh pi@raspberrypi
If everything is set up correctly, you should be able to log in without being prompted for a password.
2. Setting Up VNC for Remote Desktop Access
Install VNC Server on Raspberry Pi
On your Raspberry Pi, install the VNC server:
sudo apt-get update
sudo apt-get install realvnc-vnc-server
Enable VNC Server
Enable the VNC server on your Raspberry Pi:
sudo raspi-config
Navigate to Interfacing Options
-> VNC
and enable it.
Install VNC Viewer on Client
Download and install VNC Viewer on your local machine from the RealVNC website.
Connect to Raspberry Pi Using VNC Viewer
Open VNC Viewer, and enter the hostname or IP address of your Raspberry Pi. You will be prompted for the Raspberry Pi’s username and password.
Secure VNC Connection with SSH Tunnel
To enhance security, create an SSH tunnel for VNC:
Create SSH Tunnel
On your local machine, create an SSH tunnel:
ssh -L 5901:localhost:5900 pi@raspberrypi
This will forward the VNC server running on Raspberry Pi’s port 5900 to your local machine’s port 5901.
Connect to VNC via Tunnel
Open VNC Viewer and connect to localhost:5901
.
Summary
- SSH Access:
- Generate key pair:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
- Copy key to Raspberry Pi:
ssh-copy-id pi@raspberrypi
- Connect:
ssh pi@raspberrypi
2. VNC Setup:
- Install VNC server on Raspberry Pi:
sudo apt-get install realvnc-vnc-server
- Enable VNC via
raspi-config
- Install VNC Viewer on local machine
- Create SSH tunnel:
ssh -L 5901:localhost:5900 pi@raspberrypi
- Connect to
localhost:5901
in VNC Viewer
By following these steps, you will have secure SSH access to your Raspberry Pi and a remote desktop setup using VNC.
What Happens Under the Hood
- Authentication: The
ssh-copy-id
command uses SSH to log into the remote machine using your password. - Copying the Key: It copies your local public key (
~/.ssh/id_rsa.pub
) to the remote machine's~/.ssh/authorized_keys
file. - Permissions: The command ensures the
~/.ssh
directory and~/.ssh/authorized_keys
file have the correct permissions on the remote machine.
Manual Alternative
If ssh-copy-id
is not available, you can manually copy the public key:
- Display the Public Key
cat ~/.ssh/id_rsa.pub
2. SSH into the Raspberry Pi
ssh pi@raspberrypi
3. Append the Public Key to authorized_keys
echo "your-public-key-content" >> ~/.ssh/authorized_keys
Make sure to replace your-public-key-content
with the actual content of your public key.
4. Set Correct Permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
By following these steps, you can set up secure, passwordless SSH access to your Raspberry Pi using a public-private key pair.
The chmod
command in Unix/Linux is used to change the file system modes (permissions) of files and directories. The numeric values you see (like 700
and 644
) represent different permission sets. Here's a breakdown of what these values mean and their differences:
Understanding the Numeric Values
- Numeric Notation: Each digit in the numeric notation corresponds to a different set of users and their permissions.
- The first digit represents the owner’s permissions.
- The second digit represents the group’s permissions.
- The third digit represents others’ (everyone else) permissions.
Each digit is a sum of the following values:
4
: Read (r)2
: Write (w)1
: Execute (x)
chmod 700
- Owner: Full permissions (read, write, and execute) —
7
(4+2+1) - Group: No permissions —
0
- Others: No permissions —
0
So, chmod 700
sets the permissions to:
- Owner: Read, write, and execute (
rwx
) - Group: No permissions (
---
) - Others: No permissions (
---
)
This is typically used for directories or files where you want only the owner to have full control, with no access for others.
chmod 644
- Owner: Read and write permissions —
6
(4+2) - Group: Read-only permissions —
4
- Others: Read-only permissions —
4
So, chmod 644
sets the permissions to:
- Owner: Read and write (
rw-
) - Group: Read-only (
r--
) - Others: Read-only (
r--
)
This is commonly used for files that should be readable by everyone but only writable by the owner.
Use Cases
chmod 700:
- Used for scripts or executables that only the owner should run.
- Used for private directories where only the owner should have access.
- Example:
chmod 700 myscript.sh
chmod 700 private_directory
chmod 644:
- Used for configuration files that should be readable by everyone but only editable by the owner.
- Common default permission for text files or web content.
Example:
chmod 644 config_file.conf
chmod 644 index.html