Apache restrictions — различия между версиями

Материал из pNp Wiki
Перейти к: навигация, поиск
(Проверка)
(Конфигурирование Apache. Ограничение доступа к директориям)
(не показано 6 промежуточных версий этого же участника)
Строка 3: Строка 3:
 
==== Предварительные требования ====
 
==== Предварительные требования ====
 
* Виртуальная машина с двумя сетевыми интерфейсами
 
* Виртуальная машина с двумя сетевыми интерфейсами
* Установленные пакеты: <code>bash-completion</code>, <code>policycoreutils</code>, <code>policycoreutils-python</code>, <code>policycoreutils-devel</code>, <code>setroubleshoot-server</code>, <code>httpd</code>, <code>elinks</code>, <code>curl</code>
+
* Установленные пакеты: <code>bash-completion</code>, <code>policycoreutils</code>, <code>policycoreutils-python</code>, <code>policycoreutils-devel</code>, <code>setroubleshoot-server</code>, <code>httpd</code>, <code>httpd-manual</code>, <code>elinks</code>, <code>curl</code>
  
 
== Конфигурирование ограничений ==
 
== Конфигурирование ограничений ==
Строка 83: Строка 83:
 
on this server.</p>
 
on this server.</p>
 
</body></html>
 
</body></html>
 +
[root@vm-02 ~]#
 +
</syntaxhighlight>
 +
=== Ограничение на основе аккаунта пользователя ===
 +
Для директории <code>/content/private</code> в конфигурационном файле <code>/etc/httpd/conf.d/vm-01.conf</code> укажем способ аутентикации и путь к файлу с аккаунтами пользователей и их
 +
паролями, для доступа к содержимому данной директории:
 +
<syntaxhighlight lang="bash">
 +
# Virtual Hosts
 +
#
 +
# Required modules: mod_log_config
 +
 +
# If you want to maintain multiple domains/hostnames on your
 +
# machine you can setup VirtualHost containers for them. Most configurations
 +
# use only name-based virtual hosts so the server doesn't need to worry about
 +
# IP addresses. This is indicated by the asterisks in the directives below.
 +
#
 +
# Please see the documentation at
 +
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
 +
# for further details before you try to setup virtual hosts.
 +
#
 +
# You may use the command line option '-S' to verify your virtual host
 +
# configuration.
 +
 +
#
 +
# VirtualHost example:
 +
# Almost any Apache directive may go into a VirtualHost container.
 +
# The first VirtualHost section is used for all requests that do not
 +
# match a ServerName or ServerAlias in any <VirtualHost> block.
 +
#
 +
<VirtualHost *:80>
 +
    ServerAdmin webmaster@vm-01.example.com
 +
    DocumentRoot "/content"
 +
    ServerName vm-01.example.com
 +
    ServerAlias www.vm-01.example.com
 +
    ErrorLog "/var/log/httpd/vm-01.example.com-error_log"
 +
    CustomLog "/var/log/httpd/vm-01.example.com-access_log" common
 +
<Directory "/content">
 +
    AllowOverride None
 +
    # Allow open access:
 +
    Require all granted
 +
</Directory>
 +
<Directory "/content/private">
 +
                AuthType basic
 +
                AuthName "Private area! Restricted access"
 +
                AuthUserFile "/etc/httpd/passwd"
 +
                Require valid-user
 +
</Directory>
 +
</VirtualHost>
 +
</syntaxhighlight>
 +
Создадим учетную запись <code>andy</code> и пароль для нее:
 +
<syntaxhighlight lang="bash">
 +
[root@vm-01 ~]# htpasswd -c /etc/httpd/
 +
conf/          conf.d/        conf.modules.d/ logs/          modules/        run/           
 +
[root@vm-01 ~]# htpasswd -c /etc/httpd/passwd andy
 +
New password:
 +
Re-type new password:
 +
Adding password for user andy
 +
[root@vm-01 ~]#
 +
</syntaxhighlight>
 +
Присвоим права пользователю <code>apache</code> на чтение и запись в файл <code>/etc/httpd/passwd</code>:
 +
<syntaxhighlight lang="bash">
 +
[root@vm-01 ~]# chmod 600 /etc/httpd/passwd
 +
[root@vm-01 ~]# grep apache /etc/passwd
 +
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
 +
[root@vm-01 ~]# chown apache:apache /etc/httpd/passwd
 +
[root@vm-01 ~]# ls -lahi /etc/httpd/passwd
 +
741770 -rw-------. 1 apache apache 43 Jan 24 12:05 /etc/httpd/passwd
 +
[root@vm-01 ~]#
 +
</syntaxhighlight>
 +
Проверяем конфигурацию и перезагружаем вебсервер:
 +
<syntaxhighlight lang="bash">
 +
[root@vm-01 ~]# httpd -t
 +
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.122.158. Set the 'ServerName' directive globally to suppress this message
 +
Syntax OK
 +
[root@vm-01 ~]# systemctl restart httpd
 +
[root@vm-01 ~]# systemctl is-active httpd
 +
active
 +
[root@vm-01 ~]#
 +
</syntaxhighlight>
 +
==== Проверка ====
 +
С виртуальной машины <code>vm-02</code> обратимся к странице при помощи утилиты <code>curl</code>:
 +
<syntaxhighlight lang="bash">
 +
[root@vm-02 ~]# curl "http://192.168.1.1/private/"
 +
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 +
<html><head>
 +
<title>401 Unauthorized</title>
 +
</head><body>
 +
<h1>Unauthorized</h1>
 +
<p>This server could not verify that you
 +
are authorized to access the document
 +
requested.  Either you supplied the wrong
 +
credentials (e.g., bad password), or your
 +
browser doesn't understand how to supply
 +
the credentials required.</p>
 +
</body></html>
 +
</syntaxhighlight>
 +
Как только добавляем имя пользователя и пароль, получаем следующее:
 +
<syntaxhighlight lang="bash">
 +
[root@vm-02 ~]# curl -u andy:password "http://192.168.1.1/private/"
 +
This is private directory.
 +
Tue Jan 23 16:28:33 MSK 2018
 
[root@vm-02 ~]#
 
[root@vm-02 ~]#
 
</syntaxhighlight>
 
</syntaxhighlight>

Версия 12:24, 24 января 2018

Конфигурирование Apache. Ограничение доступа к директориям

Предварительные требования

  • Виртуальная машина с двумя сетевыми интерфейсами
  • Установленные пакеты: bash-completion, policycoreutils, policycoreutils-python, policycoreutils-devel, setroubleshoot-server, httpd, httpd-manual, elinks, curl

Конфигурирование ограничений

Ограничение на основе хоста

Создадим директорию /content/private и в ней файл index.html:

[root@vm-01 ~]# mkdir /content/private
[root@vm-01 ~]# printf "This is private directory.\n$(date)\n" > /content/private/index.html
[root@vm-01 ~]# restorecon -vR /content/
[root@vm-01 ~]# ls -lahiZ /content/private/
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 .
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 ..
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
[root@vm-01 ~]#

Для директории /content/private в конфигурационном файле /etc/httpd/conf.d/vm-01.conf укажем адрес с которого разрешено обращаться к содержимому данной директории:

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin webmaster@vm-01.example.com
    DocumentRoot "/content"
    ServerName vm-01.example.com
    ServerAlias www.vm-01.example.com
    ErrorLog "/var/log/httpd/vm-01.example.com-error_log"
    CustomLog "/var/log/httpd/vm-01.example.com-access_log" common
	<Directory "/content">
    		AllowOverride None
    		# Allow open access:
    		Require all granted
	</Directory>
	<Directory "/content/private">
    		AllowOverride None
    		# Allow open access:
    		Require ip 192.168.1.2
	</Directory>
	
</VirtualHost>

Проверка

С виртуальной машины vm-02 обратимся к странице при помощи утилиты curl:

[root@vm-02 ~]# curl "http://192.168.1.1/private/"
This is private directory.
Tue Jan 23 16:28:33 MSK 2018
[root@vm-02 ~]#

Как только изменяем значение директивы Require виртуального хоста vm-01, получаем следующее:

[root@vm-02 ~]# curl "http://192.168.1.1/private/"
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /private/
on this server.</p>
</body></html>
[root@vm-02 ~]#

Ограничение на основе аккаунта пользователя

Для директории /content/private в конфигурационном файле /etc/httpd/conf.d/vm-01.conf укажем способ аутентикации и путь к файлу с аккаунтами пользователей и их паролями, для доступа к содержимому данной директории:

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
<VirtualHost *:80>
    ServerAdmin webmaster@vm-01.example.com
    DocumentRoot "/content"
    ServerName vm-01.example.com
    ServerAlias www.vm-01.example.com
    ErrorLog "/var/log/httpd/vm-01.example.com-error_log"
    CustomLog "/var/log/httpd/vm-01.example.com-access_log" common
	<Directory "/content">
    		AllowOverride None
    		# Allow open access:
    		Require all granted
	</Directory>
	<Directory "/content/private">
                AuthType basic
                AuthName "Private area! Restricted access"
                AuthUserFile "/etc/httpd/passwd"
                Require valid-user
	</Directory>
</VirtualHost>

Создадим учетную запись andy и пароль для нее:

[root@vm-01 ~]# htpasswd -c /etc/httpd/
conf/           conf.d/         conf.modules.d/ logs/           modules/        run/            
[root@vm-01 ~]# htpasswd -c /etc/httpd/passwd andy 
New password: 
Re-type new password: 
Adding password for user andy
[root@vm-01 ~]#

Присвоим права пользователю apache на чтение и запись в файл /etc/httpd/passwd:

[root@vm-01 ~]# chmod 600 /etc/httpd/passwd 
[root@vm-01 ~]# grep apache /etc/passwd
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
[root@vm-01 ~]# chown apache:apache /etc/httpd/passwd
[root@vm-01 ~]# ls -lahi /etc/httpd/passwd 
741770 -rw-------. 1 apache apache 43 Jan 24 12:05 /etc/httpd/passwd
[root@vm-01 ~]#

Проверяем конфигурацию и перезагружаем вебсервер:

[root@vm-01 ~]# httpd -t
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 192.168.122.158. Set the 'ServerName' directive globally to suppress this message
Syntax OK
[root@vm-01 ~]# systemctl restart httpd
[root@vm-01 ~]# systemctl is-active httpd
active
[root@vm-01 ~]#

Проверка

С виртуальной машины vm-02 обратимся к странице при помощи утилиты curl:

[root@vm-02 ~]# curl "http://192.168.1.1/private/"
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Unauthorized</title>
</head><body>
<h1>Unauthorized</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

Как только добавляем имя пользователя и пароль, получаем следующее:

[root@vm-02 ~]# curl -u andy:password "http://192.168.1.1/private/"
This is private directory.
Tue Jan 23 16:28:33 MSK 2018
[root@vm-02 ~]#