IP2Location Country Blocking

IP2location Country Blocking

Create an account with ip2location, and access the free country blocking content:

https://lite.ip2location.com/
sign in… (or create an account)

Click on Download, and under IP2Location Database, download the DB1.LITE IP_Countrt IPv4 database BIN file.

Then go to:

https://www.ip2location.com/development-libraries/ip2location/apache

Download the Apache module.

IN the Installation steps, step number 2, you will see “Download IP2Location C library from here”, so click on the link to download the C Library as well.

You now have three files:

IP2LOCATION-LITE-DB1.BIN.ZIP
ip2location-apache-master.zip
IP2Location-C-Library-master.zip

Create a directory, upload the files to it and unzip them as shown below:

(You can download a version of the files below from July 2022 if it helps for testing or to see what the files are…)

Configurations
cd /home/ec2-user
mkdir ip2location
chmod 2775 ip2location
cd ip2location

[These are the files you will have: ip2location-apache-master.zip  IP2Location-C-Library-master.zip  IP2LOCATION-LITE-DB1.BIN.ZIP]

unzip ip2location-apache-master.zip
unzip IP2Location-C-Library-master.zip
unzip IP2LOCATION-LITE-DB1.BIN.ZIP

[Check you have installed the following packages:]

dnf -y install autoconf automake libtool httpd-devel

cd IP2Location-C-Library-master
vi Makefile.am
[After the line AM_CPPFLAGS add the following:]
ACLOCAL_AMFLAGS = -I m4

[Save and exit the editor]

vi configure.ac
[After the line AC_C_BIGENDIAN add the following:]
AC_CONFIG_MACRO_DIR([m4])
[After the line AC_PROG_LIBTOOL add the following:]
AM_PROG_CC_C_O

[Save and exit the editor]

[Run these commands:]

mkdir m4
autoreconf -i -v --force
./configure
make
make install

[Run these commands:]

cd ..
cd ip2location-apache-master
apxs -i -a -L /usr/local/lib/ -I ../IP2Location-C-Library-master/libIP2Location/ -l IP2Location -c mod_ip2location.c
ln -s /usr/local/lib/libIP2Location.so.1 /usr/lib/libIP2Location.so.1

[Then add these lines to the end of your /etc/httpd/conf/httpd.conf file:]

<IfModule mod_ip2location.c>
    IP2LocationEnable On
    IP2LocationDetectProxy On
    IP2LocationSetmode ALL
    IP2LocationDBFile /home/ec2-user/ip2location/IP2LOCATION-LITE-DB1.BIN
</IfModule>

[You will notice this new line: LoadModule IP2Location_module /usr/lib64/httpd/modules/mod_ip2location.so is now in httpd.conf]

[Fix file permissions:]

cd /home/ec2-user/ip2location
find . -type d -exec sudo chmod 2775 {} \;
find . -type f -exec sudo chmod 0664 {} \;
chmod 777 /home/ec2-user/ip2location/IP2LOCATION-LITE-DB1.BIN
cd /home/ec2-user
chown apache ip2location
chgrp ec2-user ip2location

[Restart httpd:]

systemctl restart httpd

[
Use the IBM 2 letter country codes to select your countries, and add lines like these near the top of your .htaccess file:
https://www.ibm.com/docs/en/iis/9.1?topic=sets-iso-territory-codes
I place the lines below my https redirect lines: (use your own domain name)
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://mydomain.au/$1 [R,L]
]

vi /var/www/html/.htaccess

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^RU$
RewriteRule ^(.*)$ https://google.com.au [L]
RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^CN$
RewriteRule ^(.*)$ https://google.com.au [L]

[save and exit]

You can test after adding entries into .htaccess – will let you think about how to do that 🙂

Part B configurations

Configuring Postfix – we use this to send internal emails.

cd /etc/postfix

Add the following lines to a new file sasl_passwd, using the square brackets as shown and the e-mail region. I use Oregon. There is no e-mail region in Australia.

You will have previously created SMTP credentials from the SES console. Use these where it says SMTPUSERNAME:SMTPPASSWORD below.

cd /etc/postfix
vi sasl_passwd

[email-smtp.us-west-2.amazonaws.com]:587 SMTPUSERNAME:SMTPPASSWORD

[save and exit - use the square brackets as shown above]

systemctl stop postfix;systemctl disable postfix;ps -ef|grep postfix

postconf -e "relayhost = [email-smtp.us-west-2.amazonaws.com]:587" \
"smtp_sasl_auth_enable = yes" \
"smtp_sasl_security_options = noanonymous" \
"smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd" \
"smtp_use_tls = yes" \
"smtp_tls_security_level = encrypt" \
"smtp_tls_note_starttls_offer = yes"

[Enter the above lines with the \ then press RETURN KEY to execute them. Remember, these lines show Oregon as the region. If you use North Virginia you would need that region.]

postmap hash:/etc/postfix/sasl_passwd
chmod 0600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db
postfix start; sudo postfix reload; postfix flush
mailq

[Now do a test e-mail, then disable postfix for security reasons and only call it from shell scripts]

sendmail -f admin@mydomain.au admin@mydomain.au
From: admin <admin@mydomain.au>
Subject: Postfix Test
This is a test message from AWS Postfix and SES
.


mailq

[It should have sent without errors. If not, clean up the /var/log and fix the error. If you are in sandbox mode, use the verified email address you created in SES, and check your DNS records.
It could also be you see errors in Cloudwatch logs in Oregon region if you perhaps made mistakes in your Lambda or SES setups. These details are as per a spearate article.]

systemctl disable postfix
postfix stop

[We stop postfix for security. We can use it in our shell scripts to send alerts.]

[Configure mariadb:]

systemctl start mariadb
mysql_secure_installation

[
Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Switch to unix_socket authentication [Y/n] n

Change the root password? [Y/n] Y
(nominate your database password)
Y for the remaining questions
]

systemctl stop mariadb
systemctl start mariadb
systemctl enable mariadb
systemctl enable httpd
systemctl enable php-fpm

php -v

[This will show version 8.1 or above]

[You can check the version of Mariadb with: dnf list|grep mariadb]

[Configuring phpMyAdmin…]

cd /usr/share
wget https://www.phpmyadmin.net/downloads/phpMyAdmin-latest-all-languages.tar.gz
ls

tar xvf .....  
[where ..... is the downloaded file.
Then delete the tar.gz file, then use the Unix command to move the directory to phpMyAdmin, e.g.: mv yourfile phpMyAdmin]

cd phpMyAdmin
mkdir tmp
chmod 777 tmp
cp -p config.sample.inc.php config.inc.php
vi config.inc.php

[
Search for the blowfish line. Do a Google search on blowfish phpmyadmin generator.
I use: https://phpsolved.com/phpmyadmin-blowfish-secret-generator/?g=[insert_php]echo%20$code;[/insert_php] from https://phpsolved.com.
Paste the generated value into the blowfish value.
Then after SaveDir as shown below, add TEMPDir...
]

$cfg['SaveDir'] = '';
$cfg['TEMPDir'] = '/tmp';

[
Restart httpd - recall we may not have SSL running, so you should not really log into phpMyAdmin at this stage.
You can check the interface is ready with http://mydomain.au/phpMyAdmin.
As a note, you can view your PHP settings with http://mydomain.au/phpinfo.php.
I have a separate article on using phpMyAdmin.
]

[Please see my separate articles on IP2location and S3FS (NFS), CDN if you wish to use those capabilities.]

dnf update

[I like to reboot:]

sync;sync;reboot

For more on SSL installations, please see my article at:
photographybyshaw.au/aws/install-postfix-apache-php-mysql-ssl/

WordPress

You may now reboot the system and verify SSL is working, then as per my other articles, create a database and user in phpMyAdmin, use FileZilla (or Putty) to upload WordPress, unzip it and move the files to /var/www/html.

Then begin installation with https://mydomain.au and enter the values you want which creates the wp-config.php file.

You can upload your themes to /var/www/html/wp-content/themes.

NOTE:

Once WordPress files are uploaded, you must change their ownership before installing WordPress.

Use the following shell script…

 

cd /var/www/html
vi chdir.sh

#!/bin/sh
chown -R apache *
chgrp -R apache *
find . -type d -exec chmod 2775 {} \;
find . -type f -exec chmod 0664 {} \;
if [ -f "./.htaccess" ] ; then
chown apache .htaccess
chgrp apache .htaccess
chmod 664 .htaccess
fi
chmod 777 *.sh
chown root chdir.sh
chgrp root chdir.sh
chmod 770 chdir.sh
exit

[save and exit the editor, then run the script]

chmod 775 chdir.sh
./chdir.sh
ls -la

After the install you will have a basic .htaccess file you can view with:

ls -la

cat .htaccess

This file can have additional security added such as:

Use your own domain name below. Use your instance’s Amazon static IP address (shown as xxx.xxx.xxx.xxx) and your own static IP address (shown as .yyy.yyy.yyy.yyy) in the examples. I have included a couple of entries for IP2Location if that is configured, showing blocks to Russia and China.

.htaccess errors will stop the web page display, or may give a blank page. Just fix the file until the page works.

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://mydomain.au/$1 [R,L]

RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^RU$
RewriteRule ^(.*)$ https://google.com.au [L]
RewriteCond %{ENV:IP2LOCATION_COUNTRY_SHORT} ^CN$
RewriteRule ^(.*)$ https://google.com.au [L]

Options -Indexes

RewriteRule ^wp-admin/install\.php$ - [F]
RewriteRule ^wp-admin/includes/ - [F]
RewriteRule !^wp-includes/ - [S=3]
RewriteRule ^wp-includes/[^/]+\.php$ - [F]
RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F]
RewriteRule ^wp-includes/theme-compat/ - [F]
RewriteRule ^wp\-content/uploads/.*\.(?:php[1-7]?|pht|phtml?|phps)$ - [NC,F]
RewriteRule ^wp\-content/themes/.*\.(?:php[1-7]?|pht|phtml?|phps)$ - [NC,F]

RewriteCond %{QUERY_STRING} https?: [OR]
RewriteCond %{QUERY_STRING} (<|%3C)script(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [NC,OR]
RewriteCond %{QUERY_STRING} base64_decode\( [NC,OR]
RewriteCond %{QUERY_STRING} %24&x [NC,OR]
RewriteCond %{QUERY_STRING} (encode|localhost|loopback) [NC,OR]
RewriteCond %{QUERY_STRING} (concat|insert|union|declare) [NC,OR]
RewriteCond %{QUERY_STRING} %[01][0-9A-F] [NC]
RewriteCond %{QUERY_STRING} !^loggedout=true
RewriteCond %{QUERY_STRING} !^action=jetpack-sso
RewriteCond %{QUERY_STRING} !^action=rp
RewriteCond %{HTTP_COOKIE} !wordpress_logged_in_
RewriteCond %{HTTP_REFERER} !^http://maps\.googleapis\.com
RewriteRule ^.* - [F]

allow from all

# deny from entries can go anywhere from here... An example is shown.

# attacks - msn
deny from 20.160.0.0/12


<Files wp-login.php>
        order deny,allow
        allow from xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy
        deny from all
</Files>

<Files xmlrpc.php>
        order deny,allow
        allow from xxx.xxx.xxx.xxx
        allow from yyy.yyy.yyy.yyy
        deny from all
</Files>

<Files wp-cron.php>
        order deny,allow
        allow from xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy
        deny from all
</Files>
<Files admin-ajax.php>
        order allow,deny
        allow from all
        satisfy any
</Files>
<Files wp-config.php>
        Order allow,deny
        allow from xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy
        Deny from all
</Files>
<Files error_log>
        Order allow,deny
        allow from xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy
        Deny from all
</Files>
<files .htaccess>
        <IfModule mod_authz_core.c>
                Require all denied
        </IfModule>
        <IfModule !mod_authz_core.c>
                Order allow,deny
                Deny from all
        </IfModule>
</files>
<files readme.html>
        <IfModule mod_authz_core.c>
                Require all denied
        </IfModule>
        <IfModule !mod_authz_core.c>
                Order allow,deny
                Deny from all
        </IfModule>
</files>

# Disable Directory Browsing
Options -Indexes

If you install a caching plugin, such as W3 Total Cache, adding Browser Cache will add important caching instructions to your .htaccess file.
It is however possible to manually add those same entries (less any branding or specific plugin entries) but it is easier to let the plugin do it.

Finally, I append values to the /var/www/html/wp-config.php file, as shown, after the line: require_once ABSPATH . ‘wp-settings.php’;

The e-mail private password key is used with the SMTP WP plugin. Use your own SES/IAM values as required.

SMTPPASSWORD is yur own IAM value. The public key would be entered into the plugin settings.

vi /var/www/html/wp-config.php

define('WP_MEMORY_LIMIT', '256M');
define('DISALLOW_FILE_EDIT', true);
define( 'ALLOW_UNFILTERED_UPLOADS', true );
define('AUTOSAVE_INTERVAL', 300);
/** define('DISABLE_WP_CRON', true); */
define( 'WPMS_ON', true );
define( 'WPMS_SMTP_PASS', 'SMTPPASSWORD' );

[save and exit - these are appended to the file at the end]

Start typing and press Enter to search