Build a two-factor verification system for Apache and SSH

Source: Internet
Author: User
Tags ssh access
If you are running a Web server that is accessible to the public but only for your own use (let's be honest, if you are reading this article, it is very likely to run such a server ), so how do you limit the risk of someone accessing your website and engaging in destructive activities? What about SSH? SSH is the tag: Apache

If you are running a Web server that is accessible to the public but only for your own use (let's be honest, if you are reading this article, it is very likely to run such a server ), so how do you limit the risk of someone accessing your website and engaging in destructive activities? What about SSH? SSH is a big risk! In today's environment, it is necessary to consider the risks you are facing and take necessary measures to minimize the risks.

In this tutorial, I will detail the specific steps to implement a self-built two-factor verification system for accessing your website and for SSH access.

Infrastructure and challenges"

Running your own hardware may be annoying. After you handle various hardware faults, such as fan failure, power failure, and hard disk failure, you may decide to discard your cabinets and hardware in the hosting center or your bedroom, resolutely put into the embrace of elastic computing. Amazon's EC2 platform is such an option. It provides many Linux versions and has one of the most reliable and mature cloud platforms on the market. I am not the representative of Amazon, but I still want to give it a try. This product is outstanding. micro instances can be used for free for one year.

In this test scenario, I used an Amazon EC2 server running Ubuntu 12.04 LTS to host several Web applications. If you use different Linux versions, you only need to change the procedure to meet your specific requirements. Assume that most of these applications are for personal use only. If you only access the website from the office or home, you only need to create firewall rules to allow access to Web traffic from those IP addresses, you can escort the website. This is exactly how you ensure SSH security.

However, assume that this practice is not suitable for your Web applications. because you are on a frequent business trip and need to be able to access those applications when you go out, only a few firewall rules will not help you. In addition, assume that your application has its own security system, but you still want an additional security mechanism.

You can build a virtual private network (VPN) server, but you may want to allow family members to access one of the websites, so the VPN method does not work.

Another method to consider is to use Google Authenticator to implement real two-factor authentication. Of course you can choose this path, but what you are looking for is a system that you can do on your own, which is independent and belongs to you.

Just like many things in the Linux field, there is always a solution if you have the will! It turns out that you can easily build your own two-factor verification solution and use it to control access to your Web applications and SSH, at the same time, other users can access your website occasionally.

Apache authentication and authorization

Since the Web server in this example is an Apache server, you may wish to make full use of the authentication and authorization functions of this server, and require the user to provide a series of logon creden。 before any of your websites can provide services to the user.

In order to make it simple, and because you will abide by the best practices, you can only allow https traffic to access your Web server, you may wish to use the mod_auth_basic module for verification.

First, become the root user and install Apache on your newly installed Ubuntu:

sudo su  apt-get install apache2

Assume that your Web application runs in the sub-folder of the main www Document folder. In this way, you only need to create a. htaccss file in the root folder of the http server to manage all your websites:

vim /var/www/.htaccess

Now, you may want to add a few lines. The Command Apache requires verification and where to find the password file:

AuthType Basic AuthName "restricted area" AuthUserFile /home/ubuntu/.htpasswd require valid-user

After completing this step, you need to change the file ownership so that the Apache process can read the file content:

chown www-data:www-data /var/www/.htaccess

Next, you need to create the. htpasswd file referenced in the. htaccess file and configure its ownership so that the Web server can read the file:

htpasswd -cb /home/ubuntu/.htpasswd jameslitton test123 chown www-data:www-data /home/ubuntu/.htpasswd

Now, you need to command Apache to verify and use the mod_auth_basic module for verification:

vim /etc/apache2/sites-available/default-ssl

Then, you need to change AllowOverride None to AllowOverride AuthConfig:

Service apache2 restart

When you access your website, you will be prompted to enter the user name and password (see ).

: Verification request from mod_auth_basic

Password/PIN once a day

Here, I want to change the password for your secondary verification once a day, instead of changing it more frequently. This makes the above mod_auth_basic method work. I won't go into the details here, but I just say: every time the password is changed, it needs to be re-verified immediately. this is not the kind of behavior you need.

Suppose we use a six-digit PIN code, which is sent to the mobile phone every midnight. I like Pushover very much. this service can quickly send instant notifications to mobile phones and tablets from your own scripts and applications.

To implement this mechanism, create a bash script:

vim /home/ubuntu/2fac.sh

Now, add the following lines:

1  #!/bin/bash
2  ppwd=`od -vAn -N4 -tu4 < /dev/urandom | tr -d '\n' | tail -c 6`
3  curl -s -F "token=id" -F "user=id" -F "message=$ppwd"
    ↪https://api.pushover.net/1/messages.json
4  htpasswd -b /home/ubuntu/.htpasswd jameslitton $ppwd
5  echo $ppwd | base64 >/home/ubuntu/.2fac

Line 3 generates a random six-digit PIN code and assigns it to a variable named ppwd. The 3rd Line will send the PIN to the Pushover service to send it to your mobile phone. Row 3 updates the. htpasswd file with the new password. Last but not least, row 3 saves the copy of the PIN in a recoverable manner. you will see it later.

Now, Save the script and make it an executable script:

chmod +x /home/ubuntu/2fac.sh

To complete the last step of the solution, you only need to schedule the task (cron) to run the script in the middle of the night every day:

crontab -e 00 00 * * * /home/ubuntu/2fac.sh

Allows it to access through the Web

Of course, you don't need to worry about it, even if it's done, but suppose you didn't receive the PIN code and want to force change it. Or you may have allowed someone to temporarily access your website, but now you want to force change your password to make sure that the person can no longer access the website. You can always use SSH to connect to the server and run the script manually, but this is too hard. Create a PHP script that can be accessed through the Web and let it handle all this for you.

First, change the ownership of the 2fac. sh script so that your Web server can run it:

chown www-data:www-data /home/Ubuntu/2fac.sh

Now, you need to create a new folder to place the script and create the PHP script itself, allowing the new "key" to be run manually:

mkdir /vaw/www/twofactor
vim /var/www/twofactor/index.php

1  2  exec('/home/ubuntu/2fac.sh');
3  header('Location: http://www.google.com');
4  ?>

As you can imagine, because you have not received the previous key, you need to forcibly use a new key, and you need to ensure that the folder where the script is placed does not need to be verified. Therefore, you need to modify the Apache configuration:

vim /etc/apache2/sites-available/default-ssl

Now, add the following content under the Directory command of/var/www:

 
        satisfy any

Now you may wish to configure ownership and restart Apache:

chown -R www-data:www-data /var/www/twofactor
Service apache2 restart

After thoroughly considering this, we can imagine that the Pushover service may be completely unavailable. This will lead to a bad situation: you cannot access your website. Be prepared for emergencies in this scenario.

To do this, create a second script to get a copy of your PIN (don't forget to save the. 2fac file) and then email it to you. In this example, you may wish to use the mobile operator's email to send messages to you via SMS Bridge.

Start to install mailutils. if you haven't installed mailutils before, you must select the internet option:

apt-get install mailutils

Now, create the second script:

vim /home/Ubuntu/2fac2.sh

Then, add the code:

#!/bin/bash
ppwd=`cat /home/ubuntu/.2fac | base64 --decode`
echo " " | mail -s $ppwd xxx5551212@vtext.com

Don't forget to change the file ownership:

chown www-data:www-data /home/ubuntu/2fac2.sh
chown www-data:www-data /home/ubuntu/.2fac

After completing this step, you need to change the PHP script:

vim /var/www/twofactor/index.php

Replace row 2nd with the following:

2 if (isset (

If you are running a Web server that is accessible to the public but only for your own use (let's be honest, if you are reading this article, it is very likely to run such a server ), so how do you limit the risk of someone accessing your website and engaging in destructive activities? What about SSH? SSH is a big risk! In today's environment, it is necessary to consider the risks you are facing and take necessary measures to minimize the risks.

In this tutorial, I will detail the specific steps to implement a self-built two-factor verification system for accessing your website and for SSH access.

Infrastructure and challenges"

Running your own hardware may be annoying. After you handle various hardware faults, such as fan failure, power failure, and hard disk failure, you may decide to discard your cabinets and hardware in the hosting center or your bedroom, resolutely put into the embrace of elastic computing. Amazon's EC2 platform is such an option. It provides many Linux versions and has one of the most reliable and mature cloud platforms on the market. I am not the representative of Amazon, but I still want to give it a try. This product is outstanding. micro instances can be used for free for one year.

In this test scenario, I used an Amazon EC2 server running Ubuntu 12.04 LTS to host several Web applications. If you use different Linux versions, you only need to change the procedure to meet your specific requirements. Assume that most of these applications are for personal use only. If you only access the website from the office or home, you only need to create firewall rules to allow access to Web traffic from those IP addresses, you can escort the website. This is exactly how you ensure SSH security.

However, assume that this practice is not suitable for your Web applications. because you are on a frequent business trip and need to be able to access those applications when you go out, only a few firewall rules will not help you. In addition, assume that your application has its own security system, but you still want an additional security mechanism.

You can build a virtual private network (VPN) server, but you may want to allow family members to access one of the websites, so the VPN method does not work.

Another method to consider is to use Google Authenticator to implement real two-factor authentication. Of course you can choose this path, but what you are looking for is a system that you can do on your own, which is independent and belongs to you.

Just like many things in the Linux field, there is always a solution if you have the will! It turns out that you can easily build your own two-factor verification solution and use it to control access to your Web applications and SSH, at the same time, other users can access your website occasionally.

Apache authentication and authorization

Since the Web server in this example is an Apache server, you may wish to make full use of the authentication and authorization functions of this server, and require the user to provide a series of logon creden。 before any of your websites can provide services to the user.

In order to make it simple, and because you will abide by the best practices, you can only allow https traffic to access your Web server, you may wish to use the mod_auth_basic module for verification.

First, become the root user and install Apache on your newly installed Ubuntu:

sudo su  apt-get install apache2

Assume that your Web application runs in the sub-folder of the main www Document folder. In this way, you only need to create a. htaccss file in the root folder of the http server to manage all your websites:

vim /var/www/.htaccess

Now, you may want to add a few lines. The Command Apache requires verification and where to find the password file:

AuthType Basic AuthName "restricted area" AuthUserFile /home/ubuntu/.htpasswd require valid-user

After completing this step, you need to change the file ownership so that the Apache process can read the file content:

chown www-data:www-data /var/www/.htaccess

Next, you need to create the. htpasswd file referenced in the. htaccess file and configure its ownership so that the Web server can read the file:

htpasswd -cb /home/ubuntu/.htpasswd jameslitton test123 chown www-data:www-data /home/ubuntu/.htpasswd

Now, you need to command Apache to verify and use the mod_auth_basic module for verification:

vim /etc/apache2/sites-available/default-ssl

Then, you need to change AllowOverride None to AllowOverride AuthConfig:

Service apache2 restart

When you access your website, you will be prompted to enter the user name and password (see ).

: Verification request from mod_auth_basic

Password/PIN once a day

Here, I want to change the password for your secondary verification once a day, instead of changing it more frequently. This makes the above mod_auth_basic method work. I won't go into the details here, but I just say: every time the password is changed, it needs to be re-verified immediately. this is not the kind of behavior you need.

Suppose we use a six-digit PIN code, which is sent to the mobile phone every midnight. I like Pushover very much. this service can quickly send instant notifications to mobile phones and tablets from your own scripts and applications.

To implement this mechanism, create a bash script:

vim /home/ubuntu/2fac.sh

Now, add the following lines:

1  #!/bin/bash
2  ppwd=`od -vAn -N4 -tu4 < /dev/urandom | tr -d '\n' | tail -c 6`
3  curl -s -F "token=id" -F "user=id" -F "message=$ppwd"
    ↪https://api.pushover.net/1/messages.json
4  htpasswd -b /home/ubuntu/.htpasswd jameslitton $ppwd
5  echo $ppwd | base64 >/home/ubuntu/.2fac

Line 3 generates a random six-digit PIN code and assigns it to a variable named ppwd. The 3rd Line will send the PIN to the Pushover service to send it to your mobile phone. Row 3 updates the. htpasswd file with the new password. Last but not least, row 3 saves the copy of the PIN in a recoverable manner. you will see it later.

Now, Save the script and make it an executable script:

chmod +x /home/ubuntu/2fac.sh

To complete the last step of the solution, you only need to schedule the task (cron) to run the script in the middle of the night every day:

crontab -e 00 00 * * * /home/ubuntu/2fac.sh

Allows it to access through the Web

Of course, you don't need to worry about it, even if it's done, but suppose you didn't receive the PIN code and want to force change it. Or you may have allowed someone to temporarily access your website, but now you want to force change your password to make sure that the person can no longer access the website. You can always use SSH to connect to the server and run the script manually, but this is too hard. Create a PHP script that can be accessed through the Web and let it handle all this for you.

First, change the ownership of the 2fac. sh script so that your Web server can run it:

chown www-data:www-data /home/Ubuntu/2fac.sh

Now, you need to create a new folder to place the script and create the PHP script itself, allowing the new "key" to be run manually:

mkdir /vaw/www/twofactor
vim /var/www/twofactor/index.php

1  2  exec('/home/ubuntu/2fac.sh');
3  header('Location: http://www.google.com');
4  ?>

As you can imagine, because you have not received the previous key, you need to forcibly use a new key, and you need to ensure that the folder where the script is placed does not need to be verified. Therefore, you need to modify the Apache configuration:

vim /etc/apache2/sites-available/default-ssl

Now, add the following content under the Directory command of/var/www:

  
        satisfy any

Now you may wish to configure ownership and restart Apache:

chown -R www-data:www-data /var/www/twofactor
Service apache2 restart

After thoroughly considering this, we can imagine that the Pushover service may be completely unavailable. This will lead to a bad situation: you cannot access your website. Be prepared for emergencies in this scenario.

To do this, create a second script to get a copy of your PIN (don't forget to save the. 2fac file) and then email it to you. In this example, you may wish to use the mobile operator's email to send messages to you via SMS Bridge.

Start to install mailutils. if you haven't installed mailutils before, you must select the internet option:

apt-get install mailutils

Now, create the second script:

vim /home/Ubuntu/2fac2.sh

Then, add the code:

#!/bin/bash
ppwd=`cat /home/ubuntu/.2fac | base64 --decode`
echo " " | mail -s $ppwd xxx5551212@vtext.com

Don't forget to change the file ownership:

chown www-data:www-data /home/ubuntu/2fac2.sh
chown www-data:www-data /home/ubuntu/.2fac

After completing this step, you need to change the PHP script:

vim /var/www/twofactor/index.php

Replace row 2nd with the following:

___FCKpd___21

Then, create two bookmarks so that whenever you want to generate a new PIN and send it to yourself through Pushover, you only need to click the link to complete the process. In case the Pushover service is not available, the second bookmarks will send copies of the existing PIN to your selected email address.

2Factor = https://www.thelittonfamily.com/twofactor/index.php 
2Factor-SMS = https://www.thelittonfamily.com/twofactor/index.php?sms=1

Extend to SSH

Extending the solution to cover SSH is actually quite simple. The key is to use the ForceCommand command, which is not well-known in the sshd_config file. This forces the SSH daemon to run the script before generating the terminal session.

Start with this script:

vim /home/ubuntu/tfac-ssh.sh

Now, add the following lines:

1  #!/bin/bash
2  code=`cat .2fac | base64 --decode`
3  echo -ne "Enter PIN: "
4  while IFS= read -r -s -n1 pass; do
5    if [[ -z $pass ]]; then
6       echo
7       break
8    else
9       echo -n '*'
10      input+=$pass
11   fi
12 done
13 if [ $code = $input ];
14 then
15   sleep 1
16   clear
17   /bin/bash
18 else
19   sleep 1
20   curl -s -F "token=id" -F "user=id" -F "message=$input"
      ↪https://api.pushover.net/1/messages.json
21 fi

The PIN of row 2nd is loaded into a variable. Lines 3rd to 12th prompt you to enter a PIN and send an asterisk back to each key. The 13th line compares the PIN entered by the user with the PIN. If the two match, lines 14th to 17th will clear the screen and start the bash session. If the PIN entered by the user does not match the PIN, send a notification to Pushover from row 18th to row 21st, so that you know that a fault has occurred and then end the session.

Configure the SSH daemon to run the script:

vim /etc/ssh/sshd_config

Now, add the following line to the top of the file:

ForceCommand /home/ubuntu/tfac-ssh.sh

: Two-factor authentication request from SSH

This method works. The only limitation is that there is no backspace. If you press the wrong key, the session will be terminated and you have to try again.

In this way, this is a simple two-factor verification system that does not require much effort. Based on my experience, it runs very reliably!

Address: http://www.linuxjournal.com/content/two-factor-authentication-system-apache-and-ssh

GET ["sms"]) {
3 exec ('/home/ubuntu/2fac2. sh ');
4} else {
5 exec ('/home/ubuntu/2fac. sh ');
6}

Then, create two bookmarks so that whenever you want to generate a new PIN and send it to yourself through Pushover, you only need to click the link to complete the process. In case the Pushover service is not available, the second bookmarks will send copies of the existing PIN to your selected email address.

___FCKpd___22

Extend to SSH

Extending the solution to cover SSH is actually quite simple. The key is to use the ForceCommand command, which is not well-known in the sshd_config file. This forces the SSH daemon to run the script before generating the terminal session.

Start with this script:

___FCKpd___23

Now, add the following lines:

___FCKpd___24

The PIN of row 2nd is loaded into a variable. Lines 3rd to 12th prompt you to enter a PIN and send an asterisk back to each key. The 13th line compares the PIN entered by the user with the PIN. If the two match, lines 14th to 17th will clear the screen and start the bash session. If the PIN entered by the user does not match the PIN, send a notification to Pushover from row 18th to row 21st, so that you know that a fault has occurred and then end the session.

Configure the SSH daemon to run the script:

___FCKpd___25

Now, add the following line to the top of the file:

___FCKpd___26

: Two-factor authentication request from SSH

This method works. The only limitation is that there is no backspace. If you press the wrong key, the session will be terminated and you have to try again.

In this way, this is a simple two-factor verification system that does not require much effort. Based on my experience, it runs very reliably!

Address: http://www.linuxjournal.com/content/two-factor-authentication-system-apache-and-ssh

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.