Same-origin policy

Политика одинакового источника(same-origin policy) определяет как документ или скрипт, загруженный из одного источника (origin), может взаимодействовать с ресурсом из другого источника. Это помогает изолировать потенциально вредоносные документы, снижая количество возможных векторов атак.

Определение origin

Две страницы имеют одинаковый origin (источник) если протокол, порт (если указан), и хост одинаковы для обеих страниц. Время от времени, вы можете видеть это как "scheme/host/port tuple" (где "tuple" переводится как кортеж или запись набор из трёх компонент, которые вместе составляют единое целое).

В следующей таблице даны примеры origin-сравнений с URLhttp://store.company.com/dir/page.html:

URL Outcome Reason
http://store.company.com/dir2/other.html Success
http://store.company.com/dir/inner/another.html Success
https://store.company.com/secure.html Failure Different protocol
http://store.company.com:81/dir/etc.html Failure Different port
http://news.company.com/dir/other.html Failure Different host

Смотрите такжеorigin definition forfile:URLs.

Наследование origins

Контент изabout:blankиjavascript:адреса наследуют источник документа, содержащего этот URL, поскольку они не содержат информации о сервере происхождения.

Примечание:Например,about:blankчасто используется в качестве URL новых, пустых окон в которые родительский скрипт записывает контент (например, с помощьюWindow.open()). Если это окно также содержит JavaScript, то скрипт будет наследовать то же происхождение, что и его родитель.

Предупреждение:data:адреса получают новый, пустой, безопасный контекст.

Исключения в Internet Explorer

Internet Explorer два основных исключения из политики одно происхождения:

Trust Zones (Зоны доверия)

Если оба домена находятся в зоне высокого доверия (например, зоны корпоративной интрасети), то ограничения на одно и то же происхождение не применяется.

Порт

IE не включает порт в same-origin проверку. Следовательно,https://company.com:81/index.htmlиhttps://company.com/index.htmlявляются адресами одного происхождения и ограничения действовать не будут.

Эти исключения являются нестандартными и не поддерживаются в любом другом браузере

Изменение origin

Страница может изменить свой оригинальный origin с некоторыми ограничениями. Скрипт может установить значениеdocument.domainна текущий домен или супердомен текущего домена. Если значение будет установлено на супердомен текущего домена, более короткий домен будет использован для последующей проверки origin'а. Например, предполагается, что скрипт в документе по адресуhttp://store.company.com/dir/other.htmlвыполняется следующим выражением:

js
document.domain="company.com";

После этого, страница может пройти такую же проверку наhttp://company.com/dir/page.html(предполагая, что http://company.com/dir/page.htmlустановилdocument.domainв значение "company.com"чтобы указать, что у него получилось разрешение - смотриdocument.domain). Однако,company.comне можетустановитьdocument.domainв значениеothercompany.com,поскольку это значение не является супердоменомcompany.com.

Номер порта проверяется браузером отдельно. Любой вызовdocument.domain,включающийdocument.domain = document.domain,заменяет номер порта, устанавливая его в значениеnull.Следовательно,невозможновызовcompany.com:8080обозначитьcompany.comодной лишь установкойdocument.domain = "company.com"в начале. Он должен быть установлен в обоих случаях и номер портов в этих случаях должны равняться значениюnull.

Примечание:Когда используетсяdocument.domainдля разрешения поддомена для родительского доступа к нему, вы должны установитьdocument.domainвтакое же значение,как в родительском домене, так и в поддомене. Это необходимо, даже если при этом просто восстанавливается исходное значение родительского домена. Несоблюдение этого правила может привести к ошибкам разрешений.

Cross-origin network access

The same-origin policy controls interactions between two different origins, such as when you useXMLHttpRequestor an<img>element. These interactions are typically placed into three categories:

  • Cross-originwritesare typically allowed. Examples are links, redirects and form submissions. Certain rarely used HTTP requests requirepreflight.
  • Cross-originembeddingis typically allowed. Examples are listed below.
  • Cross-originreadsare typically not allowed, but read access is often leaked by embedding. For example, you can read the width and height of an embedded image, the actions of an embedded script, or theavailability of an embedded resource.

Here are some examples of resources which may be embedded cross-origin:

  • JavaScript with<script src= "..." ></script>.Error messages for syntax errors are only available for same-origin scripts.
  • CSS with<link rel= "stylesheet" href= "..." >.Due to therelaxed syntax rulesof CSS, cross-origin CSS requires a correctContent-Typeheader. Restrictions vary by browser:IE,Firefox,Chrome,Safari(scroll down to CVE-2010-0051) andOpera.
  • Images with<img>.Supported image formats include PNG, JPEG, GIF, BMP, SVG,...
  • Media files with<video>and<audio>.
  • Plug-ins with<object>,<embed>and<applet>.
  • Fonts with@font-face.Some browsers allow cross-origin fonts, others require same-origin fonts.
  • Anything with<frame>and<iframe>.A site can use theX-Frame-Optionsheader to prevent this form of cross-origin interaction.

How to allow cross-origin access

UseCORSto allow cross-origin access.

How to block cross-origin access

  • To prevent cross-origin writes, check for an unguessable token in the request, known as aCross-Site Request Forgery (CSRF)token. You must prevent cross-origin reads of pages that know this token.
  • To prevent cross-origin reads of a resource, ensure that it is not embeddable. It is often necessary to prevent embedding because embedding a resource always leaks some information about it.
  • To prevent cross-origin embedding, ensure that your resource cannot be interpreted as one of the embeddable formats listed above. The browser does not respect theContent-Typein most cases. For example, if you point a<script>tag at an HTML document, the browser will try to parse the HTML as JavaScript. When your resource is not an entry point to your site, you can also use a CSRF token to prevent embedding.

Cross-origin script API access

JavaScript APIs such asiframe.contentWindow,window.parent,window.openandwindow.openerallow documents to directly reference each other. When the two documents do not have the same origin, these references provide very limited access toWindowandLocationobjects, as described in the next two sections.

To communicate further between documents from different origins, usewindow.postMessage.

Window

Specification:http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#security-window.

The following cross-origin access toWindowproperties is allowed:

Methods
window.blur
window.close
window.focus
window.postMessage
Attributes
window.closed Read only.
window.frames Read only.
window.length Read only.
window.location Read/write.
window.opener Read only.
window.parent Read only.
window.self Read only.
window.top Read only.
window.window Read only.

Some browsers allow access to more properties than the specification allows.

Location

Specification:http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#security-location.

The following cross-origin access toLocationproperties is allowed:

Methods
location.replace
Attributes
URLUtils.href Write only.

Some browsers allow access to more properties than the specification allows.

Cross-origin data storage access

Access to data stored in the browser such aslocalStorageandIndexedDBare separated by origin. Each origin gets its own separate storage, and JavaScript in one origin cannot read from or write to the storage belonging to another origin.

Cookies use a separate definition of origins. A page can set a cookie for its own domain or any parent domain, as long as the parent domain is not a public suffix. Firefox and Chrome use thePublic Suffix Listto determine if a domain is a public suffix. Internet Explorer uses its own internal method to determine if a domain is a public suffix. The browser will make a cookie available to the given domain including any sub-domains, no matter which protocol (HTTP/HTTPS) or port is used. When you set a cookie, you can limit its availability using the Domain, Path, Secure and Http-Only flags. When you read a cookie, you cannot see from where it was set. Even if you use only secure https connections, any cookie you see may have been set using an insecure connection.

Смотрите также