How to secure and optimize websites on Linux host?
Linux hosting is better known for security, open source web application deployment and of course cheapest hosting solution as compare to windows host. If you're new to using, administering or deploying application on Linux hosting, you should know following things to keep your website secured, optimized and trouble free.
You don't need to care much about server core security and performance as hosting tech guys are always there, but it is important and it's something everybody needs to be aware of. The system administrator and support technician will always make sure that your server is running secure binaries, compatible/recommended LAMP stack and other security applications are installed and updated properly. Whether you host customized application or popular open source wordpress blog, there is a day in hosting life you get something wired error or warning, and yes you first start googling for possible issues and solutions. Although you get solution which fixes up your problem do you ever look back at exact issue, reason and overall affect due to suggested solution or setting ? No ? Oops! That might create loophole to compromise your website security. also their suggested solution could create performance issue on the shared server which directly leads to account suspension.
In this post Iâ€™m not focusing how to harden server security but a hosting account with proper PHP environment settings that every Linux hosting account holder should know. Here I have revealed some important points about website security and performance optimization.
Security, threats and prevention:
My website got hacked.. What should I do? How do I secure my site? What are the security tips? What are the security issues on Linux server? PHP and Apache hardening? How to increase PHP security? blah blah blah .. ..
Well system security is not action but continuous process which requires every user participation. If you want a secure system follow the general guidelines, don't ignore security policy. Youâ€™ll be on your way to more informed and secure hosting. There are some known security issues and vulnerability to the web sites or server at all. Common threats include network services attack - ddos, root-kits infection, worms, Cross-site scripting and SQL injection which are attempted via any browser on any OS. Also social engineering work, Phishing attempts are stealing personal and financial information via browser based attacks.
In order to keep your website secure you should consider required compatible and customized LAMP environment setting. Web developer, web masters often assess and optimize the PHP, Apache (web server), MySQL (database server) setting before deploying websites in the production environment. If you are a newbie who know nothing in LAMP and running free open source applications then do not put/edit anything in php.ini, .htaccess file. Do not disable mod security in the .htaccess file even your application in not working properly or showing something error. Just update your issue to the host support and let them know exact URL link, steps to reproduce same issue so conflicting URL, string can be excluded from mod_security rules. Also you can ask them questions as, on what server my site is hosted? Can I use php.ini, .htaccess file under my account to modify server setting? Do I enable/disable that setting? Support people, expert system administrator are always there to assist you with recommended setting.
Why do hosts recommend disabling PHP functions on the Linux servers?
PHP a most popular server side scripting language is also known for its best vulnerability in the programming world. There is long history of PHP security problems but taking appropriate preventive actions you can use and enjoy this user friendly language. There are some powerful functions in the PHP which can run script/command remotely, manage system process and crack the server security so disabling these functions will restrict PHP script execution and call for system binaries/files.
disable_functionsÂ =>Â system,passthru,execÂ
This directive allows you to disable vulnerable PHP functions in php.ini file. It takes on a comma-delimited list of functions.
Note: Disabling these functions may affect your websites functionality, but it's strongly recommended.. ! So check your code from the developer and find something alternative solution rather than breaking your account and server security as well.
system - It executes an external program and display the result.
exec - It executes an external command.
passthru â€“ It is similar to the exec() function which execute commands.
popen â€“ It opens process file pointer.
proc_close - It closes a process opened by proc_open and returns the exit code of that process
proc_open - It executes a command and opens file pointers for Input/Output
proc_get_status- It gets information about a process opened by proc_open()
proc_nice- Change the priority of the current process
show_source - show the source of a file
proc_terminate- Kills a process opened by proc_open
highlight_file- Syntax highlighting of a file
escapeshellcmd- Escape shell metacharacters
define_syslog_variables- Initializes all syslog related variables
posix_getpwuid- Return info about a user by user id
apache_child_terminate- Terminate apache process after this request
posix_kill- Send a signal to a process
posix_mkfifo - Create a fifo special file (a named pipe)
posix_setpgid- Set process group id for job control
posix_setsid- Make the current process a session leader
posix_setuid- Set the UID of the current process
escapeshellarg- Escape a string to be used as a shell argument
posix_uname- Get system name
ftp_exec- Requests execution of a command on the FTP server
ftp_connect- Opens an FTP connection
ftp_login- Logs in to an FTP connection
ftp_get- Downloads a file from the FTP server
ftp_put- Uploads a file to the FTP server
ftp_nb_fput- Stores a file from an open file to the FTP server (non-blocking)
ftp_raw- Sends an arbitrary command to an FTP server
ftp_rawlist- Returns a detailed list of files in the given directory
ini_alter- This function is an alias of: ini_set()
ini_restore- Restores the value of a configuration option
syslog- Generate a system log message
openlog- Open connection to system logger
define_syslog_variables- Initializes all syslog related variables
apache_setenv - Set an Apache subprocess_env variable
mysql_pconnect - Open a persistent connection to a MySQL server
eval- Evaluate a string as PHP code
fputs â€” Alias of fwrite()
shell_exec - execute command via shell and return the complete output as a string
curl_exec - perform a cURL session
curl_multi_exec - run the sub-connections of the current cURL handle
dl - loads a PHP extension at runtime
fsockopen - open internet or unix domain socket connection
parse_ini_file - parse a configuration file
symlink - creates a symbolic link
Below are important PHP configuration directives/parameters/arguments used in .htaccess, php.ini files with recommended options.
It is important to know that in which PHP/Apache environment you can use php.ini file or .htaccess file to modify the account setting. Using inappropriate setting can cause 500 internal server errors so contact your host support and know more about environment setting. You can use php.ini file or .htaccess file to affect a specific directory or script using appropriate directive syntax.
php_value name value : It sets the value of the specified directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives. To clear a previously set value use none as the value. Note: Don't use php_value to set boolean values. php_flag (see below) should be used instead.
php_flag name on|off : Used to set a boolean configuration directive. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives.
php_admin_value name value : Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or virtualhost directives. To clear a previously set value use none as the value.
php_admin_flag name on|off : It is used to set a boolean configuration directive. This can not be used in .htaccess files. Any directive type set with php_admin_flag can not be overridden by .htaccess or virtualhost directive
Directive : safe_mode
How to set in php.ini : safe_mode = On
How to set in .htaccess : php_value safe_mode "1"
Recommendation : Keep safe_mode ON (now deprecated)
Did you know ? : Security and Safe Mode: The PHP safe mode is an attempt to solve the shared-server security issue. This option has been DEPRECATED as of PHP 5.3.0. In this mode, access to files not owned by Apache is disabled, and access to environment variables and execution of binary programs are also disabled. In some cases you'll want to use a group to check ownership (for instance in the case that you have multiple people deploying web application scripts). Please note that Safe mode support is removed in PHP 6.
Directive : register_globals
How to set in php.ini : register_globals = Off
How to set in .htaccess : php_flag register_globals off
Recommendation :Keep register globals Off for security reasons.
Did you know ? :A number of older scripts assume that the data sent by a form will automatically have a PHP variable of the same name. If your form has an input field with a name of "somename", older PHP scripts assume that the PHP will automatically create a variable called $somename that contains the value set in that field.
Directive : allow_url_fopen
How to set in php.ini : allow_url_fopen=Off
How to set in .htaccess : php_flag allow_url_fopen on
Recommendation : Many host set this to OFF on shared servers due to security reason. Set this to Off if your script dont need it.
Did you know ? :This directive allows PHP's file functions ( file_get_contents, include and require statements ) to retrieve data from remote locations, like FTP or HTTP. If an attacker can manipulate the arguments to those functions, they can use a URL under their control as the argument and run their own remote scripts. The vulnerability is called Remote file inclusion or RFI.
It prevents URLs from being used in PHP. A command like include ("http://www.eukhost.com/cpanel-web-hosting.php") will not be allowed to execute. Only files that reside within your site can be included: include("/home/cpuser/public_html/config.inc.php").
Directive : allow_url_include
How to set in php.ini : allow_url_include = On
How to set in .htaccess : php_flag allow_url_include on
Recommendation : Keep allow_url_include Off for security reasons
Did you know ? :If disabled, allow_url_include blocks remote file access via the include and require statements, but leaves it available for other file functions like fopen and file_get_contents. Include and require are the most common attack points for code injection attempts, so this setting plugs that particular hole without affecting the remote file access capabilities of the standard file functions.
Directive : open_basedir
How to set in php.ini : open_basedir = "/home/cpuser/public_html:/usr/local/php/"
How to set in .htaccess : php_value open_basedir /www/folder/:/tmp ( Please note that some server do nor allow to use open_basedir in htaccess file )
Recommendation : Limit file operations to the defined directory for security reasons
Did you know ? :open_basedir limits the PHP process from accessing files outside of specifically designated directories. Set open_basedir to only allow access to required portions of the file system, like your web site's documents and any shared libraries.
Directive : upload_max_filesize
How to set in php.ini : upload_max_filesize = 2M
How to set in .htaccess : php_value upload_max_filesize 6M
Recommendation : Put lower upload_max_filesize for security reasons
Did you know ? : This setting defines the maximum size of files that PHP will accept through uploads. Attackers may attempt to send grossly big sized files to exhaust your server resources.
Directive : max_execution_time
How to set in php.ini : max_execution_time = 30
How to set in .htaccess : php_value max_execution_time 600
Recommendation : It is safe to set max_execution_time up to 1200
Did you know ? :This sets the maximum time in seconds a script is allowed to run before it is terminated by the parser. This helps prevent poorly written scripts from tying up the server. The default setting is 30.
Directive : memory_limit
How to set in php.ini : memory_limit = 8M
How to set in .htaccess : php_value memory_limit "64M"
Recommendation : Use minimum memory_limit in php.ini if your account is hosted on shared server.
Did you know ? :You can protect your applications from certain types of denial of service attacks and also from bugs in applications (infinite loops or other memory intensive mistakes) if you will enable a realistic memory_limit. A setting of 8MB is sufficient but still aggressive enough to catch problems before too much damage is done.
Directive : expose_php
How to set in php.ini : expose_php = Off
How to set in .htaccess :You can only disable expose_php in the php.ini file.
Recommendation : It's strongly recommended to disable expose_php. for security reasons
Did you know ? : When enabled, expose_php reports in every request that PHP is being enabled, and what version of PHP is installed. Malicious users looking for potentially vulnerable targets can use this to identify a weakness. This directive must be set in php.ini.
Directive : display_errors
How to set in php.ini : display_errors = On
How to set in .htaccess : php_flag display_errors Off
Recommendation :Keep display_errors Off for security reasons.
Did you know ? :This determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user. The display_errors directive determines whether error messages should be sent to the browser. These messages frequently contain sensitive information about your web application environment and should always be disabled.
Directive : upload_tmp_dir
How to set in php.ini : upload_tmp_dir = /home/cpuser/tmp
How to set in .htaccess :php_value upload_tmp_dir /path/to/file
Recommendation : You should set upload_tmp_dir to a folder that is outside the document root of your website and is not readable or writable by any other system users.
Did you know ? : Upload_tmp_dir allows you to specify the temporary directory used for storing files. If this directory is within the document root of the web site and/or accessible to system users other than PHP's user, it could be modified or overwritten while PHP is processing it. By default upload_tmp_dir is set to the system's standard temporary directory, which can typically be accessed by all system users.
Directive : session.save_path
How to set in php.ini : session.save_path = /tmp
How to set in .htaccess : php_value session.save_path'/home/cpuser/public_html/temp'
Recommendation : Keep session.save_path to a safe location in php.ini for security reasons. Many hosts keep it to /tmp partition.
Did you know ? : This directive allows you to specify where session files should be saved when using the default session handler. This must be a directory outside the document root and should only be accessible by the web user. save_path should be unique on a virtual host basis when those virtual hosts are controlled by different entities to prevent sites from reading each others sessions ( shared hosting ).
Directive : post_max_size
How to set in php.ini : post_max_size = 8M
How to set in .htaccess : php_flag post_max_size 15M
Recommendation : Keep lower post_max_size ini php.ini for security reasons
Did you know ? : This protection allows you to limit the maximum size POST request that PHP will process. Attackers may attempt to send over sized POST requests to exhaust your server resources.
Directive : magic_quotes_gpc
How to set in php.ini : magic_quotes_gpc = On
How to set in .htaccess :php_flag magic_quotes_gpc off
Recommendation :Disable Magic Quotes in php.ini for security reasons
Did you know ? : magic_quotes_gpc provides some rudimentary protection against SQL injection and is a generic solution that doesn't include all the characters that require escaping. It effectively executes addslashes() on all information received over COOKIE, GET and POST. Because it's inconsistent and ineffective, it's recommended to disable magic_quotes_gpc.
Directive : ini_set
How to set in php script : ini_set('memory_limit', '128M');
Recommendation : Do not use this function to allocate more resources if your account is hosted on shared server.
Did you know ? : It allows to set the value of a php configuration option in any php script. not all the available options can be changed using ini_set().
To secure your website:
â€¢ Choose strong passwords for Shell (SSH), cPanel/Plesk control panels, website admin and FTP account access, which contain a combination of upper, lower case letters, numbers and special characters such as ) eg. <@ILovE#eUKHost!.
â€¢ Block all other IP addresses in .htaccess file for admin area folder access.
â€¢ Keep recommended permission, ownership for files/folders. Do not set maximum permissions, nobody ownership which gives read, write and execute access to the world.
â€¢ Do not enable display errors setting in php.ini or .htaccess file or in applicationâ€™s configuration file.
â€¢ Do not disable mod security protection in .htaccess file or httpd.conf.
â€¢ Do not enable vulnerable PHP functions or above censure directives in php.ini or .htaccess file.
â€¢ Disable directory index listing/browsing using .htaccess file.
â€¢ Hide your CMS application name and version in all pages.
â€¢ Update your CMS applications, themes and plugins to the stable, patched version.
â€¢ Do not install vulnerable CMS applications, themes and plug-ins.
â€¢ Install SSL certificate which provides data encryption, server authentication, message integrity and client authentication for TCP/IP connections. It also prevent cyber crimes like hacking, fishing. ( Highly recommended for E-commerce and payment gateway websites)
Script, Database optimization:
Why my hosting account has been suspended ? How do I speed up my website? How to optimize script and databases? Support people say my site is using highest resources but how and why? blah blah blah.. ..
There are chances of account suspensions if your scripts, databases are using maximum resources on the shared server. If your website is taking more time to load, consuming maximum CPU, memory usage then you need to review your code, databases from the web developer/designer for possible issues. Website speed, performance can be improved by optimizing script, images and database queries with best practices and available tools/technologies.
To optimize and speed up your websites:
â€¢ Always use latest and compatible versions of the CMS applications.
â€¢ Do optimize and repair your databases from Cpanel/Plesk or PHPmyadmin option.
â€¢ Use MySQL query caching.
â€¢ Install the eAccelerator module.
â€¢ Close your database connection when youâ€™re entry is done.
â€¢ Make less HTTP requests.
â€¢ Do not set/use maximum memory_limit, avoid large file uploads.
â€¢ Use Gzip compression, HTTP compression.
â€¢ Turn on apache's mod_deflate module which compresses your data and reduce the transfer up to 80%
â€¢ Use Cache Plugins for wordpress, joomla and magento websites.
â€¢ Use maximum CSS designs; minimize use of bitmaps, images.
â€¢ Optimize images, use .gif where possible, they are smaller.
â€¢ Remove excessive spaces and empty lines from scripts.
â€¢ Reduce the number of links to external websites.
â€¢ A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer PHP scripts.
â€¢ Install a PHP caching product to typically increase performance by 25-100% by removing compile times. Use memcached.
â€¢ Use HTTP caching, don't make the users download the same picture, JS, CSS, HTML or any other "static" file over and over again.
â€¢ Upload large pictures to a free picture storage sites. this will also save your bandwidth.
â€¢ Use https only for the web pages which contains sensitive information.
â€¢ Remove or change any code which is affecting site/server performance.
â€¢ Use AJAX - This will reduce the load from the server (the page will not have to create and send each time) and make your site more user friendly.
==> Please Contact us for More information 011-2604120 or email@example.com
- 0 Users Found This Useful
Fine Tuning Your WordPress InstallWe offer WordPress as a one-click install, and there is a...
Below given are some of the security tips for wordpress: 1.)Blocking WP- folders from being...
How to optimize Wordpress Wordpress is an amazing CMS or Content Management System that...
A Growth Industry Recently the number of sites being hacked or infiltrated has risen rapidly. We...
Do you want me to restore your website from some available old backup with us so Please contact...