Install Config Server Firewall (CSF)

Introduction

Config Server Firewall (or CSF) is a free and advanced firewall for most Linux distributions and Linux based VPS. In addition to the basic functionality of a firewall – filtering packets – CSF includes other security features, such as login/intrusion/flood detections. CSF includes UI integration for cPanel, DirectAdmin and Webmin, but this tutorial only covers the command line usage. CSF is able to recognize many attacks, such as port scans, SYN floods, and login brute force attacks on many services. It is configured to temporarily block clients who are detected to be attacking the cloud server.

The full list of supported operating systems and features can be found on ConfigServer’s website.

This tutorial is written for Debian based VPS, such as Debian and Ubuntu. The commands should be executed with root permissions, by logging in as root, or initiating a root shell with the following command if sudo is installed:

sudo su

Features

Config Server Firewall offers a wide range of protections for your VPS.

Login authentication failure daemon:
CSF checks the logs for failed login attempts at regular time interval, and is able to recognize most unauthorized attempts to gain access to your cloud server. You can define the desired action CSF takes and after how many attempts in the configuration file.

The following applications are supported by this feature:

Courier imap, Dovecot, uw-imap, Kerio
openSSH
cPanel, WHM, Webmail (cPanel servers only)
Pure-ftpd, vsftpd, Proftpd
Password protected web pages (htpasswd)
Mod_security failures (v1 and v2)
Suhosin failures
Exim SMTP AUTH

In addition to these, you are able define your own login files with regular expression matching. This can be helpful if you have an application which logs failed logins, but does block the user after specific number of attempts.

Process tracking
CSF can be configured to track processes in order to detect suspicious processes or open network ports, and send an email to the system administrator if any is detected. This may help you to identify and stop a possible exploit on your VPS.

Directory watching
Directory watching monitors the /temp and other relevant folders for malicious scripts, and sends an email to the system administrator when one is detected.

Messenger service
Enabling this feature allows CSF to send a more informative message to the client when a block is applied. This feature has both pros and cons. On one hand, enabling it provides more information to the client, and thus may cause less frustration for instance in case of failed logins. On the other hand, this provides more information, which might make it easier for an attacker to attack your VPS.

Port flood protection
This setting provides protection against port flood attacks, such as denial of service (DoS) attacks. You may specify the amount of allowed connections on each port within time period of your liking. Enabling this feature is recommended, as it may possibly prevent an attacker forcing your services down. You should pay attention to what limits you set, as too restrictive settings will drop connections from normal clients. Then again, too permissive settings may allow an attacker to succeed in a flood attack.

Port knocking
Port knocking allows clients to establish connections a server with no ports open. The server allows clients connect to the main ports only after a successful port knock sequence. You may find this useful if you offer services which are available to only limited audience.

Read more about port knocking

Connection limit protection
This feature can be used to limit the number concurrent of active connections from an IP address to each port. When properly configured, this may prevent abuses on the server, such as DoS attacks.

Port/IP address redirection
CSF can be configured to redirect connections to an IP/port to another IP/port. Note: After redirection, the source address of the client will be the server’s IP address. This is not an equivalent to network address translation (NAT).

UI integration
In addition to command line interface, CSF also offers UI integration for cPanel and Webmin. If you are not familiar with Linux command line, you might find this feature helpful.

IP block lists
This feature allows CSF to download lists of blocked IP addresses automatically from sources defined by you.

Installing ConfigServer Firewall

Step 1: Downloading
Config Server Firewall is not currently available in Debian or Ubuntu repositories, and has to be downloaded from the ConfigServer’s website.

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

This will download CSF to your current working directory.

Step 2: Uncompressing
The downloaded file is a compressed from of tar package, and has to be uncompressed and extracted before it can be used.

tar -xzf csf.tgz

Step 3: Installing
If you are using another firewall configuration scripts, such as UFW, you should disable it before proceeding. Iptables rules are automatically removed.

UFW can be disabled by running the following command:

ufw disable

Now it is time to execute the CSF’s installer script.

cd csf
sh install.sh

The firewall is now installed, but you should check if the required iptables modules are available.

perl /usr/local/csf/bin/csftest.pl

The firewall will work if no fatal errors are reported.

Note: Your IP address was added to the whitelist if possible. In addition, the SSH port has been opened automatically, even if it uses custom port. The firewall was also configured to have testing mode enabled, which means that the iptables rules will be automatically removed five minutes after starting CSF. This should be disabled once you know that your configuration works, and you will not be locked out.

Basic Configuration
CSF can be configured by editing its configuration file csf.conf in /etc/csf:

nano /etc/csf/csf.conf

The changes can be applied with command:

csf -r

Step 1: Configuring ports
The less access there is to your VPS, the more secure your server is. However, not all ports can be closed as the clients must be able to use your services.

The ports opened by default are the following:

TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995"
TCP_OUT = "20,21,22,25,53,80,110,113,443"
UDP_IN = "20,21,53"
UDP_OUT = "20,21,53,113,123"

Services using the open ports:

Port 20: FTP data transfer
Port 21: FTP control
Port 22: Secure shell (SSH)
Port 25: Simple mail transfer protocol (SMTP)
Port 53: Domain name system (DNS)
Port 80: Hypertext transfer protocol (HTTP)
Port 110: Post office protocol v3 (POP3)
Port 113: Authentication service/identification protocol
Port 123: Network time protocol (NTP)
Port 143: Internet message access protocol (IMAP)
Port 443: Hypertext transfer protocol over SSL/TLS (HTTPS)
Port 465: URL Rendesvous Directory for SSM (Cisco)
Port 587: E-mail message submission (SMTP)
Port 993: Internet message access protocol over SSL (IMAPS)
Port 995: Post office protocol 3 over TLS/SSL (POP3S)
It is possible that you are not using all of these services, so you can close the ports that are not used. I would recommend closing all ports (removing port number form the list), and then adding the ports you need.

Below are port sets that should be opened if you are running the listed service:

On any server:

TCP_IN: 22,53
TCP_OUT: 22,53,80,113,443
UPD_IN: 53
UPD_OUT: 53,113,123

Apache:

TCP_IN: 80,443
FTP server:
TCP_IN: 20,21
TCP_OUT: 20,21
UPD_IN: 20,21
UPD_OUT:20,21

Mail server:

TCP_IN: 25,110,143,587,993,995
TCP_OUT: 25,110

MySQL server (if remote access is required)

TCP_IN: 3306
TCP_OUT: 3306

Note: If you are using IPv6 for your services, you should also configure TCP6_IN, TCP6_OUT, UPD6_IN, and UPD6_OUT similarly to how IPv4 ports were configured earlier.

You can find a comprehensive list of TCP and UDP ports on Wikipedia. You should open the ports of all the services you use.

Step 2: Additional settings
CSF offers a vast number of different options in its configuration files. Some of the most commonly used settings are explained below.

ICMP_IN
Setting ICMP_IN to 1 allows ping to your server and 0 refuses are such requests. If you are hosting any public services, it is recommended to allow ICMP requests, as these can be used to determine whether or not your service is available.

ICMP_IN_LIMIT
Sets the number of ICMP (ping) requests allowed from one IP address within a specified amount of time. There is usually no need to change the default value (1/s)

DENY_IP_LIMIT
Sets the number of blocked IP addresses CSF keeps track of. It is recommended to limit the number of denied IP addresses as having too many blocks may slow down the server performance.

DENY_TEMP_IP_LIMIT
Same as above, but for temporary IP address blocks.

PACKET_FILTER
Filter invalid, unwanted and illegal packets.

SYNFLOOD, SUNFLOOD_RATE and SYNFLOOD_BURST
This offers protection against SYN flood attacks. This slows down the initialization of every connection, so you should enable this only if you know that your server is under attack.

CONNLIMIT
Limits the number of concurrent active connections on port.

Value:

22;5;443;20

would allow 5 concurrent connections on port 22 and 20 concurrent connections on port 443.

PORTFLOOD
Limits the number of connections per time interval that new connections can be made to specific ports. Value:

22;tcp;5;250

would limit block the IP address if more than 5 connections are established on port 22 using TCP protocol within 250 seconds. The block is removed once 250 seconds have passed after the last packet sent by the client to this port. You may add more ports by separating them by commas like described below.

port1;protocol1;connection_count1;time1,port2;protocol2;connection_count2;time2

More settings
CSF offers a wide range of settings which are not covered in this tutorial. The default values are generally good, and can be used on almost any server. The default settings are configured to prevent most flood attacks, port scans and unauthorized access attempts.

If you would, however, like to adjust the configuration in more detail, please read the comments in /etc/csf/csf.conf and edit them as you like.

Step 3: Applying the Changes

Whenever you are altering the settings in csf.conf, you should save the files and restart CSF in order for the changes to take effect. Once you are ready with the configuration, close the file by pressing Ctrl + X. When you are asked whether to save the changes or not, press Y to save the changes.

After this, you should apply the changes by restarting CSF with command:

csf -r

If everything went like planned, and you are still able to access the server, open the configuration file once more:

nano /etc/csf/csf.conf

and change setting TESTING at the beginning of the configuration file to 0 as shown below:

TESTING = "0"

Save the file, and apply the changes with command:

csf -r

Blocking and Allowing IP Addresses
One of the most basic features of a firewall is the ability to block certain IP addresses. You may deny (blacklist), allow (whitelist) or ignore IP addresses by editing the configuration files csf.deny, csf.allow and csf.ignore.

Blocking IP addresses
If you would like to block an IP address or range, open csf.deny.

nano /etc/csf/csf.deny

Blocked IP addresses or ranges all reserve one line in csf.deny file. If you would like to block IP address 1.2.3.4 as well as IP range 2.3.*.*, you should add the following lines to the file:

1.2.3.4
2.3.0.0/16

IP ranges are represented using the CIDR notation

Allowing IP addresses
If you would like an IP address or range to be excluded from all blocks and filters, you may add them to csf.allow file. Please note that allowed IP addresses are allowed even if they are explicitly blocked in csf.deny file.

Allowing IP addresses works similarly to blocking them. The only difference is that you should edit /etc/csf/csf.allow instead of csf.deny.

nano /etc/csf/csf.allow

Ignoring IP addresses
CSF also offers ability to exclude IP addresses from the firewall filters. IP addresses in csf.ignore will bypass the firewall filters, and can only be blocked if listed in csf.deny file.

nano /etc/csf/csf.ignore

In order to changes take effect, you should restart CSF after editing any of the files described above with command:

csf -r

From: digitalocean.com

Nginx Redirect Mobile to Mobile Version Of the Web Site

Nginx configurations:

set $mobile_rewrite do_not_perform;
## chi http_user_agent for mobile / smart phones ##
if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino") {
  set $mobile_rewrite perform;
}
if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)") {
  set $mobile_rewrite perform;
}
## redirect to m.example.com ##
if ($mobile_rewrite = perform) {
  rewrite ^ http://m.example.com$request_uri? redirect;
  break;
}

Continue reading

Sửa lỗi VMware Workstation 9 cứ cấp IP động là 192.168.255.xxx

Vào 1 ngày đẹp trời nào đó, ta không thể connect được vmware từ client(ssh, ping) vì vmware của ta cấp phát IP động theo dòng 192.168.255.xxx. Mà theo kiến thức ta được học thì không connect được với subnet 255, vậy vấn đề có thể là IP đẹp đã bị chiếm hết, để giải quyết vấn đề trên, ta làm như sau: Continue reading

Android project cấu hình trong git

- Xóa folder /bin, /gen
- git add -Af
- git commit -m 'remove bin, gen folder'
- Tạo file .gitignore có nội dung:
    /bin
    /gen
- git add -Af
- git commit -m 'add gitignore file'
- Khi run project bằng eclipse, khi gặp lỗi: AndroidManifest.xml: error: Unable to open file for read: No such file or directory thì chọn
    Project -> Clean...

Next bookmark trong eclipse

Nếu bạn nào đã quen dùng các editor khác như Notepad++ hay Sublime Text 2, sẽ thường dùng Ctlr + F2 để add bookmark. Phím F2 để di chuyển giữa các bookmark với nhau.

Nhưng với Eclipse thì khác, sau khi ta add bookmark bằng phím Ctrl + F2, ta dùng phím F2 để move thì không được, vì mặc định Eclipse không có chức năng này. Để bật lên, ta cần config như sau: Continue reading

Remove Windows 7 Genuine

Khi cài phần mềm không đúng, bạn sẽ thấy lỗi “This copy of Windows is not genuine”. Để fix nó, bạn có thể kiểm tra theo tuần tự các bước sau:

1) Kiểm tra đã active window 7 chưa, nếu chưa thì active trước.
2) Vào cmd bằng quyền Admin. Gõ "SLMGR –REARM"
3) Nếu bị lỗi "Error: 0xC004D307 The maximum allowed number of re-arms has been exceeded. You must re-install the OS before trying to re-arm again"
Thì vào: [HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows NT/CurrentVersion/SoftwareProtectionPlatform]
Sửa “SkipRearm”=dword:00000000 thành 00000001.

Cuối cùng thì Restart lại máy.

10 Signs That You Are An Awesome Web Developer

So you know how to make a website or two. But are you worthy enough to be called an awesome web developer? Here are 10 positive signs that you are.

1. You use a framework
Even if you are a rockstar programmer, a web development framework makes a lot of sense. It gives you a collection of good practices and libraries that let you concentrate on your web app, instead of reinventing the wheel. As a bonus, you get things like templating, pretty URLs, session management, ORM, testing facilities and more for free. A framework leads to easier to manage code and minimizes the chances for security issues to arise, so you probably should use one. See a huge list of frameworks here.

2. You use version control
Version control systems allow you to keep track of every change that you’ve made to your code, to compare, branch and work collaboratively without stepping on your team members’ toes. Git is the most popular system with web developers today and it is easy to get started with – you can turn your project folder into a repository with a single init command. Experienced web developers make full use of git’s advanced abilities, but so can you – every IDE offers integration with it these days, so even if you don’t know the commands there is a lot that you can do with git.

3. You reuse code
Reinventing the wheel and the NIH syndrome are big issues for programmers. You might have spent a day coding, feeling incredibly productive, only to discover that a 30 second Google search would have revealed a library that does exactly what you need. A positive trait of awesome developers is that they use their language’s package managers to search for libraries that they can use before solving the problems themselves. Every language has an online repository that makes things easy to find – PHP’s Packagist, Node’s NPM, Ruby’s Gemsand more. The same issues apply to reusing one’s own code. Extracting common functionality as libraries can save you time in the long run.

4. You write tests
You should never trust that your code is bug free only because everything works when you refresh the browser tab. Things can break in subtle and unforeseen ways. Awesome web developers know that automated testing is the only way to be certain that their apps work and continue to work after every code change. Testing takes many complimentary forms. Your framework likely has built-in facilities for constructing and running tests. There are also tools like seleinum which you can use to simulate how a user would interact with your site.

5. You take security seriously
CSRF, SQL injection attacks, XSS, session fixation, MITM attacks are only some of the hot topics that a security minded developer should be aware of. Luckily, your framework’s authors have to worry about these issues, but it is important that you know what the threats are and how to mitigate them. Here is a video tutorial series to get you started.

6. You document your code
Experienced developers know that code is written once, but read many times. This is why they try to make their code as easy as possible to understand by naming their variables and functions descriptively, and by leaving plenty of comments. Every language has conventions for writing doc blocks – descriptions that appear before every class or method. They describe the parameters expected by the method, and can be picked up by an IDE and shown contextually, or by a program that turns these comments into HTML documentation.
Other developers even take the time and write down the architecture of their apps and the technical decisions behind it in a wiki or another document. Such documentation is very valuable in a team setting, where new developers can join at any time. Even if you don’t go all the way and write documentation, making it a habit to leave comments in your code will still win you the awesome badge.

7. You can set up a web server from scratch
Basic administration skills can go a long way if you are a web developer. After all, every site that you create needs to be run on a properly configured web server. Knowing how things work will help you debug problems, set up your development environment, and to save on hosting bills by running your own server. Another place where such skills can be handy is in setting up a deployment strategy. Uploading stuff via ftp is prone to error as well as insecure. Here is a nice collection of guides to get you started with system administration.

8. You keep track of new libraries and tools
Web development is an extremely dynamic part of the software industry. Every year there are major new libraries, automation tools, build systems, css frameworks and preprocessors, and even languages that compile down to JavaScript. Awesome web developers are able to keep up with what is new, and are open to change. But they don’t adopt every new tool or framework they come across. They know that their time is valuable and treat everything they learn as an investment. A library should have an active and enthusiastic community, good documentation and clear benefits over the old way of doing things before they consider it seriously. Our twitter feed is a great place to learn about what’s new in web dev.

9. You manage your time efficiently
Everybody knows what it is like to waste hours in front of your computer, doing everything except working on the things you are supposed to. Awesome web developers don’t have this problem. They are able to plan a week in advance, break down large tasks into smaller ones, and start working first thing in the morning. They start with the easy things and move on to harder problems while picking up speed. They know where they work best – some are more productive from home, others from the office, and third from coffee shops or other public places. Here are some time management tips.

10. You know how to stay healthy
Although it is in the lifestyle category, staying healthy has everything to do with your productivity as a programmer. We spend most of our days sitting and staring at computer screens half a meter away. This can lead to everything from chronic back and neck pain, eye problems, weight gain and more. It is not difficult to prevent these problems – taking breaks, going for a midday walk, doing the 7 minute workout in the evenings and getting plenty of sleep can have a good energizing effect on your mind.