Building secure Web servers under FreeBSD (2)

Source: Internet
Author: User
Tags execution flush connect sql mysql mysql client net sql injection


The following are the referenced contents:
# When the program crashes, it's not logged
Kern.coredump=0
# Lo Local data stream receive and send space
net.local.stream.recvspace=65536
net.local.dgram.maxdgram=16384
net.local.dgram.recvspace=65536
# packet data segment size, ADSL 1452.
net.inet.tcp.mssdflt=1460
# provides buffering when connecting to network data
Net.inet.tcp.inflight_enable=1
# packet data segment minimum, ADSL 1452
net.inet.tcp.minmss=1460
# Maximum number of local data
net.inet.raw.maxdgram=65536
# Local data stream receive space
net.inet.raw.recvspace=65536
#ipfw防火墙动态规则数量, the default is 4096, increasing this value prevents certain viruses from sending a large number of TCP connections, resulting in the inability to establish a normal connection
net.inet.ip.fw.dyn_max=65535
#设置ipf防火墙TCP连接空闲保留时间, default 8640000 (120 hours)
net.inet.ipf.fr_tcpidletimeout=864000

Iii. security settings for the service program

Here is the focus of this article, we will spend more text to describe, of course, so the description is not necessarily very correct, but also hope to have some help to you. Our system is run by default, including Apache, Mysql, Vsftpd,ssh and other services, we have one by one explanations below.

1. Apache Security Settings

Apache's core setup is in the httpd.conf, we installed the Apache directory is under/usr/local/apache2/, then our configuration file is in/usr/local/apache2/conf/httpd.conf , if you are installing using ports, the configuration file should be in the/etc or/usr/local/etc directory. To open a profile using EE or VI:

# ee/usr/local/apache2/conf/httpd.conf

Below we are going to make more security settings, the basic services, ports, home directory, and so on settings do not say, only to talk about security-related settings.

(1) Specify the users and groups running the Apache service

This is more important because permissions are inherited, and if the user rights to run the Apache service are too high, it is likely that intruders will be severely threatened by the webshell of the system. In general we run Apache with nobody users and nobody groups. The user and group options are found between the 250-275 lines of httpd.conf, such as our default settings as follows (the annotation information is removed):

The following are the referenced contents:
<ifmodule!mpm_winnt.c>
<ifmodule!mpm_netware.c>
User Nobody
Group #-1
</IfModule>
</IfModule>

(2) Apache log files

Apache log file is very important, you can find Apache health and access, for the detection of intrusion and so have important help. Its default options are:

# error log storage directory, default is stored in the Apache installation directory under the logs

ErrorLog Logs/error_log

# level of logging, level has debug, info, notice, warn, error, crit, etc., default is "warn" level

LogLevel warn

# access to the format of the log records, each format has different content, tailored to your needs to obtain the most access information

The following are the referenced contents:
Logformat "%h%l%u%t \%r\"%>s%b \ "%{referer}i\" \ "%{user-agent}i\" "combined
Logformat "%h%l%u%t \"%r\ "%>s%b" common
Logformat "%{referer}i->%u" Referer
Logformat "%{user-agent}i" Agent

# using the form above, the default is to use the common

Customlog Logs/access_log Common

File format predefined format content:

The following are the referenced contents:
%a Remote User IP
%A the IP of the local httpd server
%f the file name of the transfer
%H Remote Host
%m Request method
%l Identd Given the remote name
httpd port number for%p connection
HTTPD Process for%P requests
%t time
%T Service Request Time

You can customize your own log format and then invoke it by Customlog Logs/access_log Common.

Note that the log file is opened by the user running Apache, and should be aware of the security of the file to prevent hackers from overwriting or deleting it.

(3) Apache Service Information Display control

One option in the configuration file is to control whether to display Apache version information, host name, Port, supported CGI, and so on:

Serversignature on

The default is on, so all information is displayed:

I intentionally visited a nonexistent file: http://www.target.com/404.html

The following message will be displayed in the error prompt:

apache/2.0.53 (Unix) php/4.3.11 Server at Target.com Port 80

All Apache and PHP information is completely exposed, which is not safe. Of course also have off and email options, off will not show any information, email will show the administrator's email address, recommended set to off or email, so as to avoid leaking Apache server information to hackers.

(4) Directory browsing

In httpd.conf you can set up Apache to be able to browse directories of Web pages that do not have index files:

The following are the referenced contents:
<directory/>
Options Indexes FollowSymLinks
AllowOverride None
</Directory>

This is neither appropriate nor safe, and it is recommended that you do not need directory browsing:

The following are the referenced contents:
<directory/>
Options FollowSymLinks
AllowOverride None
</Directory>

(5) User homepage

To set the httpd.conf in:

Userdir public_html

Enables each user who uses the system to create a public_html directory in his or her home directory and then can put his or her web page into that directory and pass:

http://www.target.com/~ User name/Web page will be able to display their own pages, which is not safe, and for our server, this is not necessary, so we directly turn off the function:

Userdir disabled

or change the content to a file name that hackers can't easily guess, such as:

Userdir Webserver_public_htmlpath

You can also allow only some users to have this feature:

Userdir enabled User1 User2 user3

(6) CGI execution directory

If your Apache is going to perform some CGI programs like Perl, then set the options:

scriptalias/cgi-bin/"/usr/local/apache/cgi-bin/"

But it also gives hackers the option of using some unsafe CGI programs to do damage, so if you don't need CGI, it's recommended to turn it off:

#ScriptAlias/cgi-bin/"/usr/local/apache/cgi-bin/"

(7) Control PHP script can only access the specified directory

Add the following in httpd.conf:

Php_admin_value open_basedir/usr/www

The following path is where you need the PHP script to be able to access the directory, if the PHP script wants to access other directories will be out of error prompts.

(8) Directory access control (not completed)

This content is the most complex, at the same time involved in a lot of things, I can only say briefly, not clear please refer to other articles.

For example, here's what:

The following are the referenced contents:
<directory/>
Options FollowSymLinks
AllowOverride None
</Directory>

is to allow access to each directory, which is set to allow the execution of the action, generally contains the actions are: Options, allowoverride, order, Allow, Deny.

Options are actions that can be performed only on the specified directory and its subdirectories, Indexes, Includes, FollowSymLinks, execcgi, MultiViews, None, all, and so on.

AllowOverride is the right to specify directory access, and of course, it can be specified by Accessfilename file. htaccess to control. Its operation has: None, all, Options, FileInfo, Authconfit, limit and so on.

Order, Allow, deny three instructions must be matched to control directory access permissions. order specifies the rules for checking orders, such as Allow, deny, which means that the Allow check is first checked, if it does not match, and then the Deny is checked. Order Deny, Allow, indicates that the Deny rule is checked first, and if the condition is not met, then the Allow is checked.

Files that control access rights to the directory

By default, you can use. htaccess on UNIX platforms to define directory permissions, but this is unsafe, it is recommended to close, and the default option is:

Accessfilename. htaccess

The proposal is set up as follows:

#AccessFileName. htaccess

All directory permission definitions use the definition in httpd.conf and do not use. htaccess.

(9) User access authentication

This technique is very important to control the access of some illegal users to this content. Suppose our site: http://www.target.com/admin is our admin directory, I do not allow some illegal users to access, then I must set access to this directory is required to verify.

First, add the directory to which you want to access authentication in httpd.conf:

The following are the referenced contents:
<directory "/usr/www/admin" >
AuthType Basic
AuthName "Private"
Authuserfile/usr/local/apache/bin/admin.dat
Require user Login_user
Options Indexes followsymlinks MultiViews
AllowOverride None
</Directory>

Above we set up our/usr/www/admin directory must be authenticated to access, and then we set access password:

The following are the referenced contents:
#/usr/local/apahche/bin/htpasswd-c/usr/local/apache/bin/admin.dat login_name
New Password: * * *
Re-type New Password: * * *
Adding password for user login_name

The next time any user accesses the Http://www.target.com/admin directory, you will need to enter the username login_name and the password you set.

2. PHP Security Settings

There are some problems with the old version of PHP itself, such as some serious bugs before php4.3.10 and php5.0.3, so it is recommended that you use the new version. In addition, the current busy SQL injection is also in PHP have a lot of ways to use, so to ensure security, PHP code writing is on the one hand, PHP configuration is very critical.

Our PHP hand-installed, PHP default profile in/usr/local/apache2/conf/php.ini, our main is to configure the content of PHP.ini, let us execute PHP can be more secure.

Security settings throughout PHP are primarily designed to prevent Phpshell and SQL injection attacks, and we'll explore it slowly. We first use any editing tool to open/etc/local/apache2/conf/php.ini, and if you are installing in a different way, the profile may not be in that directory.

(1) Open PHP security mode

The PHP security model is a very important embedded security mechanism that controls some functions in PHP, such as System (), and allows you to control many file manipulation functions, and not allow files for certain key files, such as/etc/passwd, But the default php.ini is not open safe mode, we turn it on:

Safe_mode = On

(2) User group security

When the Safe_mode is turned on, the Safe_mode_gid is turned off, so the PHP script can access the file and the same group of users can access the file.

The recommended setting is:

Safe_mode_gid = Off

If you do not set up, we may not be able to operate on our server Web site directory, such as when we need to operate on the file.

(3) Safe Mode executable Program Home directory

If Safe mode is open, but you want to execute some programs, you can specify the home directory where you want to execute the program:

Safe_mode_exec_dir =/usr/bin
Typically, there is no program to perform, so it is recommended that you do not execute the System program directory, point to a directory, and then copy the program that needs to be executed, such as:

Safe_mode_exec_dir =/tmp/cmd

However, I recommend that you do not execute any programs, then you can point to our web directory:

Safe_mode_exec_dir =/usr/www

(4) Include files in Safe mode

If you want to include some public files in Safe mode, modify the options:

Safe_mode_include_dir =/usr/www/include/

In fact, the general PHP script contains files are in the program itself has been written, this can be set according to the specific needs.

(5) Control the directory that the PHP script can access

Using the Open_basedir option to control PHP scripts can only access the specified directory, so that you can avoid PHP script access to/etc/passwd and other files, to some extent limit the harm of phpshell, we can generally set to access only the site directory:

Open_basedir =/usr/www

(6) Close the dangerous function

If Safe mode is turned on, the function prohibition is not necessary, but we consider it for security. For example, we don't want to execute PHP functions that can execute commands, including system (), or to see phpinfo () functions such as PHP information, so we can ban them:

Disable_functions = System,passthru,exec,shell_exec,popen,phpinfo

If you want to disable the operation of any files and directories, you can turn off many file operations

Disable_functions = Chdir,chroot,dir,getcwd,opendir,readdir,scandir,fopen,unlink,delete,copy,mkdir,rmdir,rename, File,file_get_contents,fputs,fwrite,chgrp,chmod,chown

The above is just a list of not commonly used file processing functions, you can also execute the above command function and this function, you can resist most of the Phpshell.

(7) Turn off the disclosure of PHP version information in HTTP headers

In order to prevent hackers from obtaining information about the PHP version of the server, you can turn off the information ramp in the HTTP header:

expose_php = Off

For example, when the hacker in Telnet www.target.com 80, then will not be able to see the PHP information

(8) Turning off registration of global variables

Variables submitted in PHP, including the use of post or get submitted variables, will be automatically registered as a global variable, can be directly accessed, which is very unsafe for the server, so we can not let it register as a global variable, the registration of global variable option to turn off:

Register_globals = Off

Of course, if this is the case, then the corresponding variable should be taken in a reasonable way, such as getting the variable var of get commit, then use $_get[' var ' to obtain, the PHP programmer should pay attention to.

(9) Open MAGIC_QUOTES_GPC to prevent SQL injection

SQL injection is a very dangerous problem, small site backstage was invaded, heavy the entire server fell, so be careful. There is a setting in php.ini:

MAGIC_QUOTES_GPC = Off

This default is closed, if it is opened will automatically put the user submitted to the SQL query conversion, such as the ' Switch to ' and so on, this to prevent SQL injection has a significant role. So we recommend setting it to:

MAGIC_QUOTES_GPC = On

(10) Error information control

General PHP is not connected to the database or other circumstances will be prompted error, the general error message will contain the current path of the PHP script information or query the SQL statements and other information, such information provided to hackers, is not safe, so the general server recommendations prohibit error tips:

Display_errors = Off

If you are trying to display an error message, be sure to set the level at which the error is displayed, such as displaying only the information above the warning:

error_reporting = e_warning & E_error

Of course, I recommend closing the error prompt.

(11) Error log

It is recommended that the error message can be logged after the display_errors is turned off to make it easier to find out why the server is running:

Log_errors = On

Also set the directory where the error log is stored, and suggest that the log of the root Apache be present together:

Error_log =/usr/local/apache2/logs/php_error.log

Note: You must allow the Apache users and groups to have write permissions to the file.

3. mysql Security settings

We have MySQL installed in the/usr/local/mysql directory, we have to create a user named MySQL, the group for MySQL users to run our MySQL, while we have its configuration file copied to the/etc directory:

The following are the referenced contents:
# CP SUPORT-FILES/MY-MEDIUM.CNF/ETC/MY.CNF
Chown root:sys/etc/my.cnf
chmod 644/etc/my.cnf

Use user MySQL to start our MySQL:

#/usr/local/mysql/bin/mysqld_safe-user=mysql &

(1) Modify the password of the root user

The default installation of MySQL is not password, so we have to modify, just in case. The following three methods are used to modify the root password.

* Use the mysqladmin command to change the root user password

# mysqladmin-uroot Password Test

Thus, the password for the MySQL database root user is changed to test. (Test just for example, we actually use the password must not use this easy to guess weak password)

* Modify password with Set password:

Mysql> Set password for Root@localhost=password (' test ');

The root user's password is then changed to test.

* Directly modify the user table root password

The following are the referenced contents:
mysql> use MySQL;
mysql> Update user Set Password=password (' Test ') where user= ' root ';
mysql> flush Privileges;

Thus, the password for the MySQL database root is also changed to test. The last command flush privileges means to force a flush of the memory authorization table, or a password in the buffer, where the illegal user can log in with the root user and the empty password until the MySQL server is restarted.

(2) Delete the default database and user

Our database is local, and we only need local PHP script to read MySQL, so many users do not need it. MySQL initialization will automatically generate a null user and test library, which poses a threat to the database, we delete all.

We use the MySQL client program to connect to the local MySQL server after the following prompts:

The following are the referenced contents:
mysql> drop database test;
mysql> use MySQL;
Mysql> Delete from DB;
Mysql> Delete from the user where not (host= "localhost" and user= "root");
mysql> flush Privileges;

(3) Change the name of the default MySQL administrator

This job is optional, depending on your personal habits, because the default MySQL administrator name is root, so if you can modify it, you can prevent some Scripting Guys from the system's exhaustive. We can modify the database directly to change the root user to "admin"

The following are the referenced contents:
mysql> use MySQL;
mysql> Update user Set user= "admin" where user= "root";
mysql> flush Privileges;

(4) Improve local security

Improve local security, mainly to prevent MySQL access to local files, such as hackers through MySQL to get/etc/passwd, will pose a threat to the system. MySQL's access to local files is implemented through SQL statements, mainly through the load DATA infile, which we can disable to prevent hackers from acquiring system core files through SQL injection.

Disabling this feature must include an argument in the [mysqld] section of the MY.CNF:

Set-variable=local-infile=0

(5) Prohibit remote connection to MySQL

Because our MySQL only needs local PHP script to connect, so we do not need to open the socket for listening, then we can completely turn off the listening function.

There are two ways to achieve this:

* Configure the My.cnf file and add skip-networking parameters in the [mysqld] section

* Add--skip-networking Startup parameters to the MYSQLD server's parameters to keep MySQL from listening for any TCP/IP connections, adding security. If you want to manage MySQL, you can install a phpmyadmin locally on the server for management.



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.