Two factor authentication linux

Содержание
  1. Two factor authentication linux
  2. What is two-factor authentication
  3. What you’ll need
  4. 2. Installing and configuring required packages
  5. Installing the Google Authenticator PAM module
  6. Configuring SSH
  7. 3. Configuring authentication
  8. 4. Adding the secret to Google Authenticator
  9. Using the QR code
  10. Using the through key
  11. 5. Getting help
  12. 6 easy steps to setup offline two factor authentication in Linux
  13. Lab Environment
  14. Google Authenticator with PAM
  15. Step 1: Install Google Authenticator on RHEL/CentOS 7 and 8 Linux
  16. Method 1: Install using DNF or YUM
  17. Method 2: Install using source code
  18. Step 2: Configure offline two factor authentication in Linux
  19. Step 3: Download and configure Google Authenticator Mobile App
  20. Step 4: Configure ssh two factor authentication
  21. Step 4.1: Configure /etc/pam.d/sshd module
  22. Step 4.2: Configure /etc/ssh/sshd_config
  23. Step 4.3: Verify ssh two factor authentication
  24. Step 5: Configure sudo two factor authentication (Optional)
  25. Step 5.1: Modify /etc/pam.d/sudo module
  26. Step 5.2: Verify sudo two factor authentication
  27. Step 6: Configure su two factor authentication (Optional)
  28. Step 6.1: Configure /etc/pam.d/su module
  29. Step 6.2: Verify su two factor authentication
  30. Related Posts
  31. Как включить двухфакторную аутентификацию в Linux Mint, Ubuntu и производных системах
  32. Настройка двухфакторной аутентификации в Linux Mint, Ubuntu и производных системах
  33. Linux Two-factor Authentication
  34. Linux Two-factor Authentication Using Google Authenticator
  35. Linux Two-factor Authentication Using Authy-ssh (SMS)
  36. Conclusion:
  37. About the author
  38. David Adams

Two factor authentication linux

SSH, the secure shell, is often used to access remote Linux systems. Because we often use it to connect with computers containing important data, it’s recommended to add another security layer. Here comes the two factor authentication (2FA).

What is two-factor authentication

Multi-factor authentication is a method of confirming your identity using at least two different ways of authentication. The most common and easiest to implement example of two-factor authentication uses a combination of passphrase (a complex password, often made of several words) and one-time-passcode generated by a special mobile app.

We will use the Google Authenticator app available for Android (in the Play Store) and iOS (in iTunes) to generate authentication codes.

What you’ll need

  • A computer running Ubuntu 16.04 LTS or above
  • A phone running Android or iOS
  • A configured SSH connection
  • You should understand the danger of stolen passwords.
  • You don’t need to know what two-factor authentication is and how it works.

Originally authored by Marcin Mikołajczak.

2. Installing and configuring required packages

Installing the Google Authenticator PAM module

Start a terminal session and type:

Configuring SSH

To make SSH use the Google Authenticator PAM module, add the following line to the /etc/pam.d/sshd file:

Now you need to restart the sshd daemon using:

Modify /etc/ssh/sshd_config – change ChallengeResponseAuthentication from no to yes , so this part of the file looks like this:

3. Configuring authentication

Google Authenticator makes the configuration of two-factor authentication much easier, comparing to (for example) libpam-oath.

In a terminal, run the google-authenticator command.

It will ask you a series of questions, here is a recommended configuration:

  • Make tokens “time-base”»: yes
  • Update the .google_authenticator file: yes
  • Disallow multiple uses: yes
  • Increase the original generation time limit: no
  • Enable rate-limiting: yes

You may have noticed the giant QR code that appeared during the process, underneath are your emergency scratch codes to be used if you don’t have access to your phone: write them down on paper and keep them in a safe place.

That’s all. Now, let’s open Google Authenticator and add our secret key to make it work.

Don’t use unencrypted services to store secret keys, such as a notes synchronization service and so on. If you don’t want to type the key manually, use the QR code.

4. Adding the secret to Google Authenticator

We will use the latest version of Authenticator from the Play Store. The process shouldn’t look very different on iOS.

Using the QR code

Touch the Add icon (+) and select “Scan a barcode”. Use phone camera to scan QR code.

Using the through key

Touch the Add icon (+) and select “Enter a provided key”. Enter a name that you will recognise as being your 2FA method for SSH, then type the secret key provided by google-authenticator command.

5. Getting help

Congratulations! You have just configured two-factor authentication for SSH shell using Google Authenticator. Now, every time you (or some bad guy with your password…) will try to log in to your SSH shell, you (or this bad guy) will be asked for an authentication key in addition to a traditional passphrase.

If you need more guidance on using two-factor authentication, help is always at hand:

Читайте также:  Для чего назначают linux

Источник

6 easy steps to setup offline two factor authentication in Linux

Table of Contents

In this article I will share Step-by-Step Guide to Install and Configure Offline Two Factor Authentication using Open Source Google Authenticator for below scenarios in Linux

  • Configure offline two factor authentication for SSH
  • Configure offline two factor authentication for SUDO
  • Configure offline two factor authentication for SU

Lab Environment

I have installed Oracle Virtual Box on Linux node on which I have created multiple Virtual Machines with RHEL/CentOS 7 and 8 Linux. The steps from this article to configure two factor authentication are verified on RHEL/CentOS 7 and 8 Linux environment.

You need internet connectivity on your Virtual Box to download and install the required Google Authenticator packages. But once two factor authentication is configured, you do not need internet connectivity for validation which means this will act as offline two factor authentication in Linux.

Google Authenticator with PAM

Using the pluggable authentication modules provided by PAM, Open Source Google Authenticator supports the following features for Offline two factor authentication in Linux, according to its GitHub page:

  • Per-user secret and status file stored in the user’s home directory
  • Support for 30-second TOTP codes
  • Support for emergency scratch codes
  • Protection against replay attacks
  • Key provisioning via display of a QRCode
  • Manual key entry of RFC 3548 base32 key strings

Step 1: Install Google Authenticator on RHEL/CentOS 7 and 8 Linux

There are two methods to install Google Authenticator on your RHEL/CentOS 7 and 8 Linux environment.

Method 1: Install using DNF or YUM

I hope you are aware of DNF which is an alternate to YUM. By default google authenticator rpm is not part of the CentOS or Red Hat repository so you must first install EPEL repository on your Linux node.

Next install google authenticator rpm before we enable offline two factor authentication:

Content of the rpm on RHEL/CentOS 7

Content of the rpm on RHEL/CentOS 8

Method 2: Install using source code

You can clone the google authenticator git repository on your Linux node

Next build and install

This will install and configure Google Authenticator on your Linux node.

Step 2: Configure offline two factor authentication in Linux

Now we do not need internet on the Linux node to enable offline two factor authentication. Execute the google-authenticator binary without any arguments as shown below, which will prompt you for various inputs

Step 3: Download and configure Google Authenticator Mobile App

Before we jump into the steps to enable and configure offline two factor authentication, we need this Google Authenticator app which will give us the OTP for verification code.

Download and Install » Google Authenticator » from your «Google Play Store» or «App Store» based on your device.

Click on «BEGIN» to go to the next screen.

Next add a account. You can use the BARCODE or the KEY which was generated at Step 2 to add a new account.

Once you add the account, you should start getting the OTP (Verification Code) which you can use to login on your Linux node configured with offline two factor authentication ssh.

Step 4: Configure ssh two factor authentication

To secure your SSH and prevent against brute force attacks you can configure SSH two factor authentication so that for every SSH attempt, you will need to also provide OTP or Verification code from Google Authenticator.

Step 4.1: Configure /etc/pam.d/sshd module

To enable SSH two factor authentication we will use the PAM module. The file /etc/pam.d/sshd needs to be adjusted to call the google-authenticator module:

Step 4.2: Configure /etc/ssh/sshd_config

Next enable ChallengeResponseAuthentication in /etc/ssh/sshd_config

Restart the sshd service to activate the changes

Step 4.3: Verify ssh two factor authentication

Open a new SSH session which should now prompt for verification code

Since we have used » auth required pam_google_authenticator.so «, Linux will prompt for verification code followed by the password of the user :

If you use » auth sufficient pam_google_authenticator.so » then Linux will only prompt for verification code before logging in :

Step 5: Configure sudo two factor authentication (Optional)

If your requirement is only to configure SSH two factor authentication the you can ignore this step. But to enhance your security, you can also configure sudo two factor authentication so that every time a user uses SUDO, the user will be prompted for a OTP (Verification Code)

Step 5.1: Modify /etc/pam.d/sudo module

To enable sudo two factor authentication we will use the PAM module. The file /etc/pam.d/sudo needs to be adjusted to call the google-authenticator module:

Читайте также:  Как убрать windows hello при запуске

Step 5.2: Verify sudo two factor authentication

Next you can try to perform a sudo operation using any user:

Step 6: Configure su two factor authentication (Optional)

Again if your requirement is limited to SUDO or SSH two factor authentication you can ignore this step. But to enhance your security, you can also configure su two factor authentication so that every time a normal user attempts to switch user (su) role, the user will be prompted for OTP (Verification Code)

Step 6.1: Configure /etc/pam.d/su module

To enable su two factor authentication we will use the PAM module. The file /etc/pam.d/su needs to be adjusted to call the google-authenticator module:

Step 6.2: Verify su two factor authentication

Next verify your PAM configuration by trying to switch user (su):

Lastly I hope the steps from the article to configure offline two factor authentication using Google Authenticator on RHEL/CentoS 7/8 Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Related Searches: two factor authentication linux ssh, ssh two factor authentication google, ssh otp google authenticator, linux 2 factor authentication

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Источник

Как включить двухфакторную аутентификацию в Linux Mint, Ubuntu и производных системах

В этом кратком руководстве мы опишем способ как включить двухфакторную аутентификацию в дистрибутиве Linux Mint. Данное руководство также можно использовать для дистрибутива Ubuntu и его производных.

Двухфакторная аутентификация или так называемая многофакторная аутентификация или двухэтапная проверка — это дополнительный уровень защиты, который призван значительно улучшить общий уровень защиты, в данном случае защиты системы.

Настройка двухфакторной аутентификации в Linux Mint, Ubuntu и производных системах

Настройка максимально простая. Открываем терминал и устанавливаем нужные пакеты:

После установки пакетов аутентификатора, необходимо добавить следующую строку в файл конфигурации. Открываем файл конфигурации:

и добавляем строку:

Комбинацией клавиш сохраняем изменения CTRL + O и закрываем редактор nano комбинацией клавиш CTRL + X .

Если для создания кодов двухфакторной аутентификации вы хотите использовать другое устройство с установленным дистрибутивом Linux, то сделать это можно с помощью приложения Authenticator.

Для использования создания кодов на смартфоне, вам нужно установить одно из соответствующих приложений, например Google Authenticator, Microsoft Authenticator или Authy.

Далее нужно сгенерировать QR-код для добавления системы в приложение аутентификации. В терминале запускаем команду:

На все вопросы отвечаем согласием, выбрав Y.

Полученный QR-код сканируем установленным приложением двухфакторной аутентификации. В приложении достаточно выбрать опцию аналогичной Добавить учетную запись > Другая учетная запись. После чего включится сканер QR-кодов.

На этом установка двухфакторной аутентификации в Linux Mint и Ubuntu завершена.

Теперь при входе в систему, если у вас включена авторизация для входа в систему, первоначально будет отображен запрос на ввод кода авторизации (verification code), а затем пароль.

Кроме того, каждый запрос на предоставление прав sudo нужно будет подтверждать кодом авторизации.

Соответственно так же и при установке программ через Менеджер приложений.

Затем подтвердить паролем администратора.

А вы пользуетесь двухфакторной аутентификацией?

Источник

Linux Two-factor Authentication

In this scenario, even if a hacker gets a PayPal or hosting password, he won’t be able to log in without the confirmation code sent to the victim’s phone or email.

Implementing the two-factor authentication is one of the best practices to protect our email, social network accounts, hosting, and more. Unfortunately, our system is not the exception.

This tutorial shows how to implement the two-factor authentication to protect your SSH access using Google Authenticator or Authy-ssh. Google Authenticator allows you to verify a login using the mobile app, while Authy-ssh can be implemented without an app using SMS verification.

Linux Two-factor Authentication Using Google Authenticator

Note: Please, before continuing, make sure you have Google Authenticator installed on your mobile device.

To start, execute the following command to install Google Authenticator (Debian-based Linux distributions):

To install Google Authenticator on Red Hat-based Linux distributions (CentOS, Fedora), run the following command:

Once installed, run Google Authenticator as shown in the screenshot below.

As you can see, a QR code shows up. You need to add the new account by clicking on the + icon in your mobile Google Authenticator App and select Scan QR code.

Google Authenticator will also provide backup codes you need to print and save in case you lose access to your mobile device.

Читайте также:  Linux best audio player

You will be asked some questions, which are detailed below, and you can accept all default options by selecting Y for all questions:

  • After scanning the QR code, the installation process will require permission to edit your home. Press Y to continue to the next question.
  • The second question recommends disabling multiple logins using the same verification code. Press Y to continue.
  • The third question refers to the expiry timing for each generated code. Again, you can allow time skew, press Y to continue.
  • Enable rate-limiting, up to 3 log in attempts every 30s. Press Y to continue.

Once Google Authenticator is installed, you need to edit the file /etc/pam.d/sshd to add a new authentication module. Use nano or any other editor as shown in the screenshot below to edit the file /etc/pam.d/sshd:

Add the following line to /etc/pam.d/sshd as shown in the image below:

Note: Red Hat instructions mention a line containing #auth substack password-auth. If you find this line in your /etc/pam.d./sshd, comment on it.

Save /etc/pam.d./sshd and edit the file /etc/ssh/sshd_config as shown in the example below:

Uncomment on it and replace no with yes:

Exit saving changes and restart the SSH service:

You can test the two-factor authentication by connecting to your localhost as shown below:

You can find the code in your Google Authentication mobile app. Without this code, no one will be able to access your device through SSH. Note: this code changes after 30 seconds. Therefore, you need to verify it fast.

As you can see, the 2FA process worked successfully. Below you can find the instructions for a different 2FA implementation using SMS instead of a mobile app.

Linux Two-factor Authentication Using Authy-ssh (SMS)

You can also implement the two-factor authentication using Authy (Twilio). For this example, a mobile app will not be required, and the process will be done through SMS verification.

To get started, go to https://www.twilio.com/try-twilio and fill the registration form.

Write and verify your phone number:

Verify the phone number using the code sent by SMS:

Once registered, go to https://www.twilio.com/console/authy and press the Get Started button:

Click the Verify Phone Number button and follow the steps to confirm your number:

Verify your number:

Once verified, return to the console by clicking on Return to Console:

Select a name for the API and click on Create Application:

Fill in the requested information and press Make Request:

Select SMS Token and press Make Request:

Go to https://www.twilio.com/console/authy/applications and click on the Application you created in the previous steps:

Once selected, you will see in the left menu the option Settings. Click on Settings and copy the PRODUCTION API KEY. We will use it in the following steps:

From the console, download authy-ssh running the following command:

Then, enter the authy-ssh directory:

Inside the authy-ssh directory run:

You will be asked to paste the PRODUCTION API KEY I requested you to copy, paste, and press ENTER to continue.

When asked about default action when api.authy.com can’t be contacted, select 1. And press ENTER.

Note: If you paste a wrong API key, you can edit it in the file /usr/local/bin/authy-ssh.conf as shown in the image below. Replace the content after “api_key=” with your API key:

Enable authy-ssh by running:

Fill the required information and press Y:

You can test authy-ssh executing:

As you can see, 2FA is working properly. Restart the SSH service, run:

You can also test it by connecting through SSH to localhost:

As illustrated, 2FA worked successfully.

Authy offers additional 2FA options, including mobile app verification. You can see all available products at https://authy.com/.

Conclusion:

As you can see, 2FA can be easily implemented by any Linux user level. Both options mentioned in this tutorial can be applied within minutes.

Ssh-authy is an excellent option for users without smartphones who can’t install a mobile app.

The two-step verification implementation can prevent any type of login-based attack, including social engineering attacks, many of which became obsolete with this technology because the victim password isn’t enough to access the victim information.

Other Linux 2FA alternatives include FreeOTP (Red Hat), World Authenticator, and OTP Client, but some of these options only offer double authentication from the same device.

I hope you found this tutorial useful. Keep following Linux Hint for more Linux tips and tutorials.

About the author

David Adams

David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.

Источник

Оцените статью