Access is allowed
Module mod_access
This module provides access control based on client hostname, IP address, or other characteristics of the client request.
Summary
The directives provided by mod_access are used in , , and sections as well as .htaccess files to control access to particular parts of the server. Access can be controlled based on the client hostname, IP address, or other characteristics of the client request, as captured in environment variables. The Allow and Deny directives are used to specify which clients are or are not allowed access to the server, while the Order directive sets the default access state, and configures how the Allow and Deny directives interact with each other.
Both host-based access restrictions and password-based authentication may be implemented simultaneously. In that case, the Satisfy directive is used to determine how the two sets of restrictions interact.
In general, access restriction directives apply to all access methods ( GET , PUT , POST , etc). This is the desired behavior in most cases. However, it is possible to restrict some methods, while leaving other methods unrestricted, by enclosing the directives in a section.
Directives
Allow directive
The Allow directive affects which hosts can access an area of the server. Access can be controlled by hostname, IP Address, IP Address range, or by other characteristics of the client request captured in environment variables.
The first argument to this directive is always from . The subsequent arguments can take three different forms. If Allow from all is specified, then all hosts are allowed access, subject to the configuration of the Deny and Order directives as discussed below. To allow only particular hosts or groups of hosts to access the server, the host can be specified in any of the following formats:
A (partial) domain-name Example: Allow from apache.org
Hosts whose names match, or end in, this string are allowed access. Only complete components are matched, so the above example will match foo.apache.org but it will not match fooapache.org . This configuration will cause the server to perform a double reverse DNS lookup on the client IP address, regardless of the setting of the HostnameLookups directive. It will do a reverse DNS lookup on the IP address to find the associated hostname, and then do a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches will access be allowed. A full IP address Example: Allow from 10.1.2.3
An IP address of a host allowed access A partial IP address Example: Allow from 10.1
The first 1 to 3 bytes of an IP address, for subnet restriction. A network/netmask pair Example: Allow from 10.1.0.0/255.255.0.0
A network a.b.c.d, and a netmask w.x.y.z. For more fine-grained subnet restriction. (Apache 1.3 and later) A network/nnn CIDR specification Example: Allow from 10.1.0.0/16
Similar to the previous case, except the netmask consists of nnn high-order 1 bits. (Apache 1.3 and later)
Note that the last three examples above match exactly the same set of hosts.
The third format of the arguments to the Allow directive allows access to the server to be controlled based on the existence of an environment variable. When Allow from env= env-variable is specified, then the request is allowed access if the environment variable env-variable exists. The server provides the ability to set environment variables in a flexible way based on characteristics of the client request using the directives provided by mod_setenvif. Therefore, this directive can be used to allow access based on such factors as the clients User-Agent (browser type), Referer , or other HTTP request header fields.
In this case, browsers with a user-agent string beginning with KnockKnock/2.0 will be allowed access, and all others will be denied.
Deny directive
This directive allows access to the server to be restricted based on hostname, IP address, or environment variables. The arguments for the Deny directive are identical to the arguments for the Allow directive.
Order directive
The Order directive controls the default access state and the order in which Allow and Deny directives are evaluated. Ordering is one of
Deny,Allow The Deny directives are evaluated before the Allow directives. Access is allowed by default. Any client which does not match a Deny directive or does match an Allow directive will be allowed access to the server. Allow,Deny The Allow directives are evaluated before the Deny directives. Access is denied by default. Any client which does not match an Allow directive or does match a Deny directive will be denied access to the server. Mutual-failure Only those hosts which appear on the Allow list and do not appear on the Deny list are granted access. This ordering has the same effect as Order Allow,Deny and is deprecated in favor of that configuration.
Keywords may only be separated by a comma; no whitespace is allowed between them. Note that in all cases every Allow and Deny statement is evaluated.
In the following example, all hosts in the apache.org domain are allowed access; all other hosts are denied access.
Order Deny,Allow
Deny from all
Allow from apache.org
In the next example, all hosts in the apache.org domain are allowed access, except for the hosts which are in the foo.apache.org subdomain, who are denied access. All hosts not in the apache.org domain are denied access because the default state is to deny access to the server.
Order Allow,Deny
Allow from apache.org
Deny from foo.apache.org
On the other hand, if the Order in the last example is changed to Deny,Allow , all hosts will be allowed access. This happens because, regardless of the actual ordering of the directives in the configuration file, the Allow from apache.org will be evaluated last and will override the Deny from foo.apache.org . All hosts not in the apache.org domain will also be allowed access because the default state will change to allow.
The presence of an Order directive can affect access to a part of the server even in the absence of accompanying Allow and Deny directives because of its effect on the default access state. For example,
will deny all access to the /www directory because the default access state will be set to deny.
The Order directive controls the order of access directive processing only within each phase of the server’s configuration processing. This implies, for example, that an Allow or Deny directive occurring in a section will always be evaluated after an Allow or Deny directive occurring in a section or .htaccess file, regardless of the setting of the Order directive. For details on the merging of configuration sections, see the documentation on How Directory, Location and Files sections work.
Apache Module mod_access_compat
Summary
The directives provided by mod_access_compat are used in , , and sections as well as .htaccess files to control access to particular parts of the server. Access can be controlled based on the client hostname, IP address, or other characteristics of the client request, as captured in environment variables. The Allow and Deny directives are used to specify which clients are or are not allowed access to the server, while the Order directive sets the default access state, and configures how the Allow and Deny directives interact with each other.
Both host-based access restrictions and password-based authentication may be implemented simultaneously. In that case, the Satisfy directive is used to determine how the two sets of restrictions interact.
The directives provided by mod_access_compat have been deprecated by the new authz refactoring. Please see mod_authz_host .
In general, access restriction directives apply to all access methods ( GET , PUT , POST , etc). This is the desired behavior in most cases. However, it is possible to restrict some methods, while leaving other methods unrestricted, by enclosing the directives in a section.
Merging of configuration sections
When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections.
Directives
Allow
Deny
Order
Satisfy
See also
Allow Directive
The Allow directive affects which hosts can access an area of the server. Access can be controlled by hostname, IP address, IP address range, or by other characteristics of the client request captured in environment variables.
The first argument to this directive is always from . The subsequent arguments can take three different forms. If Allow from all is specified, then all hosts are allowed access, subject to the configuration of the Deny and Order directives as discussed below. To allow only particular hosts or groups of hosts to access the server, the host can be specified in any of the following formats:
A (partial) domain-name
Hosts whose names match, or end in, this string are allowed access. Only complete components are matched, so the above example will match foo.example.org but it will not match fooexample.org . This configuration will cause Apache httpd to perform a double DNS lookup on the client IP address, regardless of the setting of the HostnameLookups directive. It will do a reverse DNS lookup on the IP address to find the associated hostname, and then do a forward lookup on the hostname to assure that it matches the original IP address. Only if the forward and reverse DNS are consistent and the hostname matches will access be allowed.
A full IP address
An IP address of a host allowed access
A partial IP address
The first 1 to 3 bytes of an IP address, for subnet restriction.
A network/netmask pair
A network a.b.c.d, and a netmask w.x.y.z. For more fine-grained subnet restriction.
A network/nnn CIDR specification
Similar to the previous case, except the netmask consists of nnn high-order 1 bits.
Note that the last three examples above match exactly the same set of hosts.
IPv6 addresses and IPv6 subnets can be specified as shown below:
The third format of the arguments to the Allow directive allows access to the server to be controlled based on the existence of an environment variable. When Allow from env= env-variable is specified, then the request is allowed access if the environment variable env-variable exists. When Allow from env=! env-variable is specified, then the request is allowed access if the environment variable env-variable doesn’t exist. The server provides the ability to set environment variables in a flexible way based on characteristics of the client request using the directives provided by mod_setenvif . Therefore, this directive can be used to allow access based on such factors as the clients User-Agent (browser type), Referer , or other HTTP request header fields.
In this case, browsers with a user-agent string beginning with KnockKnock/2.0 will be allowed access, and all others will be denied.
Merging of configuration sections
When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections.
Deny Directive
This directive allows access to the server to be restricted based on hostname, IP address, or environment variables. The arguments for the Deny directive are identical to the arguments for the Allow directive.
Order Directive
The Order directive, along with the Allow and Deny directives, controls a three-pass access control system. The first pass processes either all Allow or all Deny directives, as specified by the Order directive. The second pass parses the rest of the directives ( Deny or Allow ). The third pass applies to all requests which do not match either of the first two.
Note that all Allow and Deny directives are processed, unlike a typical firewall, where only the first match is used. The last match is effective (also unlike a typical firewall). Additionally, the order in which lines appear in the configuration files is not significant — all Allow lines are processed as one group, all Deny lines are considered as another, and the default state is considered by itself.
Ordering is one of:
Allow,Deny First, all Allow directives are evaluated; at least one must match, or the request is rejected. Next, all Deny directives are evaluated. If any matches, the request is rejected. Last, any requests which do not match an Allow or a Deny directive are denied by default. Deny,Allow First, all Deny directives are evaluated; if any match, the request is denied unless it also matches an Allow directive. Any requests which do not match any Allow or Deny directives are permitted. Mutual-failure This order has the same effect as Order Allow,Deny and is deprecated in its favor.
Keywords may only be separated by a comma; no whitespace is allowed between them.
In the following example, all hosts in the example.org domain are allowed access; all other hosts are denied access.
In the next example, all hosts in the example.org domain are allowed access, except for the hosts which are in the foo.example.org subdomain, who are denied access. All hosts not in the example.org domain are denied access because the default state is to Deny access to the server.
On the other hand, if the Order in the last example is changed to Deny,Allow , all hosts will be allowed access. This happens because, regardless of the actual ordering of the directives in the configuration file, the Allow from example.org will be evaluated last and will override the Deny from foo.example.org . All hosts not in the example.org domain will also be allowed access because the default state is Allow .
The presence of an Order directive can affect access to a part of the server even in the absence of accompanying Allow and Deny directives because of its effect on the default access state. For example,
will Deny all access to the /www directory because the default access state is set to Deny .
The Order directive controls the order of access directive processing only within each phase of the server’s configuration processing. This implies, for example, that an Allow or Deny directive occurring in a section will always be evaluated after an Allow or Deny directive occurring in a section or .htaccess file, regardless of the setting of the Order directive. For details on the merging of configuration sections, see the documentation on How Directory, Location and Files sections work.
Merging of configuration sections
When any directive provided by this module is used in a new configuration section, no directives provided by this module are inherited from previous configuration sections.
allowed access
1 allowed access to a
2 allowed access to
access code — код вызова; код доступа
3 allowed access to a
4 allowed access
5 allowed access
См. также в других словарях:
access — [[t]æ̱kses[/t]] ♦♦♦ accesses, accessing, accessed 1) N UNCOUNT: usu N to n If you have access to a building or other place, you are able or allowed to go into it. The facilities have been adapted to give access to wheelchair users. For… … English dictionary
Access Linux Platform — The Access Linux Platform, sometime referred to as a next generation version of the Palm OS is an open source based operating system for mobile devices developed and marketed by Access Co., of Tokyo, Japan. The platform includes execution… … Wikipedia
Access control — is the ability to permit or deny the use of a particular resource by a particular entity. Access control mechanisms can be used in managing physical resources (such as a movie theater, to which only ticketholders should be admitted), logical… … Wikipedia
Access Control Matrix — or Access Matrix is an abstract, formal computer protection and security model used in computer systems, that characterizes the rights of each subject with respect to every object in the system. It was first introduced by Butler W. Lampson in… … Wikipedia
access profile — UK US noun [countable] [singular access profile plural access profiles] business information kept on a computer that gives details about a user, for example their name, password , and the parts of the system they are allowed to use … Useful english dictionary
Access token — In Microsoft Windows operating systems, an access token contains the security information for a login session and identifies the user, the user s groups, and the user s privileges. OverviewAn access token is as an object encapsulating the… … Wikipedia
Access control list — In computer security, an access control list (ACL) is a list of permissions attached to an object. The list specifies who or what is allowed to access the object and what operations are allowed to be performed on the object. In a typical ACL,… … Wikipedia
access — ▪ I. access ac‧cess 1 [ˈækses] noun [uncountable] 1. MARKETING the right to sell goods to a particular market or country without breaking any laws or agreements: access to • Japan agreed to allow foreign manufacturers of satellite equipment equal … Financial and business terms
access profile — UK / US noun [countable] Word forms access profile : singular access profile plural access profiles business information kept on a computer that gives details about a user, for example their name, password, and the parts of the system they are… … English dictionary
access — (verb) This is when someone is using a BBS with their computer. My boss was accessing a BBS bulletin board when he was interrupted by the doorbell. (noun) Refers to an intangible amount (usually represented by a security level or flags) that… … Dictionary of telecommunications
Что такое CORS
Многие из нас встречались с подобной ошибкой:
Access to XMLHttpRequest at ‘XXXX’ from origin ‘YYYY’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource..
Эта статья рассказывает что означает эта ошибка и как от нее избавиться.
Создадим тестовый сайт на Node.js с открытым API и запустим его по адресу http://127.0.0.1:3000.
Пусть там будет примерно такая функция получения GET запроса:
Пусть там будет простая функция входа в систему, где пользователи вводят общее секретное слово secret и им затем ему устанавливается cookie, идентифицируя их как аутентифицированных:
И пусть у нас будет некое приватное API для каких нибудь личных данных в /private, только для аутентифицированных пользователей.
Запрос нашего API через AJAX из других доменов
И допустим у нас есть какое-нибудь клиентское приложение работающее с нашим API. Но учтем что, наше API находится по адресу http://127.0.0.1:3000/public, а наш клиент размещен на http://127.0.0.1:8000, и на клиенте есть следующий код:
И это не будет работать!
Если мы посмотрим на вкладку network в консоле Хрома при обращение c http://127.0.0.1:8000 к http://127.0.0.1:3000 то там не будет ошибок:
Сам по себе запрос был успешным, но результат оказался не доступен. Описание причины можно найти в консоли JavaScript:
Ага! Нам не хватает заголовка Access-Control-Allow-Origin. Но зачем он нам и для чего он вообще нужен?
Same-Origin Policy
Причиной, по которой мы не получим ответ в JavaScript, является Same-Origin Policy. Эта ограничительная мера была придумана разработчиками браузеров что бы веб-сайт не мог получить ответ на сгенерированный AJAX запрос к другому веб-сайту находящемуся по другому адресу .
Например: если вы заходите на sample.org, вы бы не хотели, чтобы этот веб-сайт отправлял запрос к примеру на ваш банковский веб-сайт и получал баланс вашего счета и транзакции.
Same-Origin Policy предотвращает именно это.
«источник (origin)» в этом случае состоит из
- протокол (например http )
- хост (например example.com )
- порт (например 8000 )
Так что http://sample.org и http://www.sample.org и http://sample.org:3000 – это три разных источника.
Пару слов о CSRF
Обратите внимание, что существует класс атак, называемый подделкой межсайтовых запросов (Cross Site Request Forgery – csrf ), от которых не защищает Same-Origin Policy.
При CSRF-атаке злоумышленник отправляет запрос сторонней странице в фоновом режиме, например, отправляя POST запрос на веб-сайт вашего банка. Если у вас в этот момент есть действительный сеанс с вашим банком, любой веб-сайт может сгенерировать запрос в фоновом режиме, который будет выполнен, если ваш банк не использует контрмеры против CSRF.
Так же обратите внимание, что, несмотря на то, что действует Same-Origin Policy, наш пример запроса с сайта secondparty.com на сайте 127.0.0.1:3000 будет успешно выполнен – мы просто не соможем получить доступ к результатам. Но для CSRF нам не нужен результат …
Например, API, которое позволяет отправлять электронные письма, выполняя POST запрос, отправит электронное письмо, если мы предоставим ему правильные данные. Злоумышленнику не нужно заботится о результате, его забота это отправляемое электронное письмо, которое он получит независимо от возможности видеть ответ от API.
Включение CORS для нашего публичного API
Допустим нам нужно разрешить работу JavaScript на сторонних сайтах (например, 127.0.0.1:8000) что бы получать доступ к нашим ответам API. Для этого нам нужно включить CORS в заголовок ответа от сервера. Это делается на стороне сервера:
Здесь мы устанавливаем заголовку Access-Control-Allow-Origin значение *, что означает: что любому хосту разрешен доступ к этому URL и ответу в браузере:
Непростые запросы и предварительные запросы (preflights)
Предыдущий пример был так называемым простым запросом. Простые запросы – это:
- Запросы: GET,POST
- Тип содержимого следующего:
- text/plain
- application/x-www-form-urlencoded
- multipart/form-data
Допустим теперь 127.0.0.1:8000 немного меняет реализацию, и теперь он обрабатывает запросы в формате JSON:
Но это снова все ломает!
На этот раз консоль показывает другую ошибку:
Любой заголовок, который не разрешен для простых запросов, требует предварительного запроса (preflight request).
Этот механизм позволяет веб-серверам решать, хотят ли они разрешить фактический запрос. Браузер устанавливает заголовки Access-Control-Request-Headers и Access-Control-Request-Method, чтобы сообщить серверу, какой запрос ожидать, и сервер должен ответить соответствующими заголовками.
Но наш сервер еще не отвечает с этими заголовками, поэтому нам нужно добавить их:
Теперь мы снова может получить доступ к ответу.
Credentials и CORS
Теперь давайте предположим, что нам нужно залогинится на 127.0.0.1:3000 что бы получить доступ к /private с конфиденциальной информацией.
При всех наших настройках CORS может ли другой сайт так же получить эту конфиденциальную информацию?
Мы пропустили код реализации входа в на сервер так как он не обязателен для объяснения материала.
Независимо от того, попытаемся ли мы залогинится на 127.0.0.1:3000 или нет, мы увидим «Please login first».
Причина в том, что cookie от 127.0.0.1:3000 не будут отправляться, когда запрос поступает из другого источника. Мы можем попросить браузер отправить файлы cookie клиенту, даже если запрос с других доменов:
Но опять это не будет работать в браузере. И это хорошая новость, на самом деле.
Итак, мы не хотим, чтобы злоумышленник имел доступ к приватным данным, но что, если мы хотим, чтобы 127.0.0.1:8000 имел доступ к /private?
В этом случае нам нужно установить для заголовка Access-Control-Allow-Credentials значение true:
Но это все равно пока еще не сработает. Это опасная практика – разрешать любые аутентифицированные запросы с других источников.
Браузер не позволит нам так легко совершить ошибку.
Если мы хотим разрешить 127.0.0.1:8000 доступ к /private, нам нужно указать точный источник в заголовке:
Теперь http://127.0.0.1:8000 также имеет доступ к приватным данным, в то время как запрос с любого другого сайта будет заблокирован.
Разрешить множественные источники (origin)
Теперь мы разрешили одному источнику делать запросы к другому источнику с данными аутентификации. Но что, если у нас есть несколько других источников?
В этом случае мы, вероятно, хотим использовать белый список:
Опять же: не отправляйте напрямую req.headers.origin в качестве разрешенного заголовка CORS. Это позволит любому веб-сайту получить доступ к приватным данным.
Из этого правила могут быть исключения, но, по крайней мере, дважды подумайте, прежде чем внедрять CORS с учетными данными без белого списка.
Заключение
В этой статье мы рассмотрели Same-Origin Policy и то, как мы можем использовать CORS, чтобы разрешать запросы между источниками, когда это необходимо.
Это требует настройки на стороне сервера и на стороне клиента и в зависимости от запроса вызовет предварительный (preflight) запрос.
При работе с аутентифицированными запросами перекрестного происхождения следует проявлять дополнительную осторожность. Белый список может помочь разрешить нескольким источникам без риска утечки конфиденциальных данных (которые защищены аутентификацией).
Выводы
- Браузер использует Same-origin policy, чтобы не обрабатывать AJAX ответы от веб-сайтов расположенных на адресах отличных от адреса с которого была загружена веб страница.
- Same-origin policy не запрещает генерировать запросы к другим сайтам, но запрещает обрабатывать от них ответ.
- CORS (Cross-Origin Resource Sharing) механизм, который использует дополнительные заголовки HTTP, чтобы дать браузерам указание предоставить веб-приложению, работающему в одном источнике, доступ к ответу на запрос к ресурсам из другого источника.
- CORS вместе с credentials (с данными аутентификации) требует осторожности.
- CORS это браузерная политика. Другие приложения не затрагиваются этим понятием.
XMLHttpRequest: кросс-доменные запросы
Материал на этой странице устарел, поэтому скрыт из оглавления сайта.
Более новая информация по этой теме находится на странице https://learn.javascript.ru/fetch-crossorigin.
Обычно запрос XMLHttpRequest может делать запрос только в рамках текущего сайта. При попытке использовать другой домен/порт/протокол – браузер выдаёт ошибку.
Существует современный стандарт XMLHttpRequest, он ещё в состоянии черновика, но предусматривает кросс-доменные запросы и многое другое.
Большинство возможностей этого стандарта уже поддерживаются всеми браузерами, но увы, не в IE9-.
Впрочем, частично кросс-доменные запросы поддерживаются, начиная с IE8, только вместо XMLHttpRequest нужно использовать объект XDomainRequest.
Кросс-доменные запросы
Разберём кросс-доменные запросы на примере кода:
- Мы создаём XMLHttpRequest и проверяем, поддерживает ли он событие onload . Если нет, то это старый XMLHttpRequest , значит это IE8,9, и используем XDomainRequest .
- Запрос на другой домен отсылается просто указанием соответствующего URL в open . Он обязательно должен быть асинхронным, в остальном – никаких особенностей.
Контроль безопасности
Кросс-доменные запросы проходят специальный контроль безопасности, цель которого – не дать злым хакерам™ завоевать интернет.
Серьёзно. Разработчики стандарта предусмотрели все заслоны, чтобы «злой хакер» не смог, воспользовавшись новым стандартом, сделать что-то принципиально отличное от того, что и так мог раньше и, таким образом, «сломать» какой-нибудь сервер, работающий по-старому стандарту и не ожидающий ничего принципиально нового.
Давайте, на минуточку, вообразим, что появился стандарт, который даёт, без ограничений, возможность делать любой странице HTTP-запросы куда угодно, какие угодно.
Как сможет этим воспользоваться злой хакер?
Он сделает свой сайт, например http://evilhacker.com и заманит туда посетителя (а может посетитель попадёт на «злонамеренную» страницу и по ошибке – не так важно).
Когда посетитель зайдёт на http://evilhacker.com , он автоматически запустит JS-скрипт на странице. Этот скрипт сделает HTTP-запрос на почтовый сервер, к примеру, http://gmail.com . А ведь обычно HTTP-запросы идут с куками посетителя и другими авторизующими заголовками.
Поэтому хакер сможет написать на http://evilhacker.com код, который, сделав GET-запрос на http://gmail.com , получит информацию из почтового ящика посетителя. Проанализирует её, сделает ещё пачку POST-запросов для отправки писем от имени посетителя. Затем настанет очередь онлайн-банка и так далее.
Спецификация CORS налагает специальные ограничения на запросы, которые призваны не допустить подобного апокалипсиса.
Запросы в ней делятся на два вида.
Простыми считаются запросы, если они удовлетворяют следующим двум условиям:
- Простой метод: GET, POST или HEAD
- Простые заголовки – только из списка:
- Accept
- Accept-Language
- Content-Language
- Content-Type со значением application/x-www-form-urlencoded , multipart/form-data или text/plain .
«Непростыми» считаются все остальные, например, запрос с методом PUT или с заголовком Authorization не подходит под ограничения выше.
Принципиальная разница между ними заключается в том, что «простой» запрос можно сформировать и отправить на сервер и без XMLHttpRequest, например при помощи HTML-формы.
То есть, злой хакер на странице http://evilhacker.com и до появления CORS мог отправить произвольный GET-запрос куда угодно. Например, если создать и добавить в документ элемент
Комментарии
- Если вам кажется, что в статье что-то не так — вместо комментария напишите на GitHub.
- Для одной строки кода используйте тег , для нескольких строк кода — тег
, если больше 10 строк — ссылку на песочницу (plnkr, JSBin, codepen…)