SSH - Ubuntu: Questions and Answers (2014)

Ubuntu: Questions and Answers (2014)

SSH

Skip to questions, Wiki by user gilles

Ubuntu installs an SSH client (openssh-client) by default. If you want to be able to log in remotely into your machine, you need the server package, openssh-server Install openssh-server. There are SSH clients for Windows as well, such as PuTTY.

Troubleshooting

If public key authentication doesn't work: make sure that on the server side, your home directory (~), the ~/.ssh directory, and the ~/.ssh/authorized_keys file, are all writable only by their owner. In particular, none of them must be writable by the group (even if the user is alone in the group). chmod 755 or chmod 700 is ok, chmod 770 is not.

What to check when something is wrong:

· Run ssh -vvv to see a lot of debugging output. If you post a question asking why you can't connect with ssh, include this output (you may want to anonymize host and user names).

· If you can, check the server logs, typically in /var/log/daemon.log or /var/log/auth.log or similar.

· If public key authentication isn't working, check the permissions again, especially the group bit (see above).

See also

· Ubuntu community documentation

· ssh tag wiki on Unix & Linux Stack Exchange


Questions

Q: How to harden an SSH server?

Tags: ssh (Next Q), security (Next Q)

What measures can/should I take to make sure that security around my SSH server is absolutely impermeable?

This will be community wiki from the start, so lets see what people does to secure their servers.

Tags: ssh (Next Q), security (Next Q)

User: source-lab


Answer by asa-ayers

Use public/private key pairs for authentication instead of passwords.

1. Generate a passphrase-protected SSH key for every computer that needs to access the server:

ssh-keygen

2. Permit public-key SSH access from the allowed computers:

Copy the contents of ~/.ssh/id_rsa.pub from each computer into individual lines of ~/.ssh/authorized_keys on the server, or run ssh-copy-id [server IP address] on every computer to which you are granting access (you'll have to enter the server password at the prompt.)

3. Disable password SSH access:

Open /etc/ssh/sshd_config, find the line that says #PasswordAuthentication yes, and change it to PasswordAuthentication no. Restart the SSH server daemon to apply the change (sudo service ssh restart.)

Now, the only possible way to SSH into the server is to use a key that matches a line in ~/.ssh/authorized_keys. Using this method, I don't care about brute force attacks because even if they guess my password, it will be rejected. Brute-forcing a public/private key pair is impossible with today's technology.


Answer by mark-davidson

I would suggest using fail2ban to prevent brute force login attempts.

Disabling logging in as root via SSH. This means an attacker had to figure out both the username and the password making an attack more difficult.

Add PermitRootLogin no to your /etc/ssh/sshd_config

Limiting the users that can SSH to the server. Either by group or just specific users.

Add AllowGroups group1 group2 or AllowUsers user1 user2 to limit who can SSH to the server.


Answer by source-lab

Make the sshd block client IP's that have failed to supply correct login information "DenyHsts" can do this job quite effectively. I have this installed on all my Linux boxes that are in some way reachable from the great outside.

This will make sure that brute force-attacks on the sshd wont be effective, but remember! this way you can end up locking your self out if you forget you password. This can be a problem on a remote server that you don't have access to.


Tags: ssh (Next Q), security (Next Q)


Q: Easiest way to copy ssh keys to another machine?

Tags: ssh (Next Q)

I am lazy at home and use password authentication for my home machines. I am ready to move to key based authentication. There are many options on the web on how to do this, including catting then sshing the key over, scping the key over directly, etc.

I am looking for the easiest and recommended way to copy a key over, hopefully there is a convenience wrapper somewhere in the Ubuntu ssh package?

I'm already aware on how to shut off password logins.

Tags: ssh (Next Q)

User: jorge-castro


Answer by marcel-stimberg

The ssh-copy-id command (in the openssh-client package and installed by default) does exactly this:

ssh-copy-id user@hostname.example.com

copies the public key of your default identity (use -i identity_file for other identities) to the remote host.

The default identity is your "standard" ssh key. It consists of two files (public and private key) in your ~/.ssh directory, normally named identity, id_rsa or id_dsa (and the same with .pub), depending on the type of key. If you did not create more than one ssh key, you do not have to worry about specifying the identity, ssh-copy-id will just pick it automatically.


Answer by huygens

I like the answer from Marcel. I did not know this command. I've always been using what I had found on a SUN web site:

cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'cat >> .ssh/authorized_keys && echo "Key copied"'

I thought to post it here still, because it is a good illustration of what can be achieved in shell code with the power of ssh. But using the ssh-copy-id is definitively a safer way to do it properly!


Answer by ændrük

Graphical method

1. Open Applications Passwords and Keys My Personal Keys.

2. Select your key and then click Remote Configure Key for Secure Shell.

Set Up Computer for SSH Connection


Tags: ssh (Next Q)


Q: How to keep processes running after ending ssh session?

Tags: ssh (Next Q)

Let's say I launch a bunch of processes from a ssh session. Is it possible to terminate the ssh session while keeping those processes running on the remote machine?

Tags: ssh (Next Q)

User: olivier-lalonde


Answer by fotomonster

As screen is not maintained anymore you should look for modern alternatives like tmux.

tmux is superior for many reasons, here are just some examples:

· Windows can be moved between session and even linked to multiple sessions

· Windows can be split horizontally and vertically into panes

· Support for UTF-8 and 256 colour terminals

· Sessions can be controlled from the shell without the need to enter a session

Basic Functionality

To get the same functionality as explained in the post with the most votes you would need to do the following:

· ssh into the remote machine

· start tmux by typing tmux into the shell

· start the process you want inside the started tmux session

· leave/detach the tmux session by typing Ctrl-B and then D

You can now safely logoff from the remote machine, your process will keep running inside tmux. When you come back again and want to check the status of your process you can use tmux attach to attach to your tmux session.

If you want to have multiple session running side-by-side you should name each session using Ctrl-B and $. You can get a list of the currently running sessions using tmux list-sessions.

tmux can do much more advanced things then handle a single window in a single session. For more information have a look in man tmux or http://tmux.sourceforge.net/. A FAQ about the main differences between screen and tmuxis available here.


Answer by lincoln

You could do that by using screen. Type man screen to find out more or follow this link.

Simple scenario:

· ssh into your remote box. type screen Then start the process you want.

· Press Ctrl-A then Ctrl-D. This will "detach" your screen session but leave your processes running. You can now log out of the remote box.

· If you want to come back later, log on again and type screen -r This will "resume" your screen session, and you can see the output of your process.


Answer by bassgey

Screen and nohup is the better way, but if you have to detach a process already running without screen or nohup you can run disown command. With disown you can close the terminal and get the process running on the machine.


Tags: ssh (Next Q)


Q: Download a file over an active SSH session

Tags: ssh (Next Q)

So I'm SSHed into my Ubuntu server from my Ubuntu desktop. I'm at a certain path and I want to download a file to my local filesystem (preferably the path I was at before I entered the SSH session).

I could mount SSH and pull the file across by mouse but what if I was trying to get a root file and logging in by root directly is disallowed? Even if that wasn't the case (it isn't now), surely there must be a simple way of pulling back a file over an active SSH connection.

Surely!

Tags: ssh (Next Q)

User: oli


Answer by spamaps

You may want to check out zssh, which is available in universe, and therefore available with

sudo apt-get install zssh

You need it on your ubuntu server and on your client, but basically when logged in with zssh, you just hit 'ctrl-@' and it brings up the "File transfer mode" which allows you to send files back down the pipe to your client machine, or upload them from client to server.

However, you don't have to re-auth or open a new window to scp.

If you're using ssh keys, and an ssh agent, you can quite easily do:

[enter]~[ctrl]-Z

Which will background ssh, and then just scp $!:/whatever/whatever .'

Once the file is transferred, fg to get ssh back.

If you aren't using ssh keys, you can still use the "ControlMaster" and "ControlPath" options added to recent OpenSSh versions, but that gets tricky, check man ssh_config


Answer by gilles

Assuming you're running an ssh server on your desktop (there are ways around this, but I think they all add complexity, and possibly have security problems), you can set up a reverse ssh tunnel. See SSH easily copy file to local system. over at unix.SE.

· Type Enter ~C Enter -R 22042:localhost:22 Enter to create a reverse port forwarding from your server to your desktop (22042 can be any port number between 1024 and 65534 that's not in use).

· Then scp -P 22042 foo localhost: will copy the file foo in your current directory on the server to your home on the desktop.

· Now move the file into your current directory on the desktop by typing Enter ~ Ctrl+Z mv ~/foo . Enter fg Enter.

Ssh escape sequences begin with ~; the tilde is only recognized after a newline. ~ Ctrl+Z puts ssh into the background. ~C enters a command line where you can create or remove a forwarding.


Tags: ssh (Next Q)


Q: Is it possible to remove a particular host key from SSH's known_hosts file?

Tags: ssh (Next Q)

Is it possible to remove a particular host key from SSH's known_hosts file?

I usually end up deleting the entire known_hosts file, which I have no problems with doing, but just out of curiosity, is it possible to remove just a single entry?

I opened the known_hosts file, but I am struggling to understand its contents.

Below is the message I faced, which led me to ask this question:

Add correct host key in /home/wissen16/.ssh/known_hosts to get rid of this message.

Offending key in /home/wissen16/.ssh/known_hosts:1

RSA host key for foo.com has changed and you have requested strict checking.

Host key verification failed.

Tags: ssh (Next Q)

User: thetuxracer


Answer by takkat

Use this command to remove entries from known_hosts:

ssh-keygen -R hostname


Answer by mike-scott

Yes, you can remove just one key. Just open it in an editor and delete the offending line. The number after the colon in the error message is the line number, so that's the line to delete -- line 1 in your example..


Tags: ssh (Next Q)


Q: How can I break out of ssh when it locks?

Tags: ssh (Next Q)

I frequently ssh into my box at home from school, but usually when I change classes and my computer suspends, the pipe will be broken. However, ssh simply locks up - Ctrl+c, Ctrl+z and Ctrl+d have no effect.

It's annoying to have to restart my terminal, and even more annoying to have to close and re-create a new screen window.

So my question, is there an easy way to make ssh die properly (i.e. when the pipe fails "normally" it will exit with a message about a broken pipe)? Or do I have to figure out what the PID is and manually kill it?

Tags: ssh (Next Q)

User: wayne-werner


Answer by geekosaur

Normal keys are forwarded over the ssh session, so none of those will work. Instead, use the escape sequences. To kill the current session hit subsequently Enter , ~, ..

More of these escape sequences can be listed with Enter , ~, ?:

Supported escape sequences:

~. - terminate session

~B - send a BREAK to the remote system

~R - Request rekey (SSH protocol 2 only)

~# - list forwarded connections

~? - this message

~~ - send the escape character by typing it twice

(Note that escapes are only recognized immediately after newline.)


Answer by scottl

As noted in geekosaur's answer, the escape sequence ~. will terminate the connection.

The full list of escape sequences and what they do can be displayed by typing ~?:

Skip code block

Supported escape sequences:

~. - terminate connection (and any multiplexed sessions)

~B - send a BREAK to the remote system

~C - open a command line

~R - Request rekey (SSH protocol 2 only)

~^Z - suspend ssh

~# - list forwarded connections

~& - background ssh (when waiting for connections to terminate)

~? - this message

~~ - send the escape character by typing it twice

(Note that escapes are only recognized immediately after newline.)


Answer by ulidtko

You may also want to setup application-level keep-alives for ssh to prevent SSH from freezing on connection issues. My ~/.ssh/config contains this:

Host *

ServerAliveInterval 15

This makes ssh client send application-level keep-alives every 15 seconds. Whenever three of them fail consecutively (configurable using ServerAliveCountMax), the client considers the connection as hung and closes it.

Opposed to the other option TCPKeepAlive, this is checked within the encrypted channel and is not spoofable.


It is being noted that those keep-alives also help to, uhm, keep long-idling connections alive, i.e. prevent you from having half-closed tcp sessions hanging for hours untouched.

I highly recommend turning this feature on if you run into this regularly, but you should also know about the slight security risk it may impose. A known-plaintext attack might become easier if the attacker knows the interval and contents of an idle connection. This might be the reasons for why it isn't enabled by default.


Tags: ssh (Next Q)


Q: How do I change my username?

Tags: ssh (Next Q), permissions (Next Q), keyrings (Next Q)

Some time ago when I installed Ubuntu I chose a rather stupid username for my account that I do not want to use anymore.

How do I change this (including the name of my home directory) without loosing settings for applications? How do I keep permissions and my keys for various authentification (e.g. email, SSH, GPG and more)? What settings could possibly get lost if I changed my username?

Both, command-line and graphical solutions are appreciated.

Tags: ssh (Next Q), permissions (Next Q), keyrings (Next Q)

User: takkat


Answer by egil

Unix(-like) operative systems decouples the user name from its user identity, so you may safely change the first without changing the other. All permissions, files etc are tied to your identity (uid), not your username.

To manage every aspect of the user database, you use the usermod tool.

To change username (it is probably best to do this without being logged in):

usermod -l newUsername oldUsername

This however, doesn't rename the home folder.

To change home-folder, use

usermod -d /home/newHomeDir -m newUsername

after you changed the username.

For instance, you could logout, drop to a console (Ctrl+Alt+F1), and sudo su - to become true root (as opposed to sudo -s, where $HOME is still /home/yourname.) Maybe you also have to kill some still running processes from this user first. To do so, enter ps -u username, look for the matching PID and kill them by kill PID-number.

Update: as arrange mentioned, some files may reference your old home directory. You can either keep a symlink for backward compatibility, e g ln -s /home/newname /home/oldname or you can change the file contents with sed -i.bak 's/*oldname*/*newname*/g' *list of files* It creates a backup for each file with a .bak extension.

Some additional information for not so experienced users like me:
As I only have ONE user account (administrator), it would not let me change the username ("you are already logged in" was the response in TTY1 (Ctrl+Alt+F1). I found some information to get around this:

1. Add a new user, e.g. "temporary". If you are still in TTY1:

2. sudo adduser temporary

set the password and just type enter exit. This should bring you to the original login prompt, if not type exit again.

2. Change the account type of your new temporary user to administrator:
In tty7 (Ctrl+Alt+F7, "normal" desktop) login in to your usual account. Change his privileges through the gui: System settings > users account. Click Unlock then change account type to "administrator".

3. Log out again.

4. Return to tty1: Login with the 'temporary' user account and password. Change your username and folder as mentioned above. exit (until you get the login prompt)

5. Go back to TTY7 (Ctrl+Alt+F7) to login on the GUI/normal desktop screen and see if this works.

6. Delete temporary user and folder:

7. sudo deluser temporary

8. sudo rm -r /home/temporary


Answer by valentin-uveges

To put it all together:

1. At the start screen press Ctrl+ALT+F1.

2. Log in using your username and password.

3. Set a password for the "root" account.
sudo passwd root

4. Log out.
exit

5. Log in using the "root" account and the password you have previously set.

6. Change the username and the home folder to the new name that you want.
usermod -l <newname> -d /home/<newname> -m <oldname>

7. Change the group name to the new name that you want.
groupmod -n <newgroup> <oldgroup>

8. Look the "root" account.
passwd -l root

9. If you were using ecryptfs (encrypted home directory). Mount your encrypted directory using ecryptfs-recover-private and edit <mountpoint>/.ecryptfs/Private.mnt to reflect your new home directory.

10.Log out.
exit

11.press Ctrl+ALT+F7.

And now you can log in using your new username.


Answer by karthick87

Restart in recovery mode and go to the root prompt shell ("Drop to root shell prompt")

First remount the root

mount -o remount,rw /

To change the username and home folder name,

usermod -l <newname> -d /home/<newname> -m <oldname>

For group name,

groupmod -n <newgroup> <oldgroup>


Tags: ssh (Next Q), permissions (Next Q), keyrings (Next Q)


Q: How can I set up password-less SSH login?

Tags: ssh (Next Q)

I want to be able to login to a remote via ssh without having to enter the password all the time.

· How do I set it up?

· Is a different command required to execute a password-less session?

Tags: ssh (Next Q)

User: oxwivi


Answer by rinzwind

Answer

Execute these two commands:

ssh-keygen

Then you'll need to copy the new key to your server.

After the key is copied, ssh into the machine as normal

ssh user@host

You can now login without entering a password from the particular machine you executed the commands at.

Example

Skip code block

not-marco@rinzwind-desktop:~$ ssh-keygen

Generating public/private rsa key pair.

Enter file in which to save the key (/home/not-marco/.ssh/id_rsa):

Created directory '/home/not-marco/.ssh'.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/not-marco/.ssh/id_rsa.

Your public key has been saved in /home/not-marco/.ssh/id_rsa.pub.

The key fingerprint is:

b1:25:04:21:1a:38:73:38:3c:e9:e4:5b:81:e9:ac:0f not-marco@rinzwind-desktop

The key's randomart image is:

+--[ RSA 2048]----+

|.o= . oo. |

|*B.+ . . |

|*=o . o . |

| = . = |

|. o S |

|E. |

| o |

| . |

| |

+-----------------+

not-marco@rinzwind-desktop:~$ ssh-copy-id not-marco@127.0.0.1

not-marco@127.0.0.1's password:

Now try logging into the machine, with "ssh 'not-marco@127.0.0.1'", and check in:

~/.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

Explanation

This assumes you already have successfully connected to your server via SSH.

You'll need to generate an SSH Keypair which will allow you to identify you as yourself without using a password. You can opt to protect keys with a passcode if you wish, but this can be left blank allowing totally password-less SSH access.

First create your SSH Keypair by running ssh-keygen this will create an id_rsa and id_rsa.pub file. The pub file is what goes on the servers, the private key (id_rsa) is what stays with you and is how you identify yourself.

Next copy the public key to your server with ssh-copy-id user@server replacing user with your remote user and server with the machine DNS name or IP address. It'll prompt for your SSH password, enter it and if all completes successfully you'll be able to access the machine via ssh user@server without needing a password.

References

· https://help.ubuntu.com/community/SSH/OpenSSH/Keys


Answer by bruno-pereira

I normally use sshpass for that, install it with sudo apt-get install sshpass and use it like this

sshpass -p 'password' ssh your_username@your_server


Tags: ssh (Next Q)


Q: How do I retrieve the public key from a SSH private key?

Tags: ssh (Next Q)

A SSH private key as generated by ssh-keygen contains a public key part. How do I retrieve this public key from the private key? I've lost my public key and need to put the contents of this public key in the servers authorized_keysfile and do not want to create a new key pair.

Alternatively phrased: how do I create the id_rsa.pub file from a id_rsa file?

Tags: ssh (Next Q)

User: lekensteyn


Answer by lekensteyn

I've found the answer on Serverfault: Create a public SSH key from the private key?

The option -y outputs the public key:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

As a side note, the comment of the public key is lost. I've had a site which required the comment (Launchpad?), so you need to edit ~/.ssh/id_rsa.pub and append a comment to the first line with a space between the comment and key data. An example public key is shown truncated below.

ssh-rsa AAAA..../VqDjtS5 ubuntu@ubuntu


Tags: ssh (Next Q)


Q: Locale variables have no effect in remote shell (perl: warning: Setting locale failed.)

Tags: ssh (Next Q)

I have a fresh ubuntu 12.04 installation. When i connect to my remote server i got errors like this:

Skip code block

~$ ssh example.com sudo aptitude upgrade

...

Traceback (most recent call last):

File "/usr/bin/apt-listchanges", line 33, in <module>

from ALChacks import *

File "/usr/share/apt-listchanges/ALChacks.py", line 32, in <module>

sys.stderr.write(_("Can't set locale; make sure $LC_* and $LANG are correct!\n"))

NameError: name '_' is not defined

perl: warning: Setting locale failed.

perl: warning: Please check that your locale settings:

LANGUAGE = (unset),

LC_ALL = (unset),

LC_TIME = "de_DE.UTF-8",

LC_MONETARY = "de_DE.UTF-8",

LC_ADDRESS = "de_DE.UTF-8",

LC_TELEPHONE = "de_DE.UTF-8",

LC_NAME = "de_DE.UTF-8",

LC_MEASUREMENT = "de_DE.UTF-8",

LC_IDENTIFICATION = "de_DE.UTF-8",

LC_NUMERIC = "de_DE.UTF-8",

LC_PAPER = "de_DE.UTF-8",

LANG = "en_US.UTF-8"

are supported and installed on your system.

perl: warning: Falling back to the standard locale ("C").

locale: Cannot set LC_ALL to default locale: No such file or directory

No packages will be installed, upgraded, or removed.

0 packages upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

Need to get 0 B of archives. After unpacking 0 B will be used.

...

I don't have this problem when i connect from an older ubuntu installation. This is output from my ubuntu 12.04 installation, LANG and LANGUAGE are set

Skip code block

$ locale

LANG=de_DE.UTF-8

LANGUAGE=de_DE:en_GB:en

LC_CTYPE="de_DE.UTF-8"

LC_NUMERIC=de_DE.UTF-8

LC_TIME=de_DE.UTF-8

LC_COLLATE="de_DE.UTF-8"

LC_MONETARY=de_DE.UTF-8

LC_MESSAGES="de_DE.UTF-8"

LC_PAPER=de_DE.UTF-8

LC_NAME=de_DE.UTF-8

LC_ADDRESS=de_DE.UTF-8

LC_TELEPHONE=de_DE.UTF-8

LC_MEASUREMENT=de_DE.UTF-8

LC_IDENTIFICATION=de_DE.UTF-8

LC_ALL=

Does anybody know what has changed in ubuntu to get this error message on remote servers?

Tags: ssh (Next Q)

User: janning


Answer by david-planella

That's because your locale in your local machine is set to German, which SSH forwards to and tries to use on the server, but your server does not have it installed.

You've got several options:

· Generate the locale. Generate the German locale on the server with sudo locale-gen de.

· Stop forwarding locale from the client. Do not forward the locale environment variable from your local machine to the server. You can comment out the SendEnv LANG LC_* line in the local /etc/ssh/ssh_config file.

· Stop accepting locale on the server. Do not accept the locale environment variable from your local machine to the server. You can comment out the AcceptEnv LANG LC_* line in the remote /etc/ssh/sshd_config file.

· Set the server locale to English. Explicitly set the locale to English on the server. As an example, you can add the following lines to your remote ~/.bashrc or ~/.profile files:

· export LANGUAGE="en"

· export LANG="C"

· export LC_MESSAGES="C"

If you don't have root access to the server, the Stop forwarding locale from the client option might be the best (and only) way to go.


Answer by izx

This can happen sometimes on fresh minimal/alternate installs or in other situations. The fix is pretty simple. Try these, in the following order, testing after each to see if the situation is fixed:

1. Reconfigure locales

· sudo dpkg-reconfigure locales

o if that doesn't work,

2. Reinstall locale language-pack

· sudo apt-get --reinstall install language-pack-de

o if that doesn't work,

3. Manually force locale settings (persistent)

· sudo update-locale LC_ALL=de_DE.UTF-8 LANG=de_DE.UTF-8


Tags: ssh (Next Q)


Q: How can I use a passcode generator for authentication for remote logins?

Tags: ssh (Next Q), security (Next Q)

I would like to strengthen the authentication of my SSH logins by adding another factor: a passcode generator device, or a passcode generation application on my mobile phone. The only obvious options in the default setup are a fixed password and key pair. How can I do this?

(If I use a password plus a passcode generator, this provides two-factor authentication (2FA): the password is what I know, and the passcode is what I have.)

Tags: ssh (Next Q), security (Next Q)

User: jorge-castro


Answer by jorge-castro

One way to do this is with a tool provided by Google called Google Authenticator.

1. Install libpam-google-authenticator Install libpam-google-authenticator

o or just sudo apt-get install libpam-google-authenticator

2. Edit /etc/pam.d/sshd to include the module:

o sudoedit /etc/pam.d/sshd and then include this line at the bottom and save:

o auth required pam_google_authenticator.so

3. Edit your SSH config file to turn on the challenge:

o sudoedit /etc/ssh/sshd_config and then change the response authentication from:

o ChallengeResponseAuthentication no to

o ChallengeResponseAuthentication yes and then save the file.

4. sudo restart ssh to restart SSH

5. Run google-authenticator

o This will give you your secret key, verification code, and emergency scratch codes. It will also ask you some rate limiting questions.

Mobile Applications:

You'll need one of these to receive the authentication code on another device.

· Android App

· iPhone App

Related and Useful:

· Most of this answer is derived from this blogpost by Jean-Francois Theroux but updated.

· Google Authenticator Wiki

· http://guides.webbynode.com/articles/security/ubuntu-google-authenticator.html

· http://www.mnxsolutions.com/security/two-factor-ssh-with-google-authenticator.html

· It is my understanding that if you're using passwordless logins via SSH keys that you can only do one or the other, see this question: How can I set up password-less SSH login?

· And if you're using Puppet, there's a puppet module here: https://github.com/camptocamp/puppet-googleauthenticator

Note that combining a password with single-use passcodes is two-factor authentication: it combines what you know (a password) with what you have (the passcode generator device). On the other hand, if you combine single-use passcodes with an SSH key pair, it's all about what you have. When two authentication factors are of the same type, you do not have two-factor authentication; this is sometimes called one-and-a-half-factor authentication.


Answer by nowen

Google Authenticator is fine for your personal servers but you might find that it doesn't tie in well with your existing identity infrastructure. If you want to explore other options think about using RADIUS as an authentication protocol and the pam-radius plugin. All the enterprise-oriented two-factor authentication systems support radius. We have written a doc on how to add WiKID two-factor authentication via pam-radius to Ubuntu.

Using radius allows you to tie in other systems besides SSH to the same authentication server. You can also route auth requests through freeradius to LDAP and then to your 2FA server to separate authorization from authentication. You can do the same with AD btw.


Tags: ssh (Next Q), security (Next Q)


Q: How do I keep track of failed SSH log-in attempts?

Tags: ssh security (Next Q)

I'd like to see if somebody has been trying to log-in by brute-force into my Ubuntu 12.04 server over SSH. How can I see if such activities have been taking place?

Tags: ssh security (Next Q)

User: ivan


Answer by izx

All login attempts are logged to /var/log/auth.log.

1. Filter for brute-force interactive SSH logins

Open a terminal, and type the below; if it's longer than 1 page you will be able to scroll up and down; type q to exit:

grep sshd.\*Failed /var/log/auth.log | less

· Here's a real example from one of my VPSs:

· Aug 18 11:00:57 izxvps sshd[5657]: Failed password for root from 95.58.255.62 port 38980 ssh2

· Aug 18 23:08:26 izxvps sshd[5768]: Failed password for root from 91.205.189.15 port 38156 ssh2

· Aug 18 23:08:30 izxvps sshd[5770]: Failed password for nobody from 91.205.189.15 port 38556 ssh2

· Aug 18 23:08:34 izxvps sshd[5772]: Failed password for invalid user asterisk from 91.205.189.15 port 38864 ssh2

· Aug 18 23:08:38 izxvps sshd[5774]: Failed password for invalid user sjobeck from 91.205.189.15 port 39157 ssh2

· Aug 18 23:08:42 izxvps sshd[5776]: Failed password for root from 91.205.189.15 port 39467 ssh2

2. Look for failed connections (i.e. no login attempted, could be a port scanner, etc.):

Use this command:

grep sshd.*Did /var/log/auth.log | less

· Example:

· Aug 5 22:19:10 izxvps sshd[7748]: Did not receive identification string from 70.91.222.121

· Aug 10 19:39:49 izxvps sshd[1919]: Did not receive identification string from 50.57.168.154

· Aug 13 23:08:04 izxvps sshd[3562]: Did not receive identification string from 87.216.241.19

· Aug 17 15:49:07 izxvps sshd[5350]: Did not receive identification string from 211.22.67.238

· Aug 19 06:28:43 izxvps sshd[5838]: Did not receive identification string from 59.151.37.10

How to reduce failed/brute-force login attempts

· Try switching your SSH to a non-standard port from the default 22

· Or install an auto-ban script such as fail2banInstall fail2ban.


Answer by oli

I would argue that monitoring logs is a weak solution especially if you have a weak password on an account. Brute attempts often try at least hundreds of keys per minute. Even if you have a cron job set to email you of brute attempts, it could be hours before you get to your server.

If you have a public-facing SSH server, you need a solution that kicksinlong beforeyoucan behacked.

I would strongly recommend fail2ban. Their wiki says what it does better than I can.

Fail2ban scans log files (e.g. /var/log/apache/error_log) and bans IPs that show the malicious signs -- too many password failures, seeking for exploits, etc. Generally Fail2Ban then used to update firewall rules to reject the IP addresses for a specified amount of time, although any arbitrary other action (e.g. sending an email, or ejecting CD-ROM tray) could also be configured. Out of the box Fail2Ban comes with filters for various services (apache, curier, ssh, etc).

Getting protection from it is as simple as sudo apt-get install fail2ban.

By default as soon as somebody has three failed attempts, their IP gets a five minute ban. That sort of delay essentially halts a SSH brute force attempt but it's not going to ruin your day if you forget your password (but you should be using keys anyway!)


Tags: ssh security (Next Q)


Q: How to harden an SSH server?


Q: Easiest way to copy ssh keys to another machine?


Q: How to keep processes running after ending ssh session?


Q: Download a file over an active SSH session


Q: Is it possible to remove a particular host key from SSH's known_hosts file?


Q: How can I break out of ssh when it locks?


Q: How do I change my username?


Q: How can I set up password-less SSH login?


Q: How do I retrieve the public key from a SSH private key?


Q: Locale variables have no effect in remote shell (perl: warning: Setting locale failed.)


Q: How can I use a passcode generator for authentication for remote logins?


Q: How do I keep track of failed SSH log-in attempts?