25 PHP Insurance practices addressed to system administrators

Source: Internet
Author: User
Tags php session php error stop sql injection apache log nginx server
25 PHP security practices addressed to system administrators

PHP is a widely used open source service-side scripting language. Through the HTTP or HTTPS protocol, the Apache Web service allows users to access files or content. Misconfiguration of the server-side scripting language can cause a variety of problems. Therefore, PHP should be used with caution. Here are 25 practical examples of safe configuration of PHP for system administrators.

Sample PHP setup for the following example

    • Documentroot:/var/www/html
    • Default Web service: Apache (can use LIGHTTPD or Nginx instead)
    • Default PHP configuration file:/etc/php.ini
    • Default PHP Extensions configuration directory:/etc/php.d/
    • PHP Security Configuration Sample file:/etc/php.d/security.ini (need to create this file using a text editor)
    • Operating system: Rhel/centos/fedora Linux (instructions should be available in all other Linux distributions, such as Debian/ubuntu, or unix-like operating system, such as Openbsd/freebsd/hp-ux under normal operation)
    • Default TCP/UDP port for PHP services: None

Most of the operations listed in the afternoon are based on the assumption that the root user can perform operations on bash or other modern shells.

$ php-v

Sample output

PHP 5.3.3 (CLI) (built:oct 08:35:41) Copyright (c) 1997-2010 the PHP Group Zend Engine v2.3.0, Copyright (c) 1998 -2010 Zend Technologies

The operating system used in this article

$ cat/etc/redhat-release

Sample output

Red Hat Enterprise Linux Server release 6.1 (Santiago)

#1: Robin

PHP-based applications face a variety of attacks:

    • XSS: Cross-site scripting is a vulnerable point for PHP Web applications. Attackers can use it to steal user information. You can configure Apache, or write more secure PHP code (verify all user input) to protect against XSS attacks
    • SQL injection: This is the vulnerable point of the database layer in PHP applications. The precautionary approach is ibid. A common approach is to use mysql_real_escape_string () to escape a parameter and then make a SQL query.
    • File Upload: It allows visitors to place (i.e. upload) files on the server. This can result in a series of problems such as deleting server files, databases, obtaining user information, and so on. You can use PHP to suppress file uploads, or to write more secure code (such as verifying user input, allowing only PNG, GIF image formats to be uploaded)
    • Contains local and remote files: An attacker could enable a remote server to open a file, run any PHP code, and then upload or delete files and install the backdoor. You can prevent remote file execution by canceling the settings
    • Eval (): This function allows a string to execute as if it were a PHP code. It is often used by attackers to hide code and tools on the server. By configuring PHP, cancel the eval () function call to implement
    • Sea-surt Attack (cross-site request forgery,csrf. Cross-site request forgery): This attack causes the end user to perform non-specified behavior under the current account. This can compromise the end user's data and operational security. If the target end user's account is used for administrator privileges, the entire web app will be compromised.

#2: Reduce the built-in PHP module

Execute the following command to view the modules that are currently being compiled by PHP

$ php-m

Sample output:

[PHP Modules] APC bcmath bz2 Calendar Core CType Curl date Dom Ereg EXIF fileinfo filter FTP GD gettext GMP hash iconv ima P JSON libxml mbstring memcache mysql mysqli OpenSSL pcntl pcre PDO pdo_mysql pdo_sqlite Phar readline Reflection session Shmop SimpleXML sockets SPL sqlite3 standard suhosin tokenizer wddx xml XmlReader xmlrpc XmlWriter xsl zip zlib [Zend modu Les]  suhosin

From a performance and security standpoint, I recommend that you reduce unnecessary modules when using PHP. For example, the above sqlite3 is not necessary. You can then cancel it by deleting or renaming the/etc/php.d/sqlite3.ini file:

# Rm/etc/php.d/sqlite3.ini

Or

# mv/etc/php.d/sqlite3.ini/etc/php.d/sqlite3.disable

Some modules can only be removed by using recompile to install PHP. For example, after downloading the PHP source from Php.net, compile gd,fastcgi and MySQL support using the following instructions:

./configure--with-libdir=lib64--with-gd--with-mysql--prefix=/usr--exec-prefix=/usr--bindir=/usr/bin--sbindir=/ Usr/sbin--sysconfdir=/etc--datadir=/usr/share--includedir=/usr/include--libexecdir=/usr/libexec--localstatedir =/var--sharedstatedir=/usr/com--mandir=/usr/share/man--infodir=/usr/share/info--cache-file=. /config.cache--with-config-file-path=/etc--with-config-file-scan-dir=/etc/php.d  --enable-fastcgi-- Enable-force-cgi-redirect

For more information, see: How to compile and reinstall PHP in Unix like operating system

#3: Prevent PHP information from leaking

PHP Information disclosure can be restricted by canceling export_php. Edit/etc/php.d/security.ini as follows:

Expose_php=off

Expose_php will be added to the HTTP header on the server, including the version of PHP information (such as x-powered-by:php/5.3.3). Also, the global uniform identifier of PHP is exposed. If export_php is enabled, you can view the PHP version information by using the following command:

$ curl-i http://www.cyberciti.biz/index.php

Sample output:

http/1.1 OK x-powered-by:php/5.3.3 content-type:text/html; Charset=utf-8 vary:accept-encoding, Cookie X-vary-options:accept-encoding;list-contains=gzip,cookie; String-contains=wikitoken;string-contains=wikiloggedout;string-contains=wiki_session Last-modified:thu, Geneva 22:32:55 GMT ...  

It is recommended to also hide information such as Apache version: Servertokens and serversignature directives in httpd.conf to hide Apache versions

#4: Minimize the load-loading PHP module (dynamic extension)

PHP supports "Dynamic Extensions". By default, Rhel loads all extension modules in the/etc/php.d/directory. To enable or cancel a module, simply comment The module out of the/etc/php.d/directory under the configuration file. You can also delete or rename the module's configuration file. To optimize PHP performance and security, you should only enable the extension required for your web app. For example, use the following command to cancel the GD module:

/sbin/service httpd Restart

Enabled is:

/sbin/service httpd Restart

#5: Log all PHP errors

Do not export the PHP error message to the user you are using. Edit the/etc/php.d/security.ini and modify the following:

Display_errors=off

Ensure that all error messages are logged to the log file

Log_errors=onerror_log=/var/log/httpd/php_scripts_error.log

#6: Prohibit file Upload

For security reasons, edit/etc/php.d/security.ini to cancel file upload as follows

File_uploads=off

If the user does need to upload the file, then turn it on, and then limit the maximum file size that PHP accepts:

file_uploads=on# user can only upload upto 1MB via phpupload_max_filesize=1m

#7: Turn off remote code execution

If this feature is enabled, PHP can get remote data such as FTP or Web content through Allow_url_fopen, in file_get_contents (), include, require. Programmers often forget to filter user input, and if those functions call that data, an injection vulnerability is formed. In PHP-based Web applications, injection vulnerabilities in a large number of code are generated. You can turn this feature off by editing/etc/php.d/security.ini:

Allow_url_fopen=off

In addition, it is advisable to cancel the allow_url_include:

Allow_url_include=off

#8: Enable SQL security mode

Modify/etc/php.d/security.ini as follows:

Sql.safe_mode=on

When this attribute is enabled, mysql_connect () and mysql_pconnect () Ignore all parameters passed in. At the same time, you need to make some changes to the code. Third-party and open source applications, such as WordPress, may not work properly under Sql.safe_mode. It is also recommended to turn off the 5.3.x version of PHP's MAGIC_QUOTES_GPC filter because it is simply rude and inefficient. It is better to use mysql_escape_string () and custom filter functions

Magic_quotes_gpc=off

#9: Control the data size of the post

HTTP post is typically used as part of a request by a client to send data to an Apache Web server, such as uploading a file or submitting a form. An attacker would attempt to send a huge post request to consume the server's resources. The following editing/etc/php.d/security.ini limit the maximum size of post:

; Set a reliable value here post_max_size=1k

The maximum size of the 1K is set here. This setting affects file uploads. To upload large files, this value needs to be larger than update_max_filesize.
It is recommended to restrict the available request methods in Apache, and edit httpd.conf as follows:

 
       
  
   
    
            Order Allow,deny     
  
    # # ADD Rest of the config goes here ... # # 
 
  

#10: Resource control (DOS control)

Set the maximum run time for each PHP script. It is also recommended to limit the maximum amount of time that is used to process request data and the maximum available memory.

# units: Seconds

Max_execution_time = 30max_input_time = 30memory_limit = 40M

#11: Install Suhosin Advanced Protection system for PHP

Specific reference Suhosin project pages: project page

#12: Canceling a dangerous PHP function

PHP has a number of functions that can be used to invade the server, which can become a vulnerability if used improperly. Remove these functions as follows:

Disable_functions =exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file, Show_source

#13: PHP fastcgi/cgi–cgi.force_redirect Management

PHP works in conjunction with FASTCGI. FastCGI can reduce the memory footprint of the Web server (footprint) and improve PHP performance. You can refer to this to configure the apache2+php+fastcgi. In this configuration, Cgi.force_redirect prevents users from invoking PHP by accessing the URL. For security reasons, enable this feature:

; Enable Cgi.force_redirect for security reasons in a typical *apache+php-cgi/fastcgi* setup Cgi.force_redirect=on

#14: PHP user and user group ID

MOD_FASTCGI is a CGI module for Apache Web services that can be connected to an external fastcgi server. You need to make sure that PHP runs with a non-root user. If it uses root or uid less than 100 user rights, it can access and even the operating system files. With Apache's suexec or mod_suphp, PHP CGI can be executed under non-privileged users. suEXEC can be the user ID of the Apache calling CGI program different from the user ID running Apache. As follows:

# PS aux | grep php-cgi

Sample output:

phpcgi      6012  0.0  0.4 225036 60140          S    Nov22   0:12/usr/bin/php-cgi phpcgi      6054  0.0  0.5 229928 62820          s    Nov22   0:11/usr/bin/php-cgi phpcgi      6055  0.1  0.4 224944 53260          s    Nov22   0:18/usr/bin/php-cgi phpcgi      6085  0.0  0.4 224680 56948          S    Nov22   0:11/usr/bin/php-cgi phpcgi      6103  0.0  0.4 224564 57956          S    Nov22   0:11/usr/bin/php-cgi phpcgi      6815  0.4  0.5 228556 61220          S    00:52   0:19/usr/bin/php-cgi phpcgi      6821  0.3  0.5 228008 61252          S    00:55   0:12/usr/bin/php-cgi

You can use SPAWN-FCGI to generate a remote or local fastcgi process for phpcgi users (provided that you have this user):

# spawn-fcgi-a 127.0.0.1-p 9000-u phpcgi-g phpcgi-f/usr/bin/php-cgi

You can now configure Apache, LIGHTHTTPD, or nginx Web service calls to run fastcgi in 127.0.0.1:9000.

#15: Restrict PHP access to the file system

Open_basedir restricts the running directory of PHP, such as directories accessible through functions such as fopen (). If the directory you are accessing is not within Open_basedir, PHP will deny that access. Do not use soft links as workspaces. For example, only access to/var/www/html, not/var/www,/tmp, or/etc directories is allowed:

; Limits the PHP process from accessing files outside  ; of specifically designated directories such as/var/www/html/op En_basedir= "/var/www/html/"; ------------------------------------ ; Multiple dirs example  ; open_basedir= "/home/httpd/vhost/cyberciti.biz/html/:/home/httpd/vhost/nixcraft.com/ Html/:/home/httpd/vhost/theos.in/html/"; ------------------------------------

#16: Session Path

The PHP session user provides data saving functionality for subsequent access. This allows the application to be more customizable and attractive. All session-related data will be stored in Session.save_path. The default settings for Rhel/centos/fedora Linux are as follows:

Session.save_path= "/var/lib/php/session"; Set the temporary directory used for storing files when doing file upload upload_tmp_dir= "/var/lib/php/session"

Verify that the path is outside of/var/www/html and cannot be accessed by other system users:

# ls-z/var/lib/php/

Sample output:

DRWXRWX---. Root Apache system_u:object_r:httpd_var_run_t:s0 Session

Note: Ls-z will display the SELinux security information, such as file mode, User,group, security information, file name, etc.

#17: Ensure PHP, software and operating system updates to the latest

An important task in maintaining Linux, Apache, PHP, and MySQL servers is to update security patches. All PHP security updates should be reviewed and updated as soon as possible. You can use the following command (if you are installing PHP through Package Manager):

# Yum Update

Or

# apt-get update && Apt-get upgrade

You can configure Red Hat/centos/fedora Linux to send Yum's package update reminders via email, or to send reminders under Debian/ubuntu Linux Apticron. or update it with a cron scheduled task.

Note: View php.net to get the latest PHP version information

#18: Restricting access to files and directories

Verify that Apache is running as a non-root user such as Apache or www. The owner of the/var/www/html directory should also be a non-root user:

# Chown-r apache:apache/var/www/html/

Files under DocumentRoot should be banned from running or created. Set the file permissions in this directory to 0444 (read-only):

# Chmod-r 0444/var/www/html/

Set all folder permissions in this directory to 0445

# find/var/www/html/-type d-print0 | Xargs-0-I {} chmod 0445 {}

#19: Write protection for Apache, PHP, MySQL configuration files

Use the chattr command to add write protection to these profiles:

# chattr +i/etc/php.ini# chattr +i/etc/php.d/*# chattr +i/etc/my.ini# chattr +i/etc/httpd/conf/httpd.conf# chattr +i/ etc/

You can also add write protection to the/var/www/html directory

# chattr +i/var/www/html/file1.php# chattr +i/var/www/html/

#20: Using Linux security extensions (such as SELinux)

Linux has a variety of security programs to prevent faulty configuration or vulnerability of service programs. Use SELinux or other Linux security schemes to limit networks and programs whenever possible. For example, SELinux provides different security policies for the Linux kernel or Apache Web services. Use the following command to list all Apache protection information:

# Getsebool-a | grep httpd

Sample output:

Allow_httpd_anon_write--off Allow_httpd_mod_auth_ntlm_winbind-off allow_httpd_mod_auth_pam---off Allow_httpd_sys_script_anon_write--off httpd_builtin_scripting-on httpd_can_check_spam and off Httpd_ Can_network_connect--off Httpd_can_network_connect_cobbler-off httpd_can_network_connect_db---off Httpd_can_network_memcache---off Httpd_can_network_relay-off Httpd_can_sendmail and off Httpd_dbus_avahi --on httpd_enable_cgi--on Httpd_enable_ftp_server--off Httpd_enable_homedirs and off Httpd_execmem--& Gt Off Httpd_read_user_content---off Httpd_setrlimit-off httpd_ssi_exec----httpd_tmp_exec-off HTTP D_tty_comm-On httpd_unified-on httpd_use_cifs-off HTTPD_USE_GPG-off Httpd_use_nfs--off

To cancel Apache CGI support, you can enter:

# setsebool-p httpd_enable_cgi off

Detailed reference: Red Hat SELinux Guide

#21: Installing Mod_security

Modsecurity is an open source intrusion detection and prevention Web application engine. Install mod_security to protect Apache and PHP applications from XSS and other attacks:

# # A Few Examples # # # do not allow to open files in/etc/secfilter/etc/# Stop SQL injection Secfilter "Delete[[:space: ]]+from "Secfilter" Select.+from "

#22: If possible, run under Chroot jail apache/php

Running the apache/php under the Chroot jail minimizes the potential loss that can be limited to a small chunk of the file system. You can use generic chroot to configure Apache:chroot kind of Setup with Apache. However, I recommend using FreeBSD jails, XEN,KVM, or OpenVZ virtualization.

#23: Restricting outgoing connections using firewalls

Attackers will use tools such as wget to download files from your Web server. Use Iptables to block outgoing connections from Apache users. The Ipt_owner module assigns different roles to the generator of the local packet. It is only valid for output chain. The following directives allow Vivek users to access externally via port 80:

/sbin/iptables-a output-o eth0-m owner--uid-owner vivek-p TCP--dport 80-m State--state new,established-j  ACCE Pt

The following example blocks outgoing connections for all Apache users, allowing only the SMTP service and the Spam Recognition API service to pass:

# ..../sbin/iptables--new-chain apache_user/sbin/iptables--append output-m State--state established,related-j accept/sbin/iptables--append output-m owner--uid-owner apache-j Apache_user # AL  Low Apache user to Connec to our SMTP server/sbin/iptables--append apache_user-p TCP--syn-d 192.168.1.100--dport 25 -j RETURN # allow Apache user to Connec to API server for spam validation/sbin/iptables--append apache_user-p TCP--sy n-d 66.135.58.62--dport 80-j return/sbin/iptables--append apache_user-p tcp--syn-d 66.135.58.61--dport 80-j RE Turn/sbin/iptables--append apache_user-p tcp--syn-d 72.233.69.89--dport 80-j return/sbin/iptables--append Apache _user-p TCP--syn-d 72.233.69.88--dport 80-j RETURN ######################### # # ADD More rules here # # ############# ############ # No Editing below # Drop everything for Apache outgoing connection/sbin/iptables--append apache_user-j RE Ject 

#24: View and Review logs

To view Apache log files:

# tail-f/var/log/httpd/error_log # grep ' login.php '/var/log/httpd/error_log # egrep-i "Denied|error|warn"/var/log/htt Pd/error_log

To view the PHP log file:

# tail-f/var/log/httpd/php_scripts_error.log # grep "... etc/passwd"/var/log/httpd/php_scripts_error.log

Viewing the log file can let you know what kind of attack the server is taking and analyze whether the current level of security is sufficient. Enable review services for system review, review SELinux time, verify events, file changes, account changes, and more. We recommend that you use Linux System monitoring tools to monitor your Web servers.

#25: Separating services from different servers or virtual machines

For a larger installation configuration, it is recommended to separate the running, database, static and dynamic content to different servers

////////////////isp/router///////////////\ |      Firewall \ | +------------+      |      LB01 |                 +------------+                 +--------------------------+                   | |                   static.lan.cyberciti.biz | +-----------------+--------------------------+                                     |                                     phpcgi1.lan.cyberciti.biz| +--------------------------+                                     |                                     phpcgi2.lan.cyberciti.biz| +--------------------------+                                     |                                     mysql1.lan.cyberciti.biz | +--------------------------+                                     |                                     mcache1.lan.cyberciti.biz| +--------------------------+

Running different network services under different servers or virtual machines can reduce the impact of intrusion on other services. For example, an attacker who invades Apache can access other services under the same server (such as the Mysql,email service, etc.). However, in the above example, you will not:

    • static.lan.cybercity.biz– use LIGHTTPD or Nginx to store static resources such as Js/css/images
    • Phpcgi1.lan.cyberciti.biz and Phpcgi2.lan.cyberciti.biz–apache Web Services +php, for generating dynamic content
    • Mysql1.lan.cyberciti.biz–mysql Database Services
    • mcache1.lan.cyberciti.biz–memcached Service (MySQL cache system). It uses libevent or epoll to accommodate any number of connections. And it uses non-blocking network IO.
    • lb01– an Nginx server for the reverse proxy of the web and Apache front end. All access connections are processed directly or distributed to the appropriate Web server via the Nginx Proxy service. The LB01 provides simple load balancing.
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.