ECommerce Insights Blog

Stay on top of it all and get ahead with useful articles, how-tos, tips and tricks on e-commerce.

How To Secure a Magento Store Against Malicious Scripts & Hackers

How To Secure a Magento Store Against Malicious Scripts & Hackers

If your Magento store is ranking within Alexa top Million it’s possible that hackers, spammers will try to break your defenses and hack it for various reasons. We will briefly walk you through and help you ensure the safety of your eCommerce store using best security practises for a Magento store. Although, this article is primarily written for CentOs 7 and Nginx but rules and configuration are valid for other versions as well.

Moving Magento on SSL

We recommend to run your store on SSL (aka HTTPS) to keep it secure. The data transmitted over HTTP protocol can be sniffed, hacked which may hurt your store as well as your customers. 2016 has seen a massive rise in hacking attempts that has made customers more reluctant in typing their sensitive information like credit card details on HTTP stores.

Magento is a well known software used by hundreds of thousands of stores. Hackers are alos aware of these usage statistics and always looking for a vulnerability in the core software, server setup or anything else which you might have ignored. A SSL certificate costs around $15 to anywhere between $1000 and you can buy certificates from your preferrred provider. For the sake of this article we are going to use LetsEncrypt FREE SSL  which are FREE, equally valid but lasts only for 90 days. It’s our responsibility to renew the certificates before their 90 days expiry period. We will also talk about how to automatically renew your SSL certificates periodically so they never expire.

Switch To FREE SSL with LetsEncrypt

LetsEncrypt provides free SSL which is valid and trusted by all major browsers. You can create a free SSL certificates on CentoOS 7 for your store by following the steps given below

  1. Install Certbot
  2. Create SSL certs using Webroot plugin
  3. Dry Running SSL Certificate Renewal
  4. Setup CRON to autorenew certs
  5. Install SSL Certificates on Nginx
  6. Hardening SSL Security

Installing Certbot on CentOs 7

Certbot is packaged in EPEL (Extra Packages for Enterprise Linux). To use Certbot, you must first enable the EPEL repository. Once, done run the following command

sudo yum install certbot

The above command will successfully install certbot on your CentOs 7 system and it’s good to go. We prefer webroot plugin as it doesn’t require you to momentarily stop NGINX/Apache for  renewing the SSL certificates.

Creating SSL certs using Webroot plugin

We are ready to create SSL certificates for our Magento store just run the following command to generate SSL certs (Replace mystore with your domain name whereever applicable)

certbot certonly --webroot -w /var/www/html/mystore_root_directory -d mystore.com -d www.mystore.com

If the above command doesn’t work and throws an acme-challenge error you can resolve it by creating an empty directory .well-known under Magento’s root directory. Ensure this directory has sufficient write permissions and files under this directory can be browsed via URL. On certain installations you might have to enable this directory under store’s Nginx configuration like

location ~ /.well-known {
                allow all;
        }

Certbot will generate necessary LetsEcrypt SSL certificates for your Magento store’s domain name and save them under

/etc/letsencrypt/live/mystore.com/

You will find your certificates files stored under mystore.com folder (your domain name).

Dry Run Test For Automatic SSL Certificate Renewal

Certbot can be configured to renew your certificates automatically before they expire. Since Let’s Encrypt certificates are valid only for 90 days, it’s highly advisable to test automatic renewal for your certificates by running this command:

certbot renew --dry-run

If the above command executed successfully you can configure a CRON job to setup automatic renewals.

CRON for Automatic SSL Certificates Renewals

We have successfully tested certificate renewals via dry-run we can safely setup a CRON job to automatically renew once it’s about to expire. Type crontab -e command to setup it up. We recommend you set your CRON to run 2 times a day that looks like the following (you are welcome to define your own periods)

0 */12 * * * certbot renew --quiet

If you’ve reached this far without issues, SSL certificate generation and auto-renewal part is already done. Now, it’s time to tell Nginx to switch the store to SSL and use the certificates we just generated.

Install SSL Certificates on Nginx for Magento

We have to make certain changes in your store’s conf file to install our SSL certifictates we generated above. First of all we have to add the following line of code at the top of store.conf file (configuration file for store).

server {
    listen       80;
    server_name  mystore.com www.mystore.com;
    return       301 https://www.mystore.com$request_uri;
}

The above code will redirect all traffic from HTTP to HTTPS store URL. Next block is SSL block that’s where we will be installing our SSL certificates.

server {
      listen 443 ssl;
      ssl on;
      server_name www.mystore.com;
      ssl_certificate /etc/letsencrypt/live/mystore.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/mystore.com/privkey.pem;
      ......
      #Other required configuration directives here
      ......
}

Restart Nginx and test your site, it should now automatically redirect to SSL version. It’s wise to search your site in Google and click on some of your links and verify that they are landing on correct SSL pages. 301 redirect will tell Google that the store has moved to SSL and it will adjust the ranking in a weeks time.

Hardening SSL Security on Nginx for Magento

Merely switching to SSL will not guarantee that your store won’t be hacked or tried for malicious code injection. We will go one step further and harden our security measures.

Forward Secrecy & Diffie Hellman Ephemeral Parameters

Before we start writing additional configuration rules in our Nginx conf file lets create dhparam.pem file for an additional level of security and trust.

Go to /etc/letsencrypt/live/mystore.com folder and run the following command (to ensure all our certs stays in same directory)

openssl dhparam -out dhparam.pem 4096

The command will take few seconds to generate a strong dhparam.pem file. Once done, open your store’s configuration file again and paste the following line of code within server block

ssl_dhparam /etc/letsencrypt/live/mystore.com/dhparam.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;  # drop SSLv3 (POODLE vulnerability)
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK';
add_header X-Frame-Options DENY;
add_header Strict-Transport-Security max-age=63072000;
server_tokens off;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy " default-src https: 'unsafe-inline' 'unsafe-eval'";
resolver 8.8.8.8;
ssl_stapling on;
# Common bandwidth hoggers and hacking tools.
if ($http_user_agent ~ "libwww-perl") {
   set $block_user_agents 1;
}

Restart Nginx, and test your site and SSL security on https://www.ssllabs.com/ssltest/ or other similar sites. You can tweak and fine tune the above parameters based on your own requirements.
Please note that changing path, URL variables in config.xml file, regenerating sitemap, changes to Analytics and Webmasters settings are not covered here. You will find lots of nifty tutorials on that. Please ensure everything is working before we move on to our next action items.

Official Security Patches

It’s vital that you install security patches timely relased by Magento and run on latest stable version. If you need help with security path installation you can take a look at few of our service packs.

Using Fail2Ban To Secure Your Server

Fail2Ban helps you setup firewall rules on your server that can proactively monitor and apply defined set of rules to protect your server/store. Hackers launching brute force attacks against your shop are likely to use malicious tactics which unfortunately ends up in a constant battle. Therefore, it is recommended to block hack sources as soon as they are identified. This is called adaptive filtering or an Intrusion Prevention System (IPS). If you have already setup Fail2Ban you should add the following entry in your /etc/fail2ban/jail.local file

[ssh-iptables]
enabled  = true
filter   = sshd
action   = iptables[name=SSH, port=ssh, protocol=tcp]
           sendmail-whois[name=SSH, dest=root, [email protected]]
logpath  = /var/log/secure
maxretry = 3

[hn-nginx-retry-ban]
# Only ban after multiple retries.
# Use this for "soft" bad behaviour.
port = http,https
filter = hn-nginx-retry-ban
logpath = /var/log/nginx/access.log #Store's access.log path
bantime = 7200
maxretry = 5

Create a file /etc/fail2ban/filter.d/hn-nginx-retry-ban.conf and paste the following code to satisfy the rule we have defined above

[Definition]
# Use this for "soft" bad behaviour, as the source will only be banned after multiple retries.
failregex = ^<HOST> .+"POST \S+(/downloader/|/downloader/index.php\?A=loggedin|/admin/index/|/admin/)\s
ignoreregex =

Keep an eye on your access.log file that helps in finding what’s going on. If you notice a particular IP or IP Range is hitting you way too much you can ban that ip by adding a rule in your Iptables like
iptables -A INPUT -s 65.55.44.100 -j DROP

Or the entire subnet like

iptables -A INPUT -s 65.55.44.0/24 -j DROP

Or entire range like

iptables -I INPUT -m iprange --src-range 65.55.44.1-65.55.44.20 -j DROP

Enough to discourage a novice attacker. Stay tuned for our next post which will cover additional security steps to prevent SQL, URL injections and malware on your Magento Store. Please leave us a  comment and let us know your feedback, suggestions or questions.