· 9 years ago · Jun 13, 2017, 10:50 AM
1Everyone likes a happy server, right? So let's avoid breaches and get to a professional level.
2This tutorial also includes how to search for the c99 & r57 shell (These shells were on HendrixCP that the ''hacker'' uploaded.)
3Apparently I also ''hacked'' HendrixCP. This is not true. I was actually fighting the ''hacker'' over the VPS.
4**// Discord: Zaseth#7550
5**// Skype: live:king.daan1 (Please don't resolve my Skype :p)
6----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
7Some cool stuff:
8https://piwik.org/
9https://github.com/swfobject/swfobject
10http://www.sqlparser.com/sql-injection-detector/
11http://gavinmiller.io/2015/fixing-sql-injection-vulnerabilities/
12https://www.owasp.org/index.php/Top_10_2017-Top_10
13https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
14https://www.owasp.org/index.php/Blind_SQL_Injection
15https://www.owasp.org/index.php/Blind_XPath_Injection
16https://www.owasp.org/index.php/XPATH_Injection
17https://www.owasp.org/index.php/LDAP_Injection_Prevention_Cheat_Sheet
18https://www.owasp.org/index.php/Server-Side_Includes_(SSI)_Injection
19https://www.owasp.org/index.php/Injection_problem
20https://www.owasp.org/index.php/Testing_for_SQL_Injection_(OTG-INPVAL-005)
21https://medoo.in/
22https://github.com/Maikuolan/phpMussel
23https://www.cloudbric.com/main.php
24https://github.com/djeraseit/PHP-backdoor-detector
25https://github.com/emposha/PHP-Shell-Detector
26https://www.cloudflare.com/
27http://suhosin.org/stories/index.html
28https://www.netsparker.com/
29https://laravel.com/
30https://security.appspot.com/vsftpd.html
31http://phpsec.org/projects/phpsecinfo/index.html
32https://httpd.apache.org/docs/current/suexec.html
33https://httpd.apache.org/docs/current/misc/security_tips.html
34https://www.owasp.org/index.php/Category:Attack
35http://sparta.secforce.com/
36https://sourceforge.net/projects/dirbuster/
37https://www.metasploit.com/
38https://www.owasp.org/index.php/OWASP_Xenotix_XSS_Exploit_Framework
39https://www.thc.org/thc-hydra/
40https://wpscan.org/
41https://www.nginx.com/resources/wiki/
42https://github.com/rezasp/joomscan
43https://varnish-cache.org/
44---------------------------------------------------
45Frequently asked questions // General stuff
46What is a 0day?: A 0day is an exploit where the developers are unknown of. 0day exploits are mostly private (Not shared.) but there is a big chance of it getting leaked. So you should still update.
47I have seen CPPS's using Drupal. If you decide to use Drupal, please don't use Drupal v7.x and keep it updated daily.
48I have XSS (Cross-site scripting) on my website. Should I fix it?: Yes. You should. There's a tool called Xenotic XSS Exploit Framework and you can do a ton of scary things with it.
49There is a function in MySQL to grant every user admin privileges. You should not do this because if you get hit by SQL injection that user also has admin privileges.
50Did you know you can actually change the name of your PHPMyAdmin URL login? -> https://www.tecmint.com/change-secure-phpmyadmin-login-url-page/ This will avoid some stuff.
51Should I use nulled (illegal / pirated) forum / wordpress software?: You should first check the source code for any shells and malicious code. It still is illegal though and updating can be hard.
52Should I use MD5?: No. MD5 is a mistake. (Just like SHA-1 so also don't use that.) just stick to Bcrypt (https://en.wikipedia.org/wiki/Bcrypt) your database can be leaked, but the passwords will be secure. So there's nothing to worry about the passwords. You could also encrypt user's IP addresses before storing it in the database.
53Should I use HTTPS?: Well yes. Every data will be insecure. And it's free. (https://www.openssl.org/) Please keep it updated (http://heartbleed.com/)
54What are the risks of having an old Apache version?: Well there are a lot of horrible Apache exploits. A famous one is called ''KillApache'' which is a Memory Exhaustion exploit (Remote DoS) And I hope this will wake you up of not using an old version: https://www.cvedetails.com/vulnerability-list/vendor_id-45/Apache.html
55Using a script to TEMP ipban someone giving a lot of requests could also be smart.
56How do you remove the Apache Version is Server Header?: There actually is a bug in this, but it is possible! http://apache-http-server.18135.x6.nabble.com/header-unset-server-does-not-work-td5006287.html You need mod_security (Which is actually in this tutorial!) so if you have that, set it to this: https://pastebin.com/raw/xE6eBgyq
57Wordpress plugins can also be vulnerable. So keep these updated as well!
58A simple list of admin urls can be found here: https://pastebin.com/raw/CXngT5F0
59Having a fail login limit on WP-ADMIN is also smart.
60Using strip_tags to avoid injection.
61htmlspecialchars also works fine to avoid sql injection:
62$query = htmlspecialchars($query);
63$query = mysql_real_escape_string($query);
64---------------------------------------------------
65Anti DDOS:
66index.php: https://pastebin.com/raw/mHAaJW9u
67anti_ddos.php: https://pastebin.com/raw/XWJtnHUp
68Or use: https://github.com/damog/planetalinux/blob/master/www/principal/suscripcion/lib/antiflood.hack.php
69Or use: https://blazingfast.io/
70---------------------------------------------------
71Monitoring POST Requests:
72$http_host = $_SERVER['HTTP_HOST'];
73$server_name = $_SERVER['SERVER_NAME'];
74$remote_ip = $_SERVER['REMOTE_ADDR'];
75$remote_host = $_SERVER["REMOTE_HOST"];
76$request_uri = $_SERVER['REQUEST_URI'];
77$http_ref = $_SERVER['HTTP_REFERER'];
78$query_string = $_SERVER['QUERY_STRING'];
79$user_agent = $_SERVER['HTTP_USER_AGENT'];
80$post_vars = clean(file_get_contents('php://input'));
81To deny all POST Requests (Not recommended), add this in httpd.conf:
82# deny all POST requests
83<IfModule mod_rewrite.c>
84 RewriteCond %{REQUEST_METHOD} POST
85 RewriteRule .* - [F,L]
86</IfModule>
87If you want to redirect to a specific page:
88RewriteRule .* /custom.php [R=301,L]
89---------------------------------------------------
90FastCGI PHP Configuration (Not needed but it can be useful)
91Make sure required packages are installed (httpd-devel and apr-devel required to compile mod_fastcgi), enter:
92yum install libtool httpd-devel apr-devel apr
93Then:
94cd /opt
95wget http://www.fastcgi.com/dist/mod_fastcgi-current.tar.gz
96Then:
97tar -zxvf mod_fastcgi-current.tar.gz
98cd mod_fastcgi-2.4.6/
99cp Makefile.AP2 Makefile
100Now this part is important, so please read!!!:
101for 32 bit system, enter:
102make top_dir=/usr/lib/httpd
103make install top_dir=/usr/lib/httpd
104
105for 64 bit system, enter:
106make top_dir=/usr/lib64/httpd
107make install top_dir=/usr/lib64/httpd
108
109Now for part 2:
110vi /etc/httpd/conf.d/mod_fastcgi.conf
111Add an entry to it like this:
112LoadModule fastcgi_module modules/mod_fastcgi.so
113Save & close file and restart with:
114service httpd restart
115
116Now for a small part 3:
117You need to disable mod_php5, to do so:
118mv /etc/httpd/conf.d/php.conf /etc/httpd/conf.d/php.conf.disable
119
120Now we are going to create a shell script:
121Create a script as follows in /var/www/cgi-bin/php.fcgi (or put in your virtual domain cgi-bin directory)
122#!/bin/bash
123# Shell Script To Run PHP5 using mod_fastcgi under Apache 2.x
124# Tested under Red Hat Enterprise Linux / CentOS 5.x
125### Set PATH ###
126PHP_CGI=/usr/bin/php-cgi
127PHP_FCGI_CHILDREN=4
128PHP_FCGI_MAX_REQUESTS=1000
129### no editing below ###
130export PHP_FCGI_CHILDREN
131export PHP_FCGI_MAX_REQUESTS
132exec $PHP_CGI
133Set permission, type:
134chmod +x /var/www/cgi-bin/php.fcgi
135
136You need to use AddHandler and Action directives for mod_fastcgi:
137 <directory "/var/www/html">
138 Options -Indexes FollowSymLinks +ExecCGI
139 AllowOverride AuthConfig FileInfo
140 AddHandler php5-fastcgi .php
141 Action php5-fastcgi /cgi-bin/php.fcgi
142 DirectoryIndex index.php index.html
143 Order allow,deny
144 Allow from all
145</directory>
146And finally:
147service httpd restart
148---------------------------------------------------
149Avoid PHP_SELF XSS (URI-BASED XSS):
150<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
151---------------------------------------------------
152Avoid exploits:
153Always keep your services up to date. (SSH, FTP)
154For FTP usage, use WinSCP
155Never share any password.
156Use bcrypt.
157---------------------------------------------------
158Apache Security:
159Open: httpd.conf
160Set:
161ServerSignature Off
162ServerTokens Prod
163Save File
164Restart Apache: /etc/init.d/httpd restart
165---------------------------------------------------
166ALWAYS Remove info.php!!!
167---------------------------------------------------
168sqlite3.ini:
169Solution 1) mv /etc/php.d/sqlite3.ini /etc/php.d/sqlite3.disable
170Solution 2) rm /etc/php.d/sqlite3.ini
171---------------------------------------------------
172Compiled in Modules:
173./configure --with-libdir=lib64 --with-gd --with-mysql --prefix=/usr --exec-prefix=/usr \
174--bindir=/usr/bin --sbindir=/usr/sbin --sysconfdir=/etc --datadir=/usr/share \
175--includedir=/usr/include --libexecdir=/usr/libexec --localstatedir=/var \
176--sharedstatedir=/usr/com --mandir=/usr/share/man --infodir=/usr/share/info \
177--cache-file=../config.cache --with-config-file-path=/etc \
178--with-config-file-scan-dir=/etc/php.d --enable-fastcgi \
179--enable-force-cgi-redirect
180---------------------------------------------------
181Restrict PHP Information Leakage:
182Edit /etc/php.d/secutity.ini
183Set: expose_php=Off
184Test: curl -I http://www.Yoursite.xdd/index.php
185---------------------------------------------------
186Minimize Loadable PHP Modules (Dynamic Extensions):
187Type these commands:
188cd /etc/php.d/
189mv gd.{ini,disable}
190/sbin/service httpd restart
191To enable php module called gd, enter:
192mv gd.{disable,ini}
193/sbin/service httpd restart
194---------------------------------------------------
195Log All PHP Errors:
196Edit /etc/php.d/security.ini and set the following directive:
197display_errors=Off
198log_errors=On
199error_log=/var/log/httpd/php_scripts_error.log
200---------------------------------------------------
201log all php errors to a log file:
202vi /etc/php.ini
203error_log = /var/log/php-scripts.log
204display_errors = Off
205Restart options:
206systemctl restart httpd.service
207restart php7.0-fpm
208/etc/init.d/httpd restart
209See logs: sudo tail -f /var/log/php-scripts.log
210---------------------------------------------------
211Disallow Uploading Files (This will get rid of some PHP shells. Not guaranteed though.):
212Edit /etc/php.d/security.ini and set the following directive to disable file uploads for security reasons:
213file_uploads=Off
214If users of your application need to upload files, turn this feature on by setting upload_max_filesize limits the maximum size of files that PHP will accept through uploads:
215file_uploads=On
216# user can only upload upto 1MB via php
217upload_max_filesize=1M
218---------------------------------------------------
219Turn Off Remote Code Execution:
220Edit /etc/php.d/security.ini and set the following directive:
221allow_url_fopen=Off
222allow_url_include=Off
223---------------------------------------------------
224Enable SQL Safe Mode:
225Edit /etc/php.d/security.ini and set the following directive:
226sql.safe_mode=On
227Either way:
228magic_quotes_gpc=Off
229---------------------------------------------------
230Control POST Size:
231Edit /etc/php.d/security.ini and set the following directive:
232; Set a realistic value here
233post_max_size=1K
234Edit, httpd.conf and set the following directive for DocumentRoot /var/www/html:
235<directory /var/www/html>
236<limitExcept GET POST>
237Order allow,deny
238</limitExcept>
239## Add rest of the config goes here... ##
240</directory>
241---------------------------------------------------
242Resource Control (DoS Control):
243Edit /etc/php.d/security.ini and set the following directives:
244# set in seconds
245max_execution_time = 30
246max_input_time = 30
247memory_limit = 40M
248---------------------------------------------------
249Install Suhosin Advanced Protection System for PHP:
250http://suhosin.org/stories/index.html
251Commands:
252cd /opt
253wget http://download.suhosin.org/suhosin-0.9.27.tgz
254yum install php-devel
255cd suhosin-0.9.27
256phpize
257./configure
258make
259make install
260echo 'extension=suhosin.so' > /etc/php.d/suhosin.ini
261Restart options:
262service httpd restart
263If you are using lighttpd, enter:
264service lighttpd restart
265To verify: php -v
266It should show Suhosin VersionHere
267---------------------------------------------------
268PHP Fastcgi / CGI – cgi.force_redirect Directive:
269Edit /etc/php.d/security.ini and set the following directive:
270; Enable cgi.force_redirect for security reasons in a typical *Apache+PHP-CGI/FastCGI* setup
271cgi.force_redirect=On
272---------------------------------------------------
273Disabling Dangerous PHP Functions:
274set list of functions in /etc/php.d/security.ini:
275disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
276---------------------------------------------------
277Session Path:
278The default is as follows under RHEL/CentOS/Fedora Linux:
279session.save_path="/var/lib/php/session"
280; Set the temporary directory used for storing files when doing file upload
281upload_tmp_dir="/var/lib/php/session"
282IMPORTANT: Make sure path is outside /var/www/html and not readable or writeable by any other system users:
283ls -Z /var/lib/php/
284---------------------------------------------------
285Keep PHP, Software, And OS Up to Date:
286Solution 1) yum update
287Solution 2) apt-get update && apt-get upgrade
288---------------------------------------------------
289Write Protect Apache, PHP, and, MySQL Configuration Files:
290Examples:
291chattr +i /etc/php.ini
292chattr +i /etc/php.d/*
293chattr +i /etc/my.ini
294chattr +i /etc/httpd/conf/httpd.conf
295chattr +i /etc/
296The chattr command can write protect your php file or files in /var/www/html directory too:
297chattr +i /var/www/html/file1.php
298chattr +i /var/www/html/
299---------------------------------------------------
300Use Linux Security Extensions (such as SELinux):
301First do this command:
302getsebool -a | grep httpd
303If output is:
304httpd_enable_cgi --> on
305Do this command:
306setsebool -P httpd_enable_cgi off
307---------------------------------------------------
308Install Mod_security:
309First, setup Mod_security with the following commands:
310yum install mod_security
311vi /etc/httpd/modsecurity.d/modsecurity_crs_10_config.conf
312And set this in the .conf file:
313SecRuleEngine On
314Then restart with the following command:
315service httpd restart
316To test:
317tail -f /var/log/httpd/error_log
318Important code snippets for conf files:
319## A few Examples ##
320# Do not allow to open files in /etc/
321SecFilter /etc/# Stop SQL injection
322SecFilter "delete[[:space:]]+from"
323SecFilter "select.+from"
324---------------------------------------------------
325Use Firewall To Restrict Outgoing Connections:
326In this example, allow vivek user to connect outside using port 80 (useful for RHN or centos repo access):
327/sbin/iptables -A OUTPUT -o eth0 -m owner --uid-owner vivek -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
328---------------------------------------------------
329Watch Your Logs & Auditing:
330Check Apache log:
331tail -f /var/log/httpd/error_log
332grep 'login.php' /var/log/httpd/error_log
333egrep -i "denied|error|warn" /var/log/httpd/error_log
334Check PHP log:
335tail -f /var/log/httpd/php_scripts_error.log
336grep "...etc/passwd" /var/log/httpd/php_scripts_error.log
337---------------------------------------------------
338To make you scared what PHP Backdoors can do:
339Download files
340Upload files
341Install rootkits
342Set a spam mail servers / relay server
343Set a proxy server to hide tracks
344Take control of server
345Take control of database server
346Steal all information
347Delete all information and database
348Open TCP / UDP ports and much more
349You must be asking: How Do I Search PHP Backdoors?
350HendrixCP got hit by c99 shell & r57.
351To search these:
352grep -iR 'c99' /var/www/html/
353grep -iR 'r57' /var/www/html/
354find /var/www/html/ -name \*.php -type f -print0 | xargs -0 grep c99
355grep -RPn "(passthru|shell_exec|system|base64_decode|fopen|fclose|eval)" /var/www/html/
356---------------------------------------------------
357Do you want to know how to generate SSH keys?:
358https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/
359Do you need some secure passwords?: http://passwordsgenerator.net/
360---------------------------------------------------
361Now you will read a long list of all the popular and it's fixes.
362---------------------------------------------------
363Denial of Service (MySQL)
364In order to fix this problem, you should first determine what causes this. Some suggestions:
365•Check max_connections settings in the MySQL configuration file, which is located in the MySQL installation folder for Windows systems, and /etc/my.cnf for Unix/Linux-like systems.
366•Do not use persistent connections on your code. This is possible only for PHP systems by disabling it through the setting on php.ini.mysql.allow_persistent=Off
367•Ensure you explicitly close the database connections.
368•Ensure you close opened database connections when an error occurs in the code.
369•Lower the MySQL connection timeout.
370---------------------------------------------------
371Directory Listing (Apache)
3721.Change your server configuration file. A recommended configuration for the requested directory should be in the following format:
373<Directory /{YOUR DIRECTORY}>
374 Options FollowSymLinks
375</Directory>
376Remove the Indexes option from configuration. Do not forget to remove MultiViews, as well.
3772.Configure the web server to disallow directory listing requests.
3783.Ensure that the latest security patches have been applied to the web server and the current stable version of the software is in use.
379^ This is serious though. With dirbuster and an Apache Vulnerability Wordlist you can discover a lot of critical things.
380---------------------------------------------------
381Insecure Crossdomain.xml (Can result in malicious .swf upload)
382Configure your Crossdomain.xml to prevent access from everywhere to your domain.
383Insecure usage:
384<cross-domain-policy>
385<allow-access-from domain="*" />
386</cross-domain-policy>
387Secure usage:
388<cross-domain-policy>
389<allow-access-from domain="domain.com" />
390<allow-access-from domain="www.domain.com" />
391<allow-access-from domain="*.domain.com" />
392</cross-domain-policy>
393---------------------------------------------------
394Directory Listing (Nginx)
3951.Change your nginx.conf file. A secure configuration for the requested directory should be similar to the following:
396location /{YOUR DIRECTORY} {
397 autoindex off;
398}
3992.Configure the web server to disallow directory listing requests.
4003.Ensure that the latest security patches have been applied to the web server and the current stable version of the software is in use.
401---------------------------------------------------
402WS_FTP Log File Detected
403If it is a file required by the application, change its permissions to prevent public users from accessing it. If it is not, then remove it from the web server.
404---------------------------------------------------
405.DS_Store File Found
406If it is a file required by the application, change its permissions to prevent public users from accessing it. If it is not, then remove it from the web server.
407---------------------------------------------------
408Backup File Disclosure
409Do not store backup files on production servers.
410---------------------------------------------------
411Insecure JSONP Endpoint
412•Make endpoints return the HTTP header Content-Disposition with filename attribute, forcing a file download.
413Content-Disposition: attachment; filename=f.txt
414•To be also protected from content sniffing attacks, prepend the reflected callback with /**/.
415---------------------------------------------------
416Internal IP Address Disclosure
417First, ensure this is not a false positive. If it is not a false positive, consider removing it.
418---------------------------------------------------
419Reflected File Download
420•Add Content-Disposition header with filename attribute in the HTTP response:
421Content-Disposition: attachment; filename=f.txt
422---------------------------------------------------
423SQL Injection
424A robust method for mitigating the threat of SQL injection-based vulnerabilities is to use parameterized queries (prepared statements). Almost all modern languages provide built-in libraries for this. Wherever possible, do not create dynamic SQL queries or SQL queries with string concatenation.
425---------------------------------------------------
426Apache Multiple Choices Enabled
4271.Change your server configuration file to disable spelling module. A recommended configuration for the requested directory should be in the following format:
428<Directory /{YOUR DIRECTORY}>
429 CheckSpelling Off
430</Directory>
431---------------------------------------------------
432Apache MultiViews Enabled
4331.Change your server configuration file. A recommended configuration for the requested directory should be in the following format:
434<Directory /{YOUR DIRECTORY}>
435 Options FollowSymLinks
436</Directory>
437Remove the MultiViews option from configuration.
438---------------------------------------------------
439Database Error Message Disclosure
440Do not provide any error messages on production environments. Save error messages with a reference number to a backend storage such as a text file or database, then show this number and a static user-friendly error message to the user.
441---------------------------------------------------
442Form Hijacking
443Do not allow user input to control the form tag's attributes. If the dynamic usage is necessary then use whitelisting.
444---------------------------------------------------
445Internal Server Error
446The impact may vary depending on the condition. Generally this indicates poor coding practices, not enough error checking, sanitization and whitelisting. However, there might be a bigger issue, such as SQL injection.
447---------------------------------------------------
448Passive Web Backdoor Detected
4491.Remove the identified passive web backdoor from your web server.
4502.You should investigate how this passive backdoor is placed on your system. There may be another critical vulnerability on your system that allows this placement.
451---------------------------------------------------
452Programming Error Message
453Do not provide error messages on production environments. Save error messages with a reference number to a backend storage such as a log, text file or database, then show this number and a static user-friendly error message to the user.
454---------------------------------------------------
455Username Disclosure (MySQL)
456•Error messages should be disabled.
457•Remove this kind of sensitive data from the output.
458---------------------------------------------------
459Version Disclosure (Nginx)
460Add the following line to your nginx.conf file to prevent information leakage from the SERVER header of its HTTP response:
461server_tokens off
462---------------------------------------------------
463Version Disclosure (mod_ssl)
464Configure your web server to prevent information leakage from the SERVER header of its HTTP response. To apply configuration, first make sure you have headers_module installed.
465Add the following line to load the headers module in the httpd.conf
466 LoadModule headers_module modules/mod_headers.so
467After headers_module is loaded, edit or include the following lines of config in the httpd.conf
468 ServerSignature Off
469 ServerTokens Prod
470<IfModule mod_headers.c>
471 Header unset Server
472</IfModule>
473---------------------------------------------------
474Source Code Disclosure (PHP)
4751.Confirm exactly what aspects of the source code are actually disclosed; due to the limitations of this type of vulnerability, it might not be possible to confirm this in all instances. Confirm this is not an intended functionality.
4762.If it is a file required by the application, change its permissions to prevent public users from accessing it. If it is not, then remove it from the web server.
4773.Ensure that the server has all the current security patches applied.
4784.Remove all temporary and backup files from the web server.
479PHP code in .html file won't work.
480HTML code in .php file will work.
481---------------------------------------------------
482Anonymous Ciphers Supported
4831.Configure your web server to disallow using anonymous ciphers.
484For Apache, you should modify the SSLCipherSuite directive in the httpd.conf.
485SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM
486---------------------------------------------------
487Apache Server-Status Detected
488Comment out the Location/server-info section from Apache configuration file httpd.conf (for Redhat, Centos, Fedora) or apache2.conf (for Debian, Ubuntu).
489---------------------------------------------------
490Base Tag Hijacking
491Do not allow user input to control the base tag. Whitelist it if the dynamic usage is necessary. Content-Security-Policy (CSP) base-uri directive can also help you prevent to change the <base> tag element. The base-uri directive defines the URIs that a user agent may use as the document base URL.
492Content-Security-Policy: base-uri 'self'
493---------------------------------------------------
494Critical Form Send to HTTP
495All sensitive data should be transferred over HTTPS rather than HTTP. Forms should be served over and form actions also should target HTTPS. All aspects of the application that accept user input, starting from the login process, should only be served over HTTPS.
496---------------------------------------------------
497Critical Form Served over HTTP
498All sensitive data should be transferred over HTTPS rather than HTTP. Forms should be served over HTTPS. All aspects of the application that accept user input, starting from the login process, should only be served over HTTPS.
499---------------------------------------------------
500CVS Detected
501Do not leave CVS repository files on production environments. If there is a business requirement to do so, implement access control mechanisms to stop public access to CVS repository files.
502---------------------------------------------------
503Frame Injection
504•Where possible do not use users' input for URLs.
505•If you definitely need dynamic URLs, make a list of valid accepted URLs and do not accept other URLs.
506•Ensure that you only accept URLs which are located on accepted domains.
507---------------------------------------------------
508HTTP Header Injection
509Do not allow newline characters in input. Where possible, use strict whitelisting.
510---------------------------------------------------
511Insecure HTTP Usage
512Configure your webserver to redirect HTTP requests to HTTPS.
513For Apache, you should have modification in the httpd.conf.
514# redirect all HTTP to HTTPS
515<VirtualHost *:80>
516 ServerAlias *
517 RewriteEngine On
518 RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [redirect=301]
519</VirtualHost>
520---------------------------------------------------
521Invalid SSL Certificate
522Fix the problem with your SSL certificate to provide secure communication between your website and its visitors.
523---------------------------------------------------
524Insecure Transportation Security Protocol Supported (SSLv3)
525•For Apache, adjust the SSLProtocol directive provided by the mod_ssl module. This directive can be set either at the server level or in a virtual host configuration.
526SSLProtocol +TLSv1 +TLSv1.1 +TLSv1.2
527•For Nginx, locate any use of the directive ssl_protocols in the nginx.conf file and remove SSLv3.
528ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
529---------------------------------------------------
530Open Redirection
531•Where possible, do not use users' input for URLs.
532•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
533•Ensure that you only accept URLs those are located on the trusted domains.
534---------------------------------------------------
535Open Redirection (DOM based)
536•Where possible, do not use users' input for URLs.
537•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
538•Ensure that you only accept URLs those are located on the trusted domains.
539---------------------------------------------------
540RSA Private Key Detected
541•Remove this kind of sensitive data from the output.
542---------------------------------------------------
543Stack Trace Disclosure (Python)
544Configure your application not to provide detailed error pages in production environments. Save all information regarding the error to a backend storage, such as a log or a text file, and show a friendly custom error page to the user.
545---------------------------------------------------
546Sublime SFTP Config File Detected
547Restrict access to this file or remove it from the web server.
548---------------------------------------------------
549Weak Ciphers Enabled
5501.For Apache, you should modify the SSLCipherSuite directive in the httpd.conf.
551SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM
552---------------------------------------------------
553Blind Cross-site Scripting
554The issue occurs because the browser interprets the input as active HTML, JavaScript or VBScript. To avoid this, output should be encoded according to the output location and context. For example, if the output goes in to a JavaScript block within the HTML document, then output needs to be encoded accordingly. Encoding can get very complex, therefore it's strongly recommended to use an encoding library such as OWASP ESAPI and Microsoft Anti-cross-site scripting.
555---------------------------------------------------
556Expression Language Injection
557Apply input validation best practices to ensure there are no EL meta characters("${" and "#{") in the input.
558---------------------------------------------------
559Local File Inclusion
560•If possible, do not permit file paths to be appended directly. Make them hard-coded or selectable from a limited hard-coded path list via an index variable.
561•If you definitely need dynamic path concatenation, ensure you only accept required characters such as "a-Z0-9" and do not allow ".." or "/" or "%00" (null byte) or any other similar unexpected characters.
562•It's important to limit the API to allow inclusion only from a directory and directories below it. This ensures that any potential attack cannot perform a directory traversal attack.
563---------------------------------------------------
564Server-Side Request Forgery (AWS)
565•Where possible, do not use users' input for URLs.
566•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
567•Ensure that you only accept URLs those are located on the trusted domains.
568---------------------------------------------------
569Server-Side Request Forgery (elmah MVC)
570•Where possible, do not use users' input for URLs.
571•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
572•Ensure that you only accept URLs those are located on the trusted domains.
573In addition to above, apply the following changes in your web.config file to disable remote access to the Elmah:
574<appSettings>
575 <add key="elmah.mvc.requiresAuthentication" value="true" />
576 <add key="elmah.mvc.allowedRoles" value="Admin" />
577</appSettings>
578---------------------------------------------------
579Server-Side Request Forgery (elmah)
580Apply the following changes in your web.config file to disable remote access to the Elmah.axd error log:
581<elmah>
582 <security allowRemoteAccess="no"/>
583</elmah>
584You can also use ASP.NET's own authorization mechanism to protect your Elmah.axd error log from attackers. The following configuration makes your Elmah.axd error log viewable by only authorized Administrators:
585<configuration>
586 <location path="elmah.axd">
587 <system.web>
588 <authorization>
589 <allow roles="Administrators"/>
590 <deny users="*"/>
591 </authorization>
592 </system.web>
593 </location>
594</configuration>
595---------------------------------------------------
596Server-Side Request Forgery (MySQL)
597•Where possible, do not use users' input for URLs.
598•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
599•Ensure that you only accept URLs those are located on the trusted domains.
600---------------------------------------------------
601Server-Side Request Forgery (SSH)
602•Where possible, do not use users' input for URLs.
603•If you definitely need dynamic URLs, use whitelisting. Make a list of valid, accepted URLs and do not accept other URLs.
604•Ensure that you only accept URLs those are located on the trusted domains.
605---------------------------------------------------
606Stored Cross-site Scripting
607The issue occurs because the browser interprets the input as active HTML, JavaScript or VBScript. To avoid this, all input and output from the application should be filtered. Output should be filtered according to the output format and location. Typically the output location is HTML. Where the output is HTML, ensure all active content is removed prior to its presentation to the server.
608Prior to sanitizing user input, ensure you have a pre-defined list of both expected and acceptable characters, with which you will populate a whitelist. This list needs only be defined once and should be used to sanitize and validate all subsequent input.
609There are a number of pre-defined, well structured whitelist libraries available for many different environments; good examples of these include OWASP Reform and Microsoft Anti cross-site scripting libraries.
610---------------------------------------------------
611XML External Entity Injection
612Multiple fixes: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
613---------------------------------------------------
614Local File Inclusion
615•If possible, do not permit file paths to be appended directly. Make them hard-coded or selectable from a limited hard-coded path list via an index variable.
616•If you definitely need dynamic path concatenation, ensure you only accept required characters such as "a-Z0-9" and do not allow ".." or "/" or "%00" (null byte) or any other similar unexpected characters.
617•It's important to limit the API to allow inclusion only from a directory and directories below it. This ensures that any potential attack cannot perform a directory traversal attack.
618---------------------------------------------------
619Backup Source Code Detected
620This is dependent on the information obtained from source code. Uncovering these forms of vulnerabilities does not require high levels of skills. However, a highly skilled attacker could leverage this form of vulnerability to obtain account information for databases or administrative panels, ultimately leading to control of the application or even the host the application resides on.
621---------------------------------------------------
622Basic Authorization over HTTP
623Move all of your directories which require authentication to be served only over HTTPS, and disable any access to these pages over HTTP.
624---------------------------------------------------
625Certificate is Signed Using a Weak Signature Algorithm
626You'll need to generate a new certificate request, and get your CA to issue you a new certificate using SHA-2.
627---------------------------------------------------
628Cookie Not Marked as Secure
629Mark all cookies used within the application as secure. (If the cookie is not related to authentication or does not carry any personal information, you do not have to mark it as secure.)
630---------------------------------------------------
631Cross-site Scripting
632<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
633The issue occurs because the browser interprets the input as active HTML, JavaScript or VBScript. To avoid this, output should be encoded according to the output location and context. For example, if the output goes in to a JavaScript block within the HTML document, then output needs to be encoded accordingly. Encoding can get very complex, therefore it's strongly recommended to use an encoding library such as OWASP ESAPI and Microsoft Anti-cross-site scripting.
634---------------------------------------------------
635Cross-site Scripting (DOM based)
636•Untrusted data should only be treated as displayable text. Never treat untrusted data as code or markup within Javascript code.
637•Avoid use of HTML rendering properties/methods. (e.g., innerHTML, outerHTML, document.write ). Instead use innerText or textContent.
638•Always encode Javascript and delimit untrusted data as quoted strings when entering the application.
639•Don’t evaluate JSON to convert it to native JavaScript objects. Instead use JSON.toJSON() and JSON.parse().
640---------------------------------------------------
641Cross-site Scripting via Remote File Inclusion
642The issue occurs because the browser interprets the input as active HTML, Javascript or VbScript. To avoid this, all input and output from the application should be filtered. Output should be filtered according to the output format and location. Typically, the output location is HTML. Where the output is HTML, ensure all active content is removed prior to its presentation to the server.
643---------------------------------------------------
644Database User Has Admin Privileges
645Create a database user with the least possible permissions for your application and connect to the database with that user. Always follow the principle of providing the least privileges for all users and applications.
646There is a function in MySQL to grant every user admin privileges. You should not do this because if you get hit by SQL injection that user also has admin privileges.
647---------------------------------------------------
648Out of Band XML External Entity Injection
649•StAX and XMLInputFactory:
650Set the javax.xml.stream.isSupportingExternalEntities property to false.
651•.NET 3.5:
652XmlReaderSettings settings = new XmlReaderSettings();
653settings.ProhibitDtd = true;
654XmlReader reader = XmlReader.Create(stream, settings);
655•.NET 4.0:
656XmlReaderSettings settings = new XmlReaderSettings();
657settings.DtdProcessing = DtdProcessing.Prohibit;
658XmlReader reader = XmlReader.Create(stream, settings);
659•PHP:
660libxml_disable_entity_loader(true);
661---------------------------------------------------
662Out-of-date Version (MySQL)
663Please upgrade your installation of MySQL to the latest stable version.
664---------------------------------------------------
665Password Transmitted over HTTP
666All sensitive data should be transferred over HTTPS rather than HTTP. Forms should be served over HTTPS. All aspects of the application that accept user input, starting from the login process, should only be served over HTTPS.
667---------------------------------------------------
668SVN Detected
669Do not leave SVN repository files on production environments. If there is a business requirement to do so, implement access control mechanisms to stop public access to SVN repository files.
670You can also use Export if you do one time deployments, instead of a checkout.
671---------------------------------------------------
672Trace.axd Detected
673Apply the following changes on your web.config file to disable ASP.NET tracing:
674<System.Web>
675 <trace enabled="false" />
676</System.Web>
677---------------------------------------------------
678Unrestricted File Upload
679•Never accept a filename and its extension directly without having a white-list filter.
680•If there is no need to have Unicode characters, it is highly recommended to only accept alpha-numeric characters and only one dot as an input for the file name and the extension.
681•Limit the file size to a maximum value in order to prevent denial of service attacks.
682•Uploaded directory should not have any "execute" permission.
683•Don't rely on client-side validation only.
684---------------------------------------------------
685Weak Basic Authentication Credentials
686Do not use weak passwords, which are short, default, common or easy to guess. Implement a strong password policy.
687---------------------------------------------------
688WebDAV Directory Has Write Permissions
689Restrict access for method PUT or if it's not being used, consider disabling it.
690---------------------------------------------------
691Code Evaluation (Apache Struts)
692Do not accept input from end users that will be directly interpreted as source code. If this is a business requirement, validate all input to the application by removing any data that could be directly interpreted as Apache Struts source code.
693---------------------------------------------------
694Code Evaluation (Perl)
695Do not accept input from end users that will be directly interpreted as source code. If this is a business requirement, validate all input to the application by removing any data that could be directly interpreted as Perl source code.
696---------------------------------------------------
697Code Evaluation (PHP)
698Do not accept input from end users that will be directly interpreted as source code. If this is a business requirement, validate all the input on the application and remove all the data that could be directly interpreted as PHP source code.
699---------------------------------------------------
700Command Injection
701Before invoking system commands within an application, consider using an API, which allows you to separate commands and parameters. This can avoid many of the problems associated with command execution. See the external references for some examples. If this is not possible, whitelist all input and encode it in accordance with the underlying subsystem. (e.g. if it is Windows, then you need to escape from cmd.exe control characters)
702---------------------------------------------------
703Remote File Inclusion
704•Wherever possible, do not allow the appending of file paths as a variable. File paths should be hard-coded or selected from a small pre-defined list.
705•Where dynamic path concatenation is a major application requirement, ensure input validation is performed and that you only accept the minimum characters required, for example, "a-Z0-9", and that you filter out and do not allow characters such as ".." or "/" or "%00" (null byte) or any other similar multifunction characters.
706•It's important to limit the API to only allow inclusion from a directory or directories below a defined path.
707---------------------------------------------------
708Bash Command Injection Vulnerability (Shellshock Bug)
709Upgrade your system by following these instructions: https://access.redhat.com/solutions/1207723
710---------------------------------------------------
711Blind Command Injection
712Before invoking system commands within an application, consider using an API, which allows you to separate commands and parameters. This can avoid many of the problems associated with command execution. See the external references for some examples. If this is not possible, whitelist all input and encode it in accordance with the underlying subsystem. (e.g. if it is Windows, then you need to escape from cmd.exe control characters)
713---------------------------------------------------
714Code Execution via File Upload
715•Never accept a filename and its extension directly without having a white-list filter.
716•Uploaded directory should not have any "execute" permission.
717---------------------------------------------------
718Code Execution via WebDAV
719Remove write permissions from this directory or disable WebDAV if it's not being used.
720---------------------------------------------------
721OpenSSL Heartbleed
722Affected users should upgrade to OpenSSL 1.0.1g. Users unable to immediately upgrade can alternatively recompile OpenSSL with -DOPENSSL_NO_HEARTBEATS.
723---------------------------------------------------
724Out of Band Code Evaluation (PHP)
725Do not accept input from end users that will be directly interpreted as source code. If this is a business requirement, validate all the input on the application and remove all the data that could be directly interpreted as PHP source code.
726---------------------------------------------------
727Out of Band Command Injection
728Before invoking system commands within an application, consider using an API, which allows you to separate commands and parameters. This can avoid many of the problems associated with command execution. See the external references for some examples. If this is not possible, whitelist all input and encode it in accordance with the underlying subsystem. (e.g. if it is Windows, then you need to escape from cmd.exe control characters)
729---------------------------------------------------
730Out of Band SQL Injection
731A robust method for mitigating the threat of SQL injection-based vulnerabilities is to use parameterized queries (prepared statements). Almost all modern languages provide built-in libraries for this. Wherever possible, do not create dynamic SQL queries or SQL queries with string concatenation.
732---------------------------------------------------
733Remote Code Execution and DoS in HTTP.sys (IIS)
734Upgrade your system by following these instructions https://support.microsoft.com/en-us/help/3042553/ms15-034-vulnerability-in-http.sys-could-allow-remote-code-execution-april-14,-2015
735---------------------------------------------------
736Protecting Web Applications SQL Injection
737
738Surely, there must be a way to simply sanitize user input and ensure an SQL injection is infeasible. Unfortunately, that is not always the case. There are perhaps an infinite number of ways to sanitize user input, from globally applying PHP's addslashes() to everything (which may yield undesirable results), all the way down to applying the sanitization to "clean" variables at the time of assembling the SQL query itself, such as wrapping the above $_GET['id'] in PHP's mysql_escape_string() function. However, applying sanitization at the query itself is a very poor coding practice and difficult to maintain or keep track of. This is where database systems have employed the use of prepared statements.
739
740Prepared Statements
741
742When you think of prepared statements, think of how printf works and how it formats strings. Literally, you assemble your string with placeholders for the data to be inserted, and apply the data in the same sequence as the placeholders. SQL prepared statements operate on a very similar concept, where instead of directly assembling your query string and executing it, you store a prepared statement, feed it with the data, and it assembles and sanitizes it for you upon execution. Great! Now there should never be another SQL injection again. So why, then, are SQL injection attacks still, for over 14 years, constantly one of the biggest and most prevalent attack methods?
743
744Insecure SQL Queries are a Problem
745
746Simply put, it perhaps boils down to web application developer laziness and lack of education and awareness. Insecure SQL queries are so extremely easy to create, and secure SQL queries are still mildly complex (or at least more complex than generic and typical in-line and often insecure queries). In the example above, a malicious hacker can inject anything he or she desires in the same line as the SQL query itself.
747
748Example and Explanation of an SQL Prepared Statement
749
750However, with prepared statements, there are multiple steps. No major database system operates like printf (with everything occurring within the same statement on the same line). MySQL, directly, requires at least two commands (one PREPARE and one EXECUTE). PHP, via the PDO library, also requires a similar stacking approach, such as the following:
751
752$stmt = $dbh->prepare("SELECT * FROM users WHERE USERNAME = ? AND PASSWORD = ?");
753
754$stmt->execute(array($username, $password));
755
756At first glance, this is not inherently problematic and, on average, increases each SQL query by only an extra line or two. However, as this requires extra caution and effort on behalf of already tired and taxed developers, often times they may get a little lazy and cut corners, opting instead to just use the easy procedural mysql_query() as opposed to the more advanced object-oriented PDO prepare().
757
758Beside of this many developers just stick with what they know to get the job done and they generally learn the easiest and most straightforward way to execute SQL queries rather than showing genuine interest in improving what they know. But this could also be an issue of lack of awareness.
759
760Deeper Into the Rabbit Hole of SQL Injection Security
761
762Say, however, this isn't the case of lazy developers, or even lack of prepared statements -- or, more precisely, say the software itself and its security is out of your hands. Perhaps it is impractical or infeasible to completely secure the SQL queries in the code you use (by one comparison, Drupal has had over 20,000 lines of code committed, WordPress has had over 60,000 lines, and Joomla! has had over 180,000 lines), or, it may simply be impossible because it is encoded or so. Whatever the case is, if you do not have control over the code you may need to employ different, more advanced "outside the box" protections.
763
764Non Development Related SQL Injection Protection
765
766Running Updated Software
767
768First and foremost, always ensure you are running the most up-to-date software you can. If you are using WordPress or any other CMS framework, keep it updated! The same goes for PHP, your web server software such as Apache and nginx, and your database server (MySQL, Postgres, or others). The more recent the version of your software is, the less chance of having a vulnerability, or at least a widely-known one. This also extends down to your other software as well, such as SSH, OpenSSL, Postfix, and even the operating system itself.
769
770Block URLs at Web Server Level
771
772Next, you should employ methods to ensure you are as minimally vulnerable to potential SQL injection attacks as possible. You could perhaps go for a quick and easy match against common SQL query keywords in URLs and just simply block them. For example, if you ran Apache as your web server, you could use the following two mod_rewrite lines in your VirtualHost directive, as explained below:
773
774RewriteCond %{QUERY_STRING} [^a-z](declare¦char¦set¦cast¦convert¦delete¦drop¦exec¦insert¦meta¦script¦select¦truncate¦update)[^a-z] [NC]
775
776RewriteRule (.*) - [F]
777
778This is indeed quite clever, but it does not protect against everything. SQL injection parameters can still be passed via POST values or other RESTful-type URLs, not to mention there are tons of different ways to bypass this kind of generic blacklisting.
779
780Securing the Database and Privileges
781
782You can also ensure your database itself is as secure as possible. In the information security field, there exists a concept known as the principle of least privilege. Effectively, this principle states that a user or program should have only the absolute very least amount of privileges necessary to complete its tasks. We already do this practically every day with Linux file permissions, so the concept is in no way foreign, and is equally applicable to databases. There is probably no reason why your log table should have anything beyond INSERT privileges, so you should not simply GRANT ALL PRIVILEGES because it is easier.
783
784Segregating Sensitive and Confidential Data
785
786Similarly, you might consider separation of data as a defense in depth approach, rather than conglomeration it into a single source. When you step back and think about it, it is probably not a very wise idea to keep your (hopefully PCI-compliant) customer credit card data stored in the same database as your forums, which are running an outdated and highly vulnerable version of phpBB, right? Not only would the principle of least privilege be very applicable in this situation, but even going so far as to entirely separate out your more sensitive data is a very sage approach. To think about it another way, would you keep all your most important paperwork inside your house, or would you keep some in a safe deposit box, too? The same concept applies with sensitive data.
787
788Analyzing HTTP Requests Before Hitting the Web Application
789
790Another option is the use of more detailed firewall systems. Typically this might include some adaptive solution that rides on top of iptables or ipfw (depending if you are using Linux or a BSD variant, respectively), or perhaps a reactive Host Intrusion Detection System (HIDS) such as OSSEC, although these are often more complicated than desired and not exactly purpose-built for these uses. Instead, you may wish to utilize a Web Application Firewall, which is designed specifically for these tasks. While there exist several enterprise-level solutions that are both a WAF and database firewall (sitting between your web application and your database), there are many open-source solutions, such as ModSecurity and IronBee, that perform remarkably well.
791
792The Truth about SQL Injection Web Vulnerability
793
794There exists no real magic wand answer to fix SQL injections and protect your web applications from them, although PHP is attempting a more brute force approach of their own. As of PHP 5.5, procedural MySQL is deprecated and soon to be removed entirely, which will require future software projects to switch either to MySQLi or PDO MySQL in order to continue to work. This is good since it forces developers into a system that handles prepared statements with relative ease, although it still requires the use of stacking a few operations. However, as many developers operate within a coding golf style; attempting to complete work in as few lines or characters as possible, many unfortunately will still opt for a single-line straight query over a two-line prepare.
795
796There still exist other options to account for any development shortcomings, including but not limited to privilege limitations, data separation, web application firewalls, and many other approaches. But until these options are as consistently employed as SQL injection attacks, we indeed may never see the day that injection-style attacks escape the OWASP's Top 10 list. Be the change that is needed to ensure data and web application security, and keep your databases safe from SQL injections!