ModSecurity: Instalasi: Difference between revisions

From OnnoCenterWiki
Jump to navigationJump to search
Onnowpurbo (talk | contribs)
New page: How To Set Up mod_security with Apache on Debian/Ubuntu Author: Jesin A • Published: Oct 21, 2013 • Updated: Aug 29, 2014 Subscribe Tagged In: Security, Apache, PHP, MariaDB, MySQL •...
 
 
(30 intermediate revisions by one other user not shown)
Line 1: Line 1:
How To Set Up mod_security with Apache on Debian/Ubuntu
Sumber: https://www.digitalocean.com/community/tutorials/how-to-set-up-mod_security-with-apache-on-debian-ubuntu
Author: Jesin A • Published: Oct 21, 2013 • Updated: Aug 29, 2014
Subscribe
Tagged In: Security, Apache, PHP, MariaDB, MySQL • Difficulty: Advanced
Prelude


Mod security is a free Web Application Firewall (WAF) that works with Apache, Nginx and IIS. It supports a flexible rule engine to perform simple and complex operations and comes with a Core Rule Set (CRS) which has rules for SQL injection, cross site scripting, Trojans, bad user agents, session hijacking and a lot of other exploits. For Apache, it is an additional module which makes it easy to install and configure.
Cara Set Up mod_security dengan Apache di Debian / Ubuntu


In order to complete this tutorial, you will need LAMP installed on your server.
Mod security adalah  Web Application Firewall (WAF) gratis yang bekerja dengan Apache, Nginx dan IIS. Mendukung aturan yang fleksibel untuk melakukan operasi sederhana dan kompleks dan dilengkapi dengan Core Rule Set (CRS) yang memiliki aturan untuk injeksi SQL, cross site scripting scripting, Trojans, user agen yang jahat, session hijacking dan banyak eksploit lainnya. Untuk Apache, ini adalah modul tambahan yang membuatnya mudah untuk menginstal dan mengkonfigurasi.
Installing mod_security


Modsecurity is available in the Debian/Ubuntu repository:
Dalam rangka untuk menyelesaikan tutorial ini, Anda akan perlu LAMP diinstal pada server anda.


apt-get install libapache2-modsecurity
==Kebutuhan==


Verify if the mod_security module was loaded.
* Instalasi Ubuntu LTS server, or yang terbaru di mesin anda.
* Instalasi Apache2 webserver, di setup dan di konfigurasi:
 
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
 
apt-get install apache2 php7.0 php7.0-xmlrpc php7.0-mysql php7.0-gd php7.0-cli \
php7.0-curl mysql-client mysql-server dovecot-common dovecot-imapd \
dovecot-pop3d postfix php7.0 php5.6 \
php5.6-mysql php5.6-mbstring php-mbstring php7.0-mbstring \
php-xdebug libapache2-mod-php5.6 libapache2-mod-php7.0
 
* Instalasi dependensi yang dibutuhkan untuk modsecurity
 
sudo apt-get install libxml2 libxml2-dev libxml2-utils \
libaprutil1 libaprutil1-dev
 
* Untuk mengguna 64bit, perlu menambahkan link berikut
 
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so /usr/lib/libxml2.so
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2 /usr/lib/libxml2.so.2
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1 /usr/lib/libxml2.so.2.9.1
 
==Instalasi mod_security==
 
Instalasi ModSecurity
 
sudo su
apt-get install libapache2-modsecurity modsecurity-crs
 
Untuk ubuntu 22.04
 
sudo su
apt-get install libapache2-mod-security2 modsecurity-crs
 
Periksa apakah modul mod_security dimuat.


  apachectl -M | grep --color security
  apachectl -M | grep --color security


You should see a module named security2_module (shared) which indicates that the module was loaded.
Akan keluar
 
security2_module (shared)
 
Anda akan melihat modul bernama security2_module (shared) yang menunjukkan bahwa modul dimuat.


Modsecurity's installation includes a recommended configuration file which has to be renamed:
Instalasi ModSecurity meliputi file konfigurasi yang disarankan yang harus diganti:


  mv /etc/modsecurity/modsecurity.conf{-recommended,}
  mv /etc/modsecurity/modsecurity.conf{-recommended,}
Line 28: Line 62:
  service apache2 reload
  service apache2 reload


You'll find a new log file for mod_security in the Apache log directory:
Cek directory log Apache, akan ada file
 
ls -l /var/log/apache2/modsec_audit.log


root@droplet:~# ls -l /var/log/apache2/modsec_audit.log
  -rw-r----- 1 root root 0 Mar 30 14:07 /var/log/apache2/modsec_audit.log
  -rw-r----- 1 root root 0 Oct 19 08:08 /var/log/apache2/modsec_audit.log


Configuring mod_security
==Konfigurasi mod_security==


Out of the box, modsecurity doesn't do anything as it needs rules to work. The default configuration file is set to DetectionOnly which logs requests according to rule matches and doesn't block anything. This can be changed by editing the modsecurity.conf file:
Apa adanya, ModSecurity tidak melakukan apa-apa karena kebutuhan aturan untuk bekerja. File konfigurasi default diset ke DetectionOnly yang mencatat permintaan sesuai dengan aturan yang cocok dan tidak memblokir apa-apa. Hal ini dapat diubah dengan mengedit file modsecurity.conf:


  nano /etc/modsecurity/modsecurity.conf
  nano /etc/modsecurity/modsecurity.conf


Find this line
Temukan kalimat ini


  SecRuleEngine DetectionOnly
  SecRuleEngine DetectionOnly


and change it to:
Ubah menjadi


  SecRuleEngine On
  SecRuleEngine On


If you're trying this out on a production server, change this directive only after testing all your rules.
Jika Anda mencoba ini pada server produksi, ubah direktif ini hanya setelah menguji semua aturan Anda.


Another directive to modify is SecResponseBodyAccess. This configures whether response bodies are buffered (i.e. read by modsecurity). This is only neccessary if data leakage detection and protection is required. Therefore, leaving it On will use up droplet resources and also increase the logfile size.
Direktif lain yang perlu dimodifikasi adalah SecResponseBodyAccess. Ini mengkonfigurasi apakah tubuh respon dibuffered (yaitu dibaca oleh ModSecurity). Ini hanya diperlukan jika deteksi kebocoran data dan perlindungan diperlukan. Oleh karena itu, membiarkannya On akan menggunakan sumber daya droplet dan juga meningkatkan ukuran logfile.


Find this
Temukan


  SecResponseBodyAccess On
  SecResponseBodyAccess On


and change it to:
Ubah menjadi


  SecResponseBodyAccess Off
  SecResponseBodyAccess Off


Now we'll limit the maximum data that can be posted to your web application. Two directives configure these:
Sekarang kita akan membatasi data maksimum yang dapat diposting ke aplikasi web Anda. Dua parameter yang mengkonfigurasi ini:


  SecRequestBodyLimit
  SecRequestBodyLimit
  SecRequestBodyNoFilesLimit
  SecRequestBodyNoFilesLimit


The SecRequestBodyLimit directive specifies the maximum POST data size. If anything larger is sent by a client the server will respond with a 413 Request Entity Too Large error. If your web application doesn't have any file uploads this value can be greatly reduced.
Parameter SecRequestBodyLimit menentukan ukuran data POST maksimal. Jika ada yang lebih besar dikirim oleh client maka server akan merespon dengan error 413 Request Entity Too Large. Jika aplikasi web Anda tidak memiliki file upload nilai ini dapat sangat dikurangi.


The value mentioned in the configuration file is
Nilai yang disebutkan dalam file konfigurasi


  SecRequestBodyLimit 13107200
  SecRequestBodyLimit 13107200


which is 12.5MB.
yaitu 12.5MB.


Similar to this is the SecRequestBodyNoFilesLimit directive. The only difference is that this directive limits the size of POST data minus file uploads-- this value should be "as low as practical."
Sama dengan cara di atas adalah parameter SecRequestBodyNoFilesLimit . Perbedaan terutama pada besarnya data yang di POST dikurangi file uploads -- nilai ini sebaiknya "sekecil-kecilnya yang memungkinkan".


The value in the configuration file is
Nilai yang disebutkan dalam file konfigurasi


  SecRequestBodyNoFilesLimit 131072
  SecRequestBodyNoFilesLimit 131072


which is 128KB.
yaitu 128KB.


Along the lines of these directives is another one which affects server performance: SecRequestBodyInMemoryLimit. This directive is pretty much self-explanatory; it specifies how much of "request body" data (POSTed data) should be kept in the memory (RAM), anything more will be placed in the hard disk (just like swapping). Since droplets use SSDs, this is not much of an issue; however, this can be set a decent value if you have RAM to spare.
Diantara parameter-parameter diatas, parameter yang mungkin akan sangat mempengaruhi performance adalah SecRequestBodyInMemoryLimit. Parameter ini menentukan berapa banyak "request body" data (POST data) yang akan di simpan di RAM, selebihnya akan di simpan di harddisk (seperti swap). Jika kita menggunakan SSD, maka hal ini bukan sebuah masalah besar. Kita dapat menset lebih besar jika kita mempunyai RAM lebih,


  SecRequestBodyInMemoryLimit 131072
  SecRequestBodyInMemoryLimit 131072


This is the value (128KB) specified in the configuration file.
Nilai ini 128KB seperti yang di set di file konfigurasi.


==Testing SQL Injection==
==Testing SQL Injection==


Before going ahead with configuring rules, we will create a PHP script which is vulnerable to SQL injection and try it out. Please note that this is just a basic PHP login script with no session handling. Be sure to change the MySQL password in the script below so that it will connect to the database:
Sebelum melanjutkan dengan konfigurasi aturan, kita akan membuat script PHP yang rentan terhadap injeksi SQL dan mencobanya. Harap dicatat bahwa ini hanyalah sebuah script PHP untuk login tanpa penanganan sesi. Pastikan untuk mengganti password MySQL di script di bawah ini sehingga akan terhubung ke database:


  /var/www/login.php
  /var/www/html/login.php
 
Jika password root MySQL adalah 123456, maka isinya


  <html>
  <html>
Line 99: Line 136:
         $username = $_POST['username'];
         $username = $_POST['username'];
         $password = $_POST['password'];
         $password = $_POST['password'];
         $con = mysqli_connect('localhost','root','password','sample');
         $con = mysqli_connect('localhost','root','123456','sample');
         $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
         $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
         if(mysqli_num_rows($result) == 0)
         if(mysqli_num_rows($result) == 0)
             echo 'Invalid username or password';
             echo 'Invalid username or password';
         else
         else
             echo '<h1>Logged in</h1><p>A Secret for you....</p>';
             echo 'Logged in - A Secret for you....';
     }
     }
     else
     else
Line 120: Line 157:
  </html>
  </html>


This script will display a login form. Entering the right credentials will display a message "A Secret for you."


We need credentials in the database. Create a MySQL database and a table, then insert usernames and passwords.


mysql -u root -p
Script ini akan menampilkan form login. Dengan memasukan password yang tepat akan menampilkan pesan "A Secret for you."


This will take you to the mysql> prompt
Kita perlu password dalam database. Buat database MySQL dan table, kemudian masukkan username dan password.
 
mysql -u root -p123456


  create database sample;
  create database sample;
Line 135: Line 172:
  quit;
  quit;


Open your browser, navigate to http://yourwebsite.com/login.php and enter the right pair of credentials.
Buka browser, masuk ke
 
http://ip-address-web-anda/login.php
 
misalnya
 
http://192.168.0.100/login.php
 
dan masukan pasangan kredensial


  Username: jesin
  Username: jesin
  Password: pwd
  Password: pwd


You'll see a message that indicates successful login. Now come back and enter a wrong pair of credentials-- you'll see the message Invalid username or password.
Kita akan melihat message yang mengindikasikan login sukses. Coba lagi, tapi masukan pasangan kredential yang salah -- kita akan melihat message
 
Invalid username or password  
 


We can confirm that the script works right. The next job is to try our hand with SQL injection to bypass the login page. Enter the following for the username field:
Langkah selanjutnya, kita dapat mencoba SQL injection untuk mem-bypass login page. Masukan perintah berikut di username:


  ' or true --  
  ' or true --  


Note that there should be a space after -- this injection won't work without that space. Leave the password field empty and hit the login button.
Perhatikan ada "spasi" sesudah -- , jika "spasi" tidak di tambahkan sesudah -- maka SQL injection ini tidak akan jalan. Biarkan password kosong. Tekan tombol login.
 
Simsalabim! script akan memperlihatkan semua message yang harusnya untuk user yang terauthentikasi!
 
==Set Up Rules / Aturan==
 
Untuk membuat hidup kita lebih mudah, akan banyak aturan yang di install bersama dengan mod_security. Hal ini di sebut CRS (Core Rule Set) dan lokasinya di


Voila! The script shows the message meant for authenticated users.
ls -l /usr/share/modsecurity-crs/


==Setting Up Rules==
total 44
drwxr-xr-x 2 root root  4096 Mar 31 06:15 activated_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 base_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 experimental_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 lua
-rw-r--r-- 1 root root 13774 Jul 13  2013 modsecurity_crs_10_setup.conf
drwxr-xr-x 2 root root  4096 Mar 31 06:15 optional_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 slr_rules
drwxr-xr-x 8 root root  4096 Mar 31 06:15 util


To make your life easier, there are a lot of rules which are already installed along with mod_security. These are called CRS (Core Rule Set) and are located in
Dokumen tersedia di


  root@droplet:~# ls -l /usr/share/modsecurity-crs/
  ls -l /usr/share/doc/modsecurity-crs/
total 40
drwxr-xr-x 2 root root  4096 Oct 20 09:45 activated_rules
drwxr-xr-x 2 root root  4096 Oct 20 09:45 base_rules
drwxr-xr-x 2 root root  4096 Oct 20 09:45 experimental_rules
drwxr-xr-x 2 root root  4096 Oct 20 09:45 lua
-rw-r--r-- 1 root root 13544 Jul  2  2012 modsecurity_crs_10_setup.conf
drwxr-xr-x 2 root root  4096 Oct 20 09:45 optional_rules
drwxr-xr-x 3 root root  4096 Oct 20 09:45 util


The documentation is available at
total 16
-rw-r--r-- 1 root root  623 Jul 12  2013 changelog.Debian.gz
-rw-r--r-- 1 root root 1297 Jul  2  2012 copyright
-rw-r--r-- 1 root root 1138 Mar 16  2012 README.Debian
-rw-r--r-- 1 root root 1485 Jul  2  2013 README.md


root@droplet1:~# ls -l /usr/share/doc/modsecurity-crs/
total 40
-rw-r--r-- 1 root root  469 Jul  2  2012 changelog.Debian.gz
-rw-r--r-- 1 root root 12387 Jun 18  2012 changelog.gz
-rw-r--r-- 1 root root  1297 Jul  2  2012 copyright
drwxr-xr-x 3 root root  4096 Oct 20 09:45 examples
-rw-r--r-- 1 root root  1138 Mar 16  2012 README.Debian
-rw-r--r-- 1 root root  6495 Mar 16  2012 README.gz


To load these rules, we need to tell Apache to look into these directories. Edit the mod-security.conf file.
Untuk me-load aturan / rules ini, kita perlu memberitahukan Apache untuk melihat directory tersebut. Edit file mod-security.conf


  nano /etc/apache2/mods-enabled/mod-security.conf
  vi /etc/apache2/mods-enabled/security2.conf


Add the following directives inside <IfModule security2_module> </IfModule>:
Tambahkan aturan berikut di dalam <IfModule security2_module> </IfModule>:


  Include "/usr/share/modsecurity-crs/*.conf"
  Include "/usr/share/modsecurity-crs/*.conf"
  Include "/usr/share/modsecurity-crs/activated_rules/*.conf"
  Include "/usr/share/modsecurity-crs/activated_rules/*.conf"


The activated_rules directory is similar to Apache's mods-enabled directory. The rules are available in directories:
Directory activated_rules sama dengan directory mods-enabled pada Apache. Rules / Aturan yang ada tersedia di directory:


  /usr/share/modsecurity-crs/base_rules
  /usr/share/modsecurity-crs/base_rules
Line 190: Line 240:
  /usr/share/modsecurity-crs/experimental_rules
  /usr/share/modsecurity-crs/experimental_rules


Symlinks must be created inside the activated_rules directory to activate these. Let us activate the SQL injection rules.
Kita perlu membuat symlinks di dalam directory activated_rules untuk mengaktifkan aturan tersebut.  
 
Contoh, untuk mengaktifkan rules / aturan SQL injection.


  cd /usr/share/modsecurity-crs/activated_rules/
  cd /usr/share/modsecurity-crs/activated_rules/
  ln -s /usr/share/modsecurity-crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf .
  ln -s /usr/share/modsecurity-crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf .


Apache has to be reloaded for the rules to take effect.
Apache harus di reload agar rules beroperasi / berefek.


  service apache2 reload
  service apache2 reload


Now open the login page we created earlier and try using the SQL injection query on the username field. If you had changed the SecRuleEngine directive to On, you'll see a 403 Forbidden error. If it was left to the DetectionOnly option, the injection will be successful but the attempt would be logged in the modsec_audit.log file.
Sekarang buka halaman login yang kita buat sebelumnya dan coba menggunakan SQL injection query pada kolom username. Jika kita sudah mengubah SecRuleEngine menjadi On, kita akan melihat 403 Forbidden error.  
Writing Your Own mod_security Rules


In this section, we'll create a rule chain which blocks the request if certain "spammy" words are entered in a HTML form. First, we'll create a PHP script which gets the input from a textbox and displays it back to the user.
Jadi semua tergantung pada opsi DetectionOnly, injection akan berhasil tapi akan tercatat pada file modsec_audit.log .


  /var/www/form.php
 
==Menulis Rules mod_security sendiri==
 
Pada bagian ini, kita akan mencoba membuat aturan yang akan memblok request juga ada kata-kata "yang tidak di inginkan" di masukan ke dalam form HTML.
 
Pertama-tama, kita akan membuat script PHP yang akan mengambil input dari textbox dan akan menampilkannya kembali ke user.
 
  /var/www/html/form.php
 
isinya


  <html>
  <html>
Line 224: Line 284:
  </html>
  </html>


Custom rules can be added to any of the configuration files or placed in modsecurity directories. We'll place our rules in a separate new file.
Custom rules dapat di tambahkan ke semua file konfigurasi atau di letakan di directory modsecurity. Kita akan mencoba untuk menempatkan aturan / rules kita di sebuah file baru:


  nano /etc/modsecurity/modsecurity_custom_rules.conf
  vi /etc/modsecurity/modsecurity_custom_rules.conf


Add the following to this file:
Tambahkan perintah kalimat berikut:


  SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
  SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
Line 234: Line 294:
  SecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"
  SecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"


Save the file and reload Apache. Open http://yourwebsite.com/form.php in the browser and enter text containing any of these words: pills, insurance, rolex.
Save file kemudian reload Apache. Buka lagi
 
http://websiteanda.com/form.php
 
atau (contoh)
 
http://192.168.0.100/form.php
 
 
Masuk ke browser dan masukan text yang ada kata-kata: pills, insurance, rolex.


You'll either see a 403 page and a log entry or only a log entry based on SecRuleEngine setting. The syntax for SecRule is
Anda akan akan melihat halman 403 dan catatan di log, atau hanya catatan di log berdasarkan konfigurasi SecRuleEngine. Sintaks untuk SecRule adalah


  SecRule VARIABLES OPERATOR [ACTIONS]
  SecRule VARIABLES OPERATOR [ACTIONS]


Here we used the chain action to match variables REQUEST_FILENAME with form.php, REQUEST_METHOD with POST and REQUEST_BODY with the regular expression (@rx) string (pills|insurance|rolex). The ?i: does a case insensitive match. On a successful match of all these three rules, the ACTION is to deny and log with the msg "Spam detected." The chain action simulates the logical AND to match all the three rules.
Disini kita menggunakan chain action untuk mencocokan variable REQUEST_FILENAME dengan form.php, REQUEST_METHOD dengan POST dan REQUEST_BODY dengan regular expression (@rx) string (pills|insurance|rolex). Variable ?i: melakukan pencocokan yang tidak case sensitive. Jika ke tiga aturan tersebut berhasil cocok dengan baik, ACTION yang dilakukan adalah menolak dan mencatat di log dengan message "Spam detected." Chain action mensimulasi operasi logical AND untuk mencocokan ke tiga rules / aturan.


==Excluding Hosts and Directories==
==Excluding Host dan Directory==


Sometimes it makes sense to exclude a particular directory or a domain name if it is running an application like phpMyAdmin as modsecurity and will block SQL queries. It is also better to exclude admin backends of CMS applications like WordPress.
Kadang kala ada baiknya kita meng-exclude directory tertentu atau domain name jika dia menjalankan aplikasi seperti phpMyAdmin karena modsecurity akan memblok SQL queries. Juga sebaiknya meng-exclude admin backend dari aplikasi CMS seperti WordPress.


To disable modsecurity for a complete VirtualHost place the following
Untuk men-disable modsecurity untuk sebuah VirtualHost lakukan / tambahkan sebagai berikut


  <IfModule security2_module>
  <IfModule security2_module>
Line 252: Line 321:
  </IfModule>
  </IfModule>


inside the <VirtualHost> section.
dalam bagian <VirtualHost>


For a particular directory:
Untuk directory tertentu:


  <Directory "/var/www/wp-admin">
  <Directory "/var/www/wp-admin">
Line 262: Line 331:
  </Directory>
  </Directory>


If you don't want to completely disable modsecurity, use the SecRuleRemoveById directive to remove a particular rule or rule chain by specifying its ID.
Jika kita tidak ingin mem-disable secara penuh modsecurity, gunakan SecRuleRemoveById untuk membuang aturan / rule / rule chain tertentu dengan menentukan ID-nya sebagai berikut


  <LocationMatch "/wp-admin/update.php">
  <LocationMatch "/wp-admin/update.php">
Line 269: Line 338:
     </IfModule>
     </IfModule>
  </LocationMatch>
  </LocationMatch>
Further Reading
Official modsecurity documentation


==Referensi==
==Referensi==

Latest revision as of 21:57, 22 January 2024

Sumber: https://www.digitalocean.com/community/tutorials/how-to-set-up-mod_security-with-apache-on-debian-ubuntu

Cara Set Up mod_security dengan Apache di Debian / Ubuntu

Mod security adalah Web Application Firewall (WAF) gratis yang bekerja dengan Apache, Nginx dan IIS. Mendukung aturan yang fleksibel untuk melakukan operasi sederhana dan kompleks dan dilengkapi dengan Core Rule Set (CRS) yang memiliki aturan untuk injeksi SQL, cross site scripting scripting, Trojans, user agen yang jahat, session hijacking dan banyak eksploit lainnya. Untuk Apache, ini adalah modul tambahan yang membuatnya mudah untuk menginstal dan mengkonfigurasi.

Dalam rangka untuk menyelesaikan tutorial ini, Anda akan perlu LAMP diinstal pada server anda.

Kebutuhan

  • Instalasi Ubuntu LTS server, or yang terbaru di mesin anda.
  • Instalasi Apache2 webserver, di setup dan di konfigurasi:
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
apt-get install apache2 php7.0 php7.0-xmlrpc php7.0-mysql php7.0-gd php7.0-cli \
php7.0-curl mysql-client mysql-server dovecot-common dovecot-imapd \
dovecot-pop3d postfix php7.0 php5.6 \
php5.6-mysql php5.6-mbstring php-mbstring php7.0-mbstring \
php-xdebug libapache2-mod-php5.6 libapache2-mod-php7.0
  • Instalasi dependensi yang dibutuhkan untuk modsecurity
sudo apt-get install libxml2 libxml2-dev libxml2-utils \
libaprutil1 libaprutil1-dev
  • Untuk mengguna 64bit, perlu menambahkan link berikut
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so /usr/lib/libxml2.so
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2 /usr/lib/libxml2.so.2
ln -s /usr/lib/x86_64-linux-gnu/libxml2.so.2.9.1 /usr/lib/libxml2.so.2.9.1

Instalasi mod_security

Instalasi ModSecurity

sudo su
apt-get install libapache2-modsecurity modsecurity-crs

Untuk ubuntu 22.04

sudo su
apt-get install libapache2-mod-security2 modsecurity-crs

Periksa apakah modul mod_security dimuat.

apachectl -M | grep --color security

Akan keluar

security2_module (shared)

Anda akan melihat modul bernama security2_module (shared) yang menunjukkan bahwa modul dimuat.

Instalasi ModSecurity meliputi file konfigurasi yang disarankan yang harus diganti:

mv /etc/modsecurity/modsecurity.conf{-recommended,}

Reload Apache

service apache2 reload

Cek directory log Apache, akan ada file

ls -l /var/log/apache2/modsec_audit.log
-rw-r----- 1 root root 0 Mar 30 14:07 /var/log/apache2/modsec_audit.log

Konfigurasi mod_security

Apa adanya, ModSecurity tidak melakukan apa-apa karena kebutuhan aturan untuk bekerja. File konfigurasi default diset ke DetectionOnly yang mencatat permintaan sesuai dengan aturan yang cocok dan tidak memblokir apa-apa. Hal ini dapat diubah dengan mengedit file modsecurity.conf:

nano /etc/modsecurity/modsecurity.conf

Temukan kalimat ini

SecRuleEngine DetectionOnly

Ubah menjadi

SecRuleEngine On

Jika Anda mencoba ini pada server produksi, ubah direktif ini hanya setelah menguji semua aturan Anda.

Direktif lain yang perlu dimodifikasi adalah SecResponseBodyAccess. Ini mengkonfigurasi apakah tubuh respon dibuffered (yaitu dibaca oleh ModSecurity). Ini hanya diperlukan jika deteksi kebocoran data dan perlindungan diperlukan. Oleh karena itu, membiarkannya On akan menggunakan sumber daya droplet dan juga meningkatkan ukuran logfile.

Temukan

SecResponseBodyAccess On

Ubah menjadi

SecResponseBodyAccess Off

Sekarang kita akan membatasi data maksimum yang dapat diposting ke aplikasi web Anda. Dua parameter yang mengkonfigurasi ini:

SecRequestBodyLimit
SecRequestBodyNoFilesLimit

Parameter SecRequestBodyLimit menentukan ukuran data POST maksimal. Jika ada yang lebih besar dikirim oleh client maka server akan merespon dengan error 413 Request Entity Too Large. Jika aplikasi web Anda tidak memiliki file upload nilai ini dapat sangat dikurangi.

Nilai yang disebutkan dalam file konfigurasi

SecRequestBodyLimit 13107200

yaitu 12.5MB.

Sama dengan cara di atas adalah parameter SecRequestBodyNoFilesLimit . Perbedaan terutama pada besarnya data yang di POST dikurangi file uploads -- nilai ini sebaiknya "sekecil-kecilnya yang memungkinkan".

Nilai yang disebutkan dalam file konfigurasi

SecRequestBodyNoFilesLimit 131072

yaitu 128KB.

Diantara parameter-parameter diatas, parameter yang mungkin akan sangat mempengaruhi performance adalah SecRequestBodyInMemoryLimit. Parameter ini menentukan berapa banyak "request body" data (POST data) yang akan di simpan di RAM, selebihnya akan di simpan di harddisk (seperti swap). Jika kita menggunakan SSD, maka hal ini bukan sebuah masalah besar. Kita dapat menset lebih besar jika kita mempunyai RAM lebih,

SecRequestBodyInMemoryLimit 131072

Nilai ini 128KB seperti yang di set di file konfigurasi.

Testing SQL Injection

Sebelum melanjutkan dengan konfigurasi aturan, kita akan membuat script PHP yang rentan terhadap injeksi SQL dan mencobanya. Harap dicatat bahwa ini hanyalah sebuah script PHP untuk login tanpa penanganan sesi. Pastikan untuk mengganti password MySQL di script di bawah ini sehingga akan terhubung ke database:

/var/www/html/login.php

Jika password root MySQL adalah 123456, maka isinya

<html>
<body>
<?php
    if(isset($_POST['login']))
    {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $con = mysqli_connect('localhost','root','123456','sample');
        $result = mysqli_query($con, "SELECT * FROM `users` WHERE username='$username' AND password='$password'");
        if(mysqli_num_rows($result) == 0)
            echo 'Invalid username or password';
        else
            echo 'Logged in - A Secret for you....';
    }
    else
    {
?>
        <form action="" method="post">
            Username: <input type="text" name="username"/>
Password: <input type="password" name="password"/>
<input type="submit" name="login" value="Login"/> </form> <?php } ?> </body> </html>


Script ini akan menampilkan form login. Dengan memasukan password yang tepat akan menampilkan pesan "A Secret for you."

Kita perlu password dalam database. Buat database MySQL dan table, kemudian masukkan username dan password.

mysql -u root -p123456
create database sample;
connect sample;
create table users(username VARCHAR(100),password VARCHAR(100));
insert into users values('jesin','pwd');
insert into users values('alice','secret');
quit;

Buka browser, masuk ke

http://ip-address-web-anda/login.php

misalnya

http://192.168.0.100/login.php

dan masukan pasangan kredensial

Username: jesin
Password: pwd

Kita akan melihat message yang mengindikasikan login sukses. Coba lagi, tapi masukan pasangan kredential yang salah -- kita akan melihat message

Invalid username or password 


Langkah selanjutnya, kita dapat mencoba SQL injection untuk mem-bypass login page. Masukan perintah berikut di username:

' or true -- 

Perhatikan ada "spasi" sesudah -- , jika "spasi" tidak di tambahkan sesudah -- maka SQL injection ini tidak akan jalan. Biarkan password kosong. Tekan tombol login.

Simsalabim! script akan memperlihatkan semua message yang harusnya untuk user yang terauthentikasi!

Set Up Rules / Aturan

Untuk membuat hidup kita lebih mudah, akan banyak aturan yang di install bersama dengan mod_security. Hal ini di sebut CRS (Core Rule Set) dan lokasinya di

ls -l /usr/share/modsecurity-crs/
total 44
drwxr-xr-x 2 root root  4096 Mar 31 06:15 activated_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 base_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 experimental_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 lua
-rw-r--r-- 1 root root 13774 Jul 13  2013 modsecurity_crs_10_setup.conf
drwxr-xr-x 2 root root  4096 Mar 31 06:15 optional_rules
drwxr-xr-x 2 root root  4096 Mar 31 06:15 slr_rules
drwxr-xr-x 8 root root  4096 Mar 31 06:15 util

Dokumen tersedia di

ls -l /usr/share/doc/modsecurity-crs/
total 16
-rw-r--r-- 1 root root  623 Jul 12  2013 changelog.Debian.gz
-rw-r--r-- 1 root root 1297 Jul  2  2012 copyright
-rw-r--r-- 1 root root 1138 Mar 16  2012 README.Debian
-rw-r--r-- 1 root root 1485 Jul  2  2013 README.md


Untuk me-load aturan / rules ini, kita perlu memberitahukan Apache untuk melihat directory tersebut. Edit file mod-security.conf

vi /etc/apache2/mods-enabled/security2.conf

Tambahkan aturan berikut di dalam <IfModule security2_module> </IfModule>:

Include "/usr/share/modsecurity-crs/*.conf"
Include "/usr/share/modsecurity-crs/activated_rules/*.conf"

Directory activated_rules sama dengan directory mods-enabled pada Apache. Rules / Aturan yang ada tersedia di directory:

/usr/share/modsecurity-crs/base_rules
/usr/share/modsecurity-crs/optional_rules
/usr/share/modsecurity-crs/experimental_rules

Kita perlu membuat symlinks di dalam directory activated_rules untuk mengaktifkan aturan tersebut.

Contoh, untuk mengaktifkan rules / aturan SQL injection.

cd /usr/share/modsecurity-crs/activated_rules/
ln -s /usr/share/modsecurity-crs/base_rules/modsecurity_crs_41_sql_injection_attacks.conf .

Apache harus di reload agar rules beroperasi / berefek.

service apache2 reload

Sekarang buka halaman login yang kita buat sebelumnya dan coba menggunakan SQL injection query pada kolom username. Jika kita sudah mengubah SecRuleEngine menjadi On, kita akan melihat 403 Forbidden error.

Jadi semua tergantung pada opsi DetectionOnly, injection akan berhasil tapi akan tercatat pada file modsec_audit.log .


Pada bagian ini, kita akan mencoba membuat aturan yang akan memblok request juga ada kata-kata "yang tidak di inginkan" di masukan ke dalam form HTML.

Pertama-tama, kita akan membuat script PHP yang akan mengambil input dari textbox dan akan menampilkannya kembali ke user.

/var/www/html/form.php

isinya

<html>
    <body>
        <?php
            if(isset($_POST['data']))
                echo $_POST['data'];
            else
            {
        ?>
                <form method="post" action="">
                        Enter something here:<textarea name="data"></textarea>
                        <input type="submit"/>
                </form>
        <?php
            }
        ?>
    </body>
</html>

Custom rules dapat di tambahkan ke semua file konfigurasi atau di letakan di directory modsecurity. Kita akan mencoba untuk menempatkan aturan / rules kita di sebuah file baru:

vi /etc/modsecurity/modsecurity_custom_rules.conf

Tambahkan perintah kalimat berikut:

SecRule REQUEST_FILENAME "form.php" "id:'400001',chain,deny,log,msg:'Spam detected'"
SecRule REQUEST_METHOD "POST" chain
SecRule REQUEST_BODY "@rx (?i:(pills|insurance|rolex))"

Save file kemudian reload Apache. Buka lagi

http://websiteanda.com/form.php

atau (contoh)

http://192.168.0.100/form.php


Masuk ke browser dan masukan text yang ada kata-kata: pills, insurance, rolex.

Anda akan akan melihat halman 403 dan catatan di log, atau hanya catatan di log berdasarkan konfigurasi SecRuleEngine. Sintaks untuk SecRule adalah

SecRule VARIABLES OPERATOR [ACTIONS]

Disini kita menggunakan chain action untuk mencocokan variable REQUEST_FILENAME dengan form.php, REQUEST_METHOD dengan POST dan REQUEST_BODY dengan regular expression (@rx) string (pills|insurance|rolex). Variable ?i: melakukan pencocokan yang tidak case sensitive. Jika ke tiga aturan tersebut berhasil cocok dengan baik, ACTION yang dilakukan adalah menolak dan mencatat di log dengan message "Spam detected." Chain action mensimulasi operasi logical AND untuk mencocokan ke tiga rules / aturan.

Excluding Host dan Directory

Kadang kala ada baiknya kita meng-exclude directory tertentu atau domain name jika dia menjalankan aplikasi seperti phpMyAdmin karena modsecurity akan memblok SQL queries. Juga sebaiknya meng-exclude admin backend dari aplikasi CMS seperti WordPress.

Untuk men-disable modsecurity untuk sebuah VirtualHost lakukan / tambahkan sebagai berikut

<IfModule security2_module>
    SecRuleEngine Off
</IfModule>

dalam bagian <VirtualHost>

Untuk directory tertentu:

<Directory "/var/www/wp-admin">
    <IfModule security2_module>
        SecRuleEngine Off
    </IfModule>
</Directory>

Jika kita tidak ingin mem-disable secara penuh modsecurity, gunakan SecRuleRemoveById untuk membuang aturan / rule / rule chain tertentu dengan menentukan ID-nya sebagai berikut

<LocationMatch "/wp-admin/update.php">
    <IfModule security2_module>
        SecRuleRemoveById 981173
    </IfModule>
</LocationMatch>

Referensi