Empowering you with the knowledge to master Linux web hosting, DevOps and Cloud

 Linux Web Hosting, DevOps, and Cloud Solutions

Category: Linux server Page 4 of 5

Apache: Multiple SSL websites on a single IP address

Apache: Multiple SSL websites on a single IP address

Update: This is a new update from a cPanel Tech
“There is nothing to enable. As long as you are using cPanel & WHM version 11.38 on CentOS, RHEL, or CloudLinux version 6 or newer, SNI works out of the box”.

One of the frustrating limitations in supporting secure websites has been the inability to share IP addresses among SSL websites.
When website administrators and IT personnel are restricted to use a single SSL Certificate per socket (combination of IP Address and socket) it can cost a lot of money. Well we can actually share IP addresses for multiple secure websites. Solving this limitation required an extension to the Transport Layer Security (TLS) protocol that includes the addition of what hostname a client is connecting to when a handshake is initiated with a web server. The name of the extension is Server Name Indication (SNI). SNI is supported in Apache v2.2.12 , and OpenSSL v0.9.8j or later.

With SNI, you can have many virtual hosts sharing the same IP address and port, and each one can have its own unique certificate

Prerequisites to use SNI

Use OpenSSL 0.9.8f or later
Build OpenSSL with the TLS Extensions option enabled (option enable-tlsext; OpenSSL 0.9.8k and later has this enabled by default).
Apache must have been built with that OpenSSL (./configure –with-ssl=/path/to/your/openssl). In that case, mod_ssl will automatically detect the availability of the TLS extensions and support SNI.
Apache must use that OpenSSL at run-time, which might require setting LD_LIBRARY_PATH or equivalent to point to that OpenSSL, maybe in bin/envvars. (You’ll get unresolved symbol errors at Apache startup if Apache was built with SNI but isn’t finding the right openssl libraries at run-time.)

Setting up SNI with Apache

The configuration is pretty simple and straight forward, though I recommend making a backup of your existing httpd.conf file before proceeding.

# Ensure that Apache listens on port 443
Listen 443

# Listen for virtual host requests on all IP addresses
NameVirtualHost *:443

# Go ahead and accept connections for these vhosts
# from non-SNI clients
SSLStrictSNIVHostCheck off

# Because this virtual host is defined first, it will
# be used as the default if the hostname is not received
# in the SSL handshake, e.g. if the browser doesn't support
# SNI.
DocumentRoot /www/example2
ServerName www.linuxwebhostingsupport.in

# Other directives here
SSLEngine On
SSLCertificateFile /path/to/linuxwebhostingsupport.in.crt
SSLCertificateKeyFile /path/to/linuxwebhostingsupport.in.key
SSLCertificateChainFile /path/to/CA.crt

DocumentRoot /www/example2
ServerName www.abdulwahabmp.co.in

# Other directives here
SSLEngine On
SSLCertificateFile /path/to/abdulwahabmp.co.in.crt
SSLCertificateKeyFile /path/to/abdulwahabmp.co.in.key
SSLCertificateChainFile /path/to/CA.crt

 

That it!!!. Just restart APache service. Now go and check your Websites using https. That should be working.

Plesk support SNI from 10.2.x version onwards.

SNI will work on following Operating systems out of box

OpenSuSE Linux 11.3 or later.
Ubuntu Linux 10.4 or later.
Debian Linux 6.0 or later.
RedHat Linux 6.0 or later.
CentOS Linux 60.0 or later

Supported Desktop Browsers
Internet Explorer 7 and later
Firefox 2 and later
Opera 8 with TLS 1.1 enabled
Google Chrome:
Supported on Windows XP on Chrome 6 and later
Supported on Vista and later by default
OS X 10.5.7 in Chrome Version 5.0.342.0 and later
Chromium 11.0.696.28 and later
Safari 2.1 and later (requires OS X 10.5.6 and later or Windows Vista and later).
Note: No versions of Internet Explorer on Windows XP support SNI

 

Installing and managing firewall using ConfigServer Firewall (CSF)

ConfigServer firewall is a popular Linux firewall security suite. It is easy to install, flexible to configure and secure with extra checks.
CSF is generally considered a more advanced firewall as there are more configuration options compared to other firewalls, while still being simple enough to install and configure that even novice administrators can use it. Some of the MANY functions of CSF are given below:-

  • Daemon process that checks for login authentication failures for:
  1. Courier imap, Dovecot, uw-imap, Kerio
  2.  openSSH
  3.  cPanel, WHM, Webmail (cPanel servers only)
  4. Pure-ftpd, vsftpd, Proftpd
  5. Password protected web pages (htpasswd)
  6. Mod_security failures (v1 and v2)
  7. Suhosin failures
  8. Exim SMTP AUTH
  9. Custom login failures with separate log file and regular expression matching

 

  • SSH login notification
  • SU login notification
  • SYN Flood protection
  • Ping of death protection
  • Port Scan tracking and blocking
  • IPv6 Support with ip6tables
  • …lots more!

Removing Your Current Firewall
To prevent any conflicts in operation we will need to remove your current firewall. The most common software firewalls on our dedicated servers are APF and CSF, so we have provided instructions on how to remove APF below. If you are using a different software firewall be sure to follow that programs uninstall directions before continuing. After completing the uninstall continue with the CSF installation below.
Using Yum to Remove APF
If it was installed via yum, which is most likely, you will first need to identify the name of your APF package:
rpm -qa |grep -i apf
In this case:
[root@host ~]# rpm -qa | grep apf
apf-9.6_5-1
In order to remove that package, and get your server ready for CSF installation, run the following command:
[root@host ~]# rpm -e apf-9.6_5-1
If you see this:
[root@host ~ ]# rpm -e apf-9.6_5-1
error: Failed dependencies:
apf >= 9.6_5-1 is needed by (installed) bfd-1.2-1.noarch
It means you have BFD installed, and it will need to be removed before you can proceed to removing APF:
[root@host ~ ]# rpm -e bfd-1.2-1.noarch
Then attempt to remove apf again:
[root@host ~ ]# rpm -e apf-9.6_5-1
Any further dependency errors can be handled in the same way as long as you are aware of what you are removing. If you have any questions or get stuck at any point feel free to contact me here.
Removing Source Installed APF
This can be a bit trickier, and if you are not sure what you’re doing you may want to contact me . If you are confident and wish to proceed you will find a list of commands below that you can use to remove APF if it is installed in the most common CentOS directories.
Stopping APF and iptables clears all of the rules from your firewall and ensures that removing the APF installation won’t cause access problems:
[root@host ~ ]# /etc/init.d/iptables stop

[root@host ~ ]# /etc/init.d/apf stop
Remove all of the APF related files:
[root@host ~ ]# rm -Rfv /etc/apf
[root@host ~ ]# rm -fv /etc/cron.daily/fw
[root@host ~ ]# rm -fv /etc/init.d/apf
Remove APF from the list of programs that start at boot:
[root@host ~ ]# chkconfig apf off

 

Installing CSF

So, login to your server via ssh and let’s start CSF installation by retrieving the package files using wget command:

# wget http://configserver.com/free/csf.tgz

Unpack the archive:

# tar xfvz csf.tgz
Navigate to the uncomperssed csf directory:

# cd csf

 

Check CSF will work on your server
CSF provides a test script. We can check whether CSF works with your Server or not prior to installing it.

#perl csftest.pl 

Testing ip_tables/iptable_filter…OK
Testing ipt_LOG…OK
Testing ipt_multiport/xt_multiport…OK
Testing ipt_REJECT…OK
Testing ipt_state/xt_state…OK
Testing ipt_limit/xt_limit…OK
Testing ipt_recent…OK
Testing xt_connlimit…OK
Testing ipt_owner/xt_owner…OK
Testing iptable_nat/ipt_REDIRECT…OK
Testing iptable_nat/ipt_DNAT…OK

RESULT: csf should function on this server

If you get this output, you can proceed to installation. Otherwise you need to enable each missing modules and then install csf.

Run the installer:
Now there founr installation scripts
install.cpanel.sh For cPanel
install.directadmin.sh
install.generic.sh
install.sh

csf installation for cPanel and DirectAdmin is preconfigured to work on those servers with all the standard ports open.. So install as per your requirement.

#sh install.sh

csf auto-configures your SSH port on installation where it’s running on a non-standard port. CSF also auto-whitelists your connected IP address where possible on installation.
Configuration

By default CSF is in Test mode. So you need to disable the test mode once you configured the firewall correctly. Then only the lfd daemon starts.

“/etc/csf/csf.conf” is the main CSF configuration file.
TCP_IN/TCP_OUT/UDP_IN/UDP_OUT = : These are the ports you want to leave open for your server to operate. If you change the default SSH port make sure to add it here. Also add any other services you might have running such as Shoutcast or game servers. All the ports not mentioed here will be blocked.

LF_DSHIELD = 0: Change this option to 86400. This is an automatic updated list of known attacking IPs. Enabling this will stop them from being able to connect to your server.

Spam Protection Alerts
If you want to add some spam protection, CSF can help. Look in the configuration for the following:

LF_SCRIPT_ALERT = 0 change this to 1. This will send an email alert to the system administrator when the limit configured below is reached within an hour.

LF_SCRIPT_LIMIT = 100 change this to 250. This will alert you when any scripts sends out 250 email messages in an hour.
Providing all the configuration options for CSF here is beyond the scope of the article. Please refer to this README from csf for more details

Note:

If you have installed CSF on cPanel/WHM, it also installs WHM plugin to manage CSF. You can access it from

WHM >> Home >> Plugins >> CnfigServer Firewall
Now TEST all your services to make sure everything is working – SSH, FTP, http. After you do a few quick tests go back into the Firewall Configuration page.

TESTING = 1 change this to 0 and click Change at the bottom. Then Restart csf+lfd using below commands

#csf -r
Or
#/etc/init.d/csf restart

That’s it, the firewall is successfully installed and running!!
Common commands:-

To block an IP Permenently
#csf -d IP

To allow or whitelist IP permenently.
#csf -a IP

To temporary block IP
#csf -td IP

To temporary allow an IP
#csf -ta IP

To check an IP is blocked in firewall
#iptables -nL | grep IP
or
# csf -g IP

To find Reason for block.

#grep IP /var/log/lfd.log

To remove a permanent block
#csf -dr IP

To remove IP from allow list
#csf -ar IP

To disable csf
#csf -x

To enable CSF
#csf -e

To restart
#csf -r
CSF is an increasingly popular alternative to the stock firewalls on some servers. Should you require any other help , please contact me.

 

Simple BIND DNS server

Hi

This is simple BIND dns server setup. You can use this for a reference. Yes, it will work because i have tested in real dedicated servers.

Installation:-

If the DNS daemon is not installed on your server, installing it is very simple. Using the built in package manager “YUM” (YellowDog Updater Modified) you can install the DNS daemon with “yum install bind”. The resulting screen will appear something like the below image, type “y” to continue the installation.

Yum Bind

 

Configuration Files

There are very few files for the BIND daemon configuration that the user will need to modify. First is the main configuration file which is referred to as named.conf and is found in the /etc directory. The other file you will need to address is the zone file for your specific domain. These files are normally located in /var/named and have filenames like domain.com.hosts.

Let’s start with the named.conf file. Using your favorite editor (if you do not have one I recommend nano as a simple text editor) open the file for editing. An example of this command using nano would be “nano /etc/named.conf”. This file can contain hundreds of options and settings, but we’re only going to concern ourselves with a select few for this configuration.

For security we will disable recursion. This is important due to spoofed DNS queries to DNS servers which allow recursion used to attack/overload a remote DNS host. So find the line that contains “recursion” and change the “yes” to “no”. This line will be in the options section, but if you cannot locate the line, use the “CTRL+W” key command to locate where the line is.

In this same section we also want to change the “listen-on” line. By default the server only listens on its local loopback port. The IP address “127.0.0.1” for IPv4 and “::1” for IPv6 is already entered into this line, remove these loopback addresses and enter your IP address or “0.0.0.0” for IPv4 and “::” for IPv6. These changes will allow your publically accessible IP addresses to respond to DNS queries. The last line in this section that must be changed is the “allow-query” line. The default setting is to not allow other hosts to query your DNS server. Change the word “localhost” in this line to “0.0.0.0” to allow anyone to query your server for the DNS information regarding the domains you host on the server.

You’re not finished with this file yet. You need to add an entry to tell the DNS server to load the zone file for the domain you want to host. Use the down arrow to move to the last line of the file and hit enter once or twice.

You are going to enter these lines, replacing “yourdomain.tld” with your domain name. For example replace “yourdomain.tld” with “serverpronto.com”. Do not put a www or mail or any other text in front of the domain name, those are hostnames or subdomains are not configured in this file.

zone “yourdomain.tld” {
type master;
file “/var/named/yourdomain.tld.db”;
notify yes;
allow-transfer { Slave-DNS-Server; };
};

The line that begins with “notify” and the line that follows only apply if you are using a slave DNS server and should be omitted if you are hosting your DNS on a single server. However, I must mention that a single server DNS configuration is not recommended.

Save this file with “CTRL+O” and exit the file with CTRL+X”.

 

Create DNS Zone File for Your Domain

Now you need to create the file that the configuration in /etc/named.conf pointed to. This file also has a very specific structure and syntax. The file you want to create will be in the /var/named directory. To create the file and edit it all at once type “/var/named/yourdomain.tld.db” replacing the “yourdomain.tld” as you did when entering the data in the named.conf file.

After you open the new file it will be empty. The contents of the file will be grouped by purpose, the first section is information for the DNS server to manage the DNS zone’s status, configuration and updates.

$TTL 86400 ; Time To Live before remote DNS server removes stale records from cache
@ IN SOA ns1.yourdomain.tld. useremail.yourdomain.tld. ( ; Responsible name server and responsible email address without the “@” symbol.

1123161063 ; serial number
10800 ; refresh (3 hours)
3600 ; retry (1 hour)
604800 ; expire (1 week)
3600 ; minimum (1 hour)
)

The above text is the first section of the file. The text in red can be left out or copied into teh file, that text is descriptive as to what the items is. Some further explanation is:

TTL – This is the time a remote DNS server will hold a record in its cache before refreshing the cache for a new record when requested again. Shorten this number to make frequent changes or a week before a major change to propagate changes quickly. Increase this number to reduce overall load on the server and allow remote DNS servers to provide data from cache and not query the server as frequently.

SOA – “Start of Authority” record. This is a specific record type used to provide responsible server and persons data.

Serial Number – This number tacks zone file versions among multiple primary/secondary DNS servers.

The remaining numbers tell the DNS servers when to refresh or expire records, and can safely be left at the default setting.

The next records that must be added to the zone file are the NS records to provide the name server data to querying clients. The NS records will look like this:

IN NS ns1.yourdomain.tld.
IN NS ns2.yourdomain.tld.

Please make note of the “.” (dot) behind records that contain hostnames. This is an important item throughout the files. These nameserver (NS) records generally match the nameserver records you create with your registrar and must contain valid hostnames that are valid “A” records within the domain they refer to. Additionally these nameservers referred to in these lines must host your domain.

The next record you should insert into the file is the MX record which identifies the Mail Exchanger (MX) host for your domain. This record should appear like this:

IN MX 10 mail.yourdomain.tld.

The hostname you use for this record must be a valid “A” record or “CNAME” record in the domain and should respond to email transfers for your domain.

Now we begin the main record portion of the file. The records you will now enter refer to hosts within the domain. Here is an example of some of the records you may enter:

IN A 127.0.0.1
mail IN A 127.0.0.1
www  IN CNAME yourdomain.tld.
ns1  IN A 127.0.0.1
ns2  IN A 127.0.0.2

After you look over these lines I want to point out a few items.

  • The “A” records for the “NS” records above are created here.
  • The “A” record for the “MX” record above is created here.
  • The “A” record for requests which contain no hostname is the first in the list.
  • The other “A” records are miscellaneous records for hostname that are common.

Once the records are entered, save this file with “CTRL+O” and exit the file with CTRL+X”.

 

Applying The New Configuration

Now that all of the data is entered for your domain simply applying these changes should activate the DNS zone on your server. To apply the changes restarting the DNS daemon is required. Use this command to restart the daemon:

“service named restart”

The textual output on the server should indicate success or failure. If success is indicated there is only one last item to check and that is the firewall rules to ensure the client queries will be allowed. Use this command to query the firewall rules for UDP port 53 access:

“iptables -vnL | grep 53″

The server should respond with a line similar to this:

”   0     0 ACCEPT     udp  —  *      *       0.0.0.0/0            0.0.0.0/0           state NEW udp dpt:53″

If this response is not received please review your IPtables rules to make changes to allow the queries.

 

 

 

 

Server migration

On occasion, you may want to move from one server to another. For example, you may be upgrading to a dedicated server or moving to a server with a different PHP deployment method. Server migration is a process in which data is moved from one server to another. Whatever the case, most people will agree that it is never a joyous event to switch server. Your sites will be down/unstable/inaccessible during the migration period and it could potentially lead to loss of sales. In this article, we are going to show you how you can migrate your site to a new server effortlessly and without any (or minimal) downtime. Below are the basic steps needs to be followed for a server migration with minimum downtime.

1. Prepare Your DNS

When you move your site(s) to a new server, you will likely get new IP addresses. The problem is that DNS servers cache domain name queries for as long as possible to provide the fastest response. Because of these DNS caching, once you change your IP, it can take up to three days before the changes propagate throughout the Internet. To keep this from happening, your first step in preparing for the migration is to change your DNS record TTL (Time To Live). This value designates how long your DNS entries should be cached. So the first thing you need to do before migrating is to lower the TTL to reasonable levels.

2. Set up Your New Server

Make sure your new server has the correct operating system installed and ready and that all hardware meets your applications specifications. Also setup the new IP addresses.

3. Tune Your Server

Check your file system and make sure your partitions are set up as you need them. Set up RAID if required. This is also the perfect time to implement any security practices within the OS and firewall (if installed). It’s important to complete these steps before you get too far because they’re much easier to do without content on the server.

4. Install Base Applications

Once you have installed the OS and setup the file system, you are ready to install the base applications, like the Web server, e-mail server, database server, PHP, etc.. Also verify the services are running fine on thr new server.

5. Begin Data Migration

Once the base applications are installed, you are ready to do the initial migration of your application data. This includes the database data, your application code files, mail server account configuration, logs, file caches, etc..

6. Bring your new server to life.

Once the data is migrated the server is configured to work everything correctly, you should change your sites domain DNS records to point to the new server address.

 

Data Migration

If you are using any Control Panels like cPanel, Plesk, etc., it rather easy to move data/accounts between servers as each control panel will give you option to move accounts.

cPanel Server to cPanel server migration

To migrate from one cPanel server to another, please do this:

1. Log into WHM as root on the new cPanel server

2. Click “Copy multiple accounts/packages from another server”

3. Fill in the required information like source server details and click “Fetch Account List”

You will then be given the option to choose which accounts and packages to transfer.

cPanel also does support migraring accounts from different control panel other than cPanel itself.

 

Server without a control panel

Rsync is a simple and very powerfull tools which can be used to transfer files between servers efficently.

First copy all the configurations files for the services like Webserver, Email server, etc. Then transfer the account data from old server.

Rsync example:-

#rsync -avz -e ssh /home root@remoteserverip:/home

-v: verbose, will tell you what file its on, how many left to check, etc.
-a: archive, will set most of the preferable options.
–progress: gives you per-file data transfer rates, and spinning progress bars if you’re into that sort of thing.
-z, –compress compress file data during the transfer

System files:-

Please note that we do not need to copy the server related files. We can exclude from the rync list. The most important excludes are the ones that reference hardware and system files that keep track of the server’s status while it’s running. That’s why directories like /boot, /proc, and /dev are essential excludes. The destination server should already have those directories and config files in place and they shouldn’t be overwritten.

Example
#rsync -avz -e ssh –exclude-from=”/home/exclude.txt” /home root@remoteserverip:/home

Finalizing the migration

Doing one pass got the more static files over to the new server. That’s good, but that may not be everything you needed to copy. An active database or a directory where a lot of files get created and deleted may have been copied but changed already. Or, more practically, they may have been in your exclude file.

To get those last files you’ll want to bring the services that use them down. That way you know the entire file will be migrated with no changes made after your last sync.

Edit your exclude file to remove references to the busy files you were holding off on then run the rsync command again.

Upgrading OpenSSH on CentOS 5 server

Upgrading openssh

RHEL5 and CentOS 5 run an older version of ssh, which makes doing a chroot sftp or scp more difficult.

Pre-requisites:=

You need to have following packages and it’s dependencies installed:-

Yum install -y rpm-devel rpm-build pam pam-devel perl openssl-devel tcp-wrappers

Steps:-

It is not recommended to build RPM as root user.

1. Login to server using SSH as a normal user.
2. In your home directory create a file .rpmmacros and add following entires to ot.

%_topdir %(echo $HOME)/rpmbuild

3. Next step is creating the build environment. In your home directory, create following directories:-

$mkdir rpmbuild
$cd rpmbuild
$mkdir BUILD RPMS SOURCES SPECS SRPMS

4. Download the latest openssh from their site. http://filedump.se.rit.edu/pub/OpenBSD/OpenSSH/portable/
5. Once it is downloaded, copy the tarball to the rpmbuild/SOURCES directory that you made.
6. You will also need to extract the tarball and copy over the spec file.

$tar xvf openssh-.tar.gz
$cd openssh-
$cp contrib/redhat/openssh.spec $HOME/rpmbuild/SPECS
$cd ..
$cp openssh-.tar.gz rpmbuild/SOURCES

7. Edit the spec file(HOME/rpmbuild/SPECS/openssh.spec).

Also change

%define no_x11_askpass 0
from 0 to 1. We don’t need the X11 accessories for this.

Do the same with

%define no_gnome_askpass 0
for the same reason. Lastly, comment out the line

%define build6x 0
As we’re not building for RHEL6.

8. Build rpm. In $HOME/rpmbuild/SPECS run the following command:-

$rpmbuild -ba openssh.spec
The above command should build and create several rpms in $HOME/rpmbuild/RPMS/i386

9. In the i386 directory holding the rpms run,

$rpm -Uvh openssh*
It should update openssh, openssh-server, and openssh-clients.

10. It will also create a new file in /etc/ssh called sshd_config.rpmnew. Make sure you have a copy of your old sshd_config. The rest of this will be done as root or with root privilege.

#cd /etc/ssh
#cp sshd_config sshd_config.orig
#mv sshd_config.rpmnew sshd_config

11. Restart the SSH service.

#/etc/init.d/sshd restart or
#service sshd restart

Check the versions of the OpenSSH installed

#rpm -qa | grep openssh

Distributed Denial of service(DDOS)

A denial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a computer or network resource unavailable to its intended users. The speciality of the DDOS is that, it relays attacks not from a single network/host like DOS. The DDOS attack will be launched from different dynamic networks which has already been compromised.

Types:-

Ping of death :-
Attacker deliverately sending a ping packet, normally 64 bytes, that is larger than the 65,535 bytes. Many computer systems cannot handle an IP packet larger than the maximum IP packet size of 65,535, and often causes computer systems crash. A ping packet of size greater than 65,535, can be sent if it is fragmented.When a receiving computer reassembles the packet, a buffer overflow occurs, which often causes computer to crash.

Ping of flood:-
An attacker overwhelming the victim’s network with ICMP Echo Request (ping) packets. A flood of ping traffic can consume singificant bandwidth on low to mid-speed networks bringing down a network to a crawl.

Smurf Attack:-
Smurf attack exploits the target by sending repeated ping request to broadcast address of the target network. The ping request packet often uses forged IP address (return address), which is the target site that is to receive the denial of service attack. The result will be lots of ping replies flooding back to the innocent, spoofed host. If number of hosts replying to the ping request is large enough, the network will no longer be able to receive real traffic.

SYN Floods :-
When establishing a session between TCP client and server, a hand-shaking message exchange occurs betwen a server and client. A session setup packet contains a SYN field that identifies the sequence in the message exchange. An attacker may send a flood of connection request and do not respond to the replies, which leaves the request packets in the buffer so that legitimate connection request can’t be accommodated.

Teardrop Attack :-
Teardrop attack exploits by sending IP fragment packets that are difficult to reassemble. A fragment packet identifies an offset that is used to assemble the entire packet to be reassembled by the receiving system. In the teardrop attack, the attacker’s IP puts a confusing offset value in the sebsequent fragments and if the receiving system doesn’t know how to handle such situation, it may cause the system to crash.

Prevetion:-

1. Install Intrusion Detection System (IDS)
2. Implement Sysctl. Prevent ping attacks (ping of death, ping of flood, and smurf attacks) by disabling ping responses on the network machines. Enable IP Spoofing protection, and TCP SYN Cookie Protection.
3. Install advanced firewall and DDoS utilities.
4. Install Apache mod_evasive and mod_security modules to protect against HTTP DDoS attacks.

Mod_security:-
Since DDOS normally targets HTTP. Its always good to have a filtering system for apache . So that the request gets analyzed before web server handles it.

Mod_evasive:-
Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:

1. Requesting the same page more than a few times per second
2. Making more than 50 concurrent requests on the same child per second
3. Making any requests while temporarily blacklisted (on a blocking list)

Note:-
1. Well there are no 100% prevention or protection against DDOS.
2. This steps won’t be enough if the DDOS attack is of very high volume.

How dns works

A DNS client “resolves” an IP address by sending a specially formatted request to a DNS server. The client has to know the address of one or more DNS servers in advance. The reply from the server may be a direct reply with the IP address associated with the hostname, a referral to another DNS server, or a response indicating the requested name can’t be found in DNS.

Typically, the request will ask the server to “recursive“, i.e. if it cannot answer the question from its own local memory, it should go ask other servers on behalf of the client. This behavior helps the local server build up its own cache of addresses frequently looked up.

Another form of query is called iterative query, where a client machine sends the request to a known DNS server , if that DNS server fail to resolve the domain name into a IP, then the client sends the request to another DNS and this process goes on and on until it get the required IP resolution by sending address resolution request to all its known DNS.If every known DNS fail to give the IP, then client goes to the root domain.

When you type a URL into your browser, it uses the following steps to locate the correct website:

A DNS client uses a resolver to request resolution of a host name to an IP address. The resolver is really just a special-purpose application that’s sole function is to act as an intermediary between name servers and various applications that need name resolution, such as Web browsers, e-mail applications, and so on. Here’s an example: Assume you fire up your browser and direct it to connect to www.mysite.com.

1. Your browser checks it’s cache (memory) to see if it knows which IP address the domain name resolves to. If it knows, it will resolve it and display the web page.
2. If the domain name is unable to be resolved, the browser will check your hosts file for a DNS entry.
3. If there’s no entry in the hosts file, the browser will check the default DNS server (specified via your computer’s network settings, /etc/resolv.conf). This is usually your ISP’s DNS server or your employer’s. If the default DNS server has an entry for that domain name, the browser will display the applicable website.
4. If the default name server has no cached results, it sends a DNS query to the root server for the .com domain.
5. The root server responds with the addresses of the name servers that are authoritative for the mysite.com domain.
6. Your ISP’s name server then builds another request for www.mysite.com and submits it to mysite.com’s name server, which responds with the IP address of www.mysite.com.
7. That information is passed back to your resolver, which passes it to your application.

How to install an SSL certificate on Ubuntu for Nginx

Introduction

SSL (Secure Sockets Layer) is a protocol that provides secure communication over the internet. It uses cryptographic algorithms to encrypt data between the web server and the client’s browser. SSL is now deprecated, and TLS (Transport Layer Security) is the newer version that’s used widely.

In this tutorial, we’ll walk you through the steps to install and secure your website with SSL on Ubuntu 22.04 using Nginx. By the end of this guide, you’ll have a secure, encrypted connection between your web server and your users’ browsers, helping to ensure their safety and privacy.

Note: Originally, this blog was written for an old versions of Nginx and Ubuntu, I have updated to match the latest Ubuntu and Nginx recently.

Section 1: Installing Nginxon Ubuntu 22.04

Apache2 is a popular open-source web server software that plays a crucial role in hosting websites on the internet. In this section, we will walk through the process of installing Apache2 on Ubuntu 22.04.

Step 1: Update the Package List
Before installing any new software, it’s always a good idea to update the package list to ensure you are installing the latest version of the software. To update the package list, open the terminal on Ubuntu 22.04 and run the following command:

sudo apt update

Step 2: Install Nginx
Once the package list is updated, you can proceed with installing Nginx by running the following command:

sudo apt install nginx

This command will download and install Nginx along with all its dependencies. During the installation process, you will be prompted to confirm the installation by typing y and pressing Enter.

Enable and Start the Apache2 service

sudo systemctl enable nginx
sudo systemctl start nginx

Step 3: Verify NginxInstallation
To test if Nginx is working correctly, open a web browser and enter your server’s IP address or domain name in the address bar. You should receive the default Nginx landing page:

Congratulations, you have successfully installed Nginx on Ubuntu 22.04! In the next section, we will proceed with securing the web server by enabling SSL.

If you encounter any issues like Connection timeout or Unable to reach the website during the verification process, one possible cause could be that the Ubuntu firewall is blocking nginx traffic.

To check if Nginx is currently enabled in the firewall, you can use the Nginx is not listed as an allowed service, you can add it by running the following command:

sudo ufw allow 'Nginx Full'

This will allow both HTTP (port 80) and HTTPS (port 443) traffic to pass through the firewall, ensuring that your website is accessible to visitors.

Section 2: Installing SSL Certificate on Ubuntu 22.04 with Nginx

There are different types of SSL certificates, including domain validated, organization validated, and extended validation certificates. Each type has different features and provides varying levels of trust and security.

To install an SSL certificate on Ubuntu 22.04 with Nginx, you’ll need to follow these steps:

  • Obtain an SSL certificate: You can purchase an SSL certificate from a certificate authority (CA) or obtain a free SSL certificate from Let’s Encrypt. If you already have an SSL certificate, make sure it is valid and up-to-date.
  • Configure Apache2 to use the SSL certificate: Apache2 needs to be configured to use the SSL certificate for secure communication. This involves creating a virtual host for the SSL-enabled website, specifying the SSL certificate and key files, and enabling SSL encryption.

    You can read more about different SSL certificate types, the process to create a Certificate signing request(CSR), etc in the below blog post:

    SSL Certificates: What They Are and Why Your Website Needs Them

    Here are the steps for creating and configuring virtual hosts for Apache on Ubuntu 22.04:

    1. Create a new virtual host configuration file:

    sudo nano /etc/nginx/sites-available/linuxwebhostingsupport.in

    Add the following configuration to the file, replacing linuxwebhostingsupport.in with your own domain name:

    server {
        listen 80;
        listen [::]:80;
    
        server_name linuxwebhostingsupport.in;
    
        root /var/www/html/linuxwebhostingsupport.in/html;
        index index.html;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
    
        server_name linuxwebhostingsupport.in;
    
        root /var/www/html/linuxwebhostingsupport.in/html;
        index index.html;
    
        ssl_certificate /etc/ssl/certs/linuxwebhostingsupport.in.crt;
        ssl_certificate_key /etc/ssl/certs/linuxwebhostingsupport.in.key;
        ssl_trusted_certificate /etc/ssl/certs/linuxwebhostingsupport.in_cabundle.crt;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }
    

    Note: replace the paths to SSL certificate files with your own paths.

    2. Create the documentroot
    Run the following command to create the directory:

    sudo mkdir -p /var/www/html/linuxwebhostingsupport.in/html

    3. Test the Nginx configuration:

    sudo nginx -t

    If there are any issues, this check will show

    4. Enable the virtual host configuration file:

    If the configuration test is successful, enable the server block by creating a symbolic link in the /etc/nginx/sites-enabled directory:

    sudo ln -s /etc/nginx/sites-available/linuxwebhostingsupport.in /etc/nginx/sites-enabled/

    5. Create an HTML file named index.html in the new directory by running the following command:

    sudo nano /var/www/html/linuxwebhostingsupport.in/html/index.html

    This will open a text editor. Add the following code to the file:

    <html>
        <head>
            <title>Hello, world!</title>
        </head>
        <body>
            <h1>Hello, world!</h1>
            <p>Welcome to my website!</p>
        </body>
    </html>
    

    5. Reload Nginx for the changes to take effect:

    sudo systemctl reload Nginx

    Section 3: Testing SSL on Ubuntu 22.04 with Nginx

    Test your SSL configuration by visiting your domain in a web browser and verifying that the SSL certificate is valid and the website loads correctly over HTTPS. The browser should display a padlock icon and the connection should be secure

    You can also use the online tools like https://www.sslshopper.com/ssl-checker.html to check the configuration further. It can show if there any issues with certificate chain or trust.

    Section 4. Troubleshooting SSL on Ubuntu 22.04 with Apache2

    1. Certificate errors: If you encounter a certificate error, such as a warning that the certificate is not trusted or has expired, check the certificate’s validity and ensure it’s installed correctly. You can check the certificate’s details using your web browser, and make sure it matches the domain name and other relevant details.

    2. Mixed content warnings: If you see mixed content warnings, which indicate that some parts of the site are not secure, check for any resources that are still being loaded over HTTP instead of HTTPS. This can include images, scripts, and other files.

    3. SSL handshake errors: If you see an SSL handshake error, this usually means there’s an issue with the SSL configuration. Check your Apache configuration files and make sure the SSL directives are properly set up. You can also check for any issues with the SSL certificate, such as an invalid or mismatched domain name.

    4. Server configuration errors: If the SSL certificate is working properly, but the site is still not loading over HTTPS, check your server configuration files to make sure the VirtualHost configuration is correct. Make sure the correct SSL certificate and key files are specified and that the SSL directives are set up correctly.

    5. Browser-specific issues: If you’re only experiencing SSL issues in a specific web browser, make sure the browser is up to date and try clearing the cache and cookies. You can also try disabling any browser extensions that may be interfering with the SSL connection.

    Remember, troubleshooting SSL issues can be complex and may require some technical expertise. If you’re not comfortable with these steps or need additional help, it’s always a good idea to consult with a professional. You can contact me at admin @ linuxwebhostingsupport.in

    Section 5: Best Practices for SSL Configuration on Ubuntu 22.04 with Apache2

    Here are some tips and best practices for configuring SSL on Ubuntu 22.04 with Apache2:

    1. Keep SSL certificates up to date: Make sure to renew your SSL certificates before they expire. This can be done through the certificate authority where you purchased the certificate. Keeping your SSL certificates up to date will ensure that your website visitors are not presented with security warnings or errors.

    2. Configure Nginx for HTTPS-only access: To ensure that your website visitors are accessing your site securely, configure your Nginx server to only serve HTTPS traffic. This can be done by redirecting all HTTP traffic to HTTPS. To do this, add the red colored line to your server block of Nginx virtual host configuration file:

    server {
        listen 80;
        server_name linuxwebhostingsupport.in;
        return 301 https://$server_name$request_uri;
    }
    

    3. Use secure ciphers and protocols: To protect the confidentiality and integrity of your website traffic, use secure ciphers and protocols. Disable weak ciphers and protocols such as SSLv2 and SSLv3. Use TLSv1.2 or higher, and prefer the use of forward secrecy. You can configure this in your Nginx virtual host configuration file by adding the following lines:

    ssl_protocols TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:10m;
    ssl_session_tickets off;
    ssl_stapling on;
    ssl_stapling_verify on;
    

    Make sure to adjust the file paths and other configuration options to match your specific setup.

    You can find more detailed instruction on making your SSL configuration strong and best practices in the below post:

    Strong TLS/SSL Security on your server

    By following these best practices, you can ensure that your SSL configuration is secure and up to date.

    Section 6. Summary

    In this tutorial, we discussed how to install and configure SSL certificates on Ubuntu 22.04 with Nginx. We covered the different types of SSL certificates, the steps for obtaining and installing an SSL certificate, and how to configure Nginx to use the SSL certificate. We also discussed how to create virtual hosts for both SSL and non-SSL sites and how to troubleshoot SSL issues.
    It’s important to emphasize the importance of SSL for website security and user trust. SSL encryption helps protect sensitive information, such as passwords and credit card numbers, from being intercepted by attackers. Additionally, having a valid SSL certificate gives users confidence that they are interacting with a legitimate website and not an imposter.

    To follow best practices for SSL configuration, it’s recommended to keep SSL certificates up to date, configure Nginx for HTTPS-only access, and use secure ciphers and protocols. By following these best practices, website owners can help ensure the security and trustworthiness of their website.

  • Case insensitive url Aapche Webserver

    How to enable Case-Insensitive url’s ?

    Webserver: Apache

    OS: Linux

    One of our customer had opened ticket. He has a very interesting need. He wants his site urls  to be Case-insensitive . I will explain with examples:- He needs the following urls to work currently he is getting 404 errors for each request.

    http://yourdomain.com/Yourpage.html

    http://yourdomain.com/YourPage.html

    We were unable to add rewrite rules in his htaccess files as we need to write rule for every single file that has a mixture of upper and lower case.

    http://yourdomain.com/yourpage.html => This is the correct url

    He needs this url http://yourdomain.com/Yourpage.html to load even if they have one spelling mistake or there is one capitalization error. This was found very strange. We have managed to fix the issue by adding an apache module server wide, which neutralise all the the upper case and lower case characters to a single format.

    Solution: If you want requested URLs to be valid whether uppercase or lowercase letters are used and with one spelling mistake, “mod_speling” module needs to be enabled in apache.

    The mod_speling module is part of the standard Apache distribution but is not enabled by default, so you need to explicitly enable it. When mod_speling is installed, it may be turned on for a particular scope (such as a directory, virtual host, or the entire server) by setting the CheckSpelling directive to On.

    For making URL case-insensitive in cPanel:

    First run belwow on Cpanel based server : /scripts/easyapache And select ‘Spelling’ from the available module list for apache. Once apache/php are recompiled with this option and easyapache finishes, you can put below code in the .htaccess or in the virtual host entry of the particular domain to apply it to any directory/directories :

    < IfModule mod_speling.c > CheckCaseOnly On CheckSpelling On < / IfModule > This helped to fix this particular issue

    Verify PHP/cURL is working correctly

    Simply, cURL is a command line tool for getting or sending files using URL syntax. It supports a range of common Internet protocols, including HTTP, FTP, SCP, SFTP, TFTP, TELNET, FILE, IMAP, POP3, SMTP and RTSP, etc. The command is designed to work without user interaction.

    Usage:-

    Basic use of cURL involves simply typing curl at the command line, followed by the URL of the output to retrieve.
    To retrieve the google.com homepage, type:
    curl www.google.com
    What is PHP/CURL?
    The module for PHP that makes it possible for PHP programs to access curl-functions from within PHP.

    How to verify cURL is working correctly?.

    cURL does have very powerfull functions which inturn not used properly may leads to complete breakdown of your server. Because of this most of the hosting companies disable some of these dangerous functions. But for a PHP Programmer cURL is an essential tool and must requires basic functionality atleast. It is very easy to check the PHP/cURL is working normal.

    Steps:-

    1. Create a php file “check_cURL.php” with following content using any of your favourite editor.

    <?php
    /**
    * Initialize the cURL session
    */
    $ch = curl_init();
    /**
    * Set the URL of the page or file to download.
    */
    curl_setopt($ch, CURLOPT_URL,
    ‘http://news.google.com/news?hl=en&topic=t&output=rss’);
    /**
    * Create a new file
    */
    $fp = fopen(‘rss.xml’, ‘w’);
    /**
    * Ask cURL to write the contents to a file
    */
    curl_setopt($ch, CURLOPT_FILE, $fp);
    /**
    * Execute the cURL session
    */
    curl_exec ($ch);
    /**
    * Close cURL session and file
    */
    curl_close ($ch);
    fclose($fp);
    ?>


    2.  Execute the “check_cURL.php” script (I just run “php -q   check_cURL.php” from the terminal)

    3.  Check the output file “rss.xml”. If the file contains data, we can conclude curl is working fine.

    How does this script works:-

    The check_cURL.php is simple php script which when called connects to the url specified(Google in our example) and download its source code. The script then writes its output to downloaded content to the output file(rss.xml in our example).

    Page 4 of 5

    Powered by WordPress & Theme by Anders Norén